c++ - 使用多线程 boost 条件变量

标签 c++ multithreading boost

在我的程序中,我有两个基本线程。第一个是主线程,第二个是 Tcp 服务器线程。 TCP 服务器将监听请求,并为每个请求创建一个相应的线程,每个新创建的线程都应该开始工作,直到它们到达必须等待主线程指示的特定点。为了解决这个问题,我使用 Boost 1.49 实现了一个条件变量。

我的主要问题是,每当任何新创建的线程到达条件变量的点时,我的整个程序就会卡住。

更多信息请查看: Boost 1.49 Condition Variable issue

直到现在我都没有收到任何正面的回应,我也无法解决这个问题。

非常感谢。

最佳答案

我没有看你的其他问题(代码太多)

不过,一般来说,您必须在相应的互斥量下等待/发出条件信号。

这是一个由 10 名等待开始信号的 worker 组成的小组的演示:

  • 查看 Live On Coliru

    #include <boost/thread.hpp>
    #include <boost/optional/optional_io.hpp>
    
    /////////////////////////
    // start condition logic
    
    boost::mutex mx;
    boost::condition_variable cv;
    
    static bool ok_to_start = false; 
    
    void await_start_condition()
    {
        boost::unique_lock<boost::mutex> lk(mx);
        cv.wait(lk, [] { return ok_to_start; });
    }
    
    void signal_start_condition()
    {
        boost::lock_guard<boost::mutex> lk(mx); 
        ok_to_start = true;
        cv.notify_all();
    }
    
    /////////////////////////
    // workers
    static boost::optional<int> shared_secret;
    
    void worker(int id)
    {
        await_start_condition();
    
        // demo worker implementation
        static boost::mutex console_mx;
        boost::lock_guard<boost::mutex> lk(console_mx);
        std::cout << "worker " << id << ": secret is " << shared_secret << "\n";
    }
    
    int main()
    {
        boost::thread_group threads;
    
        for (int i = 0; i<10; i++)
            threads.create_thread(boost::bind(worker, i));
    
        // demo - initialize some state before thread start
        shared_secret = 42;
    
        // signal threads can start
        signal_start_condition();
    
        // wait for all threads to finish
        threads.join_all();
    }
    
  • 在 C++03 的情况下,您可以用手写谓词替换 lambda: Live On Coliru

    namespace /* anon detail */
    {
        bool ok_to_start_predicate() { return ok_to_start; }
    }
    
    void await_start_condition()
    {
        boost::unique_lock<boost::mutex> lk(mx);
        cv.wait(lk, ok_to_start_predicate);
    }
    
  • 或者您可以使用 Boost Lambda/Boost Phoenix 为您解决这个问题: Live On Coliru

    #include <boost/phoenix.hpp>
    void await_start_condition()
    {
        boost::unique_lock<boost::mutex> lk(mx);
        cv.wait(lk, boost::phoenix::cref(ok_to_start));
    }
    

关于c++ - 使用多线程 boost 条件变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22424353/

相关文章:

c++ - 如何设置 QTextEdit 的行数?

c++ - Arduino makefile无法编译

java - 删除在循环Java中的arraylist中创建的对象

c++ - 错误 : `boost' has not been declared

c++ - 通过 T* 从 std::set<shared_ptr<T>> 移除

c++ - 为什么 _tcstod 在解析字符串时使用我的 Windows 区域设置?

C++11 使用代理将成员函数传递给线程

objective-c - 线程可以与队列类似地使用,还是它们意味着不同的东西?

c++ - 序列化可变状态并通过网络异步发送它,几乎是零拷贝(Cap'n Proto + ZeroMQ)

c++ - 根据模板整数参数选择整数类型