【100题】第三十四 实现一个队列
生活随笔
收集整理的這篇文章主要介紹了
【100题】第三十四 实现一个队列
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
一,題目:
? ? ? ?生產者消費者線程演示??
? ? ? ? ? ? ? ? ? 一個生產者線程將int類型的數入列,一個消費者線程將int類型的數出列?
二,分析:
????????
? ? ? ? 這一個,為操作系統上的一個經典例子,以下是july給出的解答 ? ?
三,源碼:
#include <windows.h> #include <stdio.h> #include <process.h> #include <iostream> #include <queue> using namespace std; HANDLE ghSemaphore; //信號量 const int gMax = 100; //生產(消費)總數 std::queue<int> q; //生產入隊,消費出隊 //生產者線程 unsigned int __stdcall producerThread(void* pParam) { int n = 0; while(++n <= gMax) { //生產 q.push(n); cout<<"produce"<<n<<endl; ReleaseSemaphore(ghSemaphore, 1,NULL); //增加信號量 Sleep(300);//生產間隔的時間,可以和消費間隔時間一起調節 } _endthread(); //生產結束 return 0; } //消費者線程 unsigned int __stdcall customerThread(void* pParam) { int n = gMax; while(n--) { WaitForSingleObject(ghSemaphore, 10000); //消費 q.pop(); cout<<"custom "<<q.front()<<endl; //小肥楊指出,原答案這句和上句搞錯了順序? Sleep(500);//消費間隔的時間,可以和生產間隔時間一起調節 } //消費結束 CloseHandle(ghSemaphore); cout<<"working end."<<endl; _endthread(); return 0; } void threadWorking() { ghSemaphore = CreateSemaphore(NULL, 0, gMax, NULL); //信號量來維護線程同步 cout<<"workingstart."<<endl; unsigned threadID; HANDLE handles[2]; handles[0] = (HANDLE)_beginthreadex( NULL, 0, producerThread, NULL, 0, &threadID); handles[1] = (HANDLE)_beginthreadex( NULL, 0, customerThread, NULL, 0, &threadID); WaitForMultipleObjects(2, handles, TRUE, INFINITE); } int main() { threadWorking(); getchar(); return 0; }
?
轉載于:https://www.cnblogs.com/tianshuai11/archive/2012/04/22/2477163.html
總結
以上是生活随笔為你收集整理的【100题】第三十四 实现一个队列的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Verilog MIPS32 CPU(八
- 下一篇: WinCC7.5 SP2 安装与授权(文