/**
作者:wwj
时间:2012/4/12
功能:实现吃水果问题
**题目内容:桌子有一只盘子,只允许放一个水果,父亲专向盘子放苹果,母亲专向盘子放桔子
儿子专等吃盘子的桔子,女儿专等吃盘子的苹果。只要盘子为空,父亲或母亲就可以向盘子放水果,
仅当盘子有自己需要的水果时,儿子和女儿可从盘子取出。请给出四个人之间的同步关系,并用
pv操作实现四个人的正确活动的问题。**
**题目分析:父亲和女儿是相互制约的,父亲进程执行完即往盘中放入苹果后,女儿进程才能执行即吃苹果,是同步关系;
母亲和儿子是相互制约的,母亲进程执行完即往盘中放入桔子,儿子进程才能执行即吃桔子,也是同步关系
而父亲和母亲这两个进程不能同时进行,是互斥关系;**
**/
#include<windows.h>
#include<iostream>
using namespace std;
//声明句柄
HANDLE EmptyPlate;
HANDLE Apple;
HANDLE orange;
HANDLE fatherThread;
HANDLE motherThread;
HANDLE sonThread;
HANDLE daughterThread;
//线程函数声明
DWORD WINAPI father(LPVOID IpParameter);
DWORD WINAPI mother(LPVOID IpParameter);
DWORD WINAPI daughter(LPVOID IpParameter);
DWORD WINAPI son(LPVOID IpParameter);
int main()
{
//创建信号量
EmptyPlate = CreateSemaphore(NULL,1,1,NULL); //盘子
Apple = CreateSemaphore(NULL,0,1,NULL); //苹果
orange = CreateSemaphore(NULL,0,1,NULL); //桔子
//创建线程
fatherThread = CreateThread(NULL,0,father,NULL,0,NULL);
motherThread = CreateThread(NULL,0,mother,NULL,0,NULL);
daughterThread = CreateThread(NULL,0,daughter,NULL,0,NULL);
sonThread = CreateThread(NULL,0,son,NULL,0,NULL);
//等线程的结束
WaitForSingleObject(fatherThread,INFINITE);
WaitForSingleObject(motherThread,INFINITE);
WaitForSingleObject(daughterThread,INFINITE);
WaitForSingleObject(sonThread,INFINITE);
//关闭线程句柄
CloseHandle(fatherThread);
CloseHandle(motherThread);
CloseHandle(daughterThread);
CloseHandle(sonThread);
//关闭信号量句柄
CloseHandle(EmptyPlate);
CloseHandle(Apple);
CloseHandle(orange);
return 0;
}
//父亲线程函数
DWORD WINAPI father(LPVOID IpParameter)
{
for(int i = 0; i < 5; ++i){
WaitForSingleObject(EmptyPlate, INFINITE); // P操作
// 开始临界区
cout << "\nFather往盘中放一个水果\n";
// 结束临界区
ReleaseSemaphore(Apple, 1, NULL); // V操作
}
return 0;
}
//母亲线程函数
DWORD WINAPI mother(LPVOID IpParmeter)
{
for(int i = 0; i < 5; ++i){
WaitForSingleObject(EmptyPlate, INFINITE); // P操作
// 开始临界区
cout << "\nMother往盘中放一个桔子\n";
// 结束临界区
ReleaseSemaphore(orange, 1, NULL); // V操作
}
return 0;
}
//女儿线程函数
DWORD WINAPI daughter(LPVOID IpParameter)
{
while(1)
{
WaitForSingleObject(Apple,INFINITE); //p操作
cout<<"女儿吃苹果"<<endl;
ReleaseSemaphore(EmptyPlate,1,NULL); //v操作
}
return 0;
}
//儿子线程函数
DWORD WINAPI son(LPVOID IpParameter)
{
while(1)
{
WaitForSingleObject(orange,INFINITE); //p操作
cout<<"儿子吃苹果"<<endl;
ReleaseSemaphore(EmptyPlate,1,NULL); //v操作
}
return 0;
}