为什么在这个简单的类中,如果我直接使用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
析构函数文档状态:
[...]程序员必须确保在线程仍可连接时永远不要执行析构函数。
如果BOOST_THREAD_PROVIDES_THREAD_DESTRUCTOR_CALLS_TERMINATE_IF_JOINABLE
已定义,则程序将中止,因为线程析构函数将调用std::terminate()
。
如果io_service
应该运行完成,请考虑在Test
析构函数中加入线程。这是一个完整的示例,演示了在线程完成时进行同步:
#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...
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句