Boost Asio总结class work
Posted thefist11
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Boost Asio总结class work相关的知识,希望对你有一定的参考价值。
1. 调用run()后,即使没有io事件, 也不会退出事件循环, 而是一直等待, 当有了新的异步io调用的时候, 还可以继续使用该循环。 asio::io_context::work可以防止io_context在没有io事件的情退出
int main()
asio::io_context ioc;
asio::ip::tcp::endpoint ep(asio::ip::address::from_string("127.0.0.1"), 6768);
asio::ip::tcp::socket sock(ioc, ep.protocol());
asio::ip::tcp::socket sock1(ioc, ep.protocol());
asio::io_context::work worker(ioc);
std::thread t([&ioc]() ioc.run(); );
sock.async_connect(ep, [](const std::error_code & err)
if (err.value() != 0)
std::cout << "Error: " << err.message() << std::endl;
);
sock1.async_connect(ep, [](const std::error_code & err)
if (err.value() != 0)
std::cout <<"Error: "<< err.message() << std::endl;
);
std::cout << "Main thread will for 3 seconds...\\n"; // 防止stop()执行过快
std::this_thread::sleep_for(std::chrono::seconds(3));
std::cout << "Main thread weak up...\\n";
ioc.stop(); // 显式停止io_context, 否则无法终止
t.join();
return 0;
2.
class io_context
::work
public:
/// Constructor notifies the io_context that work is starting.
/**
* The constructor is used to inform the io_context that some work has begun.
* This ensures that the io_context object's run() function will not exit
* while the work is underway.
*/
explicit work(boost::asio::io_context& io_context);
/// Copy constructor notifies the io_context that work is starting.
/**
* The constructor is used to inform the io_context that some work has begun.
* This ensures that the io_context object's run() function will not exit
* while the work is underway.
*/
work(const work& other);
/// Destructor notifies the io_context that the work is complete.
/**
* The destructor is used to inform the io_context that some work has
* finished. Once the count of unfinished work reaches zero, the io_context
* object's run() function is permitted to exit.
*/
~work();
/// Get the io_context associated with the work.
boost::asio::io_context& get_io_context();
private:
// Prevent assignment.
void operator=(const work& other);
// The io_context implementation.
detail::io_context_impl& io_context_impl_;
;
#endif // !defined(BOOST_ASIO_NO_DEPRECATED)
#if !defined(BOOST_ASIO_NO_DEPRECATED)
inline io_context::work::work(boost::asio::io_context& io_context)
: io_context_impl_(io_context.impl_)
io_context_impl_.work_started();
inline io_context::work::work(const work& other)
: io_context_impl_(other.io_context_impl_)
io_context_impl_.work_started();
inline io_context::work::~work()
io_context_impl_.work_finished();
inline boost::asio::io_context& io_context::work::get_io_context()
return static_cast<boost::asio::io_context&>(io_context_impl_.context());
#endif // !defined(BOOST_ASIO_NO_DEPRECATED)
以上是关于Boost Asio总结class work的主要内容,如果未能解决你的问题,请参考以下文章
Boost Asio总结(14)class basic_endpoint
Boost Asio总结(15)class basic_stream_socket