Boost::Asio : io_service.run() vs poll() or how do I integrate boost::asio in mainloop

前端 未结 3 1290
梦谈多话
梦谈多话 2020-11-27 03:43

I am currently trying to use boost::asio for some simple tcp networking for the first time, and I allready came across something I am not really sure how to deal with. As fa

相关标签:
3条回答
  • 2020-11-27 04:06

    A drawback is that you'll make a busy loop.

    while(true) {
        myIoService.poll()
    }
    

    will use 100% cpu. myIoService.run() will use 0% cpu.

    myIoService.run_one() might do what you want but it will block if there is nothing for it to do.

    0 讨论(0)
  • 2020-11-27 04:15

    A loop like this lets you poll, doesn't busy-wait, and resets as needed. (I'm using the more recent io_context that replaced io_service.)

    while (!exitCondition) {
        if (ioContext.stopped()) {
            ioContext.restart();
        }
        if (!ioContext.poll()) {
            if (stuffToDo) {
                doYourStuff();
            } else {
                std::this_thread::sleep_for(std::chrono::milliseconds(3));
            }
        }
    }
    
    0 讨论(0)
  • 2020-11-27 04:19

    Using io_service::poll instead of io_service::run is perfectly acceptable. The difference is explained in the documentation

    The poll() function may also be used to dispatch ready handlers, but without blocking.

    Note that io_service::run will block if there's any work left in the queue

    The work class is used to inform the io_service when work starts and finishes. This ensures that the io_service object's run() function will not exit while work is underway, and that it does exit when there is no unfinished work remaining.

    whereas io_service::poll does not exhibit this behavior, it just invokes ready handlers. Also note that you will need to invoke io_service::reset on any subsequent invocation to io_service:run or io_service::poll.

    0 讨论(0)
提交回复
热议问题