Haatschii
Haatschii

Reputation: 9319

How to prevent that a Boost::Asio timer blocks the return of the io_service::run()?

I have the following (minimized) Class handling my server connection:

class AsioServer {
protected:
    boost::asio::io_service ioService;
public:
    AsioServer() {}

    void add_request() {
        //Adding async requests to the ioService
    }

    void timeout() {
        //Stop all pedning async operations
        ioService.stop();
    }

    void perform() {
        //Set a timer
        boost::asio::deadline_timer timer(ioService);
        timer.expires_from_now(boost::posix_time::seconds(5));
        timer.async_wait(std::bind(&AsioServer::timeout, this));

        //Performe all Async operations
        ioService.run();
        ioService.reset();
    }
};

My Problem is that the deadline timer prevents the return of ioService.run() until it expires. What I want is the the timer is only called when expering and then canceling the async operations, but not act as work in the context of the io_service. Are there timers not acting as work, or another good way dealing with this situation?

Upvotes: 1

Views: 1865

Answers (1)

Igor R.
Igor R.

Reputation: 15075

The io_service::run does not exit (if not stopped explicitly) as long as it has some work - this includes completion handlers of any i/o objects and timers, because io_service is solely responsible for dispatching all these handlers.

If you don't want the timer to wait anymore after a socket i/o operation completes - just cancel() the timer or re-schedule it, if appropriate. You can find such an approach in asio examples.

Upvotes: 1

Related Questions