生产者消费者模型 使用信号量和互斥锁能够较好地实现
Semaphore mutex = 1; //缓存区互斥操作的互斥信号量
Semaphore empty = n; //空缓冲区数目
Semaphore full = 0; //满缓冲区数目
item buffer[n];
int in = 0, out = 0;
producer(){//生产者进程
while(1){
produce an item nextp;
P(empty);
P(mutex);//互斥是必须的,特别是如果缓存区是一个链表,更需要互斥,数组作为缓存区还好一点
buffer(in) = nextp;
in = (in + 1) % n;
V(mutex);
V(full);
}
}
Consumer(){//消费者进程
while(1){
P(full);
P(mutex);
nextc = buffer(out);
out = (out + 1) % n;
V(mutex);
V(empty);
consumer the item in nextc;
}
}
另外使用mutex 和waitcondition也可以实现生产者和消费者模型,详见:https://blog.youkuaiyun.com/xiaoyink/article/details/99710637