我已經看過周圍堆棧溢出,並且在這方面有幾個非常好的答案(我的代碼實際上是基於this answer here),但由於某種原因我收到了奇怪的行爲 - 該thread_func應該被調用ls1次,但它只在線程退出前的0到2次之間運行。看起來ioService.stop()在完成之前切斷排隊的作業,但從我理解的情況來看,這不應該發生。這裏是相關的代碼片段:使用Boost線程和io_service創建線程池
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();
任何幫助將不勝感激,謝謝!
運行''總是必須在'post()'之後調用嗎? –