How to do Asynchronous Operation using boost::asio?

Boost::asio was initially designed for accomplishing time-consuming networking I/O (Input/Output) operations in asynchronous way. I/O operations over network usually takes some time to complete. If you call a function that does I/O operation over network, the calling thread will block until the I/O operation is complete. This is a problem in many situations. For example, if UI (User Interface) program calls such function and the function blocks for some time, the UI will freeze for that duration which is not acceptable.

Boost::asio came with the solution that the main thread (or calling thread) will not block but there will be a pool of threads (one or more) that will do the time consuming I/O operation.

Here we’ll see how to write program to do the time consuming tasks asynchronously in different pool of threads. We don’t need to do network I/O operation but we’ll define some function that will take some time to return.

Here is our time consuming function.

This function simply waits for some time based on the parameter passed as x. If the function is called with 5, the the function will wait for 50 milliseconds. If we call doSomething() from the main function, the main function will block until doSomething() returns.

Now we’ll see how to write a program to run the time consuming function doSomething() asynchronously with the help of boost::asio.

The main function will always be free even when the function doSomething() waits in one of the worker threads. We would also be able to call the function multiple times. Multiple such calls can get executed by the pool of worker threads at the same time.

The Program to Async Operation Using Boost::asio

In the main() function, we created the io_service object and a work object such that does not terminate for lack of work.

Then we created 5 worker threads by these lines.

Then we posted 10 works. Our work is basically calling doSomething() function with a random number between 1 to 9.

Output of our program.

If we look into this output carefully, then we’ll realize how the works got executed. From the first 5 lines, we can see that 5 threads execute 5 works simultaneously.

Thread 7ff3bfd6f700 finished its work first because it got a work to wait 20ms. Immediately it got another work to wait 90 ms.
Thread 7ff3bfd6f700 finished the first set of works because it got a work to wait for 90ms.
Similar way all 10 works got executed by 5 different threads.

Leave a Reply

Your email address will not be published. Required fields are marked *