将数据从调用方线程传递到另一个 boost::thread 中的方法

Passing data from caller thread to the method in another boost::thread

本文关键字:boost 另一个 thread 方法 调用 数据 方线程 线程      更新时间:2023-10-16

我有一个关于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;
 [...]
};