






















进程机制与并发程序设计-Linux下C实现(一) 睡觉的理发师问题
实验目的:
理解进程同步概念及实现的方法,去学习如何合理分配资源。
一、问题分析:
理发师问题:
一个理发店由一个有几张椅子的等待室和一个放有一张理发椅的理发室组成。
1. 若没有要理发的顾客,则理发师去睡觉;
2. 若一顾客进入理发店,理发师正在为别人理发,且等待室有空椅子,则该顾客就找张椅子按顺序坐下;
3. 若一顾客进入理发店,理发师在睡觉,则叫醒理发师为该顾客理发;
4. 若一顾客进入理发店且所有椅子都被占用了,则该顾客就离开。
二、伪码实现:
互斥信号量:mutex 用来互斥对临界变量count的访问
计数信号量 customers用来记录等候的顾客数据,barbers用来记录等待的理发师数,这里barbers只有两种取值,要不是0要不是1
临界变量:count由理发师进程和顾客进程共同访问,用来记录在椅子上等着的顾客数
N 椅子数,为最多等候的顾客数
理发师进程
1
Barbers()
2
{
3
While(true)
4
{
5
P(customers)
6
P(mutex)
7
Count--;
8
V(mutex)
9
V(barbers)
10
理发师理发;
11
}
12
}
13
顾客进程
1
Customer()
2
{
3
While(true)
4
{
5
P(mutex);
6
If(count<N)
7
{
8
Count++
9
V(mutex);
10
V(customer)
11
P(barbers);
12
顾客被理发
13
}
14
else
15
V(mutex);
16
}
17
}
18
三 、Linux实现[redhat 9.0]
1
//2007-12-23 10:46:11
2
3
4
#include <stdio.h>
5
#include <stdlib.h>
6
#include <unistd.h>
7
#include <pthread.h>
8
#include <errno.h>
9
#include <sys/ipc.h>
10
#include <semaphore.h>
11
#include <fcntl.h>
12
#define n 5
13
time_t end_time; /*end time*/
14
sem_t mutex,customers,barbers;
15
int count = 0;//等待理发的顾客数
16
void barber(void* arg);
17
void customer(void* arg);
18
19
int main(int argc, char *argv[])
20
{
21
22
pthread_t id1,id2;
23
int ret = 0;
24
end_time = time(NULL)+20;
25
//初使化信号量的个数
26
sem_init(&mutex,0,1);
27
sem_init(&customers,0,0);
28
ret = sem_init(&barbers,0,1);
29
if(0!=ret)
30
perror("sem init.");
31
//初使化两个线程
32
ret = pthread_create(&id1,NULL,(void *)barber,NULL);
33
if(0!=ret)
34
perror("create barbers.");
35
ret = pthread_create(&id2,NULL,(void *)customer,NULL);
36
if(0!=ret)
37
perror("create customers.");
38
//让顾客进程先阻塞
39
pthread_join(id2,NULL);
40
pthread_join(id1,NULL);
41
42
exit(0);
43
}
44
45
/*理发师进程*/
46
void barber(void *arg)
47
{
48
while(time(NULL)<end_time||count>0)
49
{
50
sem_wait(&customers);//p(customers)
51
sem_wait(&mutex);//p(mutex)
52
count--;
53
printf("Barber:cut hair,count is:%d.\n",count);
54
sem_post(&mutex);//v(mutex);
55
sem_post(&barbers);//v(barbers) 通知已进来的,在等理发师的顾客进程
56
sleep(3);
57
}
58
}/*customer*/
59
60
61
/*顾客进程*/
62
void customer(void *arg)
63
{
64
while(time(NULL)<end_time)
65
{
66
sem_wait(&mutex);//p(mutex)
67
if(count<n)
68
{
69
count++;
70
printf("Customer:add count,count is:%d.\n",count);
71
sem_post(&mutex);//v(mutex)
72
sem_post(&customers);//v(customers)
73
sem_wait(&barbers);//p(barbers)
74
}
75
else
76
{
77
//v(mutex) 注意 如果个客户数已满了,则把互斥锁放掉,
78
sem_post(&mutex);
79
}
80
sleep(1);
81
}/*end of while(time()<end_time)*/
82
}/*customer*/
83
下载
五.参考文献
1.<最新UNIX程序设计编程技巧>
2.<嵌入式Linux应用程序开发详解>
此内容由惯性聚合(RSS阅读器)自动聚合整理,仅供阅读参考。 原文来自 — 版权归原作者所有。