linux理发师多线程问题
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
用多线程同步方法解决睡眠理发师问题(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
#include
#include
#include
#include
#include
#include
#include
#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 || count>0)
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;i<5;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)
perror("create customers");
ret = pthread_create(&id5, NULL, (void*)customer, "id5");
if(0!=ret)
perror("create custmers");
ret = pthread_create(&id6, NULL, (void*)customer, "id6"); if (0!= ret)
perror("create customers");
ret = pthread_create ( &id7,NULL,(void*)customer, "id7"); if (0!= ret)
perror("create customers");
ret = pthread_create(&id8, NULL, (void*)customer, "id8"); if (0!=ret)
perror("create customers");
ret = pthread_create(&id9, NULL, (void*)customer, "id9"); if (0!=ret)
perror("create customers");
ret = pthread_create(&id10, NULL, (void*)customer, "id10"); if (0!=ret)
perror("create customers");
pthread_join(id1, NULL);
pthread_join(id2, NULL);
pthread_join(id3, NULL);
pthread_join(id4, NULL);
pthread_join(id5, NULL);
pthread_join(id6, NULL);
pthread_join(id7, NULL);