4.信号量
什么是信号量
//消费
void P(sem_t *sem) { // wait
wait_until(sem->count > 0) {
sem->count--;
}
}
//生产
void V(sem_t *sem) { // post (signal)
sem->count++;
}理解1
理解2
信号量实现生产者-消费者
信号量的应用
哲学家吃饭问题
最后更新于
#define YES 1
#define NO 0
void lock() {
wait_until(count == YES) {
count = NO;
}
}
void unlock() {
count = YES;
}PV 是荷兰语。#include "thread.h"
#include "thread-sync.h"
sem_t fill, empty;
void Tproduce() {
while (1) {
P(&empty);
printf("(");
V(&fill);
}
}
void Tconsume() {
while (1) {
P(&fill);
printf(")");
V(&empty);
}
}
int main(int argc, char *argv[]) {
assert(argc == 2);
SEM_INIT(&fill, 0);
SEM_INIT(&empty, atoi(argv[1]));
for (int i = 0; i < 8; i++) {
create(Tproduce);
create(Tconsume);
}
}empty->val = 3;
fill-val = 0;