34.
实现一个队列。
队列的应用场景为:
一个生产者线程将int类型的数入列,一个消费者线程将int类型的数出列
COPY的,原理挺简单,小编对进程方面的代码不熟悉。只能看懂,不会写
#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(int argc, _TCHAR* argv[]) { PVOperationGo(); return 0; }