【发布时间】:2010-09-17 10:29:39
【问题描述】:
我想实现一个生产者/消费者场景,该场景遵循大致如下的接口:
class Consumer {
private:
vector<char> read(size_t n) {
// If the internal buffer has `n` elements, then dequeue them
// Otherwise wait for more data and try again
}
public:
void run() {
read(10);
read(4839);
// etc
}
void feed(const vector<char> &more) {
// Safely queue the data
// Notify `read` that there is now more data
}
};
在这种情况下,feed 和 run 将在不同的线程上运行,read 应该是阻塞读取(如 recv 和 fread)。显然,我的双端队列需要某种互斥机制,我需要某种通知系统来通知read 重试。
我听说 条件变量 是要走的路,但我所有的多线程经验都依赖于 Windows,我很难完全理解它们。
感谢您的帮助!
(是的,我知道返回向量是低效的。我们不要讨论这个。)
【问题讨论】:
标签: c++ multithreading pthreads producer-consumer