?? 哲學(xué)家問(wèn)題.c
字號(hào):
#include "ourhdr.h"
#include <unistd.h>
#include <sys/stat.h>
int num;
#define N 5
#include <fcntl.h>
#include <sys/types.h>
#define LEFT (i) % num
#define RIGHT (i + 1) % num
#include <sys/types.h>
void down(int);
void up(int);
void initforks();
void put_fork(int);
void take_fork(int);
char **list;
void think(int i)
{
printf("Philosopher %d is thinking\n", i);
sleep(2);
}
void eat(int i)
{ printf("Philosopher %d is eating\n", i);
sleep(2);
}
void take_fork(int i)
{
if(i != 0) {
down(LEFT);
down(RIGHT);
}
else {
down(RIGHT);
down(LEFT);
}
}
void put_fork(int i)
{
if(i != 0) {
up(LEFT);
up(RIGHT);
}
else {
up(RIGHT);
up(LEFT);
}
}
void philosopher(int i)
{
while(1) {
think(i);
take_fork(i);
eat(i);
put_fork(i);
}
}
int num;
main(int argc,char *argv[])
{
int i;
pid_t pid;
if(argc>1)
num=atoi(argv[1]);
else num=N;
initforks();
for(i = 0; i < num; i++) {
if( (pid = fork()) < 0)
err_sys("fork error");
if(pid == 0) {
philosopher(i);
exit(1);
}
}
wait(0);
exit(1);
}
void down(int i)
{
int fd;
while( (fd = open(list[i], O_RDONLY | O_CREAT | O_EXCL, FILE_MODE)) < 0
)
close(fd);
}
void up(int i)
{
unlink(list[i]);
}
void initforks()
{ int i;
list = (char **)malloc(sizeof(char *)*num);
for(i=0;i<num;i++)
{
list[i] = (char *)malloc(sizeof(char *)*num);
list[i][0]='0'+i; list[i][1]=(char)0;
up(i);
}
}
?? 快捷鍵說(shuō)明
復(fù)制代碼
Ctrl + C
搜索代碼
Ctrl + F
全屏模式
F11
切換主題
Ctrl + Shift + D
顯示快捷鍵
?
增大字號(hào)
Ctrl + =
減小字號(hào)
Ctrl + -