吃苹果问题
首先,父亲放一个苹果在盘,儿子马上取苹果这件事与父亲放一个香蕉,女儿马上取之这件事是互斥的。即在程序中体现在:当父亲每次放水果之后马上唤醒儿子或女儿来取,当一个孩子还没有拿到水果之前,父亲不允许放水果,另外一个孩子也不许来破坏。我们用“临界区”区实现:
父亲函数:
………
进入临界区
放苹果或香蕉
………
儿子或女儿函数:
………
取苹果或香蕉
退出临界区
………..
另外,儿子和女儿在默默等待,只要父亲放了水果他们就拿。程序中表现在:儿女见到盘子没有水果,就被阻塞,父亲每次放水果后唤醒阻塞的孩子函数。我们分别用信息量Apple_和Banana_来作为父亲唤醒儿女和儿女等待的途径。
其中用到的API函数(注意,其具体参数和返回值请参考 VC6.0的 MSDM):
1) WaitForMultipleObjects:等待所有对象的完成,可用于最后主函数的延迟
还可以使用Sleep()让主线程睡觉
2 ) InitializeCriticalSection:给临界区初始化
EnterCriticalSection :进入临界区
LeaveCriticalSection :退出临界区
3) CreateSemaphore:产生信号量
OpenSemaphore:开始用信号量
WaitForSingleObject:用于信号量的 P原语
ReleaseSemaphore:用于信号量的 V原语
4) CreateThread:产生线程
#include<windows.h>
#include<iostream.h>
#include<time.h>
static int k=0; //for father to list the order of throwing fruit
CRITICAL_SECTION mmutex; //用于互斥的临界区
HANDLE Apple_,Banana_;
DWORD WINAPI Son(LPVOID n)
{
int i = 1;
while (1)
{
::WaitForSingleObject(Apple_,INFINITE);// 等苹果
cout<<"Son eats "<<i<<" apples"<<endl;
LeaveCriticalSection(&mmutex);
i++;
}
::CloseHandle(Apple_);
return 0;
}
DWORD WINAPI Daughter(LPVOID n)
{
int i = 1;
while (1)
{
::WaitForSingleObject(Banana_,INFINITE);// 等香蕉
cout<<"Daughter eats "<<i<<" bananas"<<endl;
LeaveCriticalSection(&mmutex);
i++;
}
::CloseHandle(Banana_);
return 0;
}
DWORD WINAPI Father(LPVOID n)
{
UINT fruit;
EnterCriticalSection(&mmutex);
fruit = rand()%2;
if (fruit == 0)
{
// 盘中放入苹果
cout<<k+1<<" father produce an apple"<<endl;
k=k+1;
::ReleaseSemaphore(Apple_,1,NULL);
}
else {// 盘中放入香蕉
cout<<k+1<<" father produce a banana"<<endl;
k=k+1;
::ReleaseSemaphore(Banana_,1,NULL);
}
return 0;
}
int main()
{
int j;
k=0;
HANDLE Father_[20];
Apple_ = ::CreateSemaphore(NULL,0,1,"apple");
Banana_ =::CreateSemaphore(NULL,0,1,"banana");
InitializeCriticalSection(&mmutex);
srand(time(NULL));
for (j= 0 ; j < 20; j++)
{
Father_[j]=::CreateThread(NULL,0,Father,NULL,0,0);
}
::CreateThread(NULL,0,Son,NULL,0,0);
::CreateThread(NULL,0,Daughter,NULL,0,0);
// Sleep(1000);
WaitForMultipleObjects(20,Father_,TRUE,INFINITE);
return 0;
}