📄 philosphi.cpp
字号:
#include <windows.h>
#include<iostream.h>
#include <stdlib.h>
#define N 5 /* 哲学家的个数 */
#define P(S) WaitForSingleObject(S, INFINITE) // 定义Windows下的P操作
#define V(S) ReleaseSemaphore(S, 1, NULL) // 定义Windows下的V操作
typedef HANDLE Semaphore; // 信号量的Windows原型
HANDLE hThread[N]; // 线程计数
Semaphore S[N]; // N根筷子, N个信号量
// 对每个哲学家的线程
DWORD WINAPI Philosopher(LPVOID para)
{
// i表示第i个哲学家
int i = *(int *)para, j;
int period = 100;
// j只是用来打印缩进用
char s[10] = "";
for (j=0; j<i; j++) strcat(s, "\t\t");
//Sleep((N-i)*100);
while ( 1 )
{
Sleep(rand()%1000);
cout<<s<<"00"<<i<<" think ..."<<endl;
Sleep(1*period);
cout<<s<<"00"<<i<<" Hungry"<<endl;
Sleep(1*period);
cout<<s<<"00"<<i<<" Get"<<i<<" ..."<<endl;
P(S[i]);
Sleep(3*period);
cout<<s<<"00"<<i<<" Got"<<i<<" OK"<<endl;
cout<<s<<"00"<<i<<" Get"<<(i+1)%N<<" ..."<<endl;
P(S[(i+1)%N]);
cout<<s<<"00"<<i<<" Got"<<(i+1)%N<<" OK"<<endl;
cout<<s<<"00"<<i<<" Eating ..."<<endl;
Sleep(2*period);
cout<<s<<"00"<<i<<" Eaten."<<endl;
cout<<s<<"00"<<i<<" Put down"<<i<<endl;
V(S[i]);
cout<<s<<"00"<<i<<" Put down"<<(i+1)%N<<endl;
V(S[(i+1)%N]);
cout<<endl;
}
return 0;
}
int main(int argc, char *argv[])
{
DWORD tid;
int i=0;
char sTmp[32];
// 初始化信号量
for (i=0; i<N; i++)
{
wsprintf(sTmp, "chopsticks=%d", i);
S[i] = CreateSemaphore(NULL, 1, 1, sTmp);
if ( !S[i] )
{
cout<<" Create S Error!"<<endl;
return -1;
}
}
// 开启5个哲学家线程
for (i=0; i<N; i++)
{
hThread[i] = CreateThread(NULL, 0, Philosopher, &i, 0, &tid);
if ( hThread[i] ) WaitForSingleObject(hThread[i], 10);
}
// 等待哲学家执行
WaitForMultipleObjects(N, hThread, TRUE, INFINITE);
return 0;
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -