文档详情

linux理发师多线程问题.doc

发布:2017-12-09约3.01千字共5页下载文档
文本预览下载声明
用多线程同步方法解决睡眠理发师问题( 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
显示全部
相似文档