在异步编程中, 如果某些条件不满足, 或者用户想强制取消某些IO操作, 此时也需要终止启动的异步操作. 下面给出一个常用的方法.
#include <boost/asio.hpp>
#include <iostream>
#include <thread>
#include <memory>
#include <chrono>
using namespace boost;
int main() {
std::string raw_ip_address = "127.0.0.1";
unsigned short port_num = 6768;
try {
asio::ip::tcp::endpoint ep(
asio::ip::address::from_string(raw_ip_address),
port_num
);
asio::io_context ioc;
std::shared_ptr<asio::ip::tcp::socket> sock(
new asio::ip::tcp::socket(ioc, ep.protocol())
);
sock->async_connect(ep,
[sock](const boost::system::error_code &ec) {
if (ec.value() != 0) {
if (ec == asio::error::operation_aborted) {
std::cout << "Operation cancelled!\n";
} else {
std::cout << "Error occurred!"
<< " Error code = "
<< ec.value()
<< ". Message: "
<< ec.message();
}
}
return;
});
// 运行Boost.Asio的事件循环, 在新的线程启动
std::thread worker_thread([&ioc]() {
try {
ioc.run();
} catch (boost::system::system_error &e) {
std::cout << "Error occurred!"
<< " Error code = " << e.code()
<< ". Message: " << e.what();
}
});
// 模拟处理其它任务
std::this_thread::sleep_for(std::chrono::seconds(2));
sock->cancel(); // 这里会启动异步回调函数
worker_thread.join();
} catch (boost::system::system_error &e) {
std::cout << "Main Error occurred! Error code = " << e.code()
<< ". Message: " << e.what();
return e.code().value();
}
return 0;
}
输出结果:
Error occurred! Error code = 111. Message: Connection refused
上述代码中, io_context
在新线程启动的原理可以参考这个笔记