是否可以仅使用互斥量而不使用条件变量来实现生产者使用者?

问题描述 投票:0回答:1

我想知道是否有任何方法可以在c中使用phtreads来实现生产者使用者,仅使用pthread_mutex变量来控制对必须具有有限大小N的缓冲区的访问,不允许使用phtread_cond变量。

c pthreads mutex producer-consumer
1个回答
0
投票
我想知道是否有实现生产者消费者的方法

当然,它不会高​​效或特别快。

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 } }

上面的伪代码还有其他效率低下的问题:produceconsume都在锁内运行,这通常是次优的。剩下的解决方法是留给读者练习。
© www.soinside.com 2019 - 2024. All rights reserved.