run/poll 等待事件)。io_service,支持兩種風格:同步調用(socket.connect())和異步調用(socket.async_connect(handler))。run():阻塞運行事件循環,處理就緒事件並調用 handler。poll():非阻塞處理已就緒事件,無事件立即返回。stop():停止 run() 循環。post(handler) / dispatch(handler):提交任務到隊列 / 立即執行(若在 io_service 線程中)。boost::asio::io_service ios;
auto work = make_shared(ios);
// 只要 work 存在,ios.run() 就不會因隊列空而返回
// 需停止時:work.reset();
ios.run();
mutable_buffer / const_buffer:指針 + 長度,不擁有內存。vector 支持 scatter/gather。異步寫入 async_write(socket, buffer(data), handler):
data 必須在 handler 執行前存活。
錯誤模式:棧上局部數組發起 async_write,函數返回棧幀銷毀 → handler 訪問野指針。
正確模式:
shared_ptr> 綁定生命週期到 handler。deque write_msgs_ ,發送前 push_back,handler 中 pop_front。chat_message* msg = new chat_message(...),handler 中 delete。| 對象 | 用途 | 典型異步方法 |
|---|---|---|
ip::tcp::socket | TCP 連接 | async_read/async_write/async_connect |
ip::tcp::acceptor | TCP 監聽 | async_accept |
ip::udp::socket | UDP | async_receive_from/async_send_to |
deadline_timer | 定時器 | async_wait |
signal_set | 信號處理 | async_wait |
posix::stream_descriptor | 文件描述符 | async_read/async_write |
多線程調用 io_service::run() 時,handler 可能並發執行。
strand 確保包裝的 handler 串行執行(不並發)。
boost::asio::strand strand(ios);
timer1.async_wait(strand.wrap(handler1));
timer2.async_wait(strand.wrap(handler2));
// handler1 和 handler2 不會同時運行
HTTP Server 3 示例中,connection 內部用 strand 保護 socket_ 和緩衝區訪問。
deadline_timer 只有「超時/未超時」兩態。
高併發場景(如每個 UDP 包 100ms 超時)需自行維護:
map,超時 handler 中檢查是否被取消。
class ChatClient {
io_service ios;
tcp::socket socket_;
deque write_msgs_;
// ...
void write(const string& msg) {
ios.post([this, msg]() { // 關鍵:post 到 io_service 線程
bool write_in_progress = !write_msgs_.empty();
write_msgs_.push_back(msg);
if (!write_in_progress) do_write();
});
}
void do_write() {
async_write(socket_, buffer(write_msgs_.front()),
[this](error_code ec, size_t) {
if (!ec) {
write_msgs_.pop_front();
if (!write_msgs_.empty()) do_write();
} else { close(); }
});
}
};
post 將寫入請求丟到 io_service 隊列,避免主線程與 I/O 線程競爭 write_msgs_,實現無鎖線程安全。
Boost.Asio 是 C++ 異步網絡編程的標準庫級方案。核心掌握:
io_service 事件循環 + work 保活。strand 解決多線程 handler 並發衝突。post 實現線程間任務分發,避免顯式鎖。建議從官方示例(HTTP Server 1/2/3、Chat)入手,逐步理解異步控制流與資源管理模式。