c++ - Boost,在io_service.post之前创建线程池

标签 c++ multithreading boost threadpool

我成功地测试了一个关于 boost io_service 的例子:

for(x = 0; x < loops; x++)
{
    // Add work to ioService.
    for (i = 0; i < number_of_threads; i++)
    {   
        ioService.post(boost::bind(worker_task, data, pre_data[i]));
    }

    // Now that the ioService has work, use a pool of threads to service it.
    for (i = 0; i < number_of_threads; i++)
    {   
        threadpool.create_thread(boost::bind(
            &boost::asio::io_service::run, &ioService));      
    }

    // threads in the threadpool will be completed and can be joined.
    threadpool.join_all();
}

这将循环多次并且需要一点时间,因为每次都会为每个循环创建线程。

有没有办法创建所有需要的线程。 然后在循环中发布每个线程的工作。 工作完成后需要等待所有线程完成工作!

像这样:

// start/create threads
for (i = 0; i < number_of_threads; i++)
{   
    threadpool.create_thread(boost::bind(
        &boost::asio::io_service::run, &ioService));      
}

for(x = 0; x < loops; x++)
{
    // Add work to ioService.
    for (i = 0; i < number_of_threads; i++)
    {   
        ioService.post(boost::bind(worker_task, data, pre_data[i]));
    }

    // threads in the threadpool will be completed and can be joined.
    threadpool.join_all();
}

最佳答案

这里的问题是您的工作线程将在创建后立即完成,因为没有工作要做。 io_service::run()将立即返回,因此除非您设法在所有工作线程有机会调用 run() 之前潜入其中一个后调用, 他们都会马上结束。

解决这个问题的两种方法:

  • 使用 barrier阻止 worker 调用run()马上。只有在作品发布后才取消阻止。
  • 使用 io_service::work 要防止的对象 run从返回。您可以在发布所有内容后销毁工作对象(并且必须在再次尝试 join 工作人员之前这样做)。

关于c++ - Boost,在io_service.post之前创建线程池,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34337690/

相关文章:

C++ 对长度说明符的支持

java - Thread.currentThread().getId() 和 Kernel32.INSTANCE.GetCurrentThreadId() 之间的区别

c++ - boost::flyweight 是否进行引用计数?

c++ - 什么时候哈希表比搜索树更好用?

c++ - int main(void) 在 C++ 中有效吗?

c++ - 是否有以下C++阻塞条件变量

c++ - 我如何使用 boost::test 和 xcode 4 来测试一些 ios c++ 代码?

c++ - 为什么这种理论上跨平台的代码不会改变 Windows 上的环境变量?

c++ - 从 vector<string> 转换为 vector<char*> 到 char** 时 execvp 不工作

java - Java 中的 spin-on-test-and-set 与 spin-on-read