• 大小: 3KB
    文件类型: .cpp
    金币: 1
    下载: 0 次
    发布日期: 2021-06-09
  • 语言: C/C++
  • 标签: 进程  同步  互斥  

资源简介

一个简单的有关于生产者和消费者问题的实例程序

资源截图

代码片段和文件信息

#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);

评论

共有 条评论