题目要求:
实现一个队列。队列的应用场景是:一个生产者线程将int型的数入列,一个消费者线程将int型的数出列。
参考资料: 编程之美1.10
题目分析:
可以按照操作系统中的生产者与消费者模型来实现代码,大致思路如下:
void producer(void) { while(1) { item = produce_item(); down(empty);//信号量 down(mutex);//互斥量 q.push(item);//队列压栈 up(mutex); up(full); } } void consumer(void) { while(1) { down(full); down(mutex); item = remove_item(); up(mutex); up(empty); q.pop(item);//队列出栈 } }
代码实现:
转自:http://blog.csdn.net/yuucyf/article/details/6717135,思路与上面的分析有些不同,可以参考代码和调试来理解。
/*----------------------------- Copyright by yuucyf. 2011.08.25 -------------------------------*/ #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 main(void) { PVOperationGo(); return 0; }