生产者与消费者的问题
代码如下:
# include <windows.h># include <stdio.h>HANDLE g_hSemaphore;int g_Count = 0, i = 1; //i用做标记,DWORD WINAPI Producer(LPVOID lpParam){ while(TRUE) { WaitForSingleObject(g_hSemaphore, INFINITE); if(g_Count > 4) { i = 0; //i = 0表示当消费者消费完所有窝头的时候,就可以退出了 ReleaseSemaphore(g_hSemaphore, 1, NULL); break; } g_Count++; printf("生产了一个,目前共有:%d 个\n", g_Count); ReleaseSemaphore(g_hSemaphore, 1, NULL); } return 0;}DWORD WINAPI Consumer(LPVOID lpParam){ while(TRUE) { WaitForSingleObject(g_hSemaphore, INFINITE); if((g_Count < 1) && (i == 0)) { ReleaseSemaphore(g_hSemaphore, 1, NULL); break; } if(g_Count < 1) continue; g_Count--; printf("消费了一个,目前剩余:%d 个\n", g_Count); ReleaseSemaphore(g_hSemaphore, 1, NULL); } return 0;}int main(){ g_hSemaphore = CreateSemaphore(NULL, 1, 2, NULL); //创建一个信号量对象,最大资源数为2,当前资源数为1 HANDLE hConsumer, hProducer; hProducer = CreateThread(NULL, 0, Producer, NULL, 0, NULL); //创建“生产者”线程 hConsumer = CreateThread(NULL, 0, Consumer, NULL, 0, NULL); //创建“消费者”线程 CloseHandle(hConsumer); CloseHandle(hProducer); Sleep(1000); //主线程睡眠1秒 CloseHandle(g_hSemaphore); return 0;}