哲學家演算法c 執行緒實現

2021-09-28 20:14:27 字數 1258 閱讀 4618

哲學家演算法c++執行緒實現

呼叫了很多stl函式

標記了注釋

具體實現了五個哲學家就餐的問題 當然 人數可以根據需求改變

#include #include #include "iostream"

using namespace std;

const unsigned int n= 5; //number of phil

const int thinking=1; // 1 means full

const int hungry=2; // 2 means hungry

const int dining=3; // 3 means eating

handle hphilosopher[n];

handle semaphore[n];

handle mutex; //typedef void* handle, output

dword winapi philosopherproc(lpvoid lpparameter) //return dword( api (32_bit

//typedef unsigned long dword

//typedef winapi __stdcall 函式引數入棧方式從右到左,一般匯出函式時用。

//typedef void* lpvoid

else

releasesemaphore(semaphore[leftfork],1,null);

}break;

case dining:

releasesemaphore(semaphore[leftfork],1,null);

releasesemaphore(semaphore[rightfork],1,null);

mystate = thinking;

strcpy(statestr, "thinking");

break;

} waitforsingleobject(mutex, infinite);

cout << "philosopher" << myid << " is: " << statestr << endl;

releasemutex(mutex);

sleep(100); }}

int main()

for (int i = 0; i < n; i++)

sleep(800);

return 0;

}

哲學家多執行緒問題

問題描述 一圓桌前坐著5位哲學家,兩個人中間有乙隻筷子,桌子 有麵條。哲學家思考問題,當餓了的時候拿起左右兩隻筷子吃飯,必須拿到兩隻筷子才能吃飯。上述問題會產生死鎖的情況,當5個哲學家都拿起自己右手邊的筷子,準備拿左手邊的筷子時產生死鎖現象。解決辦法 1 新增乙個服務生,只有當經過服務生同意之後才能...

哲學家問題

問題描述 有五個哲學家繞著圓桌坐,每個哲學家面前有一盤面,兩人之間有一支筷子,這樣每個哲學家左右各有一支筷子。哲學家有2個狀態,思考或者拿起筷子吃飯。如果哲學家拿到乙隻筷子,不能吃飯,直到拿到2只才能吃飯,並且一次只能拿起身邊的一支筷子。一旦拿起便不會放下筷子直到把飯吃完,此時才把這雙筷子放回原處。...

哲學家就餐

include include include include include include 筷子作為mutex pthread mutex t chopstick 6 void eat think void arg int i for pthread mutex lock chopstick r...