15,471
社区成员
发帖
与我相关
我的任务
分享
#include <iostream>
#include <cstdio>
#include <process.h>
#include <windows.h>
using namespace std;
HANDLE hMutex1, hMutex2;
class Product
{
public:
int F1 ;
int F2 ;
Product()
{
F1 = 0;
F2 = 0;
hMutex1 = CreateMutex(NULL,FALSE,NULL);
hMutex2 = CreateMutex(NULL,FALSE,NULL); //互斥量生成
start_Threads();
}
friend void produce_A(void* p);
friend void produce_B(void* p);
friend void merge_AB(void* p);
void start_Threads()
{
while(1)
{
_beginthread(produce_A, 0, (void*)this);
_beginthread(produce_B, 0, (void*)this);
_beginthread(merge_AB, 0, (void*)this);
Sleep(1000);
}
}
};
void produce_A(void* p)
{
Product* product = (Product*)p;
//等待获得互斥对象的所有权
WaitForSingleObject(hMutex1,INFINITE);
if(product->F1 < 10)
{
product->F1++;
printf("Part A been produced, now total is %d .\n",product->F1);
}
Sleep(1000);
//释放互斥对象的句柄
ReleaseMutex(hMutex1);
}
void produce_B(void* p)
{
Product* product = (Product*)p;
//等待获得互斥对象的所有权
WaitForSingleObject(hMutex2,INFINITE);
if(product->F2 < 10)
{
product->F2++;
printf("Part B been produced, now total is %d .\n",product->F2);
}
Sleep(2000);
//释放互斥对象的句柄
ReleaseMutex(hMutex2);
}
void merge_AB(void* p)
{
Product* product = (Product*)p;
WaitForSingleObject(hMutex1,INFINITE);
WaitForSingleObject(hMutex2,INFINITE);
if(product->F1 > 0 && product->F2 > 0)
{
product->F1--;
product->F2--;
puts("a Finished Product!\n");
}
Sleep(3000);
ReleaseMutex(hMutex2);
ReleaseMutex(hMutex1);
}
int main()
{
Product p;
system("pause");
return 0;
}