linux多线程【4】哲学家用餐-sem_t

来源:互联网 发布:网络诊断错误代码-7 编辑:程序博客网 时间:2024/04/28 15:37

ref:

http://blog.csdn.net/acceptedxukai/article/details/8307247


sem_t信号量,如果信号量取值为1,那么只能有01两种状态,那么不就跟mutex差不多吗。

sem_wait和sem_trywait加锁。

sem_post解锁。

注意初始化的时候:sem_init(&st,0,1);中间的参数如果不是0,表示允许进程间共享,否则只能在当前进程内部使用。但是linux规定不能出当前进程,所以那个参数只能写0了。

原理跟上一篇差不多。

#include <semaphore.h>#include <stdio.h>#include<errno.h>#define N 5#define M 10int cholk[N];sem_t st[N];void *func(void *);int main(){pthread_t person[N];int i;//init threadfor(i=0;i<N;i++){sem_init(st+i,0,1);}// create N threadsfor(i=0;i<N; i++){if(pthread_create(person+i, NULL, func, (void*)i)!=0 ){fprintf(stderr, "create error\n");exit(2);}}//wait for thread terminalfor(i=0;i<N;i++){pthread_join(*(person+i), NULL);}       for(i=0;i<N;i++)sem_destroy(st+i); return 0;}void *func(void *p){while(1){int i=(int)p;int j=M;while(0 != sem_trywait(st+i) ){usleep(rand()%100);} // lock the left one!//pthread_mutex_lock(st+i);while(j){if(0==sem_trywait (st +(i+1)%N  ) )  // try to lock the right one, terminal after M times failsbreak;j--;}if(j==0) // fail,release the left one{sem_post(st+i);continue;}cholk[i]=i;cholk[(i+1)%N]=i;//usleep(100); printf("The %d th person have dinner! %d,%d  %s\n", i, cholk[i], cholk[(i+1)%N],                     (cholk[i]==cholk[(i+1)%N] && cholk[i]==i) ? "right":"wrong" );// after eat dinner, release both;sem_post(st+i);sem_post(st+(i+1)%N);usleep(100);}return NULL;}


原创粉丝点击