thread.c
来自「liunx下的shell实现;进程、线程同步的实现;I/O系统调用的比较(mma」· C语言 代码 · 共 83 行
C
83 行
#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 + =
减小字号Ctrl + -
显示快捷键?