简单的win32多线程---生产者、消费者模型

    xiaoxiao2021-12-14  19

    #include < iostream> #include < windows.h> using namespace std; #define BUFSIZE 5 static int SharedBuffer[BUFSIZE]; static int head = 0, tail = 0; static int count = 0; static HANDLE hMutex; static HANDLE hNotFullEvent, hNotEmptyEvent; static void BB_Producer() { int i; for (i=20; i>=0; i--) { Sleep(2000); while (true) { WaitForSingleObject(hMutex,INFINITE); if (count == BUFSIZE) // 缓冲区满 { ReleaseMutex(hMutex); //释放锁 WaitForSingleObject(hNotFullEvent,INFINITE); //等待消费者取走 continue; } // 得到互斥锁且缓冲区非满,跳出while循环 break; } // 得到互斥锁且缓冲区非满,开始产生新数据 cout << "Produce: " << i << endl; SharedBuffer[tail] = i; tail = (tail+1) % BUFSIZE; count++; ReleaseMutex(hMutex); // 结束临界区 PulseEvent(hNotEmptyEvent); // 唤醒消费者线程 } } static void BB_Consumer() { int result; while (1) { WaitForSingleObject(hMutex,INFINITE); if (count == 0) { ReleaseMutex(hMutex); // 释放互斥锁且等待 WaitForSingleObject(hNotEmptyEvent,INFINITE); } else if (SharedBuffer[head] == 0) { cout << "Consumed 0: end of data" << endl; ReleaseMutex(hMutex); // 结束临界区 ExitThread(0); } else { result = SharedBuffer[head]; cout << "Consumed: " << result << endl; head = (head+1) % BUFSIZE; count--; ReleaseMutex(hMutex); // 结束临界区 PulseEvent(hNotFullEvent); // 唤醒生产者线程 Sleep(2000); } } } int main() { HANDLE hThreadVector[2]; DWORD ThreadID; hMutex = CreateMutex(NULL,FALSE,NULL); hNotFullEvent = CreateEvent(NULL,TRUE,FALSE,NULL); hNotEmptyEvent = CreateEvent(NULL,TRUE,FALSE,NULL); hThreadVector[0] = CreateThread (NULL, 0, (LPTHREAD_START_ROUTINE) BB_Producer, NULL, 0, (LPDWORD)&ThreadID); cout<<"Producer thread ID: "<<ThreadID<<", "<<hThreadVector[0]<<endl; hThreadVector[1] = CreateThread (NULL, 0, (LPTHREAD_START_ROUTINE) BB_Consumer, NULL, 0, (LPDWORD)&ThreadID); cout<<"Consumer thread ID: "<<ThreadID<<", "<<hThreadVector[1]<<endl; WaitForMultipleObjects(2,hThreadVector,TRUE,INFINITE); return 0; }
    转载请注明原文地址: https://ju.6miu.com/read-964168.html

    最新回复(0)