线程同步问题
#include <stdio.h>#include <process.h>
#include <windows.h>
#include <stdlib.h>
const int END_PRODUCE_NUMBER = 10;
int integer;
CRITICAL_SECTION g_cs;//互斥信号量
HANDLE g_hSemaphoreBufferEmpty, g_hSemaphoreBufferFull;
unsigned int __stdcall ProducerThreadFun(PVOID pM)
{
while(true)
{
printf("\n---------------正在向陛下申请生产资源");
WaitForSingleObject(g_hSemaphoreBufferEmpty, INFINITE);
EnterCriticalSection(&g_cs);
integer+=1;
printf("\n禀告陛下,臣已经生产完成一件产品,现在仓库还有%d件产品。",integer);
LeaveCriticalSection(&g_cs);
ReleaseSemaphore(g_hSemaphoreBufferFull, 1, NULL);
if(getchar()!='\n')
break;
}
printf("\n陛下,生产大臣已经超额完成任务,英勇牺牲。");
return 0;
}
unsigned int __stdcall ConsumerThreadFun(PVOID pM)
{
while(true)
{
printf("\n---------------贪官正在向陛下申请消费资源");
WaitForSingleObject(g_hSemaphoreBufferFull, INFINITE);
EnterCriticalSection(&g_cs);
integer-=1;
printf("\n %d禀告陛下,臣发现丢失一件产品,现在仓库还有%d件产品。",GetCurrentThreadId(),integer);
ReleaseSemaphore(g_hSemaphoreBufferEmpty, 1, NULL);
LeaveCriticalSection(&g_cs);
if(getchar()!='\n')
break;
}
printf("\n陛下,大臣家中发现大量财物,判断为贪官。");
return 0;
}
int main()
{
printf(" 生产者消费者问题 1生产者 2消费者 4缓冲区\n");
//InitializeCriticalSection(&g_cs);
InitializeCriticalSection(&g_cs);
g_hSemaphoreBufferEmpty = CreateSemaphore(NULL, 1, 1, NULL);
g_hSemaphoreBufferFull = CreateSemaphore(NULL, 0, 1, NULL);
integer=0;
HANDLE hThread[1];
hThread[0] = (HANDLE)_beginthreadex(NULL, 0, ProducerThreadFun, NULL, 0, NULL);
hThread[1] = (HANDLE)_beginthreadex(NULL, 0, ConsumerThreadFun, NULL, 0, NULL);
WaitForMultipleObjects(2, hThread, TRUE, INFINITE);
for (int i = 0; i <2; i++)
CloseHandle(hThread[i]);
CloseHandle(g_hSemaphoreBufferEmpty);
CloseHandle(g_hSemaphoreBufferFull);
DeleteCriticalSection(&g_cs);
system("pause");
return 0;
}
锁进程时候出现问题