📄 3b.c
字号:
#include<stdio.h>#include<pthread.h>#include<unistd.h>#include<semaphore.h>#include<stdlib.h>#include<string.h>#include<sys/sem.h>int num=0;int flag=0;sem_t sem[9];void *thread_function(void *arg){ int i; i=num; sem_post(sem+8); if(i==0) { while(1) {sem_wait(sem); printf("\nI am thread p%d\n",i+1); sem_post(sem+1); sem_post(sem+2); } return NULL; } if(i==1) { while(1) { flag++; if(flag%2==0) sleep(1); sem_wait(sem+1); printf("I am thread p%d\n",i+1); sem_post(sem+3); sem_post(sem+4); } return NULL; } if(i==2) { while(1) { sem_wait(sem+2); printf("I am thread p%d\n",i+1); sem_post(sem+5); } return NULL; } if(i==3) { while(1) { sem_wait(sem+3); printf("I am thread p%d\n",i+1); sem_post(sem+6); } return NULL; } if(i==4) { while(1) { sem_wait(sem+4); sem_wait(sem+5); printf("I am thread p%d\n",i+1); sem_post(sem+7); } return NULL; } if(i==5) { while(1) { sem_wait(sem+6); sem_wait(sem+7); printf("I am thread p%d\n",i+1); sem_post(sem); } return NULL; }}int main(){ int i,j; pthread_t mythread[6]; for(i=0;i<9;i++) sem_init(&sem[i],0,0); sem_init(&sem[0],0,1); for(num=0;num<6;num++) { pthread_create(&mythread[num],NULL,thread_function,NULL); sem_wait(sem+8); } getchar(); for(i=0;i<6;i++) sem_destroy(&sem[i]); return 1; }
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -