建议我有以下代码:
#include <boost/asio/io_service.hpp>
#include <boost/thread.hpp>
#include <condition_variable>
#include <iostream>
#include <mutex>
const int THREAD_POOL_SIZE = 2;
std::condition_variable g_cv;
std::mutex g_cv_mutex;
bool g_answer_ready;
void foo()
{
std::cout << "foo \n";
std::unique_lock<std::mutex> lock(g_cv_mutex);
g_answer_ready = true;
g_cv.notify_all();
}
int main()
{
boost::asio::io_service io_service;
for (int i = 0; i < 10; ++i)
{
std::auto_ptr<boost::asio::io_service::work> work(new boost::asio::io_service::work(io_service));
boost::thread_group threads;
for (int i = 0; i < THREAD_POOL_SIZE; ++i)
{
threads.create_thread(boost::bind(&boost::asio::io_service::run, &io_service));
}
std::unique_lock<std::mutex> lock(g_cv_mutex);
io_service.post(foo);
g_answer_ready = false;
g_cv.wait_for(lock, std::chrono::milliseconds(2000));
if (!g_answer_ready)
{
std::cout << "timed_out \n";
}
io_service.stop();
threads.join_all();
}
}
节目发布之间的输出会有所不同。例如,
foo
timed_out
foo
foo
但是,如果我在循环中移动boost :: asio :: io_service对象构造,它会按预期工作:
foo
foo
foo
foo
foo
foo
foo
foo
foo
foo
为什么呢?我究竟做错了什么?我该如何解决?
提升1.54,MSVC-11.0
答案 0 :(得分:1)
如果我理解正确,您需要修复循环中的最后一行(请参阅说明的注释):
// io_service.stop();
// threads.join_all();
work.reset(); // <- signal to process all pending jobs and quit from io_service::run function
threads.join_all(); // <- wait for all threads
io_service.reset(); // <- now `io_service` can accept new tasks
因此,原始代码中存在两个问题:
io_service.stop()
将取消已发布但尚未处理的作业(通常这不是程序员想要的),io_service.reset()
需要将io_service
的状态从“已停止”更改为“准备接受新工作”。