//有個疑惑: 向io_context對象中提交的任務只能被順序化的執行.
//下面這個構造函數表明可以運行多線程啊。。。。。
/**
* Construct with a hint about the required level of concurrency.
*
* @param concurrency_hint A suggestion to the implementation on how many
* threads it should allow to run simultaneously.
*/
BOOST_ASIO_DECL explicit io_context(int concurrency_hint);
io_context類為異步I/O對象提供核心功能,對象包括:
- boost::asio::ip::tcp::socket
- boost::asio::ip::tcp::acceptor
- boost::asio::ip::udp::socket
- boost::asio::deadline_timer
boost::asio::io_context io_context;
...
for (;;)
{
try
{
io_context.run();
break; // run() exited normally
}
catch (my_exception& e)
{
// Deal with exception as appropriate.
}
}
使用以下函數向io_context提交任務
- boost::asio::dispatch
- boost::asio::post
- boost::asio::defer
void my_task()
{
...
}
...
boost::asio::io_context io_context;
// Submit a function to the io_context.
boost::asio::post(io_context, my_task);
// Submit a lambda object to the io_context.
boost::asio::post(io_context,
[]()
{
...
});
// Run the io_context until it runs out of work.
// Run the io_context until it runs out of work.
// Run the io_context until it runs out of work.
io_context.run();
io_context.restart();
boost::asio::post(io_context, my_task);
io_context.run();
如果希望在調用run()函數后即使做完任務后也不要run()函數返回,則可使用以下類實現
boost::asio::executor_work_guard<io_context::executor_type>
asio::io_context io_context;
asio::executor_work_guard<asio::io_context::executor_type>
work = asio::make_work_guard(io_context);
......
work.reset(); // Allow run() to exit. @endcode
成員函數
1. count_type run();
- 調用 run() 函數后程序將被阻塞到任務被完成同時沒用其他任務派遣,或者直到
io_context調用 stop() 函數停止為止- 多線程中可以調用 run() 函數來開啟一個線程池,
io_context可以在線程池中執行處理程序。在池中等待的所有線程都是等效的,io_context可以選擇其中的任何一個線程來調用處理程序。- 在 run() 函數正常退出后立即調用
run()、run_one()、poll()或poll_one()函數將會立即返回,除非在調用這些函數前調用restart()函數。- 返回被處理的程序的數量 count_type
2. std::size_t run_for(const chrono::duration<Rep, Period>& rel_time);
- 在一定時間內處理事件循環,阻塞到任務被完成同時沒用其他任務派遣,或者直到
io_context調用 stop() 函數停止 或 超時 為止rel_time: 表示時間段
3. std::size_t run_until(const chrono::time_point<Clock, Duration>& abs_time);
abs_time: 阻塞到哪個時間點
4. count_type run_one();
- 最多處理一個任務, 處理完就退出 或 io_context被停止
- 函數正常退出后立即調用 run()、 run_one()、poll() 或 poll_one() 函數將會立即返回,除非在調用這些函數前調用 restart() 函數。
count_type: 返回 0 表示io_conutext被停止
5. std::size_t run_one_for(const chrono::duration<Rep, Period>& rel_time);
6. std::size_t run_one_until(const chrono::time_point<Clock, Duration>& abs_time);
7. count_type poll();
- 以非阻塞方式處理任務
- 返回處理的任務數量
8. count_type poll_one();
- 以非阻塞方式處理任務,最多處理一個
- 返回 0 表示io_context被終止
9. void stop();
此函數將終止io_context對象的事件處理,此函數不阻塞,而只是向io_context發出停止信號。它的run()或run_one()成員函數的所有調用都應該盡快返回。對run()、run_one()、poll()或poll_one()的后續調用將立即返回,直到調用restart()。
10. bool stopped() const;
判斷io_context對象的事件處理是否被終止
11. void restart();
重新啟動io_context,為后續調用 run() 做准備。必須在run()、run_one()、poll()或poll_one()函數的第二次或更高的調用集之前調用此函數。
