促进线程间通信

Pan*_*ant -2 c++ multithreading boost

我必须实现Boost线程间通信。考虑以下代码:

#include <boost/thread/thread.hpp>
#include <Windows.h>
void threadA()
{
    while(true)
    {
        std::cout << "From thread A" << std::endl;
        Sleep(3000); //pretend to do the work
    }
}

void threadB()
{
    while(true)
    {
        std::cout << "From thread B" << std::endl;
        Sleep(3000); //pretend to do the work
    }
}

int main()
{
    boost::thread *th1 = new boost::thread(&threadA);
    boost::thread *th2 = new boost::thread(&threadB);
    th1->join();
    th2->join();
    delete th1;
    delete th2;
}
Run Code Online (Sandbox Code Playgroud)

如果我运行上面的代码,它将生成两个线程。我想要做的是启动,threadA然后向发送一些消息threadB,该消息在接收时将启动线程。或更笼统地说,如果这两个线程都独立运行,该如何处理通信?

seh*_*ehe 5

有很多方法。

  • 使用条件变量(又名事件)
  • 使用并发队列(例如消息)或更一般地使用信号量
  • 使用无锁并发数据结构

Boost提供了以上所有功能的实现。