multithread c (2) producer/consumer
2010-04-23 23:31:12| 分类:
默认分类
| 标签:
|举报
|字号大中小 订阅
//typical sample of multithread
//VS2005
#include <windows.h>
#include <process.h>
#include <stdio.h>
enum { BUFFERSIZE = 3 };
int g_buffer[BUFFERSIZE]; //global buffer to simulate a queue
HANDLE g_hMutex;
HANDLE g_hNotFullSemaphore,g_hNotEmptySemaphore;
DWORD WINAPI producer(LPVOID lpParam);
DWORD WINAPI consumer(LPVOID lpParam);
int main()
{
g_hMutex = CreateMutex(NULL,FALSE,NULL);
if(g_hMutex==NULL)
{
printf("failed to create handle mutex\n");
return EXIT_FAILURE;
}
//initial value BUFFERSIZE-1
g_hNotFullSemaphore = CreateSemaphore(NULL,BUFFERSIZE-1,BUFFERSIZE-1,NULL);//signalled
if(g_hNotFullSemaphore==NULL)
{
printf("failed to create full semaphore\n");
return EXIT_FAILURE;
}
//initial value 0
g_hNotEmptySemaphore = CreateSemaphore(NULL,0,BUFFERSIZE-1,NULL);//not signalled
if(g_hNotEmptySemaphore==NULL)
{
printf("failed to create empty semaphore\n");
return EXIT_FAILURE;
}
HANDLE hThread[2];
DWORD dwThreadID;
LPTSTR lpProducerParam("producing product ");
LPTSTR lpConsumerParam("consuming product ");
hThread[0] = CreateThread(
NULL,
0,
producer,
lpProducerParam,
0,
&dwThreadID );
if(hThread[0] == NULL)
{
printf("failed to create producer thread\n");
return EXIT_FAILURE;
}
hThread[1] = CreateThread(
NULL,
0,
consumer,
lpConsumerParam,
0,
&dwThreadID );
if(hThread[1] == NULL)
{
printf("failed to create consumer thread\n");
return EXIT_FAILURE;
}
WaitForMultipleObjects(2,hThread,TRUE,INFINITE);
CloseHandle(hThread[0]);
CloseHandle(hThread[1]);
ReleaseMutex(g_hMutex);
CloseHandle(g_hMutex);
return EXIT_SUCCESS;
}
DWORD WINAPI producer(LPVOID lpParam)
{
int count = 0;
for(int i=10;i>=0;i--)
{
WaitForSingleObject(g_hNotFullSemaphore,INFINITE); // if get ownership of shared source,NotFullsemaphore decreased by 1
WaitForSingleObject(g_hMutex,INFINITE);
g_buffer[count] = i;
count = (count+1)%BUFFERSIZE;
printf("%s:%d\n",(LPTSTR)lpParam,i);
Sleep(100);
ReleaseMutex(g_hMutex);
ReleaseSemaphore(g_hNotEmptySemaphore,1,NULL);//NotEmptySemaphore increased by 1
}
return EXIT_SUCCESS;
}
DWORD WINAPI consumer(LPVOID lpParam)
{
int count = 0;
int result;
while(1)
{
WaitForSingleObject(g_hNotEmptySemaphore,INFINITE);
WaitForSingleObject(g_hMutex,INFINITE);
result = g_buffer[count];
Sleep(80);
printf("%s:%d\n",(LPTSTR)lpParam,result);
if(result ==0)
{
printf("exiting thread...\n");
ExitThread(EXIT_SUCCESS);
}
count =(count+1)%BUFFERSIZE;
ReleaseMutex(g_hMutex);
ReleaseSemaphore(g_hNotFullSemaphore,1,NULL);
}
return EXIT_SUCCESS;
}
评论这张
转发至微博
转发至微博
评论