http://blog.csdn.net/v_july_v/article/details/6126444ios
隊列的應用場景爲:
一個生產者線程將int類型的數入列,一個消費者線程將int類型的數出列windows
生產者消費者線程演示
一個生產者線程將int類型的數入列,一個消費者線程將int類型的數出列 spa
#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<<"working start."<<endl; unsigned threadID; HANDLE handles[2]; handles[0] = (HANDLE)_beginthreadex( NULL, 0, producerThread, nullptr, 0, &threadID); handles[1] = (HANDLE)_beginthreadex( NULL, 0, customerThread, nullptr, 0, &threadID); WaitForMultipleObjects(2, handles, TRUE, INFINITE); } int main() { threadWorking(); getchar(); return 0; }