gpt4 book ai didi

c++ - boost Asio : waiting until thread_group has processed all posted tasks?

转载 作者:塔克拉玛干 更新时间:2023-11-03 02:24:14 25 4
gpt4 key购买 nike

我有一个对象,一旦创建就会在后台执行许多任务,但应该阻塞直到/所有/发布的任务完成。即:

struct run_many{
boost::asio::io_service m_io_service;
boost::thread_group m_threads;
boost::asio::signal_set m_signals;

void evaluate(std::string work, int i){ /*...*/ }

void run_tasks(int tasks, std::string work){
{
boost::asio::io_service::work w(m_io_service); //
for(int i=0;i<tasks;i++)
m_io_service.post(boost::bind(&run_many::evaluate, this, work, i));
}

//m_io_service.run(); // blocks forever
m_io_service.stop(); // seems to cut off queued jobs
m_threads.join_all(); // works only after m_io_service.stop()
}

run_many(int n_workers)
{
m_threads.create_thread(boost::bind(&boost::asio::io_service::run,m_io_service);
}
};

所以我卡住了……看来我要么永远等待,要么在每个线程中当前运行的作业之后切断队列。文档中一定有我遗漏的东西吗?

最佳答案

根据文档,这个想法应该可行(伪代码):

...

// put a few handlers into io_service

...

// don't forget to destroy all boost::asio::io_service::work objects
while (m_io_service.stopped())
{
m_io_service.run();
}

// when code reaches this line m_io_service will be in stopped state and all handlers will be executed

// this code can be called without any doubts about being locked

m_threads.join_all();

关于c++ - boost Asio : waiting until thread_group has processed all posted tasks?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9080562/

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