- 1、本文档共8页,可阅读全部内容。
- 2、原创力文档(book118)网站文档一经付费(服务费),不意味着购买了该文档的版权,仅供个人/单位学习、研究之用,不得用于商业用途,未经授权,严禁复制、发行、汇编、翻译或者网络传播等,侵权必究。
- 3、本站所有内容均由合作方或网友上传,本站不对文档的完整性、权威性及其观点立场正确性做任何保证或承诺!文档内容仅供研究参考,付费前请自行鉴别。如您付费,意味着您自己接受本站规则且自行承担风险,本站不退款、不进行额外附加服务;查看《如何避免下载的几个坑》。如果您已付费下载过本站文档,您可以点击 这里二次下载。
- 4、如文档侵犯商业秘密、侵犯著作权、侵犯人身权等,请点击“版权申诉”(推荐),也可以打举报电话:400-050-0827(电话支持时间:9:00-18:30)。
查看更多
(A4纸或A3纸折叠)#includestdlib.h
#includetime.h
#includewindows.h
#includesys/timeb.h
#includestdio.h
HANDLE hFull;
HANDLE hEmpty;
HANDLE hMutex;
HANDLE hThreadP[50];
HANDLE hThreadC[50];
int iHandle_Count=0;//操作数
int iStore=0;//共享资源数
int iGood_id=0;//货物ID
/*******货物*********/
struct goods
{
int iGood_id;
int iProduct_id;
}goods[100];
/**********生产者和消费者信息*************/
typedef struct
{
int iId;
int iMax_Store;
}threadinfo;
/************运行函数*************/
DWORD WINAPI Producer(LPVOID *INFO)//生产者函数
{
int i;
threadinfo* info=(threadinfo*)INFO;
for(i=0;iinfo-iMax_Store;i++)
{
WaitForSingleObject(hEmpty,INFINITE);
WaitForSingleObject(hMutex,INFINITE);
iHandle_Count++;
iStore++;
iGood_id++;
goods[i].iGood_id=iGood_id;
goods[i].iProduct_id=info-iId;
printf(%d号生产者 生产了%d号产品 目前操作次数:%d 仓库中共享资源数量:%d\n
,goods[i].iProduct_id,goods[i].iGood_id,iHandle_Count,iStore);
ReleaseSemaphore(hFull,1,NULL);
ReleaseMutex(hMutex);
}
}
DWORD WINAPI Consumer(LPVOID *INFO)//消费者函数
{
int i;
threadinfo* info=(threadinfo*)INFO;
for(i=0;iinfo-iMax_Store;i++)
{
WaitForSingleObject(hFull,INFINITE);
WaitForSingleObject(hMutex,INFINITE);
iHandle_Count++;
iStore--;
printf(%d号消费者 消费了%d号产品 目前操作次数:%d 仓库中共享资源数量:%d\n
,info-iId,goods[i].iGood_id,iHandle_Count,iStore);
ReleaseSemaphore(hEmpty,1,NULL);
ReleaseMutex(hMutex);
}
}
void WINAPI run(int iMax_Store, int iProducer_num,int iConsumer_num)
{
threadinfo infoP[50];
threadinfo infoC[50];
int iProducer,iConsumer;
hMutex=CreateMutex(NULL,FALSE,NULL);
hFull=CreateSemaphore(NULL,0,iMax_Store,NULL);
hEmpty=CreateSemaphore(NULL,iMax_Store,iMax_Store,NULL);
WaitForSingleObject(hMutex,INFINITE);
/**********创建消费者和生产者线程**************/
printf(******创建生产者和消费者线程******\n);
for(iProducer=1;iProducer=iProducer_num;iProducer++)
{
infoP[iProducer-1].iId=iProducer;
infoP[iProducer-1].iMax_Store=iMax_Store;
hThreadP[iProducer-1]=CreateThread(NULL,0,(LPTHREAD_START_ROUTINE)Producer,infoP[iProducer-1],0,NULL);//创建生产
文档评论(0)