用户注册



邮箱:

密码:

用户登录


邮箱:

密码:
记住登录一个月忘记密码?

发表随想


还能输入:200字
云代码 - c代码库

用多线程同步方法解决睡眠理发师问题 - 操作系统课程设计(pv信号量)

2012-09-26 作者: 小蜜锋举报

[c]代码库

#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<pthread.h>
#include<semaphore.h>
#include<fcntl.h>
#include<errno.h>
#define n 5   //有五把椅子

//三个信号量: mutex,customer,barbers
sem_t mutex,customers,barbers;
int waiting=0;  //等待的顾客数量
int chair[5];
void * barber();
void * customer ( void *arg );

int main ( int argc,char *argv[] )
{
	//创建10个顾客和1个理发师
	pthread_t Customer_id[10],Barber_id;
	int i;
	sem_init ( &mutex,0,1 );  //互斥信号量初始化1
	sem_init ( &customers,0,0 );//顾客信号量初始化0
	sem_init ( &barbers,0,1 );//理发师信号量初始化1

	for ( i=0; i<5; i++ )
		pthread_create ( &Barber_id,NULL, ( void* ) barber,NULL );
	for ( i=0; i<10; i++ )
		pthread_create ( &Customer_id[i],NULL, ( void* ) customer, ( void* ) ( i+1 ) );
	for ( i=0; i<10; i++ )
		pthread_join ( Customer_id[i],NULL );
	for ( i=0; i<5; i++ )
		pthread_join ( Barber_id,NULL );
	return 0;
}

//创建理发师线程
void * barber()
{
	int i;
	int next;
	//等待顾客,如果没有顾客,理发师睡觉
	sem_wait ( &customers );
	sem_wait ( &mutex );  //等待互斥锁释放
	waiting--;   //等待的顾客减1
	for ( i=0; i<5; i++ )
	{
		if ( chair[i]!=0 )
		{
			next= chair[i];
			chair[i]=0;
			break;
		}
	}
	printf ( "The barber is cutting %dth customer's hair\n",next );
	sleep ( 3 );
	sem_post ( &mutex );
	sem_post ( &barbers );
}

//创建顾客线程
void * customer ( void *arg )
{
	int i;
	sem_wait ( &mutex ); //等待互斥锁释放
	if ( waiting<n )
	{
		waiting++;  //等待的顾客加1
		for ( i=0; i<5; i++ )
		{
			if ( chair[i]==0 )
			{
				chair[i]= ( int ) arg;
				break;
			}
		}

		printf ( "***************************************************\n" );
		printf ( "Entered:Number %d customer comes,and sits at %d chair \n", ( int ) arg, ( i+1 ) );
		printf ( "There are %d customer on the chair\n",waiting );
		printf ( "The customers' location are:" );
		for ( i=0; i<5; i++ )
			printf ( "%d   ",chair[i] );
		printf ( "\n" );

		sleep ( 1 );
		sem_post ( &mutex ); //释放互斥锁
		sem_post ( &customers );
		sem_wait ( &barbers ); //理发师等待
	}
	else
	{
		printf ( "Number %d comes,there are no chairs,the customer %d is leaving\n", ( int ) arg, ( int ) arg );
		sem_post ( &mutex );
	}
}


网友评论    (发表评论)


发表评论:

评论须知:

  • 1、评论每次加2分,每天上限为30;
  • 2、请文明用语,共同创建干净的技术交流环境;
  • 3、若被发现提交非法信息,评论将会被删除,并且给予扣分处理,严重者给予封号处理;
  • 4、请勿发布广告信息或其他无关评论,否则将会删除评论并扣分,严重者给予封号处理。


扫码下载

加载中,请稍后...

输入口令后可复制整站源码

加载中,请稍后...