資源簡介
一個簡單的有關于生產者和消費者問題的實例程序
代碼片段和文件信息
#include?“windows.h“
#include?
#include?
const?unsigned?short?BUFFER_SIZE?=?10;?
short?writer_id?=?0;?
short?reader_id?=?0;?
short?in?=?0;?
short?out?=?0;?
int?buffer[BUFFER_SIZE];?
bool?continu?=?true;?
HANDLE?hmutex;?
HANDLE?hfullsemaphore;?
HANDLE?hemptysemaphore;?
double?eRandom(int?upLimit);
typedef?struct
{ int?data;
}INTEGER;
void?Reader()
{
??reader_id=buffer[out];
??out=(out+1)%BUFFER_SIZE;
}
void?Writer()
{
???buffer[in]=writer_id;
???in=(in+1)%BUFFER_SIZE;
}
DWORD?WINAPI?reader(LPVOID?lppara)
{
while(continu){
WaitForSingleobject(hemptysemaphoreINFINITE);
WaitForSingleobject(hmutexINFINITE);
????if(reader_id==10)
????return?0;
int?tNo=((INTEGER*)lppara)->data;
printf(“第?%d?個讀者讀出?%d?\n“tNo++reader_id);
int?sleepTime=20*(int)eRandom(50+tNo);
Sleep(sleepTime);
??
Reader();
ReleaseMutex(hmutex);
ReleaseSemaphore(hfullsemaphore1NULL);
}
return?0;
}
DWORD?WINAPI?writer(LPVOID?lppara)
{
while(continu){
WaitForSingleobject(hfullsemaphoreINFINITE);???
WaitForSingleobject(hmutexINFINITE);
????????if(writer_id==10)
????????return?0;
???
int?tNo=((INTEGER*)lppara)->data;
printf(“第?%d?個寫入者寫入?%d?\n“tNo++writer_id);
int?sleepTime=10*(int)eRandom(50+tNo);
Sleep(sleepTime);
Writer();
ReleaseMutex(hmutex);
- 上一篇:socket文件傳輸C++
- 下一篇:C語言經典程序設計源代碼之畫圖軟件
評論
共有 條評論