完整代码实现:

#include <stdio.h>
#include <unistd.h>
#include <time.h>
#include <stdlib.h>
#include <pthread.h>
#include <semaphore.h>
#define CUSTOMER_NUMBER 20
void *customer(void *param);
void *barber(void *param); int seat_num = 5;
int interval[CUSTOMER_NUMBER] = {100, 100, 200, 100, 250, 400, 200, 100, 200, 700, 100, 200, 600, 100, 250, 400, 200, 100, 200, 700}; sem_t cust_ready;
sem_t barber_ready;
sem_t mutex; int main(int argc, char *argv[]) {
pthread_t barberid;
pthread_t clientids[CUSTOMER_NUMBER];
sem_init(&mutex,0,1);
sem_init(&barber_ready,0,0);
sem_init(&cust_ready,0,0);
pthread_create(&barberid, NULL, barber, NULL);
for (int i = 0; i < CUSTOMER_NUMBER; i++){
usleep(interval[i]*1000);
time_t t = time(NULL);
struct tm tm = *localtime(&t);
pthread_create(&clientids[i], NULL, customer, NULL);
printf("%d:%d:%d: One customer comes, now there are %d seats left now\n", tm.tm_hour, tm.tm_min, tm.tm_sec, seat_num);
}
} void *barber(void *param) {
int worktime = 500;
while(1) {
sem_wait(&cust_ready);
sem_wait(&mutex);
seat_num += 1;
time_t t = time(NULL);
struct tm tm = *localtime(&t);
printf("%d:%d:%d: Barber works, there are %d seats left now\n", tm.tm_hour, tm.tm_min, tm.tm_sec, seat_num);
usleep(worktime*1000);
t = time(NULL);
tm = *localtime(&t);
printf("%d:%d:%d: Barber has cut hair, there are %d seats left now\n", tm.tm_hour, tm.tm_min, tm.tm_sec, seat_num);
sem_post(&barber_ready);
sem_post(&mutex);
}
} void *customer(void *param) {
sem_wait(&mutex);
if(seat_num > 0){
seat_num --;
time_t t = time(NULL);
struct tm tm = *localtime(&t);
printf("%d:%d:%d: One customer comes, now there are %d seats left now\n", tm.tm_hour, tm.tm_min, tm.tm_sec, seat_num);
sem_post(&cust_ready);
sem_post(&mutex);
sem_wait(&barber_ready);
t = time(NULL);
tm = *localtime(&t);
printf("%d:%d:%d: One customer leaves with haircut, now there are %d seats left now\n", tm.tm_hour, tm.tm_min, tm.tm_sec, seat_num);
} else {
time_t t = time(NULL);
struct tm tm = *localtime(&t);
printf("%d:%d:%d: One customer leaves with no haircut\n", tm.tm_hour, tm.tm_min, tm.tm_sec);
sem_post(&mutex);
}
}

最新文章

  1. NGUI裁剪模型和粒子
  2. Mac Android开发环境变量的配置(java、sdk、ndk、gradle)
  3. MongoDB学习笔记~关于官方驱动集成IQueryable之后的一些事
  4. 使用jQuery+PHP+Mysql实现抽奖程序
  5. jquery- pagination使用
  6. socket.io稳定性及事件测试
  7. 第六篇 SQL Server安全执行上下文和代码签名
  8. Java 正则表达式 向前、向后匹配
  9. C#利用最新版的WPS实现导入导出
  10. 解读MMS(Microsoft Media Server)协议
  11. cocos2d-x 音乐播放猜想
  12. 1秒破解 js packer 加密
  13. Flask 框架 简介
  14. Vue框架axios请求(类似于ajax请求)
  15. maven的配置-2019-4-13
  16. Jmeter性能测试之关联(三)
  17. 基于 Confluence 6 数据中心的 SAML 单点登录设置 SSL/TLS
  18. 解决Linux文件系统变成只读的方法
  19. 『TensorFlow』0.x_&amp;_1.x版本框架改动汇总
  20. java多线程系列13 设计模式 Future 模式

热门文章

  1. 最近有安装了一次hadoop集群,NameNode启动失败,及原因
  2. STL——容器(Set &amp; multiset)的迭代器
  3. Day11 python高级特性-- 迭代器 Iterator
  4. python 全局变量与局部变量 垃圾回收机制
  5. Java基础语法吐血整理
  6. css进阶 04-如何让一个元素水平垂直居中?
  7. Redis 基础知识点总结
  8. BERT 论文阅读笔记
  9. 类似818tu.c微信小说分销系统设计之多公众号网页授权自动登录源码分享
  10. Dubbo服务暴露源码解析②