每天学习一算法系列(31)(实现一个队列,队列的应用场景为:一个生产者线程将int 类型的数入列,一个消费者线程将int 类型的数出列)

来源:互联网 发布:张家口软件培训班 编辑:程序博客网 时间:2024/05/17 00:57

题目:

实现一个队列。
队列的应用场景为:一个生产者线程将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;}


 

 

原创粉丝点击