第一范文网 - 专业文章范例文档资料分享平台

系统调用中的信号量PV操作 理发师问题

来源:用户分享 时间:2025/5/31 11:29:29 本文由loading 分享 下载这篇文档手机版
说明:文章内容仅供预览,部分内容可能不全,需要完整文档或者需要复制内容,请下载word后使用。下载word有问题请添加微信号:xxxxxxx或QQ:xxxxxx 处理(尽可能给您提供完整文档),感谢您的支持与谅解。

源程序代码

#include #include #include #include #include #include

#include

#define n 5 //the shop have five chairs

//design three semaphores: mutex,customer,barbers sem_t mutex,customers,barbers;

int waiting=0; //the number of waiting customers int chair[5]; void * barber();

void * customer(void *arg);

int main(int argc,char *argv[]) {

//create 10 semaphores and one Barber semaphore pthread_t Customer_id[10],Barber_id; int i;

sem_init(&mutex,0,1); //init mutex semaphore to 1 sem_init(&customers,0,0);//init semaphore customers to 0 sem_init(&barbers,0,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; }

//creat barber pthread void * barber() {

int i; int next;

//wait(customers),if no customers,barber sleeping sem_wait(&customers);

sem_wait(&mutex); //wait(mutex)

waiting--; //the numer of waiting reduce one for(i=0;i<5;i++) {

if (chair[i]!=0) {

next= chair[i]; chair[i]=0; break; } }

printf(\ sleep(3);

sem_post(&mutex); sem_post(&barbers); }

//creat customer pthread void * customer(void *arg) {

int i;

sem_wait(&mutex); //wait(mutex) if(waiting

waiting++; //the numer of waiting plus one for(i=0;i<5;i++) {

if (chair[i]==0) {

chair[i]=(int)arg; break; } }

printf(\ printf(\%d customer comes,and sits at %d chair \\n\

printf(\ printf(\ for(i=0;i<5;i++)

printf(\ printf(\

系统调用中的信号量PV操作 理发师问题.doc 将本文的Word文档下载到电脑,方便复制、编辑、收藏和打印
本文链接:https://www.diyifanwen.net/c6ulnc9nc7n8jj329nacs_4.html(转载请注明文章来源)
热门推荐
Copyright © 2012-2023 第一范文网 版权所有 免责声明 | 联系我们
声明 :本网站尊重并保护知识产权,根据《信息网络传播权保护条例》,如果我们转载的作品侵犯了您的权利,请在一个月内通知我们,我们会及时删除。
客服QQ:xxxxxx 邮箱:xxxxxx@qq.com
渝ICP备2023013149号
Top