-
大小: 6KB文件類型: .rar金幣: 2下載: 0 次發(fā)布日期: 2021-06-11
- 語言: 其他
- 標(biāo)簽:
資源簡介
哲學(xué)家吃飯問題(vc代碼)
哲學(xué)家吃飯問題(vc代碼)
哲學(xué)家吃飯問題(vc代碼)
哲學(xué)家吃飯問題(vc代碼)
哲學(xué)家吃飯問題(vc代碼)

代碼片段和文件信息
#include?“windows.h“
#include?“stdlib.h“
#include?“stdio.h“
#include?“iostream.h“
#include?“process.h“
const?int?PHILOSOPHERS?=?5;//哲學(xué)家人數(shù)
const?int?TIME_EATING?=?50;//吃飯需要的時間?毫秒
HANDLE?event[PHILOSOPHERS];//主線程同工作線程保持同步的句柄數(shù)組
HANDLE?mutex[PHILOSOPHERS];//mutex數(shù)組,這里相當(dāng)于公共資源筷子
CRITICAL_SECTION?cs;?//控制打印的臨界區(qū)變量
UINT?WINAPI?ThreadFunc(void*?arg)
{
????int?num?=?(int)arg;
????
????DWORD?ret?=?0;
????while?(1)
????{
????????ret?=?WaitForMultipleobjects(2mutexTRUE1000);
????????if?(ret?==?WAIT_TIMEOUT)
????????{
????????????Sleep(100);
????????????continue;
????????}
????????EnterCriticalSection(&cs);
cout?<“philosopher?“?<????????LeaveCriticalSection(&cs);
????????Sleep(TIME_EATING);
????????break;
????}
????//設(shè)置時間為有信號
????SetEvent(event[num]);
????return?1;
}
int?main(int?argc?char*?argv[])
{
HANDLE?hThread;
InitializeCriticalSection(&cs);
//循環(huán)建立線程
for?(int?i?=?0;?i? {
mutex[i]?=?CreateMutex(NULL?FALSE““);//INFINITE
event[i]?=?CreateEvent(NULL?TRUE?FALSE““);
hThread?=?(HANDLE)_beginthreadex(NULL0ThreadFunc(void*)i0NULL);
if?(hThread?==?0)
{
cout?<“create?thread?“?< DeleteCriticalSection(&cs);
return?-1;
}
CloseHandle(hThread);
}
//等待所有的哲學(xué)家吃飯結(jié)束
DWORD?ret?=?WaitForMultipleobjects(PHILOSOPHERSeventTRUE?INFINITE);
if?(ret?==?WAIT_object_0)
{
cout?<“all?the?philosophers?had?a?dinner!“?< }
else
{
cout?<“WaitForMultipleobjects?failed?with?code:?“?< }
DeleteCriticalSection(&cs);
for?(int?j?=?0;?j? {
CloseHandle(mutex[j]);
}
return?1;
}
?屬性????????????大小?????日期????時間???名稱
-----------?---------??----------?-----??----
?????文件???????1827??2008-09-27?18:38??03\03.cpp
?????文件???????4273??2008-09-27?18:40??03\03.dsp
?????文件????????527??2008-09-27?17:30??03\03.dsw
?????文件??????41984??2008-09-28?09:34??03\03.ncb
?????文件??????54784??2008-09-28?09:34??03\03.opt
?????文件????????238??2008-09-28?09:16??03\03.plg
?????目錄??????????0??2008-09-28?09:35??03
-----------?---------??----------?-----??----
???????????????103633????????????????????7
評論
共有 條評論