【问题标题】:Is it possible to change the io_context of a socket in boost::asio?是否可以在 boost::asio 中更改套接字的 io_context?
【发布时间】:2019-03-11 07:52:51
【问题描述】:

我目前正在编写一个多线程服务器,其中每个线程都有一个 io_context 和一个要执行的任务对象列表,每个任务对象都有一个关联的 ip::tcp::socket 对象。

为了负载平衡,我有时会将任务从一个线程迁移到另一个线程,但我也想在不断开连接的情况下迁移它们的套接字。

我可以简单地在线程之间传递套接字对象的所有权,但是套接字的 io_context 将保持其原始线程的所有权,这会增加显着的复杂性/减速。

我有什么方法可以在将套接字连接移动到不同的 io_context 时保持它?还是有其他推荐的方法?

非常感谢

【问题讨论】:

  • 我不认为io_context 真正拥有套接字。我想它拥有服务,它肯定拥有挂起/活动的处理程序。现在,我 /think/ 使用套接字,它只是实际共享的句柄。至少,我已经用这个(多个io_services 和来回传递套接字)运行了一段时间(几年)并且没有发现任何问题。不过有趣的问题。 +1

标签: multithreading boost-asio epoll


【解决方案1】:

您不能直接更改 io_context,但有一个解决方法

只需使用 releaseassign

这是一个例子:

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();

【讨论】:

    猜你喜欢
    • 2020-06-17
    • 2019-02-21
    • 2021-11-22
    • 1970-01-01
    • 1970-01-01
    • 2020-08-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多