Saturday, March 4, 2017

Using Asio C++ library based ThreadPool class

Category: C++, Concurrency Programming, Thread pool, Asio

Prerequisites: C++, Asio C++ programming concept, Multithreading

Requirement: Asio C++ library

What is it?
It is only a C++ header file that defines ThreadPool class based on Asio C++ Library.

Why is it created?
It is created to serve the following purposes:
  1. To use C++ multithreading with thread pool.
  2. To use task based concurrency programming.
  3. Can use strictly sequential invocation of handlers.
  4. Can use C++ Exception handling.

How can you use it?
  1. Create the client class that will use thread pool.
  2. Create any tasks that you want to execute in sequential or parallel order. In our case we use sequential for simplicity.
  3. If you want to handle exception. Modify previous code, add final task to start and stop MainIoService as shown in the following code.
  4. In the main code, create ThreadPool instance. Then create client instance by using shared_ptr. Make a call from the client and try to throw an exception in the client code to test exception handling.
  5. If you use _threadPool.strand() instead of _threadPool.enqueue(), any tasks called can not be executed concurrently.
How to dowload the ThreadPool Class?
The ThreadPool Class is in ThreadPool.h header file on github.

No comments:

Post a Comment