#include <iostream> #include <stdio.h> #include <windows.h> #include<fstream> //ifstream using namespace std; HANDLE Empty, Full, Mutex; //声明3个信号量,mutex为互斥信号量,剩下的为同步信号量,同事同步信号量也起到计数器的作用 句柄类型 int x = 0; int y = 0; ofstream outf; DWORD WINAPI produce(LPVOID param) { int j = 0; do { WaitForSingleObject(Empty, INFINITE);//P(Empty) WaitForSingleObject(Mutex, INFINITE);//P(Mutex),形成互斥,生产者、消费者,生产者、生产者;只能一个人占用这个资源 //cout << "produce, "; printf("produce,\n"); outf<<"produce,\n"; j++; ReleaseSemaphore(Mutex, 1, NULL);//V(Mutex),取消互斥,允许其他线程生产,占用此互斥资源 ReleaseSemaphore(Full, 1, NULL);//V(Full),放一个物品到货架,可以消费量+1 } while (j != 2); //每个线程生产200次 return 0; } DWORD WINAPI consume(LPVOID param) { int j = 0; do { WaitForSingleObject(Full, INFINITE);//P(Full),将可以消费量-1 WaitForSingleObject(Mutex, INFINITE);//P(Mutex),形成互斥访问,消费者、生产者,消费者、消费者;只能一个人占用这个资源 //cout << "consume, "; printf("consume,\n"); outf<<"consume,\n"; j++; ReleaseSemaphore(Mutex, 1, NULL);//V(Mutex),取消互斥,允许其他线程消费 ReleaseSemaphore(Empty, 1, NULL);//V(Empty) } while (j != 2); //每个线程可以消费200次 return 0; } int main() { int i; Empty = CreateSemaphore(NULL, 20, 20, NULL);//声明同步信号量,初始值为20 最大值20 Full = CreateSemaphore(NULL, 0, 20, NULL);//声明同步信号量,初始值0 Mutex = CreateSemaphore(NULL, 1, 1, NULL);//互斥信号量,初始值为1 outf.open("C:\\out.txt");//需要写入的文本文件 DWORD* ThreadId = (DWORD*)malloc(20 * sizeof(DWORD*)); HANDLE* ThreadHandle = (HANDLE*)malloc(20 * sizeof(HANDLE));//创建线程句柄并分配内存空间 //创建10个生产者进程和消费者进程 for (i = 0; i < 10; i++) { ThreadHandle[i] = CreateThread(NULL, 0, produce, NULL, 0, &ThreadId[i]); //ThreadHandle[i + 10] = CreateThread(NULL, 0, consume, NULL, 0, &ThreadId[i + 10]); } for (i = 0; i < 10; i++) { ThreadHandle[i + 10] = CreateThread(NULL, 0, consume, NULL, 0, &ThreadId[i + 10]); } Sleep(1000); return 0; }