在官方chat example,chat_client::write()
推遲通過io_service::post()
工作的io_service
,這將:
- 要求,即
io_service
通過當前調用線程執行指定的處理程序poll()
,poll_one()
,run()
,或run_one()
功能io_service
- 不允許在調用函數內調用給定的處理程序(例如,
chat_client::write()
)
由於只有一個線程正在運行io_service
,並且所有套接字的讀取,寫入和關閉操作僅從發佈到io_service
的處理程序啓動,所以該程序滿足socket
的線程安全要求。
class chat_client
{
void write(const chat_message& msg)
{
// The nullary function `handler` is created, but not invoked within
// the calling function. `msg` is captured by value, allowing `handler`
// to append a valid `msg` object to `write_msgs_`.
auto handler = [this, msg]()
{
bool write_in_progress = !write_msgs_.empty();
write_msgs_.push_back(msg);
if (!write_in_progress)
{
do_write();
}
};
// Request that `handler` be invoked within the `io_service`.
io_service_.post(handler);
}
};
可能是io_service線程(t)免於此規則。 – Chris