操作系统实验三程序
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
#include "stdafx.h"
#include "windows.h"
#include "iostream.h"
const unsigned short SIZE_OF_BUFFER=10;
unsigned short ProductID=0;
unsigned short ConsumeID=0;
unsigned short in =0;
unsigned short out=0;
int Buffer[SIZE_OF_BUFFER];
bool g_continue =true; //stop this thread radomly
HANDLE Mutex;
HANDLE Full;
HANDLE Empty;
DWORD WINAPI Producer(LPVOID);
DWORD WINAPI Consumer(LPVOID);
int main(int argc, char* argv[])
{
Mutex=CreateMutex(NULL,FALSE,NULL);//false is give up quanli
Full=CreateSemaphore(NULL,0,SIZE_OF_BUFFER,NULL);
Empty=CreateSemaphore(NULL,SIZE_OF_BUFFER,SIZE_OF_BUFFER,NULL);
const unsigned short PRODUCERS_COUNT=3;
const unsigned short CONSUMERS_COUNT=3;
const unsigned short THREADS_COUNT= PRODUCERS_COUNT+CONSUMERS_COUNT;
HANDLE Thread[THREADS_COUNT];
for(int i=0;i
Thread[i]=CreateThread(NULL,0,Producer,NULL,0,NULL);
if(Thread[i]==NULL) return -1;
}
for( i=0;i
Thread[PRODUCERS_COUNT+i]=CreateThread(NULL,0,Consumer,NULL,0,NULL);
if(Thread[i]==NULL) return -1;
}
//总控开关
while(g_continue)
{
if(getchar())//control program running
{
g_continue=false;
}
CloseHandle(Mutex);
CloseHandle(Full);
for(i=0;i
CloseHandle(Thread[i]); ///
return 0;
}
}
void Produce()
{
cout<<"procducing "<<++ProductID<
void Append() //缓冲区
{
cout<<"Appending a product ...";
Buffer[in]=ProductID;
in=(in+1)%SIZE_OF_BUFFER;
cout<<"Success\n";
//显示缓冲区
for(int i=0;i
cout<if(i==in) cout<<"<---生产";
if(i==out) cout<<"<---消费";
cout<
}
void take()
{
cout<<"tAKING a product";
ConsumeID=Buffer[out];
Buffer[out]=-1;
out=(out+1)%SIZE_OF_BUFFER;
cout<<"success"<
for(int i=0;i
cout<if(i==in) cout<<"<---生产";
if(i==out) cout<<"<---消费";
cout<
}
void Consume()
{
cout<<"consuming"<
//生产者线程
DWORD WINAPI Producer(LPVOID f)
{
while(g_continue)
{ Produce();
WaitForSingleObject(Empty,INFINITE);
WaitForSingleObject(Mutex,INFINITE);
// Produce();
Append();
Sleep(500);
ReleaseMutex(Mutex);
ReleaseSemaphore(Full,1,NULL);
}
return 0;
}
DWORD WINAPI Consumer(LPVOID)
{
while(g_continue)
{ //Produce();
WaitForSingleObject(Full,INFINITE);
WaitForSingleObject(Mutex,INFINITE);
// Produce();
take();
//Append();
Sleep(1500);
ReleaseMutex(Mutex);
ReleaseSemaphore(Empty,1,NULL);
Consume();
}
return 0;
}