
BS::thread_pool: a fast, lightweight, modern, and easy-to-use C++17 / C++20 / C++23 thread pool library
By Barak Shoshany
Email: [email protected]
Website: https://baraksh.com/
GitHub: https://github.com/bshoshany
This is the complete documentation for v5.1.0 of the library, released on 2026-01-03.
Introduction
Motivation
Multithreading is essential for modern high-performance computing. Since C++11, the C++ standard library has included built-in low-level multithreading support using constructs such as std::thread. However, std::thread creates a new thread each time it is called, which can have a significant performance overhead. Furthermore, it is possible to create more threads than the hardware can handle simultaneously, potentially resulting in a substantial slowdown.
The library presented here contains a C++ thread pool class, BS::thread_pool, which avoids these issues by creating a fixed pool of threads once and for all, and then continuously reusing the same threads to perform different tasks throughout the lifetime of the program. By default, the number of threads in the pool is equal to the maximum number of threads that the hardware can run in parallel.
The user submits tasks to be executed into a queue. Whenever a thread becomes available, it retrieves the next task from the queue and executes it. The pool optionally produces an std::future for each task, which allows the user to wait for the task to finish executing and/or obtain its eventual return value, if applicable. Threads and tasks are autonomously managed by the pool in the background, without requiring any input from the user aside from submitting the desired tasks.
The design of this library is guided by four important principles. First, compactness: the entire library consists of just one self-contained header file, with no other components or dependencies. Second, portability: the library only utilizes the C++ standard library, without relying on any compiler extensions or 3rd-party libraries, and is therefore compatible with any modern standards-conforming C++ compiler on any platform, as long as it supports C++17 or later. Third, ease of use: the library is extensively documented, and programmers of any level should be able to use it right out of the box.
The fourth and final guiding principle is performance: each and every line of code in this library was carefully designed with maximum performance in mind, and performance was tested and verified on a variety of compilers and platforms. Indeed, the library was originally designed for use in the author’s own computationally-intensive scientific computing projects, running both on high-end desktop/laptop computers and high-performance computing nodes.
Among the available C++ thread pool libraries, BS::thread_pool occupies the crucial middle ground between small bare-bones thread pool classes that offer rudimentary functionality and are only suitable for simple programs, and very large libraries that offer many advanced features but consist of multiple components and dependencies and involve complex APIs that require a substantial time investment to learn. BS::thread_pool was designed for users who want a simple and lightweight header-only library that is easy to learn and use, and can be readily incorporated into existing or new projects, but do not want to compromise on performance or functionality.
Obtaining the library is quick and easy; it can be downloaded manually from the GitHub repository, or installed automatically using a variety of package managers and build systems. The library can be imported either as a traditional header-only library, or as a modern C++20 module. BS::thread_pool has undergone extensive testing on multiple platforms and is actively used by thousands of C++ developers worldwide for a wide range of applications, from scientific computing to game development.
Overview of features
- Fast:
- Built from scratch with maximum performance in mind.
- Suitable for use in high-performance computing nodes with a very large number of CPU cores.
- Reusing threads avoids the overhead of creating and destroying them for individual tasks.
- A task queue ensures that there are never more tasks running in parallel than is allowed by the hardware.
- All optional features can be selectively turned on to ensure minimal overhead.
- Lightweight:
- Single header file: simply
#include "BS_thread_pool.hpp" and you’re all set!
- Header-only: no need to install or build the library.
- Self-contained: no external requirements or dependencies.
- Portable: uses only the C++ standard library, and works with any C++17-compliant compiler on any platform.
- Only 536 lines of code, including all optional features and utility classes (excluding comments, blank lines, lines containing only a single brace, C++17/20 polyfills, and native extensions).
- Modern:
- Fully supports C++17, C++20, and C++23, taking advantage of the latest language features when available for maximum performance, reliability, and usability.
- In C++20, the library can be imported as a C++20 module using
import BS.thread_pool, with many benefits, such as faster compilation times and avoiding namespace pollution.
- In C++23, the library can import the C++ Standard Library as a module using
import std on supported compilers and platforms.
- Makes use of modern C++ programming practices for readability, maintainability, performance, safety, portability, and reliability.
- Easy to use:
- Very simple operation, using only a handful of member functions for basic use, with many additional member functions, classes, and functions for more advanced use.
- Every task submitted to the queue using
submit_task() automatically generates an std::future, which can be used to wait for the task to finish executing, obtain its eventual return value, and/or catch any thrown exceptions.
- Loops can be automatically parallelized into any number of tasks using
submit_loop(), which returns a BS::multi_future that can be used to track the execution of all parallel tasks at once.
- If futures are not needed, tasks may be submitted using
detach_task(), and loops can be parallelized using detach_loop() - sacrificing convenience for even greater performance. In that case, wait(), wait_for(), and wait_until() can be used to wait for all the tasks in the queue to complete.
- Extremely thorough and detailed documentation, with numerous examples, is available in the library’s
README.md file, with a total of 3,486 lines and 26,700 words!
- The code is thoroughly documented using Doxygen comments - not only the interface, but also the implementation, in case the user would like to make modifications.
- Optionally, the included Python script
compile_cpp.py can be used to easily compile any programs that are using the library, with full support for C++20 modules and C++23 Standard Library modules where applicable.
- Additional features:
- Optional features:
- Optional features can be enabled by passing a bitmask template parameter to the
BS::thread_pool class template.
- Assign a priority to each task using the optional task priority feature. The priority, in the range -128 to +127, is passed as the last argument to all
submit and detach member functions. Tasks with higher priorities will be executed first.
- Freely pause and resume the pool using
pause(), unpause(), and is_paused() with the optional pausing feature. When paused, threads do not retrieve new tasks out of the queue.
- Avoid deadlocks using the optional wait deadlock checks feature. If a deadlock is detected while waiting for tasks, the pool will throw the exception
BS::wait_deadlock.
- Native extensions:
- Well-tested:
- The included test program
BS_thread_pool_test.cpp performs hundreds of automated tests, and also serves as a comprehensive example of how to properly use the library.
- The test program also performs benchmarks using a highly-optimized multithreaded algorithm which generates a plot of the Mandelbrot set.
- The included Python script
compile_cpp.py provides a portable way to automatically run the tests with all available compilers with one command.
- Compatibility is comprehensively tested on the latest versions of Windows, Ubuntu, and macOS, using Clang, GCC, and MSVC.
- Under continuous and active development. Bug reports and feature requests are welcome, and should be made via GitHub issues.
Getting started
Installing the library
To install BS::thread_pool, simply download the latest release from the GitHub repository, place the header file BS_thread_pool.hpp from the include folder in the desired folder, and include it in your program:
#include "BS_thread_pool.hpp"
The thread pool will now be accessible via the BS::thread_pool class. For an even quicker installation, you can download the header file itself directly at this URL; no additional files are required, as the library is a single-header library.
This library is also available on various package managers and build systems, including vcpkg, Conan, Meson, and CMake. Please see below for more details.
If C++20 features are available, the library can also be imported as a C++20 module, in which case #include "BS_thread_pool.hpp" should be replaced with import BS.thread_pool;. This requires one additional file, and the module must be compiled before it can be used; please see detailed instructions below.
Compiling and compatibility
This library officially supports C++17, C++20, and C++23. If compiled with C++20 and/or C++23 support, the library will make use of newly available features for maximum performance and usability. However, the library is fully compatible with C++17, and should successfully compile on any C++17 standard-compliant compiler, on all operating systems and architectures for which such a compiler is available.
Compatibility was verified using the bundled test program BS_thread_pool_test.cpp, compiled using the bundled Python script compile_cpp.py with native extensions enabled, importing the library as a C++20 module where applicable, and importing the C++23 Standard Library as a module where applicable, on a 24-core (8P+16E) / 32-thread Intel i9-13900K CPU, using the following compilers, C++ standard libraries, and platforms:
- Windows 11 25H2 build 26200.7462:
- Ubuntu 25.10:
- Clang v21.1.8 with LLVM libc++ v21.1.8
- GCC v15.2.0 with GNU libstdc++ v15 (20250917)
- macOS 15.1 build 24B83:
- Clang v21.1.8 with LLVM libc++ v21.1.8 (Homebrew build)
- Note: Apple Clang is currently not officially supported, as it does not support C++20 modules.
As this library requires C++17 features, the code must be compiled with C++17 support:
- For Clang or GCC, use the
-std=c++17 flag.
- For MSVC, use
/std:c++17, and also /permissive- to ensure standards conformance.
For maximum performance, it is recommended to compile with all available compiler optimizations:
- For Clang or GCC, use the
-O3 flag.
- For MSVC, use
/O2.
As an example, to compile the test program BS_thread_pool_test.cpp with compiler optimizations, first create the build folder using mkdir build, and then run the following command in the root folder of the repository:
- Windows:
- GCC:
g++ -std=c++17 -O3 -I include tests/BS_thread_pool_test.cpp -o build/BS_thread_pool_test.exe
- Clang:
clang++ -std=c++17 -O3 -I include tests/BS_thread_pool_test.cpp -o build/BS_thread_pool_test.exe
- MSVC:
cl /std:c++17 /permissive- /O2 /EHsc /I include tests/BS_thread_pool_test.cpp /Fo:build/BS_thread_pool_test.obj /Fe:build/BS_thread_pool_test.exe (in the Visual Studio Developer PowerShell for your CPU architecture)
- Linux/macOS:
- GCC:
g++ -std=c++17 -O3 -I include tests/BS_thread_pool_test.cpp -o build/BS_thread_pool_test
- Clang:
clang++ -std=c++17 -O3 -I include tests/BS_thread_pool_test.cpp -o build/BS_thread_pool_test
If your compiler and codebase support C++20 and/or C++23, it is recommended to enable them in order to allow the thread pool library access to the latest features:
- For Clang or GCC, use the
-std=c++20 or -std=c++23 flag.
- For MSVC, use
/std:c++20 for C++20 or /std:c++latest for C++23.
In addition, if C++20 features are available, the library can be imported as a module; instructions for doing so are provided below.
Constructors
The default constructor creates a thread pool with as many threads as the hardware can handle concurrently, as reported by the implementation via std::thread::hardware_concurrency(). This is usually determined by the number of cores in the CPU. If a core is hyperthreaded, it will count as two threads. For example:
// Constructs a thread pool with as many threads as are available in the hardware.
BS::thread_pool pool;
Optionally, a number of threads different from the hardware concurrency can be specified as an argument to the constructor. However, note that adding more threads than the hardware can handle will not improve performance, and in fact will most likely hinder it. This option exists in order to allow using fewer threads than the hardware concurrency, in cases where you wish to leave some threads available for other processes. For example:
// Constructs a thread pool with only 12 threads.
BS::thread_pool pool(12);
Usually, when the thread pool is used, a program’s main thread should only submit tasks to the thread pool and wait for them to finish, and should not perform any computationally intensive tasks on its own. If this is the case, it is recommended to use the default value for the number of threads. This ensures that all the threads available in the hardware will be put to work while the main thread waits.
However, if the main thread also performs computationally intensive tasks, it may be beneficial to use one fewer thread than the hardware concurrency, leaving one hardware thread available for the main thread. Furthermore, if more than one thread pool is used in the program simultaneously, the total number of threads across all pools should not exceed the hardware concurrency.
Note: If the native extensions are enabled, a pool created with the default constructor will only use the number of threads available to the process, as obtained from BS::get_os_process_affinity(), which can be less than the number of hardware threads.
Getting and resetting the number of threads in the pool
The member function get_thread_count() returns the number of threads in the pool. This will be equal to std::thread::hardware_concurrency() if the default constructor was used (or to BS::get_os_process_affinity() if the native extensions are enabled).
It is generally unnecessary to change the number of threads in the pool after it has been created, since the whole point of a thread pool is that you only create the threads once. However, if needed, this can be done, safely and on-the-fly, using the reset() member function.
reset() will wait for all tasks to be completed, both those that are currently running in the threads and those that are still waiting in the queue. Then it will destroy the thread pool and create a new one with the desired new number of threads, as specified in the function’s argument (if no argument is given, it behaves like the default constructor), with an empty task queue.
If pausing is enabled (see below), reset() will only wait for tasks that are currently running before destroying the pool; once the pool is reset, it will then resume executing the tasks that remained in the queue and any newly submitted tasks. If the pool was paused before resetting it, the new pool will be paused as well. reset() can also be used to change the thread initialization function (see below).
The member function get_thread_ids() returns a vector containing the unique identifiers for each of the pool’s threads, as obtained by std::thread::get_id(). These values are not so useful on their own, but can be used to identify and distinguish between threads, or for allocating resources.
Submitting tasks to the queue
Submitting tasks with no arguments and receiving a future
In this section we will learn how to submit a task with no arguments, but potentially with a return value, to the queue. Once a task has been submitted, it will be executed as soon as a thread becomes available. Tasks are executed in the order that they were submitted (first-in, first-out), unless task priority is enabled (see below).
For example, if the pool has 8 threads and an empty queue, and we submitted 16 tasks, then we should expect the first 8 tasks to be executed in parallel, with the remaining tasks being picked up by the threads one by one as each thread finishes executing its first task, until no tasks are left in the queue.
The member function submit_task() is used to submit tasks to the queue. It takes exactly one input, the task to submit. This task must be a function with no arguments, but it can have a return value.
submit_task() returns an std::future associated to the task. If the submitted task has a return value of type T, then the future will be of type std::future<T>, and will be set to the task’s return value when the task finishes its execution. If the submitted task does not have a return value, then the future will be an std::future<void>, which will not contain any value, but may still be used to wait for the task to finish.
To wait until the task finishes, use the member function wait() of the future. To obtain the return value, use the member function get(), which will also automatically wait for the task to finish if it hasn’t yet. Here is a simple example:
#include "BS_thread_pool.hpp" // BS::thread_pool
#include <future> // std::future
#include <iostream> // std::cout
int the_answer()
{
return 42;
}
int main()
{
BS::thread_pool pool;
std::future<int> my_future = pool.submit_task(the_answer);
std::cout << my_future.get() << '\n';
}
In this example we submitted the function the_answer(), which returns an int. The member function submit_task() of the pool therefore returned an std::future<int>. We then used the get() member function of the future to get the return value, and printed it out.
In addition to submitting a pre-defined function, we can also use a lambda expression to quickly define the task on-the-fly. Rewriting the previous example in terms of a lambda expression, we get:
#include "BS_thread_pool.hpp" // BS::thread_pool
#include <future> // std::future
#include <iostream> // std::cout
int main()
{
BS::thread_pool pool;
std::future<int> my_future = pool.submit_task([]{ return 42; });
std::cout << my_future.get() << '\n';
}
Here, the lambda expression []{ return 42; } has two parts:
- An empty capture clause, denoted by
[]. This signifies to the compiler that a lambda expression is being defined.
- A code block
{ return 42; } that simply returns the value 42.
It is generally simpler and faster to submit lambda expressions rather than pre-defined functions, especially due to the ability to capture local variables, which we will discuss in the next section.
Of course, tasks do not have to return values. In the following example, we submit a function with no return value and then using the future to wait for it to finish executing:
#include "BS_thread_pool.hpp" // BS::thread_pool
#include <chrono> // std::chrono
#include <future> // std::future
#include <iostream> // std::cout
#include <thread> // std::this_thread
int main()
{
BS::thread_pool pool;
const std::future<void> my_future = pool.submit_task(
[]
{
std::this_thread::sleep_for(std::chrono::milliseconds(500));
});
std::cout << "Waiting for the task to complete... ";
my_future.wait();
std::cout << "Done." << '\n';
}
Here we split the lambda into multiple lines to make it more readable. The command std::this_thread::sleep_for(std::chrono::milliseconds(500)) instructs the task to simply sleep for 500 milliseconds, simulating a computationally-intensive task.
Submitting tasks with arguments and receiving a future
As stated in the previous section, tasks submitted using submit_task() cannot have any arguments. However, it is easy to submit tasks with arguments either by wrapping the function in a lambda or using lambda captures directly. The following is an example of submitting a pre-defined function with arguments by wrapping it in a lambda:
#include "BS_thread_pool.hpp" // BS::thread_pool
#include <future> // std::future
#include <iostream> // std::cout
double multiply(const double lhs, const double rhs)
{
return lhs * rhs;
}
int main()
{
BS::thread_pool pool;
std::future<double> my_future = pool.submit_task(
[]
{
return multiply(6, 7);
});
std::cout << my_future.get() << '\n';
}
As you can see, to pass the arguments to multiply() we simply called multiply(6, 7) explicitly inside a lambda. If the arguments are not literals, we can use the lambda capture clause to capture the arguments from the local scope:
#include "BS_thread_pool.hpp" // BS::thread_pool
#include <future> // std::future
#include <iostream> // std::cout
double multiply(const double lhs, const double rhs)
{
return lhs * rhs;
}
int main()
{
BS::thread_pool pool;
constexpr double first = 6;
constexpr double second = 7;
std::future<double> my_future = pool.submit_task(
[first, second]
{
return multiply(first, second);
});
std::cout << my_future.get() << '\n';
}
We could even get rid of the multiply() function entirely and just put everything inside a lambda, if desired:
#include "BS_thread_pool.hpp" // BS::thread_pool
#include <future> // std::future
#include <iostream> // std::cout
int main()
{
BS::thread_pool pool;
constexpr double first = 6;
constexpr double second = 7;
std::future<double> my_future = pool.submit_task(
[first, second]
{
return first * second;
});
std::cout << my_future.get() << '\n';
}
Detaching and waiting for tasks
Usually, it is best to submit a task to the queue using submit_task(). This allows you to wait for the task to finish and/or get its return value later. However, sometimes a future is not needed, for example when you just want to “set and forget” a certain task, or if the task already communicates with the main thread or with other tasks without using futures, such as via condition variables.
In such cases, you may wish to avoid the overhead involved in assigning a future to the task, in order to increase performance. This is called “detaching” the task, as the task detaches from the main thread and runs independently.
Detaching tasks is done using the detach_task() member function, which allows you to detach a task to the queue without generating a future for it. As with submit_task(), the task must have no arguments, but you can pass arguments by wrapping it in a lambda, as shown in the previous section. However, tasks executed via detach_task() cannot have a return value, as there would be no way for the main thread to retrieve that value.
Since detach_task() does not return a future, there is no built-in way for the user to know when the task finishes executing. You must manually ensure that the task finishes executing before trying to use anything that depends on its output. Otherwise, bad things will happen!
BS::thread_pool provides the member function wait() to facilitate waiting for all the tasks in the queue to complete, whether they were detached or submitted with a future. The wait() member function works similarly to the wait() member function of std::future. Consider, for example, the following code:
#include "BS_thread_pool.hpp" // BS::thread_pool
#include <chrono> // std::chrono
#include <iostream> // std::cout
#include <thread> // std::this_thread
int main()
{
BS::thread_pool pool;
int result = 0;
pool.detach_task(
[&result]
{
std::this_thread::sleep_for(std::chrono::milliseconds(100));
result = 42;
});
std::cout << result << '\n';
}
This program first defines a local variable named result and initializes it to 0. It then detaches a task in the form of a lambda expression. Note that the lambda captures result by reference, as indicated by the & in front of it. This means that the task can modify result, and any such modification will be reflected in the main thread.
The task changes result to 42, but it first sleeps for 100 milliseconds. When the main thread prints out the value of result, the task has not yet had time to modify its value, since it is still sleeping. Therefore, the program will actually print out the initial value 0, which is not what we want.
To wait for the task to complete, we must use the wait() member function after detaching it:
#include "BS_thread_pool.hpp" // BS::thread_pool
#include <chrono> // std::chrono
#include <iostream> // std::cout
#include <thread> // std::this_thread
int main()
{
BS::thread_pool pool;
int result = 0;
pool.detach_task(
[&result]
{
std::this_thread::sleep_for(std::chrono::milliseconds(100));
result = 42;
});
pool.wait();
std::cout << result << '\n';
}
Now the program will print out the value 42, as expected. Note, however, that wait() will wait for all the tasks in the queue, including any other tasks that were potentially submitted before or after the one we care about. If we want to wait just for one task, submit_task() would be a better choice.
Waiting for submitted or detached tasks with a timeout
Sometimes you may wish to wait for the tasks to complete, but only for a certain amount of time, or until a specific point in time. For example, if the tasks have not yet completed after some time, you may wish to let the user know that there is a delay.
For tasks submitted with futures using submit_task(), this can be achieved using two member functions of std::future:
wait_for() waits for the task to be completed, but stops waiting after the specified duration, given as an argument of type std::chrono::duration, has passed.
wait_until() waits for the task to be completed, but stops waiting after the specified time point, given as an argument of type std::chrono::time_point, has been reached.
In both cases, the functions will return std::future_status::ready if the future is ready, meaning the task is finished and its return value, if any, has been obtained. However, they will return std::future_status::timeout if the future is not yet ready when the timeout has expired.
Here is an example:
#include "BS_thread_pool.hpp" // BS::thread_pool
#include <chrono> // std::chrono
#include <future> // std::future
#include <iostream> // std::cout
#include <thread> // std::this_thread
int main()
{
BS::thread_pool pool;
const std::future<void> my_future = pool.submit_task(
[]
{
std::this_thread::sleep_for(std::chrono::milliseconds(1000));
std::cout << "Task done!\n";
});
while (true)
{
if (my_future.wait_for(std::chrono::milliseconds(200)) != std::future_status::ready)
std::cout << "Sorry, the task is not done yet.\n";
else
break;
}
}
The output should look similar to this:
Sorry, the task is not done yet.
Sorry, the task is not done yet.
Sorry, the task is not done yet.
Sorry, the task is not done yet.
Task done!
For detached tasks, since we do not have futures for them, we cannot use this method. However, BS::thread_pool has two member functions, also named wait_for() and wait_until(), which similarly wait for a specified duration or until a specified time point, but do so for all tasks (whether submitted or detached). Instead of an std::future_status, the thread pool’s wait functions return true if all tasks finished running, or false if the duration expired or the time point was reached but some tasks are still running.
Here is the same example as above, using detach_task() and pool.wait_for():
#include "BS_thread_pool.hpp" // BS::thread_pool
#include <chrono> // std::chrono
#include <iostream> // std::cout
#include <thread> // std::this_thread
int main()
{
BS::thread_pool pool;
pool.detach_task(
[]
{
std::this_thread::sleep_for(std::chrono::milliseconds(1000));
std::cout << "Task done!\n";
});
while (true)
{
if (!pool.wait_for(std::chrono::milliseconds(200)))
std::cout << "Sorry, the task is not done yet.\n";
else
break;
}
}
Class member functions as tasks
Let us consider the following program:
#include <iostream> // std::boolalpha, std::cout
class flag_class
{
public:
[[nodiscard]] bool get_flag() const
{
return flag;
}
void set_flag(const bool arg)
{
flag = arg;
}
private:
bool flag = false;
};
int main()
{
flag_class flag_object;
flag_object.set_flag(true);
std::cout << std::boolalpha << flag_object.get_flag() << '\n';
}
This program creates a new object flag_object of the class flag_class, sets the flag to true using the setter member function set_flag(), and then prints out the flag’s value using the getter member function get_flag().
What if we want to submit the member function set_flag() as a task to the thread pool? We can simply wrap the entire statement flag_object.set_flag(true); in a lambda, and pass flag_object to the lambda by reference, as in the following example:
#include "BS_thread_pool.hpp" // BS::thread_pool
#include <iostream> // std::boolalpha, std::cout
class flag_class
{
public:
[[nodiscard]] bool get_flag() const
{
return flag;
}
void set_flag(const bool arg)
{
flag = arg;
}
private:
bool flag = false;
};
int main()
{
BS::thread_pool pool;
flag_class flag_object;
pool.submit_task(
[&flag_object]
{
flag_object.set_flag(true);
})
.wait();
std::cout << std::boolalpha << flag_object.get_flag() << '\n';
}
Of course, this will also work with detach_task(), if we call wait() on the pool itself instead of on the returned future.
Note that in this example, instead of getting a future from submit_task() and then waiting for that future, we simply called wait() on that future straight away. This is a common way of waiting for a task to complete if we have nothing else to do in the meantime. Note also that we passed flag_object by reference to the lambda, since we want to set the flag on that same object, not a copy of it.
Another thing you might want to do is call a member function from within the object itself, that is, from another member function. This follows a similar syntax, except that you must also capture this (i.e. a pointer to the current object) in the lambda. Here is an example:
#include "BS_thread_pool.hpp" // BS::thread_pool
#include <iostream> // std::boolalpha, std::cout
BS::thread_pool pool;
class flag_class
{
public:
[[nodiscard]] bool get_flag() const
{
return flag;
}
void set_flag(const bool arg)
{
flag = arg;
}
void set_flag_to_true()
{
pool.submit_task(
[this]
{
set_flag(true);
})
.wait();
}
private:
bool flag = false;
};
int main()
{
flag_class flag_object;
flag_object.set_flag_to_true();
std::cout << std::boolalpha << flag_object.get_flag() << '\n';
}
Note that in this example we defined the thread pool as a global object, so that it is accessible outside the main() function. Although we could have, in theory, passed a reference to the thread pool in our call to set_flag_to_true(), that would be very cumbersome to do if multiple different functions need to use the same thread pool. Defining the thread pool as a global object is common practice, as it allows all functions to access the same thread pool without having to pass it around as an argument.
Parallelizing loops
Automatic parallelization of loops
One of the most common and effective methods of parallelization is splitting a loop into smaller sub-loops and running them in parallel. It is most effective in “embarrassingly parallel” computations, such as vector or matrix operations, where each iteration of the loop is completely independent of every other iteration.
For example, if we are summing up two vectors of 1000 elements each, and we have 10 threads, we could split the summation into 10 blocks of 100 elements each, and run all the blocks in parallel, potentially increasing performance by up to a factor of 10.
BS::thread_pool can automatically parallelize loops, making it very easy to implement many parallel algorithms without having to worry about the details. To see how this works, consider the following generic loop:
for (T i = start; i < end; ++i)
loop(i);
where:
T is any signed or unsigned integer type.
- The loop is over the range
[start, end), i.e. inclusive of start but exclusive of end.
loop() is an operation performed for each loop index i, such as modifying an array with end - start elements.
This loop may be automatically parallelized and submitted to the thread pool’s queue using the member function submit_loop(), which has the following syntax:
pool.submit_loop(start, end, loop, num_blocks);
where:
start is the first index in the range.
end is the index after the last index in the range, such that the full range is [start, end). In other words, the loop will be equivalent to the generic loop above, but parallelized. Note that if end <= start, nothing will happen; the loop cannot go backwards.
loop() is the function that should run in every iteration of the loop. It must take exactly one argument, the loop index. It cannot have a return value, as it will be executed multiple times by each task, so a return value would not make sense.
num_blocks is the number of blocks of the form [a, b) to split the loop into. For example, if the range is [0, 9) and there are 3 blocks, then the blocks will be the ranges [0, 3), [3, 6), and [6, 9). This argument can be omitted, in which case the number of blocks will be the number of threads in the pool.
The thread pool’s internal algorithm ensures that each of the blocks has one of two sizes, differing by 1, with the larger blocks always first, so that the tasks are as evenly distributed as possible, to optimize performance. For example, if the range [0, 100) is split into 15 blocks, the result will be 10 blocks of size 7, which will be submitted first, and 5 blocks of size 6.
Each block will be submitted to the thread pool’s queue as a separate task. Therefore, a loop that is split into 3 blocks will be split into 3 individual tasks, which may run in parallel. If there is only one block, then the entire loop will run as one task, and no parallelization will take place.
To parallelize the generic loop above, we use the following commands:
BS::multi_future<void> loop_future = pool.submit_loop(start, end, loop, num_blocks);
loop_future.wait();
submit_loop() returns an object of the helper class BS::multi_future<T>. This is essentially a specialization of std::vector<std::future<T>> with additional member functions. Each of the num_blocks blocks will have an std::future<T> assigned to it, and all these futures will be stored inside the returned BS::multi_future<T>. When loop_future.wait() is called, the main thread will wait until all tasks generated by submit_loop() finish executing, and only those tasks - not any other tasks that also happen to be in the queue. This is essentially the role of the BS::multi_future<T> class: to wait for a specific group of tasks, in this case the tasks running the loop blocks.
As a simple example, the following code calculates and prints a table of squares of all integers from 0 to 99:
#include <cstddef> // std::size_t
#include <iomanip> // std::setw
#include <iostream> // std::cout
int main()
{
constexpr std::size_t max = 100;
std::size_t squares[max];
for (std::size_t i = 0; i < max; ++i)
squares[i] = i * i;
for (std::size_t i = 0; i < max; ++i)
std::cout << std::setw(2) << i << "^2 = " << std::setw(4) << squares[i] << ((i % 5 != 4) ? " | " : "\n");
}
We can parallelize it as follows:
#include "BS_thread_pool.hpp" // BS::multi_future, BS::thread_pool
#include <cstddef> // std::size_t
#include <iomanip> // std::setw
#include <iostream> // std::cout
int main()
{
BS::thread_pool pool(10);
constexpr std::size_t max = 100;
std::size_t squares[max];
const BS::multi_future<void> loop_future = pool.submit_loop(0, max,
[&squares](const std::size_t i)
{
squares[i] = i * i;
});
loop_future.wait();
for (std::size_t i = 0; i < max; ++i)
std::cout << std::setw(2) << i << "^2 = " << std::setw(4) << squares[i] << ((i % 5 != 4) ? " | " : "\n");
}
Since there are 10 threads, and we omitted the num_blocks argument, the loop will be divided into 10 blocks, each calculating 10 squares.
As a side note, notice that here we parallelized the calculation of the squares, but we did not parallelize printing the results. This is for two reasons:
- We want to print out the squares in ascending order, and we have no guarantee that the blocks will be executed in the correct order. This is very important; you must never expect that the parallelized loop will execute at the same order as the non-parallelized loop.
- If we did print out the squares from within the parallel tasks, we would get a huge mess, since all 10 blocks would print to the standard output at once. Later we will see how to synchronize printing to a stream from multiple tasks at the same time.
Optimizing the number of blocks
The most important factor to consider when parallelizing loops is the number of blocks num_blocks to split the loop into. Naively, it may seem that the number of blocks should simply be equal to the number of threads in the pool, but that is usually not the optimal choice. Inevitably, some blocks will finish before other blocks; if there is only one block per thread, then any threads that have already finished executing their blocks will remain idle until the rest of the blocks are done, wasting many CPU cycles.
It is therefore generally better to use a larger number of blocks than the number of threads, to ensure that all threads work at maximum capacity. On the other hand, parallelization with too many blocks will eventually suffer from diminishing returns due to increased overhead. A good rule of thumb is to use a number of blocks equal to the square of the number of threads, but this is not necessarily the optimal number in all cases.
In the end, the optimal number of blocks will always depend on the specific algorithm being parallelized and the total number of indices in the loop, and may differ between different compilers, operating systems, and hardware configurations. For best performance, it is strongly recommended to do your own benchmarks to find the optimal number of blocks for your particular use case; see the benchmarks code in the bundled test program for an example of how to do this.
Finally, note that the discussion here only pertains to situations where the parallelized loop is the only thing running in the pool. If there are many other tasks running in parallel from other sources, then you probably do not need to worry about idle time, since the threads will be kept busy by the other tasks anyway.
Common index types
Let us now consider a subtlety regarding the types of the start and end indices. In the example above, the start index is 0, which is of type int, while the end index is max, which is of type std::size_t. These two types are not compatible, as they are both of different signedness and (on a 64-bit system) of different bit width. In such cases, submit_loop() uses a custom type trait BS::common_index_type to determine the common type of the indices.
The common index type of two signed integers or two unsigned integers is the larger of the integers, while the common index type of a signed and an unsigned integer is a signed integer that can hold the full ranges of both integers. (This is in contrast to std::common_type, which would choose the unsigned integer in the latter case, causing a loop with a negative start index and an unsigned end index to fail due to integer overflow.)
The exception to this rule is when one of the integers is a 64-bit unsigned integer, and the other is a signed integer (of any bit width), since there is no fundamental signed type that can hold the full ranges of both integers. In this case, we choose a 64-bit unsigned integer as the common index type, since the most common scenario where this might happen is when the indices go from 0 to an index of type std::size_t - as in our example in the previous section.
However, it is important to note that this will fail if the first index is in fact negative. Therefore, only in the edge case where one index is a negative integer and the other is of an unsigned 64-bit integer type such as std::size_t, the user must cast both indices explicitly to the desired common type. In all other cases, this is handled automatically behind the scenes using BS::common_index_type.
Parallelizing loops without futures
Just as in the case of detach_task() vs. submit_task(), sometimes you may want to parallelize a loop, but you don’t need it to return a BS::multi_future. In this case, you can save the overhead of generating the futures (which can be significant, depending on the number of blocks) by using detach_loop() instead of submit_loop(), with the same arguments.
For example, we could detach the loop of squares example above as follows:
#include "BS_thread_pool.hpp" // BS::thread_pool
#include <cstddef> // std::size_t
#include <iomanip> // std::setw
#include <iostream> // std::cout
int main()
{
BS::thread_pool pool(10);
constexpr std::size_t max = 100;
std::size_t squares[max];
pool.detach_loop(0, max,
[&squares](const std::size_t i)
{
squares[i] = i * i;
});
pool.wait();
for (std::size_t i = 0; i < max; ++i)
std::cout << std::setw(2) << i << "^2 = " << std::setw(4) << squares[i] << ((i % 5 != 4) ? " | " : "\n");
}
Warning: Since detach_loop() does not return a BS::multi_future, there is no built-in way for the user to know when the loop finishes executing. You must use either wait() as we did here, or some other method such as condition variables, to ensure that the loop finishes executing before trying to use anything that depends on its output. Otherwise, bad things will happen! If the loop is the only thing running in the pool, then generally detach_loop() followed by wait() is the optimal choice in terms of performance.
Parallelizing individual indices vs. blocks
We have seen that detach_loop() and submit_loop() execute the function loop(i) for each index i in the loop. However, behind the scenes, the loop is split into blocks, and each block executes the loop() function multiple times. Each block has an internal loop of the form (where T is the type of the indices):
for (T i = start; i < end; ++i)
loop(i);
The start and end indices of each block are determined automatically by the pool. For example, in the previous section, the loop from 0 to 100 was split into 10 blocks of 10 indices each: start = 0 to end = 10, start = 10 to end = 20, and so on; the blocks are not inclusive of the last index, since the for loop has the condition i < end and not i <= end.
However, this also means that the loop() function is executed multiple times per block. This generates additional overhead due to the multiple function calls. For short loops, this should not affect performance. However, for very long loops, with millions of indices, the performance cost may be significant.
For this reason, the thread pool library provides two additional member functions for parallelizing loops: detach_blocks() and submit_blocks(). While detach_loop() and submit_loop() execute a function loop(i) once per index but multiple times per block, detach_blocks() and submit_blocks() execute a function block(start, end) only once per block.
The main advantage of this method is increased performance, but the main disadvantage is slightly more complicated code. In particular, the user must define the loop from start to end manually within each block, ensuring that all the indices in the block are handled. Here is the previous example again, this time using detach_blocks():
#include "BS_thread_pool.hpp" // BS::thread_pool
#include <cstddef> // std::size_t
#include <iomanip> // std::setw
#include <iostream> // std::cout
int main()
{
BS::thread_pool pool(10);
constexpr std::size_t max = 100;
std::size_t squares[max];
pool.detach_blocks(0, max,
[&squares](const std::size_t start, const std::size_t end)
{
for (std::size_t i = start; i < end; ++i)
squares[i] = i * i;
});
pool.wait();
for (std::size_t i = 0; i < max; ++i)
std::cout << std::setw(2) << i << "^2 = " << std::setw(4) << squares[i] << ((i % 5 != 4) ? " | " : "\n");
}
Note how the block function takes two arguments, and includes the internal loop. Also, since we are using detach_blocks(), we must wait for the loop to finish executing using wait(). Alternatively, we could have used submit_blocks() and waited on the returned BS::multi_future<void> object.
Generally, compiler optimizations should be able to make detach_loop() and submit_loop() perform roughly the same as detach_blocks() and submit_blocks(). However, detach_blocks() and submit_blocks() are always going to be inherently faster, at the cost of being slightly more complicated to use. In addition, having low-level control of each block can allow for further optimizations, such as allocating resources per block instead of per index. As usual, you should perform your own benchmarks to see which option works best for your particular use case.
Loops with return values
As mentioned above, unlike submit_task(), the member function submit_loop() only takes loop functions with no return value. The reason is that each block is running the loop function multiple times, so a return value would not make sense. In contrast, submit_blocks() allows the block function to have a return value, as each block can return a unique value.
The block function will be executed once for each block, but the blocks are managed by the thread pool, with the user only able to select the number of blocks, but not the range of each block. Therefore, there is limited usability in returning one value per block. However, for cases where this is desired, such as for summation or some sorting algorithms, submit_blocks() does accept functions with return values, in which case it returns a BS::multi_future<T> object where T is the type of the return value.
Here’s an example of a function template summing all elements of type T in a given range:
#include "BS_thread_pool.hpp" // BS::multi_future, BS::thread_pool
#include <cstdint> // std::uint64_t
#include <future> // std::future
#include <iostream> // std::cout
BS::thread_pool pool;
template <typename T>
T sum(T min, T max)
{
BS::multi_future<T> loop_future = pool.submit_blocks(
min, max + 1,
[](const T start, const T end)
{
T block_total = 0;
for (T i = start; i < end; ++i)
block_total += i;
return block_total;
},
100);
T result = 0;
for (std::future<T>& future : loop_future)
result += future.get();
return result;
}
int main()
{
std::cout << sum<std::uint64_t>(1, 1'000'000);
}
Note that we needed to specify the type T explicitly as std::uint64_t, that is, an unsigned 64-bit integer, as the result, 500,000,500,000, would not fit in a 32-bit integer.
Here we used the fact that BS::multi_future<T> is a specialization of std::vector<std::future<T>>, so we can use a range-based for loop to iterate over the futures, and use the get() member function of each future to get its value. The values of the futures will be the partial sums from each block, so when we add them up, we will get the total sum. Note that we divided the loop into 100 blocks, so there will be 100 futures in total, each with the partial sum of 10,000 numbers.
The range-based for loop will likely start before the loop finished executing, and each time it calls a future, it will get the value of that future if it is ready, or it will wait until the future is ready and then get the value. This increases performance, since we can start summing the results without waiting for the entire loop to finish executing first - we only need to wait for individual blocks.
If we did want to wait until the entire loop finishes before summing the results, we could have used the get() member function of the BS::multi_future<T> object itself, which returns an std::vector<T> with the values obtained from each future. In that case, the sum could be obtained after calling submit_blocks(), for example using std::reduce, as follows:
#include "BS_thread_pool.hpp" // BS::multi_future, BS::thread_pool
#include <cstdint> // std::uint64_t
#include <iostream> // std::cout
#include <numeric> // std::reduce
#include <vector> // std::vector
BS::threa</vector></numeric></iostream></cstdint></t></t></std::future></t></sum></end></t></typename></iostream></future></max></void></iostream></iomanip></max></iostream></iomanip></cstddef></t></t></t></std::future></t></std::boolalpha></iostream></thread></iostream></chrono></void></thread></iostream></future></result></thread></iostream></result></thread></iostream></my_future></double></iostream></my_future></double></iostream></my_future></double></iostream></future></void></thread></iostream></future></my_future></int></iostream></future></my_future></int></iostream></future></void></t></https:></baraksh>
> README 内容过长,已截取前 64 KB。完整内容请前往 GitHub 仓库查看。
评论