【问题标题】:C++ 11 std::thread in cyclesC++ 11 std::thread 循环
【发布时间】:2015-05-18 21:35:52
【问题描述】:

我在 C++11 中有一个这样的循环:

while (true) 
{
    std::thread t0(some_work, 0);
    ...
    std::thread tn(some_work, n);
    t0.join();
    ...
    tn.join();
}

但在每次迭代中创建新线程当然不好。在 C 中,很容易使用消息来告诉线程等待另一次迭代,但我想使用 C++11 工具来完成。我查看了condition_variable,但我认为这不是解决方案。我能用它做什么?

【问题讨论】:

    标签: c++ multithreading c++11


    【解决方案1】:

    使用 Boost 打通!

    注意:我没有 C++11,所以我将向您展示的代码是用于 C++98 的 Boost libraries。大多数 Boost 内容都以 std::tr1 和随后的标准版本结束,因此其中大部分内容可能无需 Boost 即可转移。

    听起来你有多个线程,你不断地但不是一致地分配工作要做。这项工作并不总是需要执行(否则您的线程可以在自己的循环中执行)或者线程可能没有执行它的信息。如果是这种情况,请考虑boost::asio::io_service。

    这样,您将需要创建一个始终运行的线程,因此您可能希望将您的线程放在一个类中(尽管您不需要这样做)。

    class WorkerThread
    {
        WorkerThread()
        : thread(&WorkerThread::HandleWorkThread, this), io_service(), runThread(true)
        {
        }
        ~WorkerThread()
        {
            // Inform the thread not to run anymore:
            runThread = false;
            // Wait for the thread to finish:
            thread.join();
        }
        void AssignWork(boost::function<void()> workFunc) { io_service.post(workFunc); }
    private:
        void HandleWorkThread()
        {
            while (runThread)
            {
                // handle work:
                io_service.run();
                // prepare for more work:
                io_service.reset();
            }
        }
    
        boost::thread thread;
        boost::asio::io_service io_service;
        bool runThread; // NB: this should be atomic
    };
    

    现在您可以拥有以下内容:

    void CalculateThings(int, int);
    void CalculateThingsComplex(int, int, double);
    
    // Create two threads. The threads will continue to run and wait for work to do
    WorkerThread thread1, thread2;
    while (true)
    {
        thread1.AssignWork(boost::bind(&CalculateThings, 20, 30));
        thread2.AssignWork(boost::bind(&CalculateThingsComplex, 2, 5, 3.14));
    }
    

    您可以根据需要继续分配尽可能多的工作。一旦WorkerThreads 超出范围,它们将停止运行并很好地关闭

    【讨论】:

    • 嗯我有一个问题,因为我希望主流调用一些函数(如 apply_changes();) 在所有线程都完成它们的工作之后,所以我可能需要类似消息
    猜你喜欢
    • 2014-10-02
    • 1970-01-01
    • 1970-01-01
    • 2013-11-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-20
    • 2017-12-03
    相关资源
    最近更新 更多