- 6
- 0
- 约3.01千字
- 约 5页
- 2017-12-11 发布于河南
- 举报
linux理发师多线程问题
用多线程同步方法解决睡眠理发师问题( Sleeping-Barber Problem)
1 . 操作系统: Linux
2 . 程序设计语言:C语言
3 . 设有1个理发师5把椅子(另外还有一把理发椅),几把椅子可用连续存储
单元.
1.技术要求:
1)为每个理发师/顾客产生一个线程,设计正确的同步算法
2)每个顾客进入理发室后,即时显示“ Entered” 及其线程自定义标识,还
同时显示理发室共有几名顾客及其所坐的位置。
3)至少有10 个顾客,每人理发至少3秒钟。
4)多个顾客须共享操作函数代码。
提示:
(1) 连续存储区可用数组实现。
(2) 编译命令可用: gcc -lpthread -o 目标文件名 源文件名
(3) 多线程编程方法参见附件。)
详细代码
#include stdio.h
#include stdlib.h
#include unistd.h
#include errno.h
#include pthread.h
#include sys/ipc.h
#include semaphore.h
#include fcntl.h
#define n 5
time_t end_time;
sem_t mutex, customers, barbers;
int count = 0;
int chair [5] = {-1, -1, -1, -1, -1 };
void barber(void *arg)
{
while (time (NULL) end_time || count0)
while (count 0)
{
sem_wait(customers);
sem_wait(mutex);
count--;
printf (the barber is cutting hair, count is : %d\n, count);
sem_post(mutex);
sem_post(barbers);
sleep(3);
}
}
void customer (void *arg)
{
int i ,id= 0, num=0;
while (time (NULL) end_time)
{
sem_wait(mutex);
if (count n)
{
count++;
num= count % 5;
num++;
printf(customer entered:the customer %s comes in and sits at %d the chair count is:
%d\n, (char *)arg, num, count);
sem_post(mutex);
sem_post(customers);
sem_wait(barbers);
}
else
{
sem_post(mutex);
}
sleep(2);
}
}
int main (int argc, char *argv[])
{
pthread_t id1, id2, id3, id4, id5, id6, id7, id8, id9, id10, id11;
int ret= 0;
int i;
end_time = time (NULL) + 30;
sem_init (mutex, 0, 1);
ret = sem_init (barbers, 0, 1);
for (i =0;i5;i++)
{
chair [i] = -1;
}
if (0!= ret)
perror(sem init);
ret= pthread_create (id11, NULL, (void*)barber,id11);
if (0!= ret)
perror(create barber);
ret = pthread_create ( id1,NULL,(void*)customer, id1);
if (0!= ret)
perror(create customers);
ret = pthread_create(id2, NULL, (void*)customer, id2);
if (0!=ret)
perror(create customers);
ret = pthread_create(id3, NULL, (void*)customer, id3);
if (0!=ret)
perror(create customers);
ret = pthread_create(id4, NULL, (void*)customer, id4);
if (0!=ret)
p
您可能关注的文档
- 高中英语选修六词汇练习(附答案).doc
- 工商导论翻译题.doc
- 人民网刊例-常规广告2011.doc
- 雅思4篇小作文.docx
- 新浪博客代码大全.doc
- 阿里旺铺装修与营销.docx
- cisco路由器的IOS常用命令的配置.doc
- 4a公司常用单词.docx
- 英语四级模拟测试题(一).doc
- B3英语答案与解析.doc
- 广东省广州省实验中学教育集团2025-2026学年八年级上学期期中考试物理试题(解析版).docx
- 广东省广州大学附属中学2025-2026学年八年级上学期奥班期中物理试题(解析版).docx
- 广东省广州市第八十六中学2025-2026学年八年级上学期期中物理试题(含答案).docx
- 广东省广州市第八十九中学2025-2026学年八年级上学期期中考试物理试题(解析版).docx
- 广东省广州市第二中学2025-2026学年八年级上学期期中考试物理试题(含答案).docx
- 广东省广州市第八十六中学2025-2026学年八年级上学期期中物理试题(解析版).docx
- 广东省广州市第八十九中学2025-2026学年八年级上学期期中考试物理试题(含答案).docx
- 广东省广州市第二中学2025-2026学年八年级上学期期中考试物理试题(解析版).docx
- 2026《中国人寿上海分公司营销员培训体系优化研究》18000字.docx
- 《生物探究性实验教学》中小学教师资格模拟试题.docx
原创力文档

文档评论(0)