boost asio单线程post()在使用poll()时不发布?

问题描述 投票:0回答:1

一切都在单个线程中处理

void GameClient::test()
{
   std::cout <<"called test" << std::endl;
    m_io_context.post([](){
        std::cout << "test" << std::endl;
    });
}

void GameClient::calledFromALoop()
{
    // Use poll instead of run to avoid blocking
    auto count = m_io_context.poll();
    std::cout << "polled: " << count << std::endl;
}

我希望每个异步任务都在

calledFromALoop()
函数中处理。 每秒大约循环调用 50 次。

这是输出:

...
polled: 0
polled: 0
polled: 0
called test
polled: 0
polled: 0
polled: 0
...

你能帮我理解为什么

post
中的 lambda 没有被执行吗? 这是一个最小的例子,最初在
test
函数中,我使用
async_resolve
,但我有相同的行为。

我不想使用

run()
,因为我不想让
calledFromALoop()
阻塞。

但是我真的不明白异步函数何时执行(而不是处理程序)。 例如,我假设

async_resolve
需要一些工作来设置分辨率,然后需要一些时间来执行网络操作,然后是处理程序(回调)。这些步骤什么时候执行?
我认为设置是在调用
async_resolve
时完成的,然后是网络时间,然后从
poll()
调用回调。我说得对吗?
使用
run()
代替
poll()
会在网络时间内阻塞。

奇怪的行为是如果我改变这条线的位置

auto count = m_io_context.poll();
像这样:

void GameClient::test()
{
   std::cout <<"called test" << std::endl;
    m_io_context.post([](){
        std::cout << "test" << std::endl;
    });
    m_io_context.poll();
}

void GameClient::calledFromALoop()
{
    
}

我有

called test test
正如所料!

c++ boost asio
1个回答
0
投票

当然可以:

住在科里鲁

#include <boost/asio.hpp>
#include <iostream>
namespace asio = boost::asio;

int main() {
    asio::io_context ioc(1);

    post(ioc, [] { std::cout << "Hello, world!" << std::endl; });

    ioc.poll();
}

打印

Hello, world!

失业了

就像其他人评论的那样,您可能会让该服务无法工作。你必须阻止它

reset()
它。

asio::io_context ioc(1);

post(ioc, [] { std::cout << "Hello, world!" << std::endl; });
ioc.poll();

post(ioc, [] { std::cout << "Hello, world!" << std::endl; });
ioc.poll(); // doesn't print anything

但是,例如:

auto work = make_work_guard(ioc);

post(ioc, [] { std::cout << "Hello, world!" << std::endl; });
ioc.poll();

post(ioc, [] { std::cout << "Hello, world!" << std::endl; });
ioc.poll(); // prints!
最新问题
© www.soinside.com 2019 - 2025. All rights reserved.