每天學習一算法系列(31)(實現一個隊列,隊列的應用場景爲:一個生產者線程將int 類型的數入列,一個消費者線程將int 類型的數出列)

題目:

實現一個隊列。
隊列的應用場景爲:一個生產者線程將int 類型的數入列,一個消費者線程將int 類型的數出列。

 

思路一:

這就是操作系統中介紹的PV操作,隊列的一個典型的應用模式。實現這個PV操作的過程中要注意兩個線程之間的通信就可以了。

 

代碼如下:

/*-----------------------------
Copyright by yuucyf. 2011.08.25
-------------------------------*/

#include "stdafx.h"
#include <windows.h>
#include <stdio.h>
#include <process.h>
#include <iostream>
#include <queue>
using namespace std;

HANDLE g_hSemaphore = NULL;		//信號量
const int g_i32PMax = 100;		//生產(消費)總數
std::queue<int> g_queuePV;		//生產入隊,消費出隊


//生產者線程
unsigned int __stdcall ProducerThread(void* pParam)
{
	int i32N = 0;
	while (++i32N <= g_i32PMax)
	{
		//生產
		g_queuePV.push(i32N);
		cout<<"Produce "<< i32N << endl;
		ReleaseSemaphore(g_hSemaphore, 1, NULL); //增加信號量
		Sleep(300);//生產間隔的時間,可以和消費間隔時間一起調節
	}

	return 0;
}

//消費者線程
unsigned int __stdcall CustomerThread(void* pParam)
{
	int i32N = g_i32PMax;
	while (i32N--)
	{
		WaitForSingleObject(g_hSemaphore, 10000);
		//消費
		queue <int>::size_type iVal = g_queuePV.front();
		g_queuePV.pop();
		cout<<"Custom "<< iVal << endl;
		Sleep(500);	//消費間隔的時間,可以和生產間隔時間一起調節
	}

	//消費結束
	cout << "Working end." << endl;

	return 0;
}

void PVOperationGo()
{
	g_hSemaphore = CreateSemaphore(NULL, 0, g_i32PMax, NULL); //信號量來維護線程同步
	if (NULL == g_hSemaphore)
		return;

	cout <<"Working start..." <<endl;
	HANDLE aryhPV[2];
	aryhPV[0] = (HANDLE)_beginthreadex(NULL, 0, ProducerThread, NULL, 0, NULL);
	aryhPV[1] = (HANDLE)_beginthreadex(NULL, 0, CustomerThread, NULL, 0, NULL);

	WaitForMultipleObjects(2, aryhPV, TRUE, INFINITE);
	CloseHandle(g_hSemaphore);
}

int _tmain(int argc, _TCHAR* argv[])
{
	PVOperationGo();

	return 0;
}


 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章