将数据从调用方线程传递到另一个 boost::thread 中的方法
Passing data from caller thread to the method in another boost::thread
我有一个关于C++并发性(使用 Boost 线程(的菜鸟问题,但我还没有找到明确的答案。我有一个在单独的线程中运行的工人类。我只在程序启动时启动工作线程一次。此工作线程是"懒惰的",并且仅在从调用线程接收数据时才执行某些数据编码。在工人中,我有一个公共方法:
void PushFrame(byte* data);
它将数据推送到 std::stack 成员变量,以便每次将新数据对象推送到那里时,工作线程都可以访问它。
我不明白的是,这种互动通常是如何完成的?我可以只从调用线程调用 PushFrame(( 并传递参数吗?还是我必须以某种特殊方式访问工作线程中的方法?
通常,您使用生产者-消费者-队列来完成此类工作。
每当工作线程耗尽工作时,他都会wait()
boost::condition_variable
上,该受与保存工作线程数据的堆栈相同的boost::mutex
保护(您可能希望在此处使用队列以最大程度地降低不公平工作调度的风险(。
现在,每当PushFrame()
函数将新数据插入堆栈时,都会对该条件变量调用notify_one()
。这样,工作线程将真正休眠(即操作系统调度程序可能不会给它任何时间片(,直到实际有工作要做。
这里最容易出错的是锁定互斥锁,同时保护堆栈和condition_variable。除了避免数据结构上的竞争之外,您还需要注意condition_variable不会错过通知呼叫,因此可能会在实际有更多工作可用时陷入等待。
class Worker {
void PushFrame(byte* data)
{
boost::lock_guard<boost::mutex> lk(m_mutex);
// push the data
// ...
m_data_cond.notify_one();
}
void DoWork()
{
while(!done) {
boost::unique_lock<boost::mutex> lk(m_mutex);
// we need a loop here as wait() may return spuriously
while(is_out_of_work()) {
// wait() will release the mutex and suspend the thread
m_data_cond.wait(lk);
// upon returning from wait() the mutex will be locked again
}
// do work from the queue
// ...
}
}
boost::mutex m_mutex;
boost::condition_variable m_data_cond;
[...]
};
相关文章:
- 如果C++对象的类在另一个boost模块中声明,如何使用boost将指向该对象的指针返回到python
- boost :: filesystem :: verver()无法访问文件,因为另一个过程正在使用该文件
- 如何将 boost::mpl::vector 转换为另一个 boost::mpl::vector
- boost::p rogram_options:是否可以将一个选项设置为另一个选项的默认值
- 使用boost递归地将给定目录中每个最低级别文件夹的文件复制到另一个目录-C++
- 调整boost :: multi_array匹配另一个
- Boost:阻塞,直到队列有另一个项目
- 如何使用 Boost.Python 将C++对象传递给另一个C++对象
- 如何打印 boost::any 的向量,当我将元素类型存储在另一个字符串向量中时
- 从另一个线程调用Boost线程Sleep_For()
- Boost python,从另一个类的方法返回一个类
- c++/boost program_options一个选项禁用另一个选项
- 使用另一个构造一个具体的boost::元组类型
- 从另一个序列初始化Boost.Fusion序列的元素
- 对boost::system::generic的另一个未定义引用
- 卸载boost并安装另一个版本
- Boost.Program_options:将"--"后面的参数转发到另一个程序
- 将数据从调用方线程传递到另一个 boost::thread 中的方法
- 如何使用boost序列化轻松地序列化包含另一个自定义类的STL容器的自定义类
- 如何使用boost运行线程另一个对象函数与回调