我想知道是否有任何方法可以在c中使用phtreads来实现生产者使用者,仅使用pthread_mutex
变量来控制对必须具有有限大小N的缓冲区的访问,不允许使用phtread_cond
变量。
我想知道是否有实现生产者消费者的方法
当然,它不会高效或特别快。
void producer()
{
while (1) {
lock();
while (q_has_space()) produce_one_item();
unlock();
sleep(); // The longer you sleep, the less CPU you burn, but the longer the
// delay between consumer freeing up space and producer putting more
// items in the queue.
}
}
void consumer()
{
while (1) {
lock();
while (q_has_items()) consume_one_item();
unlock();
sleep(); // Same considerations as in producer
}
}
上面的伪代码还有其他效率低下的问题:produce
和consume
都在锁内运行,这通常是次优的。剩下的解决方法是留给读者练习。