Search code examples
c++boost-asioasio

Asio difference between work(), require() and make_work_guard()


Sorry to interrupt, I am a newbie in C++ and Asio...

I just come from here Asio difference between prefer, require and make_work_guard.

I am trying to make a "dummy work" for my io_context.

It is really confusing to a beginner who just wants to make a simple "UDP socket".

The ancient book from Packt and Youtube (https://www.youtube.com/watch?v=2hNdkYInj4g&t=2292s) tutorial tells me to use "work()", the old document tell me to use a much more complex class called "excutor_work_guard", and the new fashion document just tell me to use something extremely unreadable "require()"...

Could I just use "make_work_guard()" and forget about everything else?

Sorry for my English...


Solution

  • As you state yourself, this is a full duplicate of the linked question.

    The answer there answers every point you make here.

    The ancient book from Packt and Youtube (https://www.youtube.com/watch?v=2hNdkYInj4g&t=2292s) tutorial tells me to use "work()"

    I have bad experiences with Packt books on Asio¹. Regardless, there was never a function work(). You probably meant

    boost::asio::io_service svc;
    boost::asio::io_service::work work(svc);
    

    The newer interface is indeed

    boost::asio::io_context ioc;
    auto work = make_work_guard(ioc);
    

    That's it.

    and the new fashion document just tell me to use something extremely unreadable "require()"...

    I have never (ever) seen that anywhere. Can you point me to the place where you found that? In fact, as the linked answer points out, it can be a bad idea to tie work to executors, because it spreads by copying, losing control and inviting deadlocks.

    Could I just use "make_work_guard()" and forget about everything else?

    Yeah. That's what the other answer already said. If you're in doubt, just re-read the summary there :)


    ¹ e.g. see Crash : terminate called after throwing an instance of 'std::system_error' what(): Resource deadlock avoided