| 12
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
 100
 101
 102
 103
 104
 105
 106
 107
 
 | #include <stdio.h>#include <windows.h>
 #include <stdlib.h>
 
 HANDLE mutex;
 HANDLE full;
 HANDLE empty;
 
 DWORD producer[1];
 DWORD consumer[2];
 
 int seq = 1;
 const int storage = 3;
 long warehouse[storage] = {0};
 int in = 0;
 int out = 0;
 int num = 0;
 int cons1 = 0;
 int cons2 = 0;
 bool flag = true;
 
 
 void producerFunction(void)
 {
 while(flag)
 {
 WaitForSingleObject(empty,INFINITE);
 WaitForSingleObject(mutex,INFINITE);
 printf("生产者生产中\n");
 printf("生产成功\n");
 printf("产品序列号:%d\n",seq);
 warehouse[in] = seq;
 in = (in + 1) % storage;
 num++;
 seq++;
 printf("已生产%d件产品\n",num);
 Sleep(1000);
 ReleaseMutex(mutex);
 ReleaseSemaphore(full,1,NULL);
 }
 }
 
 
 void consumer1Function(void)
 {
 while(flag)
 {
 WaitForSingleObject(full,INFINITE);
 WaitForSingleObject(mutex,INFINITE);
 printf("消费者1抢到互斥量\n");
 printf("消费者1消费中\n");
 warehouse[out] = 0;
 out = (out + 1) % storage;
 cons1++;
 Sleep(500);
 printf("消费者1已消费1个产品,共消费了%d件产品\n",cons1);
 printf("已有%d件产品被消费\n",cons1 + cons2);
 printf("消费者1释放互斥量\n");
 ReleaseMutex(mutex);
 ReleaseSemaphore(empty,1,NULL);
 }
 }
 
 
 void consumer2Function(void)
 {
 while(flag)
 {
 WaitForSingleObject(full,INFINITE);
 WaitForSingleObject(mutex,INFINITE);
 printf("消费者2抢到互斥量\n");
 printf("消费者2消费中\n");
 warehouse[out] = 0;
 out = (out + 1) % storage;
 cons2++;
 Sleep(1000);
 printf("消费者2已消费1个产品,共消费了%d件产品\n",cons2);
 printf("已有%d件产品被消费\n",cons1 + cons2);
 printf("消费者2释放互斥量\n");
 ReleaseMutex(mutex);
 ReleaseSemaphore(empty,1,NULL);
 }
 }
 
 
 int main(int argc, char* argv[])
 {
 printf("程序开始运行\n输入0结束\n");
 mutex = CreateMutex(NULL,false,NULL);
 full = CreateSemaphore(NULL,0,storage,NULL);
 empty = CreateSemaphore(NULL,storage,storage,NULL);
 CreateThread(NULL,0,(LPTHREAD_START_ROUTINE)producerFunction,NULL,0,&producer[0]);
 CreateThread(NULL,0,(LPTHREAD_START_ROUTINE)consumer1Function,NULL,0,&consumer[1]);
 CreateThread(NULL,0,(LPTHREAD_START_ROUTINE)consumer2Function,NULL,0,&consumer[0]);
 while(flag)
 {
 if(getchar())
 {
 flag = false;
 }
 }
 
 system("pause");
 return 0;
 }
 
 
 
 |