/* 生產(chǎn)者消費(fèi)者線程演示 一個(gè)生產(chǎn)者線程將int類型的數(shù)入列,一個(gè)消費(fèi)者線程將int類型的數(shù)出列 */ #include <windows.h> #include <stdio.h> #include <process.h> #include <iostream> #include <queue> using namespace std; HANDLE ghSemaphore; //信號(hào)量 const int gMax = 100; //生產(chǎn)(消費(fèi))總數(shù) std::queue<int> q; //生產(chǎn)入隊(duì),消費(fèi)出隊(duì) //生產(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); //增加信號(hào)量 Sleep(300);//生產(chǎn)間隔的時(shí)間,可以和消費(fèi)間隔時(shí)間一起調(diào)節(jié) } _endthread(); //生產(chǎn)結(jié)束 return 0; } //消費(fèi)者線程 unsigned int __stdcall customerThread(void* pParam) { int n = gMax; while(n--) { WaitForSingleObject(ghSemaphore, 10000); //消費(fèi) q.pop(); cout<<"custom "<<q.front()<<endl; Sleep(500);//消費(fèi)間隔的時(shí)間,可以和生產(chǎn)間隔時(shí)間一起調(diào)節(jié) } //消費(fèi)結(jié)束 CloseHandle(ghSemaphore); cout<<"working end."<<endl; _endthread(); return 0; } void threadWorking() { ghSemaphore = CreateSemaphore(NULL, 0, gMax, NULL); //信號(hào)量來維護(hù)線程同步 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; }
|