作者热门文章
- c - 在位数组中找到第一个零
- linux - Unix 显示有关匹配两种模式之一的文件的信息
- 正则表达式替换多个文件
- linux - 隐藏来自 xtrace 的命令
为什么在这个简单的类中,如果我直接使用 io.run() 函数将被调用,否则如果要求运行到其他线程,打印将不会被调用?
#include <iostream>
#include <boost/thread.hpp>
#include <boost/asio.hpp>
using namespace std;
class test
{
public:
test()
{
io.post(boost::bind(&test::print, this));
//io.run();
t = boost::thread(boost::bind(&boost::asio::io_service::run, &io));
}
void print()
{
cout << "test..." << endl;
}
private:
boost::thread t;
boost::asio::io_service io;
};
int main()
{
test();
return 0;
}
最佳答案
线程对象在允许 io_service
完全运行之前被销毁。 thread
析构函数 documentation状态:
[...] the programmer must ensure that the destructor is never executed while the thread is still joinable.
如果定义了 BOOST_THREAD_PROVIDES_THREAD_DESTRUCTOR_CALLS_TERMINATE_IF_JOINABLE
,程序将中止,因为线程析构函数将调用 std::terminate()
。
如果 io_service
应该运行完成,则考虑在 Test
的析构函数中加入线程。这是一个完整的例子 demonstrates在线程完成时同步:
#include <iostream>
#include <boost/asio.hpp>
#include <boost/thread.hpp>
class test
{
public:
test()
{
io.post(boost::bind(&test::print, this));
t = boost::thread(boost::bind(&boost::asio::io_service::run, &io));
}
~test()
{
if (t.joinable())
t.join();
}
void print()
{
std::cout << "test..." << std::endl;
}
private:
boost::thread t;
boost::asio::io_service io;
};
int main()
{
test();
return 0;
}
输出:
test...
关于c++ - io_service 在线程内运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26510075/
我是一名优秀的程序员,十分优秀!