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;}
- linux多线程【4】哲学家用餐-sem_t
- Linux 多线程同步之哲学家用餐问题
- linux多线程【3】哲学家用餐-mutex实现
- linux多线程【5】哲学家用餐-另一种思路
- Linux 多线程同步之哲学家用餐问题
- Linux 多线程同步之哲学家用餐问题
- Linux 多线程同步之哲学家用餐问题分析
- 哲学家用餐模型分析
- 哲学家用餐模型分析
- 哲学家用餐问题(Java)
- linux多线程-哲学家就餐问题
- java 线程 死锁(哲学家用餐案例讲解) -------thinking java 4
- linux下 多线程编程 哲学家就餐问题
- Linux信号量 sem_t简介
- Linux信号量 sem_t简介
- Linux信号量 sem_t简介
- Linux信号量 sem_t简介
- Linux信号量 sem_t简介
- CentOS上安装rlwrap, 给Oracle sqlplus添加上下键功能
- 2013第十一周上机任务【项目2 三角形类 直线类】
- meteor 渲染template实例
- HTTP协议详解
- [你必须知道的异步编程]——异步编程模型(APM)
- linux多线程【4】哲学家用餐-sem_t
- IOS push
- WinCE6.0 BootloaderMain源码分析之OEMDebugInit
- JBoss7 入门指南
- 单片机中断
- Tor源码分析六 -- 总体框架图
- hdu 1556
- 解决无法访问远程MySQL
- hdu2036