实验二进程同步实验报告 下载本文

semop(semid,buf,2); }

void philosophere(int no,int semid) { srand(getpid()); for(;;) { #if 0 printf(\ sleep(DELAY); printf(\ wait_for_2chopstick(no,semid); printf(\ sleep(DELAY); free_2chopstick(no,semid); #else int left = no; int right = (no + 1) % 5; printf(\ sleep(DELAY); printf(\ wait_1chopstick(left,semid); sleep(DELAY); wait_1chopstick(right,semid); printf(\ sleep(DELAY); free_1chopstick(left,semid); free_1chopstick(right,semid); #endif } }

int main(int argc,char *argv[]) { int semid; semid = semget(IPC_PRIVATE,5,IPC_CREAT | 0666); if(semid < 0) { ERR_EXIT(\ } union semun su; su.val = 1; int i; for(i = 0;i < 5;++i) { semctl(semid,i,SETVAL,su);

}

}

int num = 0; pid_t pid;

for(i = 1;i < 5;++i) { pid = fork(); if(pid < 0) { ERR_EXIT(\ } if(0 == pid) { num = i; break; } }

philosophere(num,semid); return 0;

五、实验结果