【发布时间】:2014-10-29 10:49:16
【问题描述】:
我无法适应线程编程。我试图用互斥锁和锁构建一个结构。但我需要以两个锁作为参数的 boost::condition_variable::wait 。但是没有两个锁的等待功能。
有没有人给我提示,或者我的方法完全错误?
我的目标是
- 允许同时 add(),将所有内容写入缓冲区
- 工作线程 operator()(),存储缓冲值
- 还有一个search(),在搜索之前等待工作线程
class Archive
{
vector externalBuffer;
vector swapBuffer;
vector internalBuffer;
boost::mutex externalBufferMutex;
boost::mutex allBufferMutex;
boost::condition_variable bufferIsFilledConditionVariable;
void operator () ()
{
unique_lock allBufferLock(allBufferMutex);
while(true)
{
{
unique_lock lock(externalBufferMutex);
while(buffer.empty())
{
bufferIsFilledConditionVariable.wait(...); // I should call it with two locks?
}
externalBuffer.swap(swapBuffer);
}
{
internalBuffer.swap(swapBuffer);
// store values from internalBuffer
...
internalBuffer.clear();
}
}
}
void add(value) // pseudo code here
{
{
lock_guard lock(externalBufferMutex);
externalBuffer.push_back(value);
}
bufferIsFilledConditionVariable.notify_one();
}
// search will not be used concurrently with add()
// it should just wait for the worker thread
someReturnValue search()
{
unique_lock lock(allBufferMutex);
// search here
...
}
}
【问题讨论】:
-
请详细说明您的问题:内部缓冲区会发生什么?搜索了吗?何时以及谁使用内部缓冲区中的数据?为什么需要 3 个缓冲区?它提醒了经典的生产者/消费者模式,除了我们没有看到消费者
标签: c++ multithreading boost