|
/* 生產(chǎn)者消費者線程演示 一個生產(chǎn)者線程將int類型的數(shù)入列,一個消費者線程將int類型的數(shù)出列 */ #include <windows.h> #include <stdio.h> #include <process.h> #include <iostream> #include <queue> using namespace std; HANDLE ghSemaphore; //信號量 const int gMax = 100; //生產(chǎn)(消費)總數(shù) std::queue<int> q; //生產(chǎn)入隊,消費出隊 //生產(chǎn)者線程 unsigned int __stdcall producerThread(void* pParam) { int n = 0; while(++n <= gMax) { //生產(chǎn) q.push(n); cout<<"produce "<<n<<endl; ReleaseSemaphore(ghSemaphore, 1, NULL); //增加信號量 Sleep(300);//生產(chǎn)間隔的時間,可以和消費間隔時間一起調(diào)節(jié) } _endthread(); //生產(chǎn)結(jié)束 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);//消費間隔的時間,可以和生產(chǎn)間隔時間一起調(diào)節(jié) } //消費結(jié)束 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; }
|