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

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 10

int cholk[N];
sem_t st[N];


void *func(void *);

int main()
{
	pthread_t person[N];
	int i;

	//init thread
	for(i=0;i<N;i++)
	{
		sem_init(st+i,0,1);
	}

	// create N threads
	for(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 terminal
	for(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 fails
				break;
			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;


}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值