Skip to content

f-squirrel/thread_pool

Repository files navigation

License CI Clang-Tidy Coverity Scan Coverage Status

C++ Thread Pool

This is a C++ 11/14 thread pool header-only implementation inspired by "C++ Concurrency in Action: Practical Multithreading" by Anthony Williams.

The library is header-only and supposed to be compatible with any C++ 11/14 compiler.
The only 3rd party is Google Test but it is optional.

Example of usage

#include <iostream>
#include <thread_pool/ThreadPool.hpp>

int sum(int a, int b) {
    return a + b;
}

int main() {

    thread_pool::ThreadPool pool{4u};
    auto fi = pool.submit(sum, 40, 2);
    auto fs = pool.submit([] { return std::string{"42"}; });
    auto fv = pool.submit([] { std::cout << "void function\n"; });
    std::cout << fi.get() << std::endl;
    std::cout << fs.get() << std::endl;
    // void
    fv.wait();
}

For more examples, please refer to the unit tests.

Change the default namespace

The default namespace is thread_pool, there are two ways to change it:

  • Via compilation flags -DTHREAD_POOL_NAMESPACE_NAME=<your favorite namespace>.
  • Via changing #define THREAD_POOL_NAMESPACE_NAME thread_pool in ThreadPool.hpp.

Integration

There are three ways to integrate thread_pool in a project:

  1. Git submodule
    • Add this repository as a git submodule to your project.
    • Add the thread_pool/include to your include path:
      include_directories(${CMAKE_SOURCE_DIR}/submodules/thread_pool/include)
      
  2. Just copy the thread_pool directory to your project directory
  3. Build the project and run sudo make install.

Build

git clone --recursive https://github.com/f-squirrel/thread_pool.git
cd thread_pool
mkdir build && cd build
cmake -DBUILD_TESTING=ON ..
make
make test