我目前正在编写一个多线程服务器,其中每个线程都有一个io_context和一个要执行的任务对象列表,每个任务对象都有一个相关的ip::tcp::socket对象。
为了平衡负载,我有时会将任务从一个线程迁移到另一个线程,但是我想在不中断连接的情况下也迁移它们的socket。
我可以简单地在线程之间传递套接字对象的所有权,但是套接字的io_context仍然是原来线程的,这将会大大增加复杂性。
有什么方法可以让我在移动socket连接到不同的io_context的同时保留它?还是有其他推荐的方法?
谢谢
你不能直接改变io_context,但是有一个变通的方法。
就用 释放 和 指派
这里有一个例子。
const char* buff = "send";
boost::asio::io_context io;
boost::asio::io_context io2;
boost::asio::ip::tcp::socket socket(io);
socket.open(boost::asio::ip::tcp::v4());
std::thread([&](){
auto worker1 = boost::asio::make_work_guard(io);
io.run();
}).detach();
std::thread([&](){
auto worker2 = boost::asio::make_work_guard(io2);
io2.run();
}).detach();
socket.connect(boost::asio::ip::tcp::endpoint(boost::asio::ip::address_v4::from_string("127.0.0.1"), 8888));
socket.async_send(boost::asio::buffer(buff, 4),
[](const boost::system::error_code &ec, std::size_t bytes_transferred)
{
std::cout << "send\n";
fflush(stdout);
});
// any pending async ops will get boost::asio::error::operation_aborted
auto fd = socket.release();
// create another socket using different io_context
boost::asio::ip::tcp::socket socket2(io2);
// and assign the corresponding fd
socket2.assign(boost::asio::ip::tcp::v4(), fd);
// from now on io2 is the default executor of socket2
socket2.async_send(boost::asio::buffer(buff, 4),
[](const boost::system::error_code &ec, std::size_t bytes_transferred){
std::cout << "send via io2\n";
fflush(stdout);
});
getchar();