gpt4 book ai didi

c++ - 使用 Boost 线程和 io_service 创建线程池

转载 作者:搜寻专家 更新时间:2023-10-31 00:14:37 25 4
gpt4 key购买 nike

我查看了 Stack Overflow 并且有一些非常好的答案,(我的代码实际上是基于 this answer here )但出于某种原因我得到了奇怪的行为 - thread_func 应该被调用 ls1 次,但它只在线程退出前运行 0 到 2 次。似乎 ioService.stop() 在完成之前切断了排队的作业,但据我所知,这不应该发生。这是相关的代码片段:

boost::asio::io_service ioService;
boost::asio::io_service::work work(ioService);

boost::thread_group threadpool;

for (unsigned t = 0; t < num_threads; t++)
{
threadpool.create_thread(boost::bind(&boost::asio::io_service::run, &ioService));
}

//Iterate over the dimensions of the matrices
for (unsigned i = 0; i < ls1; i++)
{
ioService.post(boost::bind(&thread_func,i, rs1, rs2, ls2, arr, left_arr, &result));
}

ioService.stop();
threadpool.join_all();

非常感谢任何帮助,谢谢!

最佳答案

io_service::stop() 使 run()run_one() 的所有调用尽快返回。它不会删除任何已排队进入 io_service 的未完成处理程序。当io_service::stop()被调用时,threadpool中的线程会尽快返回,导致每个线程执行完毕。

作为io_service::post()将在请求 io_service 调用处理程序后立即返回,在 io_service 之前,threadpool 中的线程将调用多少已发布的处理程序是不确定的 已停止。

如果您希望 thread_func 被调用 ls1 次,那么一个简单的替代方法是重新组织代码,以便将工作添加到 io_servicethreadpool 服务它之前,然后应用程序让 io_service 运行完成。

boost::asio::io_service ioService;

// Add work to ioService.
for (unsigned i = 0; i < ls1; i++)
{
ioService.post(boost::bind(
&thread_func,i, rs1, rs2, ls2, arr, left_arr, &result));
}

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

// Once all work has been completed (thread_func invoked ls1 times), the
// threads in the threadpool will be completed and can be joined.
threadpool.join_all();

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com