资源简介
理发师问题:三个理发师,四人沙发,7人的等候室,一个收银机。最多50个客户。字符演示进程执行过程
代码片段和文件信息
// sleeping barber implementation
// UML-CS 91.308 Fall 2005 fredm
// based on solution in Tanenbaum
// this version requires that you compile with “-lm“ flag
// so that trig functions included in normal and bursty work.
//gcc -o barbershop -lpthread -lm barbershop.c
#include
#include
#include
#include
#include
#include
#include
#define CHAIRS 5 /* # chairs for waiting customers */
sem_t customers; /* # of customers waiting for service */
sem_t barbers; /* # of barbers waiting for customers */
pthread_mutex_t mutex; /* for mutual exclusion */
int waiting = 0; /* customers are waiting (not being cut) */
int cust_num = 1; /* count of potential customers */
void barber (void);
void customer (void *num);
void cut_hair(void);
double timediff(struct timeval i struct timeval j);
void seed_random(void);
double flat(void);
double normal(void);
double bursty(void);
int main()
{
int i;
pthread_t barber_t;
pthread_t customer_t;
struct timeval earlier now;
float delay;
seed_random();
// create 1 barber thread
pthread_create(&barber_t NULL (void *)&barber NULL);
// create customers with a delay between each
gettimeofday (&earlier (struct timezone *)0); // capture start time
for (i=0; i<1000; i++) {
pthread_create(&customer_t NULL (void *)&customer (void *)cust_num);
cust_num++;
delay = 0.010; // delay between arriving customers in seconds
while (1) {
// loop until proper amount of real time expires
gettimeofday (&now (struct timezone *)0);
if (timediff(now earlier) >= delay) {
earlier.tv_sec = now.tv_sec;
earlier.tv_usec = now.tv_usec;
break;
}
}
}
// stay alive after this happens for the last few customers to be served
sleep(3);
// this is a place where you can print out the success ratio
}
double timediff(struct timeval now struct timeval earlier) {
if (now.tv_sec == earlier.tv_sec)
return (now.tv_usec - earlier.tv_usec) / 1000000.;
else
return (1000000 * (now.tv_sec - earlier.tv_sec) +
now.tv_usec - earlier.tv_usec) / 1000000.;
}
void barber(void)
{
while (1) {
sem_wait(&customers); /* go to sleep if # of customers is 0 */
pthread_mutex_lock(&mutex); /* acquire access to
- 上一篇:C8051F410官方例程
- 下一篇:组态王中使用IEC104设置
评论
共有 条评论