生产者-消费者问题1
1.实践内容说明
使用互斥区和事件解决生产者-消费者问题。程序中设置一个生产者,一个消费者,一个缓冲区。
2.程序性质
(1)控制台应用程序
(2)多线程(工程-设置-分类-CodeGeneration-Multithreaded)
3.实现程序
#include <stdio.h>
#include <process.h>
#include <windows.h>
const int END_PRODUCE_NUBER=10;
int g_Buffer;
CRITICAL_SECTION g_cs;
HANDLE g_hEventBufferEmpty,g_hEventBufferFull;
unsigned int __stdcall ProducerThreadFun(PVOID pM)
{
int i;
for(i=1;i<=END_PRODUCE_NUMBER;i++)
{
WaitForSingleObjet(g_hEventBufferEmpty,INFINITE);
EnterCriticalSection(&g_cs);
g_Buffer=i;
printf("生产者将数据%d放入缓冲区\n",i);
LeaveCriticalSection(&g_cs);
SetEvent(g_hEventBufferFull);
}
return 0;
}
unsigned int __stdcall ConsumerThreadFun(PVOID pM)
{
volatile int flag=1;
while(flag)
{
WaitForSingleObjet(g_hEventBufferEmpty,INFINITE);
EnterCriticalSection(&g_cs);
printf("---消费者从缓冲区中取数据%d\n",g_Buffer);
if(g_Buffer==END_PRODUCCE_NUMBER)
flag=0;
LeaveCriticalSection(&g_cs);
SetEvent(g_hEventBufferEmpty);
Sleep(10);
}
return 0;
}
int main()
{
HANDLE hThread[2];
printf("\t生产者消费者问题<一>\n");
InitializeCrititicalSection(&g_cs);
g_hEventBufferEmpty=CreateEvent(NULL,FALSE,TRUE,NULL);
g_hEventBufferFull=CreateEvent(NULL,FALSE,FALSE,NULL);}
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);
CloseHandle(hThread[0]);
CloseHandle(hThread[1]);
CloseHandle(g_hEventBufferEmpty);
CloseHandle(g_hEventBufferFull);
DeleteCriticalSection(&g_cs);
return 0;
}