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