📄 thread.c
字号:
#include <stdio.h>#include <stdlib.h>#include <unistd.h>#include <pthread.h>#include <semaphore.h>#define N 6sem_t t[6];int tindex=0;voidupdate_msg (int index){ int sval; switch (index) { case 0: printf ("I am process p%d\n", index + 1); sem_post (&t[0]); sem_post (&t[0]); break; case 1: sem_wait (&t[0]); printf ("I am process p%d\n", index + 1); sem_post (&t[1]); sem_post (&t[1]); break; case 2: sem_wait (&t[0]); printf ("I am process p%d\n", index + 1); sem_post (&t[2]); break; case 3: sem_wait (&t[1]); printf ("I am process p%d\n", index + 1); sem_post (&t[3]); break; case 4: sem_wait (&t[1]); sem_wait (&t[2]); printf ("I am process p%d\n", index + 1); sem_post (&t[4]); break; case 5: sem_wait (&t[3]); sem_wait (&t[4]); printf ("I am process p%d\n", index + 1); break; default: break; }}void *printmsg (void* data){ int index=*((int*)data); int i; long j; for(i=0;i<3;i++) { update_msg (index); for(j=0;j<1000000;j++); }}intmain (int argc, char *argv[]){ int i; int num[N]; pthread_t thres[N]; for (i = 0; i < N; i++) { sem_init (&t[i], 0, 0); num[i]=i; } for (i = 0; i < N; i++) pthread_create (&thres[i], NULL,printmsg,(void *)&num[i]); for (i = 0; i < N; i++) pthread_join(thres[i],NULL); printf ("main: we're done\n"); return 0;}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -