1
0
mirror of https://github.com/bshoshany/thread-pool.git synced 2026-07-23 12:02:59 +04:00

4 Commits

Author SHA1 Message Date
Barak Shoshany cabb3df587 Updated to v3.5.0 2023-05-25 22:58:28 -04:00
Barak Shoshany 87d415f89c Updated to v3.4.0 2023-05-12 14:45:07 -04:00
Barak Shoshany 67fad04348 Updated to v3.3.0 2022-08-03 14:23:38 -04:00
Barak Shoshany 670e3ab3ed Updated to v3.2.0 2022-07-28 22:20:07 -04:00
12 changed files with 3762 additions and 1730 deletions
+190
View File
@@ -0,0 +1,190 @@
---
Language: Cpp
AccessModifierOffset: -4
AlignAfterOpenBracket: Align
AlignArrayOfStructures: None
AlignConsecutiveMacros: None
AlignConsecutiveAssignments: None
AlignConsecutiveBitFields: None
AlignConsecutiveDeclarations: None
AlignEscapedNewlines: Right
AlignOperands: Align
AlignTrailingComments: true
AllowAllArgumentsOnNextLine: true
AllowAllParametersOfDeclarationOnNextLine: true
AllowShortEnumsOnASingleLine: true
AllowShortBlocksOnASingleLine: Never
AllowShortCaseLabelsOnASingleLine: false
AllowShortFunctionsOnASingleLine: Empty
AllowShortLambdasOnASingleLine: All
AllowShortIfStatementsOnASingleLine: Never
AllowShortLoopsOnASingleLine: false
AlwaysBreakAfterDefinitionReturnType: None
AlwaysBreakAfterReturnType: None
AlwaysBreakBeforeMultilineStrings: false
AlwaysBreakTemplateDeclarations: Yes
AttributeMacros:
- __capability
BinPackArguments: true
BinPackParameters: true
BraceWrapping:
AfterCaseLabel: false
AfterClass: false
AfterControlStatement: Never
AfterEnum: false
AfterFunction: false
AfterNamespace: false
AfterObjCDeclaration: false
AfterStruct: false
AfterUnion: false
AfterExternBlock: false
BeforeCatch: false
BeforeElse: false
BeforeLambdaBody: false
BeforeWhile: false
IndentBraces: false
SplitEmptyFunction: true
SplitEmptyRecord: true
SplitEmptyNamespace: true
BreakBeforeBinaryOperators: None
BreakBeforeConceptDeclarations: true
BreakBeforeBraces: Allman
BreakBeforeInheritanceComma: false
BreakInheritanceList: BeforeColon
BreakBeforeTernaryOperators: true
BreakConstructorInitializersBeforeComma: false
BreakConstructorInitializers: BeforeColon
BreakAfterJavaFieldAnnotations: false
BreakStringLiterals: true
ColumnLimit: 10000
CommentPragmas: "^ IWYU pragma:"
QualifierAlignment: Leave
CompactNamespaces: false
ConstructorInitializerIndentWidth: 4
ContinuationIndentWidth: 4
Cpp11BracedListStyle: true
DeriveLineEnding: true
DerivePointerAlignment: false
DisableFormat: false
EmptyLineAfterAccessModifier: Never
EmptyLineBeforeAccessModifier: LogicalBlock
ExperimentalAutoDetectBinPacking: false
PackConstructorInitializers: BinPack
BasedOnStyle: ""
ConstructorInitializerAllOnOneLineOrOnePerLine: false
AllowAllConstructorInitializersOnNextLine: true
FixNamespaceComments: true
ForEachMacros:
- foreach
- Q_FOREACH
- BOOST_FOREACH
IfMacros:
- KJ_IF_MAYBE
IncludeBlocks: Preserve
IncludeCategories:
- Regex: '^"(llvm|llvm-c|clang|clang-c)/'
Priority: 2
SortPriority: 0
CaseSensitive: false
- Regex: '^(<|"(gtest|gmock|isl|json)/)'
Priority: 3
SortPriority: 0
CaseSensitive: false
- Regex: ".*"
Priority: 1
SortPriority: 0
CaseSensitive: false
IncludeIsMainRegex: "(Test)?$"
IncludeIsMainSourceRegex: ""
IndentAccessModifiers: false
IndentCaseLabels: false
IndentCaseBlocks: false
IndentGotoLabels: true
IndentPPDirectives: None
IndentExternBlock: AfterExternBlock
IndentRequires: false
IndentWidth: 4
IndentWrappedFunctionNames: false
InsertTrailingCommas: None
JavaScriptQuotes: Leave
JavaScriptWrapImports: true
KeepEmptyLinesAtTheStartOfBlocks: true
LambdaBodyIndentation: Signature
MacroBlockBegin: ""
MacroBlockEnd: ""
MaxEmptyLinesToKeep: 1
NamespaceIndentation: None
ObjCBinPackProtocolList: Auto
ObjCBlockIndentWidth: 4
ObjCBreakBeforeNestedBlockParam: true
ObjCSpaceAfterProperty: false
ObjCSpaceBeforeProtocolList: true
PenaltyBreakAssignment: 2
PenaltyBreakBeforeFirstCallParameter: 19
PenaltyBreakComment: 300
PenaltyBreakFirstLessLess: 120
PenaltyBreakOpenParenthesis: 0
PenaltyBreakString: 1000
PenaltyBreakTemplateDeclaration: 10
PenaltyExcessCharacter: 1000000
PenaltyReturnTypeOnItsOwnLine: 60
PenaltyIndentedWhitespace: 0
PointerAlignment: Left
PPIndentWidth: -1
ReferenceAlignment: Pointer
ReflowComments: true
RemoveBracesLLVM: false
SeparateDefinitionBlocks: Leave
ShortNamespaceLines: 1
SortIncludes: CaseSensitive
SortJavaStaticImport: Before
SortUsingDeclarations: true
SpaceAfterCStyleCast: false
SpaceAfterLogicalNot: false
SpaceAfterTemplateKeyword: true
SpaceBeforeAssignmentOperators: true
SpaceBeforeCaseColon: false
SpaceBeforeCpp11BracedList: true
SpaceBeforeCtorInitializerColon: true
SpaceBeforeInheritanceColon: true
SpaceBeforeParens: ControlStatements
SpaceBeforeParensOptions:
AfterControlStatements: true
AfterForeachMacros: true
AfterFunctionDefinitionName: false
AfterFunctionDeclarationName: false
AfterIfMacros: true
AfterOverloadedOperator: false
BeforeNonEmptyParentheses: false
SpaceAroundPointerQualifiers: Default
SpaceBeforeRangeBasedForLoopColon: true
SpaceInEmptyBlock: false
SpaceInEmptyParentheses: false
SpacesBeforeTrailingComments: 1
SpacesInAngles: Never
SpacesInConditionalStatement: false
SpacesInContainerLiterals: true
SpacesInCStyleCastParentheses: false
SpacesInLineCommentPrefix:
Minimum: 1
Maximum: -1
SpacesInParentheses: false
SpacesInSquareBrackets: false
SpaceBeforeSquareBrackets: false
BitFieldColonSpacing: Both
Standard: Latest
StatementAttributeLikeMacros:
- Q_EMIT
StatementMacros:
- Q_UNUSED
- QT_REQUIRE_VERSION
TabWidth: 4
UseCRLF: false
UseTab: Never
WhitespaceSensitiveMacros:
- STRINGIZE
- PP_STRINGIZE
- BOOST_PP_STRINGIZE
- NS_SWIFT_NAME
- CF_SWIFT_NAME
---
+7 -1
View File
@@ -6,9 +6,15 @@
What does your pull request fix or add to the library?
**Style**
Have you formatted your code using the `.clang-format` file attached to this project?
**Testing**
Have you tested the new code using the provided automated test program and/or performed any other tests to ensure that it works correctly? If so, please provide information about the test system(s):
Have you tested the new code using the provided automated test program `BS_thread_pool_test.cpp` (preferably with the provided multi-compiler test script `BS_thread_pool_test.ps1`) and/or performed any other tests to ensure that the new code works correctly?
If so, please provide information about the test system(s):
* CPU model, architecture, # of cores and threads:
* Operating system:
+1
View File
@@ -0,0 +1 @@
build
-536
View File
@@ -1,536 +0,0 @@
#pragma once
/**
* @file BS_thread_pool.hpp
* @author Barak Shoshany (baraksh@gmail.com) (http://baraksh.com)
* @version 3.1.0
* @date 2022-07-13
* @copyright Copyright (c) 2022 Barak Shoshany. Licensed under the MIT license. If you found this project useful, please consider starring it on GitHub! If you use this library in software of any kind, please provide a link to the GitHub repository https://github.com/bshoshany/thread-pool in the source code and documentation. If you use this library in published research, please cite it as follows: Barak Shoshany, "A C++17 Thread Pool for High-Performance Scientific Computing", doi:10.5281/zenodo.4742687, arXiv:2105.00613 (May 2021)
*
* @brief BS::thread_pool: a fast, lightweight, and easy-to-use C++17 thread pool library. This header file contains the entire library, including the main BS::thread_pool class and the helper classes BS::multi_future, BS:synced_stream, and BS::timer.
*/
#define BS_THREAD_POOL_VERSION "v3.1.0 (2022-07-13)"
#include <atomic> // std::atomic
#include <chrono> // std::chrono
#include <condition_variable> // std::condition_variable
#include <exception> // std::current_exception
#include <functional> // std::function
#include <future> // std::future, std::promise
#include <iostream> // std::cout, std::ostream
#include <memory> // std::make_shared, std::make_unique, std::shared_ptr, std::unique_ptr
#include <mutex> // std::mutex, std::scoped_lock, std::unique_lock
#include <queue> // std::queue
#include <thread> // std::thread
#include <type_traits> // std::common_type_t, std::decay_t, std::is_void_v, std::invoke_result_t
#include <utility> // std::move, std::swap
#include <vector> // std::vector
namespace BS
{
using concurrency_t = std::invoke_result_t<decltype(std::thread::hardware_concurrency)>;
// ============================================================================================= //
// Begin class multi_future //
/**
* @brief A helper class to facilitate waiting for and/or getting the results of multiple futures at once.
*/
template <typename T>
class [[nodiscard]] multi_future
{
public:
/**
* @brief Construct a multi_future object with the given number of futures.
*
* @param num_futures_ The desired number of futures to store.
*/
multi_future(const size_t num_futures_ = 0) : f(num_futures_) {}
/**
* @brief Get the results from all the futures stored in this multi_future object.
*
* @return A vector containing the results.
*/
[[nodiscard]] std::vector<T> get()
{
std::vector<T> results(f.size());
for (size_t i = 0; i < f.size(); ++i)
results[i] = f[i].get();
return results;
}
/**
* @brief Wait for all the futures stored in this multi_future object.
*/
void wait() const
{
for (size_t i = 0; i < f.size(); ++i)
f[i].wait();
}
/**
* @brief A vector to store the futures.
*/
std::vector<std::future<T>> f;
};
// End class multi_future //
// ============================================================================================= //
// ============================================================================================= //
// Begin class thread_pool //
/**
* @brief A fast, lightweight, and easy-to-use C++17 thread pool class.
*/
class [[nodiscard]] thread_pool
{
public:
// ============================
// Constructors and destructors
// ============================
/**
* @brief Construct a new thread pool.
*
* @param thread_count_ The number of threads to use. The default value is the total number of hardware threads available, as reported by the implementation. This is usually determined by the number of cores in the CPU. If a core is hyperthreaded, it will count as two threads.
*/
thread_pool(const concurrency_t thread_count_ = 0) : thread_count(determine_thread_count(thread_count_)), threads(std::make_unique<std::thread[]>(determine_thread_count(thread_count_)))
{
create_threads();
}
/**
* @brief Destruct the thread pool. Waits for all tasks to complete, then destroys all threads. Note that if the variable paused is set to true, then any tasks still in the queue will never be executed.
*/
~thread_pool()
{
wait_for_tasks();
destroy_threads();
}
// =======================
// Public member functions
// =======================
/**
* @brief Get the number of tasks currently waiting in the queue to be executed by the threads.
*
* @return The number of queued tasks.
*/
[[nodiscard]] size_t get_tasks_queued() const
{
const std::scoped_lock tasks_lock(tasks_mutex);
return tasks.size();
}
/**
* @brief Get the number of tasks currently being executed by the threads.
*
* @return The number of running tasks.
*/
[[nodiscard]] size_t get_tasks_running() const
{
const std::scoped_lock tasks_lock(tasks_mutex);
return tasks_total - tasks.size();
}
/**
* @brief Get the total number of unfinished tasks: either still in the queue, or running in a thread. Note that get_tasks_total() == get_tasks_queued() + get_tasks_running().
*
* @return The total number of tasks.
*/
[[nodiscard]] size_t get_tasks_total() const
{
return tasks_total;
}
/**
* @brief Get the number of threads in the pool.
*
* @return The number of threads.
*/
[[nodiscard]] concurrency_t get_thread_count() const
{
return thread_count;
}
/**
* @brief Parallelize a loop by automatically splitting it into blocks and submitting each block separately to the queue.
*
* @tparam F The type of the function to loop through.
* @tparam T1 The type of the first index in the loop. Should be a signed or unsigned integer.
* @tparam T2 The type of the index after the last index in the loop. Should be a signed or unsigned integer. If T1 is not the same as T2, a common type will be automatically inferred.
* @tparam T The common type of T1 and T2.
* @tparam R The return value of the loop function F (can be void).
* @param first_index The first index in the loop.
* @param index_after_last The index after the last index in the loop. The loop will iterate from first_index to (index_after_last - 1) inclusive. In other words, it will be equivalent to "for (T i = first_index; i < index_after_last; ++i)". Note that if first_index == index_after_last, no blocks will be submitted.
* @param loop The function to loop through. Will be called once per block. Should take exactly two arguments: the first index in the block and the index after the last index in the block. loop(start, end) should typically involve a loop of the form "for (T i = start; i < end; ++i)".
* @param num_blocks The maximum number of blocks to split the loop into. The default is to use the number of threads in the pool.
* @return A multi_future object that can be used to wait for all the blocks to finish. If the loop function returns a value, the multi_future object can be used to obtain the values returned by each block.
*/
template <typename F, typename T1, typename T2, typename T = std::common_type_t<T1, T2>, typename R = std::invoke_result_t<std::decay_t<F>, T, T>>
[[nodiscard]] multi_future<R> parallelize_loop(const T1& first_index, const T2& index_after_last, const F& loop, size_t num_blocks = 0)
{
T first_index_T = static_cast<T>(first_index);
T index_after_last_T = static_cast<T>(index_after_last);
if (first_index_T == index_after_last_T)
return multi_future<R>();
if (index_after_last_T < first_index_T)
std::swap(index_after_last_T, first_index_T);
if (num_blocks == 0)
num_blocks = thread_count;
const size_t total_size = static_cast<size_t>(index_after_last_T - first_index_T);
size_t block_size = static_cast<size_t>(total_size / num_blocks);
if (block_size == 0)
{
block_size = 1;
num_blocks = total_size > 1 ? total_size : 1;
}
multi_future<R> mf(num_blocks);
for (size_t i = 0; i < num_blocks; ++i)
{
const T start = (static_cast<T>(i * block_size) + first_index_T);
const T end = (i == num_blocks - 1) ? index_after_last_T : (static_cast<T>((i + 1) * block_size) + first_index_T);
mf.f[i] = submit(loop, start, end);
}
return mf;
}
/**
* @brief Push a function with zero or more arguments, but no return value, into the task queue.
*
* @tparam F The type of the function.
* @tparam A The types of the arguments.
* @param task The function to push.
* @param args The arguments to pass to the function.
*/
template <typename F, typename... A>
void push_task(const F& task, const A&... args)
{
{
const std::scoped_lock tasks_lock(tasks_mutex);
if constexpr (sizeof...(args) == 0)
tasks.push(std::function<void()>(task));
else
tasks.push(std::function<void()>([task, args...] { task(args...); }));
}
++tasks_total;
task_available_cv.notify_one();
}
/**
* @brief Reset the number of threads in the pool. Waits for all currently running tasks to be completed, then destroys all threads in the pool and creates a new thread pool with the new number of threads. Any tasks that were waiting in the queue before the pool was reset will then be executed by the new threads. If the pool was paused before resetting it, the new pool will be paused as well.
*
* @param thread_count_ The number of threads to use. The default value is the total number of hardware threads available, as reported by the implementation. This is usually determined by the number of cores in the CPU. If a core is hyperthreaded, it will count as two threads.
*/
void reset(const concurrency_t thread_count_ = 0)
{
const bool was_paused = paused;
paused = true;
wait_for_tasks();
destroy_threads();
thread_count = determine_thread_count(thread_count_);
threads = std::make_unique<std::thread[]>(thread_count);
paused = was_paused;
create_threads();
}
/**
* @brief Submit a function with zero or more arguments into the task queue. If the function has a return value, get a future for the eventual returned value. If the function has no return value, get an std::future<void> which can be used to wait until the task finishes.
*
* @tparam F The type of the function.
* @tparam A The types of the zero or more arguments to pass to the function.
* @tparam R The return type of the function (can be void).
* @param task The function to submit.
* @param args The zero or more arguments to pass to the function.
* @return A future to be used later to wait for the function to finish executing and/or obtain its returned value if it has one.
*/
template <typename F, typename... A, typename R = std::invoke_result_t<std::decay_t<F>, std::decay_t<A>...>>
[[nodiscard]] std::future<R> submit(const F& task, const A&... args)
{
std::shared_ptr<std::promise<R>> task_promise = std::make_shared<std::promise<R>>();
push_task(
[task, args..., task_promise]
{
try
{
if constexpr (std::is_void_v<R>)
{
task(args...);
task_promise->set_value();
}
else
{
task_promise->set_value(task(args...));
}
}
catch (...)
{
try
{
task_promise->set_exception(std::current_exception());
}
catch (...)
{
}
}
});
return task_promise->get_future();
}
/**
* @brief Wait for tasks to be completed. Normally, this function waits for all tasks, both those that are currently running in the threads and those that are still waiting in the queue. However, if the pool is paused, this function only waits for the currently running tasks (otherwise it would wait forever). Note: To wait for just one specific task, use submit() instead, and call the wait() member function of the generated future.
*/
void wait_for_tasks()
{
waiting = true;
std::unique_lock<std::mutex> tasks_lock(tasks_mutex);
task_done_cv.wait(tasks_lock, [this] { return (tasks_total == (paused ? tasks.size() : 0)); });
waiting = false;
}
// ===========
// Public data
// ===========
/**
* @brief An atomic variable indicating whether the workers should pause. When set to true, the workers temporarily stop retrieving new tasks out of the queue, although any tasks already executed will keep running until they are finished. Set to false again to resume retrieving tasks.
*/
std::atomic<bool> paused = false;
private:
// ========================
// Private member functions
// ========================
/**
* @brief Create the threads in the pool and assign a worker to each thread.
*/
void create_threads()
{
running = true;
for (concurrency_t i = 0; i < thread_count; ++i)
{
threads[i] = std::thread(&thread_pool::worker, this);
}
}
/**
* @brief Destroy the threads in the pool.
*/
void destroy_threads()
{
running = false;
task_available_cv.notify_all();
for (concurrency_t i = 0; i < thread_count; ++i)
{
threads[i].join();
}
}
/**
* @brief Determine how many threads the pool should have, based on the parameter passed to the constructor or reset().
*
* @param thread_count_ The parameter passed to the constructor or reset(). If the parameter is a positive number, then the pool will be created with this number of threads. If the parameter is non-positive, or a parameter was not supplied (in which case it will have the default value of 0), then the pool will be created with the total number of hardware threads available, as obtained from std::thread::hardware_concurrency(). If the latter returns a non-positive number for some reason, then the pool will be created with just one thread.
* @return The number of threads to use for constructing the pool.
*/
[[nodiscard]] concurrency_t determine_thread_count(const concurrency_t thread_count_)
{
if (thread_count_ > 0)
return thread_count_;
else
{
if (std::thread::hardware_concurrency() > 0)
return std::thread::hardware_concurrency();
else
return 1;
}
}
/**
* @brief A worker function to be assigned to each thread in the pool. Waits until it is notified by push_task() that a task is available, and then retrieves the task from the queue and executes it. Once the task finishes, the worker notifies wait_for_tasks() in case it is waiting.
*/
void worker()
{
while (running)
{
std::function<void()> task;
std::unique_lock<std::mutex> tasks_lock(tasks_mutex);
task_available_cv.wait(tasks_lock, [&] { return !tasks.empty() || !running; });
if (running && !paused)
{
task = std::move(tasks.front());
tasks.pop();
tasks_lock.unlock();
task();
tasks_lock.lock();
--tasks_total;
if (waiting)
task_done_cv.notify_one();
}
}
}
// ============
// Private data
// ============
/**
* @brief An atomic variable indicating to the workers to keep running. When set to false, the workers permanently stop working.
*/
std::atomic<bool> running = false;
/**
* @brief A condition variable used to notify worker() that a new task has become available.
*/
std::condition_variable task_available_cv = {};
/**
* @brief A condition variable used to notify wait_for_tasks() that a tasks is done.
*/
std::condition_variable task_done_cv = {};
/**
* @brief A queue of tasks to be executed by the threads.
*/
std::queue<std::function<void()>> tasks = {};
/**
* @brief An atomic variable to keep track of the total number of unfinished tasks - either still in the queue, or running in a thread.
*/
std::atomic<size_t> tasks_total = 0;
/**
* @brief A mutex to synchronize access to the task queue by different threads.
*/
mutable std::mutex tasks_mutex = {};
/**
* @brief The number of threads in the pool.
*/
concurrency_t thread_count = 0;
/**
* @brief A smart pointer to manage the memory allocated for the threads.
*/
std::unique_ptr<std::thread[]> threads = nullptr;
/**
* @brief An atomic variable indicating that wait_for_tasks() is active and expects to be notified whenever a task is done.
*/
std::atomic<bool> waiting = false;
};
// End class thread_pool //
// ============================================================================================= //
// ============================================================================================= //
// Begin class synced_stream //
/**
* @brief A helper class to synchronize printing to an output stream by different threads.
*/
class [[nodiscard]] synced_stream
{
public:
/**
* @brief Construct a new synced stream.
*
* @param out_stream_ The output stream to print to. The default value is std::cout.
*/
synced_stream(std::ostream& out_stream_ = std::cout) : out_stream(out_stream_) {}
/**
* @brief Print any number of items into the output stream. Ensures that no other threads print to this stream simultaneously, as long as they all exclusively use the same synced_stream object to print.
*
* @tparam T The types of the items
* @param items The items to print.
*/
template <typename... T>
void print(const T&... items)
{
const std::scoped_lock lock(stream_mutex);
(out_stream << ... << items);
}
/**
* @brief Print any number of items into the output stream, followed by a newline character. Ensures that no other threads print to this stream simultaneously, as long as they all exclusively use the same synced_stream object to print.
*
* @tparam T The types of the items
* @param items The items to print.
*/
template <typename... T>
void println(const T&... items)
{
print(items..., '\n');
}
private:
/**
* @brief The output stream to print to.
*/
std::ostream& out_stream;
/**
* @brief A mutex to synchronize printing.
*/
mutable std::mutex stream_mutex = {};
};
// End class synced_stream //
// ============================================================================================= //
// ============================================================================================= //
// Begin class timer //
/**
* @brief A helper class to measure execution time for benchmarking purposes.
*/
class [[nodiscard]] timer
{
public:
/**
* @brief Start (or restart) measuring time.
*/
void start()
{
start_time = std::chrono::steady_clock::now();
}
/**
* @brief Stop measuring time and store the elapsed time since start().
*/
void stop()
{
elapsed_time = std::chrono::steady_clock::now() - start_time;
}
/**
* @brief Get the number of milliseconds that have elapsed between start() and stop().
*
* @return The number of milliseconds.
*/
[[nodiscard]] std::chrono::milliseconds::rep ms() const
{
return (std::chrono::duration_cast<std::chrono::milliseconds>(elapsed_time)).count();
}
private:
/**
* @brief The time point when measuring started.
*/
std::chrono::time_point<std::chrono::steady_clock> start_time = std::chrono::steady_clock::now();
/**
* @brief The duration that has elapsed between start() and stop().
*/
std::chrono::duration<double> elapsed_time = std::chrono::duration<double>::zero();
};
// End class timer //
// ============================================================================================= //
} // namespace BS
-851
View File
@@ -1,851 +0,0 @@
/**
* @file BS_thread_pool_test.cpp
* @author Barak Shoshany (baraksh@gmail.com) (http://baraksh.com)
* @version 3.1.0
* @date 2022-07-13
* @copyright Copyright (c) 2022 Barak Shoshany. Licensed under the MIT license. If you found this project useful, please consider starring it on GitHub! If you use this library in software of any kind, please provide a link to the GitHub repository https://github.com/bshoshany/thread-pool in the source code and documentation. If you use this library in published research, please cite it as follows: Barak Shoshany, "A C++17 Thread Pool for High-Performance Scientific Computing", doi:10.5281/zenodo.4742687, arXiv:2105.00613 (May 2021)
*
* @brief BS::thread_pool: a fast, lightweight, and easy-to-use C++17 thread pool library. This program tests all aspects of the library, but is not needed in order to use the library.
*/
// Get rid of annoying MSVC warning.
#ifdef _MSC_VER
#define _CRT_SECURE_NO_WARNINGS
#endif
#include <algorithm> // std::min, std::min_element, std::sort, std::unique
#include <atomic> // std::atomic
#include <chrono> // std::chrono
#include <cmath> // std::abs, std::llround, std::round, std::sqrt
#include <condition_variable> // std::condition_variable
#include <ctime> // std::localtime, std::strftime, std::time_t
#include <exception> // std::exception
#include <fstream> // std::ofstream
#include <future> // std::future
#include <iomanip> // std::setprecision, std::setw
#include <ios> // std::fixed
#include <iostream> // std::cout
#include <limits> // std::numeric_limits
#include <mutex> // std::mutex, std::scoped_lock, std::unique_lock
#include <random> // std::mt19937_64, std::random_device, std::uniform_int_distribution, std::uniform_real_distribution
#include <stdexcept> // std::runtime_error
#include <string> // std::string, std::to_string
#include <thread> // std::this_thread, std::thread
#include <utility> // std::pair
#include <vector> // std::begin, std::end, std::vector
// Include the header file for the thread pool library.
#include "BS_thread_pool.hpp"
// ================
// Global variables
// ================
// Whether to output to a log file in addition to the standard output.
constexpr bool output_log = true;
// Whether to perform the tests.
constexpr bool enable_tests = true;
// Whether to perform the benchmarks.
constexpr bool enable_benchmarks = true;
// Two global synced_streams objects. One prints to std::cout, and the other to a file.
BS::synced_stream sync_cout(std::cout);
std::ofstream log_file;
BS::synced_stream sync_file(log_file);
// A global thread pool object to be used throughout the test.
BS::thread_pool pool;
// A global random_device object to be used to seed some random number generators.
std::random_device rd;
// Global variables to measure how many checks succeeded and how many failed.
size_t tests_succeeded = 0;
size_t tests_failed = 0;
// ================
// Helper functions
// ================
/**
* @brief Print any number of items into both std::cout and the log file, syncing both independently.
*
* @tparam T The types of the items.
* @param items The items to print.
*/
template <typename... T>
void dual_print(const T&... items)
{
sync_cout.print(items...);
if (output_log)
sync_file.print(items...);
}
/**
* @brief Print any number of items into both std::cout and the log file, followed by a newline character, syncing both independently.
*
* @tparam T The types of the items.
* @param items The items to print.
*/
template <typename... T>
void dual_println(const T&... items)
{
dual_print(items..., '\n');
}
/**
* @brief Print a stylized header.
*
* @param text The text of the header. Will appear between two lines.
* @param symbol The symbol to use for the lines. Default is '='.
*/
void print_header(const std::string& text, const char symbol = '=')
{
dual_println();
dual_println(std::string(text.length(), symbol));
dual_println(text);
dual_println(std::string(text.length(), symbol));
}
/**
* @brief Get a string representing the current time.
*
* @return The string.
*/
std::string get_time()
{
const std::time_t t = std::time(nullptr);
char time_string[32];
std::strftime(time_string, sizeof(time_string), "%Y-%m-%d_%H.%M.%S", std::localtime(&t));
return std::string(time_string);
}
/**
* @brief Check if a condition is met, report the result, and keep count of the total number of successes and failures.
*
* @param condition The condition to check.
*/
void check(const bool condition)
{
if (condition)
{
dual_println("-> PASSED!");
++tests_succeeded;
}
else
{
dual_println("-> FAILED!");
++tests_failed;
}
}
/**
* @brief Check if the expected result has been obtained, report the result, and keep count of the total number of successes and failures.
*
* @param condition The condition to check.
*/
template <typename T1, typename T2>
void check(const T1 expected, const T2 obtained)
{
dual_print("Expected: ", expected, ", obtained: ", obtained);
if (expected == obtained)
{
dual_println(" -> PASSED!");
++tests_succeeded;
}
else
{
dual_println(" -> FAILED!");
++tests_failed;
}
}
// =========================================
// Functions to verify the number of threads
// =========================================
/**
* @brief Count the number of unique threads in the pool. Submits a number of tasks equal to twice the thread count into the pool. Each task stores the ID of the thread running it, and then waits until released by the main thread. This ensures that each thread in the pool runs at least one task. The number of unique thread IDs is then counted from the stored IDs.
*/
BS::concurrency_t count_unique_threads()
{
const BS::concurrency_t num_tasks = pool.get_thread_count() * 2;
std::vector<std::thread::id> thread_IDs(num_tasks);
std::mutex ID_mutex, total_mutex;
std::condition_variable ID_cv, total_cv;
std::unique_lock<std::mutex> total_lock(total_mutex);
BS::concurrency_t total_count = 0;
bool ID_release = false;
pool.wait_for_tasks();
for (std::thread::id& id : thread_IDs)
pool.push_task(
[&]
{
id = std::this_thread::get_id();
{
const std::scoped_lock total_lock_local(total_mutex);
++total_count;
}
total_cv.notify_one();
std::unique_lock<std::mutex> ID_lock_local(ID_mutex);
ID_cv.wait(ID_lock_local, [&] { return ID_release; });
});
total_cv.wait_for(total_lock, std::chrono::milliseconds(500), [&] { return total_count == pool.get_thread_count(); });
{
const std::scoped_lock ID_lock(ID_mutex);
ID_release = true;
}
ID_cv.notify_all();
total_cv.wait_for(total_lock, std::chrono::milliseconds(500), [&] { return total_count == num_tasks; });
std::sort(thread_IDs.begin(), thread_IDs.end());
return static_cast<BS::concurrency_t>(std::unique(thread_IDs.begin(), thread_IDs.end()) - thread_IDs.begin());
}
/**
* @brief Check that the constructor works.
*/
void check_constructor()
{
dual_println("Checking that the thread pool reports a number of threads equal to the hardware concurrency...");
check(std::thread::hardware_concurrency(), pool.get_thread_count());
dual_println("Checking that the manually counted number of unique thread IDs is equal to the reported number of threads...");
check(pool.get_thread_count(), count_unique_threads());
}
/**
* @brief Check that reset() works.
*/
void check_reset()
{
pool.reset(std::thread::hardware_concurrency() / 2);
dual_println("Checking that after reset() the thread pool reports a number of threads equal to half the hardware concurrency...");
check(std::thread::hardware_concurrency() / 2, pool.get_thread_count());
dual_println("Checking that after reset() the manually counted number of unique thread IDs is equal to the reported number of threads...");
check(pool.get_thread_count(), count_unique_threads());
pool.reset(std::thread::hardware_concurrency());
dual_println("Checking that after a second reset() the thread pool reports a number of threads equal to the hardware concurrency...");
check(std::thread::hardware_concurrency(), pool.get_thread_count());
dual_println("Checking that after a second reset() the manually counted number of unique thread IDs is equal to the reported number of threads...");
check(pool.get_thread_count(), count_unique_threads());
}
// =======================================
// Functions to verify submission of tasks
// =======================================
/**
* @brief Check that push_task() works.
*/
void check_push_task()
{
dual_println("Checking that push_task() works for a function with no arguments or return value...");
{
bool flag = false;
pool.push_task([&flag] { flag = true; });
pool.wait_for_tasks();
check(flag);
}
dual_println("Checking that push_task() works for a function with one argument and no return value...");
{
bool flag = false;
pool.push_task([](bool* flag_) { *flag_ = true; }, &flag);
pool.wait_for_tasks();
check(flag);
}
dual_println("Checking that push_task() works for a function with two arguments and no return value...");
{
bool flag1 = false;
bool flag2 = false;
pool.push_task([](bool* flag1_, bool* flag2_) { *flag1_ = *flag2_ = true; }, &flag1, &flag2);
pool.wait_for_tasks();
check(flag1 && flag2);
}
}
/**
* @brief Check that submit() works.
*/
void check_submit()
{
dual_println("Checking that submit() works for a function with no arguments or return value...");
{
bool flag = false;
pool.submit([&flag] { flag = true; }).wait();
check(flag);
}
dual_println("Checking that submit() works for a function with one argument and no return value...");
{
bool flag = false;
pool.submit([](bool* flag_) { *flag_ = true; }, &flag).wait();
check(flag);
}
dual_println("Checking that submit() works for a function with two arguments and no return value...");
{
bool flag1 = false;
bool flag2 = false;
pool.submit([](bool* flag1_, bool* flag2_) { *flag1_ = *flag2_ = true; }, &flag1, &flag2).wait();
check(flag1 && flag2);
}
dual_println("Checking that submit() works for a function with no arguments and a return value...");
{
bool flag = false;
std::future<int> my_future = pool.submit(
[&flag]
{
flag = true;
return 42;
});
check(my_future.get() == 42 && flag);
}
dual_println("Checking that submit() works for a function with one argument and a return value...");
{
bool flag = false;
std::future<int> my_future = pool.submit(
[](bool* flag_)
{
*flag_ = true;
return 42;
},
&flag);
check(my_future.get() == 42 && flag);
}
dual_println("Checking that submit() works for a function with two arguments and a return value...");
{
bool flag1 = false;
bool flag2 = false;
std::future<int> my_future = pool.submit(
[](bool* flag1_, bool* flag2_)
{
*flag1_ = *flag2_ = true;
return 42;
},
&flag1, &flag2);
check(my_future.get() == 42 && flag1 && flag2);
}
}
/**
* @brief Check that wait_for_tasks() works.
*/
void check_wait_for_tasks()
{
const BS::concurrency_t n = pool.get_thread_count() * 10;
std::unique_ptr<std::atomic<bool>[]> flags = std::make_unique<std::atomic<bool>[]>(n);
for (BS::concurrency_t i = 0; i < n; ++i)
pool.push_task(
[&flags, i]
{
std::this_thread::sleep_for(std::chrono::milliseconds(10));
flags[i] = true;
});
dual_println("Waiting for tasks...");
pool.wait_for_tasks();
bool all_flags = true;
for (BS::concurrency_t i = 0; i < n; ++i)
all_flags = all_flags && flags[i];
check(all_flags);
}
// ========================================
// Functions to verify loop parallelization
// ========================================
/**
* @brief Check that parallelize_loop() works for a specific number of indices split over a specific number of tasks, with no return value.
*
* @param start The first index in the loop.
* @param end The last index in the loop plus 1.
* @param num_tasks The number of tasks.
*/
void check_parallelize_loop_no_return(const int64_t random_start, int64_t random_end, const BS::concurrency_t num_tasks)
{
if (random_start == random_end)
++random_end;
dual_println("Verifying that a loop from ", random_start, " to ", random_end, " with ", num_tasks, num_tasks == 1 ? " task" : " tasks", " modifies all indices...");
const size_t num_indices = static_cast<size_t>(std::abs(random_end - random_start));
const int64_t offset = std::min(random_start, random_end);
std::unique_ptr<std::atomic<bool>[]> flags = std::make_unique<std::atomic<bool>[]>(num_indices);
pool.parallelize_loop(
random_start, random_end,
[&flags, offset](const int64_t start, const int64_t end)
{
for (int64_t i = start; i < end; ++i)
flags[static_cast<size_t>(i - offset)] = true;
},
num_tasks)
.wait();
bool all_flags = true;
for (size_t i = 0; i < num_indices; ++i)
all_flags = all_flags && flags[i];
check(all_flags);
}
/**
* @brief Check that parallelize_loop() works for a specific number of indices split over a specific number of tasks, with a return value.
*
* @param start The first index in the loop.
* @param end The last index in the loop plus 1.
* @param num_tasks The number of tasks.
*/
void check_parallelize_loop_return(const int64_t random_start, int64_t random_end, const BS::concurrency_t num_tasks)
{
if (random_start == random_end)
++random_end;
dual_println("Verifying that a loop from ", random_start, " to ", random_end, " with ", num_tasks, num_tasks == 1 ? " task" : " tasks", " correctly sums all indices...");
const std::vector<int64_t> sums_vector = pool.parallelize_loop(
random_start, random_end,
[](const int64_t start, const int64_t end)
{
int64_t total = 0;
for (int64_t i = start; i < end; ++i)
total += i;
return total;
},
num_tasks)
.get();
int64_t sum = 0;
for (const int64_t& s : sums_vector)
sum += s;
check(std::abs(random_start - random_end) * (random_start + random_end - 1), sum * 2);
}
/**
* @brief Check that parallelize_loop() works using several different random values for the range of indices and number of tasks.
*/
void check_parallelize_loop()
{
std::mt19937_64 mt(rd());
std::uniform_int_distribution<int64_t> index_dist(-1000000, 1000000);
std::uniform_int_distribution<BS::concurrency_t> task_dist(1, pool.get_thread_count());
constexpr uint64_t n = 10;
for (uint64_t i = 0; i < n; ++i)
check_parallelize_loop_no_return(index_dist(mt), index_dist(mt), task_dist(mt));
for (uint64_t i = 0; i < n; ++i)
check_parallelize_loop_return(index_dist(mt), index_dist(mt), task_dist(mt));
}
// ===============================================
// Functions to verify task monitoring and control
// ===============================================
/**
* @brief Check that task monitoring works.
*/
void check_task_monitoring()
{
BS::concurrency_t n = std::min<BS::concurrency_t>(std::thread::hardware_concurrency(), 4);
dual_println("Resetting pool to ", n, " threads.");
pool.reset(n);
dual_println("Submitting ", n * 3, " tasks.");
std::unique_ptr<std::atomic<bool>[]> release = std::make_unique<std::atomic<bool>[]>(n * 3);
for (BS::concurrency_t i = 0; i < n * 3; ++i)
pool.push_task(
[&release, i]
{
while (!release[i])
std::this_thread::yield();
dual_println("Task ", i, " released.");
});
constexpr std::chrono::milliseconds sleep_time(300);
std::this_thread::sleep_for(sleep_time);
dual_println("After submission, should have: ", n * 3, " tasks total, ", n, " tasks running, ", n * 2, " tasks queued...");
dual_print("Result: ", pool.get_tasks_total(), " tasks total, ", pool.get_tasks_running(), " tasks running, ", pool.get_tasks_queued(), " tasks queued ");
check(pool.get_tasks_total() == n * 3 && pool.get_tasks_running() == n && pool.get_tasks_queued() == n * 2);
for (BS::concurrency_t i = 0; i < n; ++i)
release[i] = true;
std::this_thread::sleep_for(sleep_time);
dual_println("After releasing ", n, " tasks, should have: ", n * 2, " tasks total, ", n, " tasks running, ", n, " tasks queued...");
dual_print("Result: ", pool.get_tasks_total(), " tasks total, ", pool.get_tasks_running(), " tasks running, ", pool.get_tasks_queued(), " tasks queued ");
check(pool.get_tasks_total() == n * 2 && pool.get_tasks_running() == n && pool.get_tasks_queued() == n);
for (BS::concurrency_t i = n; i < n * 2; ++i)
release[i] = true;
std::this_thread::sleep_for(sleep_time);
dual_println("After releasing ", n, " more tasks, should have: ", n, " tasks total, ", n, " tasks running, ", 0, " tasks queued...");
dual_print("Result: ", pool.get_tasks_total(), " tasks total, ", pool.get_tasks_running(), " tasks running, ", pool.get_tasks_queued(), " tasks queued ");
check(pool.get_tasks_total() == n && pool.get_tasks_running() == n && pool.get_tasks_queued() == 0);
for (BS::concurrency_t i = n * 2; i < n * 3; ++i)
release[i] = true;
std::this_thread::sleep_for(sleep_time);
dual_println("After releasing the final ", n, " tasks, should have: ", 0, " tasks total, ", 0, " tasks running, ", 0, " tasks queued...");
dual_print("Result: ", pool.get_tasks_total(), " tasks total, ", pool.get_tasks_running(), " tasks running, ", pool.get_tasks_queued(), " tasks queued ");
check(pool.get_tasks_total() == 0 && pool.get_tasks_running() == 0 && pool.get_tasks_queued() == 0);
dual_println("Resetting pool to ", std::thread::hardware_concurrency(), " threads.");
pool.reset(std::thread::hardware_concurrency());
}
/**
* @brief Check that pausing works.
*/
void check_pausing()
{
BS::concurrency_t n = std::min<BS::concurrency_t>(std::thread::hardware_concurrency(), 4);
dual_println("Resetting pool to ", n, " threads.");
pool.reset(n);
dual_println("Pausing pool.");
pool.paused = true;
dual_println("Submitting ", n * 3, " tasks, each one waiting for 200ms.");
for (BS::concurrency_t i = 0; i < n * 3; ++i)
pool.push_task(
[i]
{
std::this_thread::sleep_for(std::chrono::milliseconds(200));
dual_println("Task ", i, " done.");
});
dual_println("Immediately after submission, should have: ", n * 3, " tasks total, ", 0, " tasks running, ", n * 3, " tasks queued...");
dual_print("Result: ", pool.get_tasks_total(), " tasks total, ", pool.get_tasks_running(), " tasks running, ", pool.get_tasks_queued(), " tasks queued ");
check(pool.get_tasks_total() == n * 3 && pool.get_tasks_running() == 0 && pool.get_tasks_queued() == n * 3);
std::this_thread::sleep_for(std::chrono::milliseconds(300));
dual_println("300ms later, should still have: ", n * 3, " tasks total, ", 0, " tasks running, ", n * 3, " tasks queued...");
dual_print("Result: ", pool.get_tasks_total(), " tasks total, ", pool.get_tasks_running(), " tasks running, ", pool.get_tasks_queued(), " tasks queued ");
check(pool.get_tasks_total() == n * 3 && pool.get_tasks_running() == 0 && pool.get_tasks_queued() == n * 3);
dual_println("Unpausing pool.");
pool.paused = false;
std::this_thread::sleep_for(std::chrono::milliseconds(300));
dual_println("300ms later, should have: ", n * 2, " tasks total, ", n, " tasks running, ", n, " tasks queued...");
dual_print("Result: ", pool.get_tasks_total(), " tasks total, ", pool.get_tasks_running(), " tasks running, ", pool.get_tasks_queued(), " tasks queued ");
check(pool.get_tasks_total() == n * 2 && pool.get_tasks_running() == n && pool.get_tasks_queued() == n);
dual_println("Pausing pool and using wait_for_tasks() to wait for the running tasks.");
pool.paused = true;
pool.wait_for_tasks();
dual_println("After waiting, should have: ", n, " tasks total, ", 0, " tasks running, ", n, " tasks queued...");
dual_print("Result: ", pool.get_tasks_total(), " tasks total, ", pool.get_tasks_running(), " tasks running, ", pool.get_tasks_queued(), " tasks queued ");
check(pool.get_tasks_total() == n && pool.get_tasks_running() == 0 && pool.get_tasks_queued() == n);
std::this_thread::sleep_for(std::chrono::milliseconds(200));
dual_println("200ms later, should still have: ", n, " tasks total, ", 0, " tasks running, ", n, " tasks queued...");
dual_print("Result: ", pool.get_tasks_total(), " tasks total, ", pool.get_tasks_running(), " tasks running, ", pool.get_tasks_queued(), " tasks queued ");
check(pool.get_tasks_total() == n && pool.get_tasks_running() == 0 && pool.get_tasks_queued() == n);
dual_println("Unpausing pool and using wait_for_tasks() to wait for all tasks.");
pool.paused = false;
pool.wait_for_tasks();
dual_println("After waiting, should have: ", 0, " tasks total, ", 0, " tasks running, ", 0, " tasks queued...");
dual_print("Result: ", pool.get_tasks_total(), " tasks total, ", pool.get_tasks_running(), " tasks running, ", pool.get_tasks_queued(), " tasks queued ");
check(pool.get_tasks_total() == 0 && pool.get_tasks_running() == 0 && pool.get_tasks_queued() == 0);
dual_println("Resetting pool to ", std::thread::hardware_concurrency(), " threads.");
pool.reset(std::thread::hardware_concurrency());
}
// ======================================
// Functions to verify exception handling
// ======================================
/**
* @brief Check that exception handling work.
*/
void check_exceptions()
{
bool caught = false;
std::future<void> my_future = pool.submit(
[]
{
dual_println("Throwing exception...");
throw std::runtime_error("Exception thrown!");
});
try
{
my_future.get();
}
catch (const std::exception& e)
{
if (e.what() == std::string("Exception thrown!"))
caught = true;
}
check(caught);
}
// =====================================
// Functions to verify vector operations
// =====================================
/**
* @brief Check that parallelized vector operations work as expected by calculating the sum of two randomized vectors of a specific size in two ways, single-threaded and multithreaded, and comparing the results.
*/
void check_vector_of_size(const size_t vector_size, const BS::concurrency_t num_tasks)
{
std::vector<int64_t> vector_1(vector_size);
std::vector<int64_t> vector_2(vector_size);
std::mt19937_64 mt(rd());
std::uniform_int_distribution<int64_t> vector_dist(-1000000, 1000000);
for (size_t i = 0; i < vector_size; ++i)
{
vector_1[i] = vector_dist(mt);
vector_2[i] = vector_dist(mt);
}
dual_println("Adding two vectors with ", vector_size, " elements using ", num_tasks, " tasks...");
std::vector<int64_t> sum_single(vector_size);
for (size_t i = 0; i < vector_size; ++i)
sum_single[i] = vector_1[i] + vector_2[i];
std::vector<int64_t> sum_multi(vector_size);
pool.parallelize_loop(
0, vector_size,
[&sum_multi, &vector_1, &vector_2](const size_t start, const size_t end)
{
for (size_t i = start; i < end; ++i)
sum_multi[i] = vector_1[i] + vector_2[i];
},
num_tasks)
.wait();
bool vectors_equal = true;
for (size_t i = 0; i < vector_size; ++i)
vectors_equal = vectors_equal && (sum_single[i] == sum_multi[i]);
check(vectors_equal);
}
/**
* @brief Check that parallelized vector operations work as expected by calculating the sum of two randomized vectors in two ways, single-threaded and multithreaded, and comparing the results.
*/
void check_vectors()
{
pool.reset();
std::mt19937_64 mt(rd());
std::uniform_int_distribution<size_t> size_dist(0, 1000000);
std::uniform_int_distribution<BS::concurrency_t> task_dist(1, pool.get_thread_count());
for (size_t i = 0; i < 10; ++i)
check_vector_of_size(size_dist(mt), task_dist(mt));
}
// ==================
// Main test function
// ==================
/**
* @brief Test that various aspects of the library are working as expected.
*/
void do_tests()
{
print_header("Checking that the constructor works:");
check_constructor();
print_header("Checking that reset() works:");
check_reset();
print_header("Checking that push_task() works:");
check_push_task();
print_header("Checking that submit() works:");
check_submit();
print_header("Checking that wait_for_tasks() works...");
check_wait_for_tasks();
print_header("Checking that parallelize_loop() works:");
check_parallelize_loop();
print_header("Checking that task monitoring works:");
check_task_monitoring();
print_header("Checking that pausing works:");
check_pausing();
print_header("Checking that exception handling works:");
check_exceptions();
print_header("Testing that vector operations produce the expected results:");
check_vectors();
}
// ==========================
// Functions for benchmarking
// ==========================
/**
* @brief Print the timing of a specific test.
*
* @param num_tasks The number of tasks.
* @param mean_sd An std::pair containing the mean as the first member and standard deviation as the second member.
*/
void print_timing(const BS::concurrency_t num_tasks, const std::pair<double, double>& mean_sd)
{
if (num_tasks == 0)
dual_print("Single-threaded");
else if (num_tasks == 1)
dual_print("With 1 task");
else
dual_print("With ", std::setw(4), num_tasks, " tasks");
dual_println(", mean execution time was ", std::setw(6), mean_sd.first, " ms with standard deviation ", std::setw(4), mean_sd.second, " ms.");
}
/**
* @brief Calculate and print the speedup obtained by multithreading.
*
* @param timings A vector of the timings corresponding to different numbers of tasks.
*/
void print_speedup(const std::vector<double>& timings, const BS::concurrency_t try_tasks[])
{
const std::vector<double>::const_iterator min_el = std::min_element(std::begin(timings), std::end(timings));
const double max_speedup = std::round(timings[0] / *min_el * 10) / 10;
const BS::concurrency_t num_tasks = try_tasks[min_el - std::begin(timings)];
dual_println("Maximum speedup obtained by multithreading vs. single-threading: ", max_speedup, "x, using ", num_tasks, " tasks.");
}
/**
* @brief Calculate the mean and standard deviation of a set of integers.
*
* @param timings The integers.
* @return An std::pair containing the mean as the first member and standard deviation as the second member.
*/
std::pair<double, double> analyze(const std::vector<std::chrono::milliseconds::rep>& timings)
{
double mean = 0;
for (size_t i = 0; i < timings.size(); ++i)
mean += static_cast<double>(timings[i]) / static_cast<double>(timings.size());
double variance = 0;
for (size_t i = 0; i < timings.size(); ++i)
variance += (static_cast<double>(timings[i]) - mean) * (static_cast<double>(timings[i]) - mean) / static_cast<double>(timings.size());
const double sd = std::sqrt(variance);
return std::pair(mean, sd);
}
/**
* @brief Generate a seed. The std::mt19937_64 in each task will be seeded using this function in order to avoid depleting the entropy of the random_device.
*
* @return A random unsigned 64-bit integer.
*/
uint64_t generate_seed()
{
static std::mt19937_64 mt(rd());
return mt();
}
/**
* @brief Benchmark multithreaded performance by generating random vectors.
*/
void check_performance()
{
// Reset the pool to ensure that we have a fresh start.
pool.reset();
// Set the formatting of floating point numbers.
dual_print(std::fixed, std::setprecision(1));
// Initialize a random distribution to randomize vectors with arbitrary floating point values.
const double range = std::sqrt(std::numeric_limits<double>::max());
std::uniform_real_distribution<double> vector_dist(-range, range);
// Initialize a timer object to measure execution time.
BS::timer tmr;
// Store the number of available hardware threads for easy access.
const BS::concurrency_t thread_count = pool.get_thread_count();
dual_println("Using ", thread_count, " threads.");
// Define the number of tasks to try in each run of the test (0 = single-threaded).
const BS::concurrency_t try_tasks[] = {0, thread_count / 4, thread_count / 2, thread_count, thread_count * 2, thread_count * 4};
// The size of the vectors to use for the test.
constexpr size_t vector_size = 500;
// How many times to repeat each run of the test in order to collect reliable statistics.
constexpr size_t repeat = 20;
dual_println("Each test will be repeated ", repeat, " times to collect reliable statistics.");
// The target duration of the single-threaded test in milliseconds. The total time spent on the test in the single-threaded case will be approximately equal to repeat * target_ms.
constexpr std::chrono::milliseconds::rep target_ms = 300;
// Vectors to store statistics.
std::vector<double> different_n_timings;
std::vector<std::chrono::milliseconds::rep> same_n_timings;
// Test how many vectors we need to generate to roughly achieve the target duration.
size_t num_vectors = 1;
do
{
num_vectors *= 2;
std::vector<std::vector<double>> vectors(num_vectors, std::vector<double>(vector_size));
std::mt19937_64 test_mt(rd());
tmr.start();
for (size_t i = 0; i < num_vectors; ++i)
{
for (size_t j = 0; j < vector_size; ++j)
vectors[i][j] = vector_dist(test_mt);
}
tmr.stop();
} while (tmr.ms() < target_ms);
num_vectors = static_cast<size_t>(std::llround(static_cast<double>(num_vectors) * static_cast<double>(target_ms) / static_cast<double>(tmr.ms())));
// Initialize the desired number of vectors.
std::vector<std::vector<double>> vectors(num_vectors, std::vector<double>(vector_size));
// Perform the test.
dual_println("\nGenerating ", num_vectors, " random vectors with ", vector_size, " elements each:");
for (BS::concurrency_t n : try_tasks)
{
for (size_t r = 0; r < repeat; ++r)
{
tmr.start();
if (n > 1)
{
pool.parallelize_loop(
0, num_vectors,
[&vector_dist, &vectors](const size_t start, const size_t end)
{
std::mt19937_64 multi_mt(generate_seed());
for (size_t i = start; i < end; ++i)
{
for (size_t j = 0; j < vector_size; ++j)
vectors[i][j] = vector_dist(multi_mt);
}
},
n)
.wait();
}
else
{
std::mt19937_64 single_mt(generate_seed());
for (size_t i = 0; i < num_vectors; ++i)
{
for (size_t j = 0; j < vector_size; ++j)
vectors[i][j] = vector_dist(single_mt);
}
}
tmr.stop();
same_n_timings.push_back(tmr.ms());
}
std::pair<double, double> mean_sd = analyze(same_n_timings);
print_timing(n, mean_sd);
different_n_timings.push_back(mean_sd.first);
same_n_timings.clear();
}
print_speedup(different_n_timings, try_tasks);
}
int main()
{
const std::string log_filename = "BS_thread_pool_test-" + get_time() + ".log";
if (output_log)
log_file.open(log_filename);
dual_println("BS::thread_pool: a fast, lightweight, and easy-to-use C++17 thread pool library");
dual_println("(c) 2022 Barak Shoshany (baraksh@gmail.com) (http://baraksh.com)");
dual_println("GitHub: https://github.com/bshoshany/thread-pool\n");
dual_println("Thread pool library version is ", BS_THREAD_POOL_VERSION, ".");
dual_println("Hardware concurrency is ", std::thread::hardware_concurrency(), ".");
if (output_log)
dual_println("Generating log file: ", log_filename, ".\n");
dual_println("Important: Please do not run any other applications, especially multithreaded applications, in parallel with this test!");
if (enable_tests)
do_tests();
if (tests_failed == 0)
{
if (enable_tests)
print_header("SUCCESS: Passed all " + std::to_string(tests_succeeded) + " checks!", '+');
if (enable_benchmarks)
{
print_header("Performing benchmarks:");
check_performance();
print_header("Thread pool performance test completed!", '+');
}
return EXIT_SUCCESS;
}
else
{
print_header("FAILURE: Passed " + std::to_string(tests_succeeded) + " checks, but failed " + std::to_string(tests_failed) + "!", '+');
dual_println("\nPlease submit a bug report at https://github.com/bshoshany/thread-pool/issues including the exact specifications of your system (OS, CPU, compiler, etc.) and the generated log file.");
return EXIT_FAILURE;
}
}
+105 -11
View File
@@ -1,18 +1,15 @@
[![DOI:10.5281/zenodo.4742687](https://zenodo.org/badge/DOI/10.5281/zenodo.4742687.svg)](https://doi.org/10.5281/zenodo.4742687)
[![arXiv:2105.00613](https://img.shields.io/badge/arXiv-2105.00613-b31b1b.svg)](https://arxiv.org/abs/2105.00613)
[![License: MIT](https://img.shields.io/github/license/bshoshany/thread-pool)](https://github.com/bshoshany/thread-pool/blob/master/LICENSE.txt)
![Language: C++17](https://img.shields.io/badge/Language-C%2B%2B17-yellow)
![File size in bytes](https://img.shields.io/github/size/bshoshany/thread-pool/BS_thread_pool.hpp)
![GitHub last commit](https://img.shields.io/github/last-commit/bshoshany/thread-pool)
[![GitHub repo stars](https://img.shields.io/github/stars/bshoshany/thread-pool?style=social)](https://github.com/bshoshany/thread-pool)
[![Twitter @BarakShoshany](https://img.shields.io/twitter/follow/BarakShoshany?style=social)](https://twitter.com/BarakShoshany)
[![Open in Visual Studio Code](https://img.shields.io/badge/-Open%20in%20Visual%20Studio%20Code-007acc)](https://vscode.dev/github/bshoshany/thread-pool)
# `BS::thread_pool`: a fast, lightweight, and easy-to-use C++17 thread pool library
By Barak Shoshany ([baraksh@gmail.com](mailto:baraksh@gmail.com)) ([https://baraksh.com/](https://baraksh.com/))
By Barak Shoshany\
Email: <baraksh@gmail.com>\
Website: <https://baraksh.com/>\
GitHub: <https://github.com/bshoshany>
* [Version history](#version-history)
* [v3.5.0 (2023-05-25)](#v350-2023-05-25)
* [v3.4.0 (2023-05-12)](#v340-2023-05-12)
* [v3.3.0 (2022-08-03)](#v330-2022-08-03)
* [v3.2.0 (2022-07-28)](#v320-2022-07-28)
* [v3.1.0 (2022-07-13)](#v310-2022-07-13)
* [v3.0.0 (2022-05-30)](#v300-2022-05-30)
* [v2.0.0 (2021-08-14)](#v200-2021-08-14)
@@ -29,6 +26,103 @@ By Barak Shoshany ([baraksh@gmail.com](mailto:baraksh@gmail.com)) ([https://bara
## Version history
### v3.5.0 (2023-05-25)
* `BS_thread_pool.hpp` and `BS_thread_pool_light.hpp`:
* Added a new member function, `purge()`, to the full (non-light) thread pool. This function purges all the tasks waiting in the queue. Tasks that are currently running will not be affected, but any tasks still waiting in the queue will be removed and will never be executed by the threads. Please note that there is no way to restore the purged tasks.
* Fix a bug which caused `wait_for_tasks()` to only block the first thread that called it. Now it blocks every thread that calls it, which is the expected behavior. In addition, all related deadlock have now been completely resolved. This also applies to the variants `wait_for_tasks_duration()` and `wait_for_tasks_until()` in the non-light version. See [#110](https://github.com/bshoshany/thread-pool/pull/110).
* Note: You should never call `wait_for_tasks()` from within a thread of the same thread pool, as that will cause it to wait forever! This fix is relevant for situations when `wait_for_tasks()` is called from an auxiliary `std::thread` or a separate thread pool.
* `push_task()` and `submit()` now avoid creating unnecessary copies of the function object. This should improve performance, especially if large objects are involved. See [#90](https://github.com/bshoshany/thread-pool/pull/90).
* Optimized the way condition variables are used by the thread pool class. Shared variables are now modified while owning the mutex, but condition variables are notified after the mutex is released, if possible. See [#84](https://github.com/bshoshany/thread-pool/pull/84).
* Instead of a variable `tasks_total` to keep track of the total number of tasks (queued + running), the thread pool class now uses a variable `tasks_running` to keep track only of the number of running tasks, with the number of tasks in the queue obtained via `tasks.size()`. This makes more sense in terms of the internal logic of the class.
* All atomic variables have been converted to non-atomic. They are now all governed by `tasks_mutex`, so they do not need to be atomic. This eliminates redundant locking, and may improve performance a bit.
* `running` has been renamed to `workers_running` and `task_done_cv` has been renamed to `tasks_done_cv`.
* The worker now only notifies thi condition variable `tasks_done_cv` if all the tasks are done, not just a single task. Checking if the tasks are done is cheaper than notifying the condition variable, so since the worker no longer notifies the condition variable every single time it finishes a task, this should improve performance a bit if `wait_for_tasks()` is used.
* `BS_thread_pool_test.cpp`:
* Combined the tests for the full and light versions into one program. The file `BS_thread_pool_light_test.cpp` has been removed.
* The tests for the light version are now much more comprehensive. The only features that are not tested in the light version are those that do not exist in it.
* Added a test for the new `purge()` member function.
* Added a test to ensure that `push_task()` and `submit()` do not create unnecessary copies of the function object.
* Added a test to ensure that `push_task()` and `submit()` correctly accept arguments passed by value, reference, and constant reference.
* Added a test to ensure that `wait_for_tasks()` blocks all external threads that call it.
* `_CRT_SECURE_NO_WARNINGS` is now set only if it has not already been defined, to prevent errors in MSVC projects which already have it set as part of the default build settings. See [#72](https://github.com/bshoshany/thread-pool/pull/72).
* `README.md`:
* Added documentation for the new `purge()` member function.
* Added an explanation for how to pass arguments by reference or constant reference when submitting functions to the queue, using the wrappers `std::ref()` and `std::cref()` respectively. See [#83](https://github.com/bshoshany/thread-pool/issues/83).
* Added a link to [my lecture notes](https://baraksh.com/CSE701/notes.php) for a course taught at McMaster University, for the benefit of beginner C++ programmers who wish to learn some of the advanced techniques and programming practices used in developing this library.
* Removed the sample test results, since the complete log file (including the deadlock tests) is now over 500 lines long.
* Other:
* A `.clang-format` file with the project's formatting conventions is now included in the GitHub repository. The pull request template now asks to format any new code using this file, so that it is consistent with the rest of the library.
* A PowerShell script, `BS_thread_pool_test.ps1`, is now provided in the GitHub repository to make running the test on multiple compilers and operating systems easier. Since it is written in PowerShell, it is fully portable and works on Windows, Linux, and macOS. The script will automatically detect if Clang, GCC, and/or MSVC are available, compile the test program using each available compiler, and then run each compiled test program 5 times and report on any errors. The pull request template now recommends using this script for testing.
* Since the root folder has become a bit crowded, the header files `BS_thread_pool.hpp` and `BS_thread_pool_light.hpp` have been moved to the `include` subfolder, and the test file `BS_thread_pool_test.cpp` has been moved to the `tests` subfolder, which also contains the new test script `BS_thread_pool_test.ps1`.
### v3.4.0 (2023-05-12)
* `BS_thread_pool.hpp` and `BS_thread_pool_light.hpp`:
* Resolved an issue which could have caused `tasks_total` to not be synchronized in some cases. See [#70](https://github.com/bshoshany/thread-pool/pull/70).
* Resolved a deadlock which could rarely be caused when the pool was destructed or reset. See [#93](https://github.com/bshoshany/thread-pool/pull/93), [#100](https://github.com/bshoshany/thread-pool/pull/100), [#107](https://github.com/bshoshany/thread-pool/pull/107), and [#108](https://github.com/bshoshany/thread-pool/pull/108).
* Resolved a deadlock which could be caused when `wait_for_tasks()` was called more than once.
* Two new member functions have been added to the non-light version: `wait_for_tasks_duration()` and `wait_for_tasks_until()`. They allow waiting for the tasks to complete, but with a timeout. `wait_for_tasks_duration()` will stop waiting after the specified duration has passed, and `wait_for_tasks_until()` will stop waiting after the specified time point has been reached.
* Renamed `BS_THREAD_POOL_VERSION` in `BS_thread_pool_light.hpp` to `BS_THREAD_POOL_LIGHT_VERSION` and removed the `[light]` tag. This allows including both header files in the same program in case we want to use both the light and non-light thread pools simultaneously.
* `BS_thread_pool_test.cpp` and `BS_thread_pool_light_test.cpp`:
* Fixed an issue that caused a compilation error when using MSVC and including `Windows.h`. See [#72](https://github.com/bshoshany/thread-pool/pull/72).
* The number and size of the vectors in the performance test (`BS_thread_pool_test.cpp` only) are now guaranteed to be multiples of the number of threads, for optimal performance.
* In `count_unique_threads()`, moved the condition variables and mutexes to the function scope to prevent cluttering the global scope.
* Three new tests have been added to `BS_thread_pool_test.cpp` to check the deadlocks issue that were resolved in this release (see above). The tests rely on the new wait for tasks with timeout feature, so they are not available in the light version.
* One test checks for deadlocks when calling `wait_for_tasks()` more than once.
* Two tests check for deadlocks when destructing and resetting the pool respectively. They are turned off by default, since they take a long time to complete, but can be turned on by setting `enable_long_deadlock_tests` to `true`.
* Two new tests have been added to the non-light version to check the new member functions `wait_for_tasks_duration()` and `wait_for_tasks_until()`.
* The test programs now return the number of failed tests upon exit, instead of just 1 if any number of tests failed, which was the case in previous versions. Also, if any tests failed, `std::quick_exit()` is invoked instead of `return`, to avoid getting stuck due to any lingering tasks or deadlocks.
* `README.md`:
* Added documentation for the two new member functions, `wait_for_tasks_duration()` and `wait_for_tasks_until()`.
* Fixed Markdown rendering incorrectly on Visual Studio. See [#77](https://github.com/bshoshany/thread-pool/pull/77).
* The sample performance tests are now taken from a 40-core / 80-thread dual-CPU computing node, which is a more typical use case for high-performance scientific software.
### v3.3.0 (2022-08-03)
* `BS_thread_pool.hpp`:
* The public member variable `paused` of `BS::thread_pool` has been made private for future-proofing (in case future versions implement a more involved pausing mechanism) and better encapsulation. It is now accessible only via the `pause()`, `unpause()`, and `is_paused()` member functions. In other words:
* Replace `pool.paused = true` with `pool.pause()`.
* Replace `pool.paused = false` with `pool.unpause()`.
* Replace `if (pool.paused)` (or similar) with `if (pool.is_paused())`.
* The public member variable `f` of `BS::multi_future` has been renamed to `futures` for clarity, and has been made private for encapsulation and simplification purposes. Instead of operating on the vector `futures` itself, you can now use the `[]` operator of the `BS::multi_future` to access the future at a specific index directly, or the `push_back()` member function to append a new future to the list. The `size()` member function tells you how many futures are currently stored in the object.
* The explicit casts of `std::endl` and `std::flush`, added in v3.2.0 to enable flushing a `BS::synced_stream`, caused ODR (One Definition Rule) violations if `BS_thread_pool.hpp` was included in two different translation units, since they were mistakenly not defined as `inline`. To fix this, I decided to make them static members of `BS::synced_stream` instead of global variables, which also makes the code better organized in my opinion. These objects can now be accessed as `BS::synced_stream::endl` and `BS::synced_stream::flush`. I also added an example for how to use them in `README.md`. See [#64](https://github.com/bshoshany/thread-pool/issues/64).
* `BS_thread_pool_light.hpp`:
* This package started out as a very lightweight thread pool, but over time has expanded to include many additional features, and at the time of writing it has a total of 340 lines of code, including all the helper classes. Therefore, I have decided to bundle a light version of the thread pool in a separate and stand-alone header file, `BS_thread_pool_light.hpp`, with only 170 lines of code (half the size of the full package). This file does not contain any of the helper classes, only a new `BS::thread_pool_light` class, which is a minimal thread pool with only the 5 most basic member functions:
* `get_thread_count()`
* `push_loop()`
* `push_task()`
* `submit()`
* `wait_for_tasks()`
* A separate test program `BS_thread_pool_light_test.cpp` tests only the features of the lightweight `BS::thread_pool_light` class. In the spirit of minimalism, it does not generate a log file and does not do any benchmarks.
* To be perfectly clear, each header file is 100% stand-alone. If you wish to use the full package, you only need `BS_thread_pool.hpp`, and if you wish to use the light version, you only need `BS_thread_pool_light.hpp`. Only a single header file needs to be included in your project.
### v3.2.0 (2022-07-28)
* `BS_thread_pool.hpp`:
* Main `BS::thread_pool` class:
* Added a new member function, `push_loop()`, which does the same thing as `parallelize_loop()`, except that it does not return a `BS::multi_future` with the futures for each block. Just like `push_task()` vs. `submit()`, this avoids the overhead of creating the futures, but the user must use `wait_for_tasks()` or some other method to ensure that the loop finishes executing, otherwise bad things will happen.
* `push_task()` and `submit()` now utilize perfect forwarding in order to support more types of tasks - in particular member functions, which in previous versions could not be submitted unless wrapped in a lambda. To submit a member function, use the syntax `submit(&class::function, &object, args)`. More information can be found in `README.md`. See [#9](https://github.com/bshoshany/thread-pool/issues/9).
* `push_loop()` and `parallelize_loop()` now have overloads where the first argument (the first index in the loop) is omitted, in which case it is assumed to be 0. This is for convenience, as the case where the first index is 0 is very common.
* Helper classes:
* `BS::synced_stream` now utilizes perfect forwarding in the member functions `print()` and `println()`.
* Previously, it was impossible to pass the flushing manipulators `std::endl` and `std::flush` to `print()` and `println()`, since the compiler could not figure out which template specializations to use. The new objects `BS::endl` and `BS::flush` are explicit casts of these manipulators, whose sole purpose is to enable passing them to `print()` and `println()`.
* `BS::multi_future::get()` now rethrows exceptions generated by the futures, even if the futures return `void`. See [#62](https://github.com/bshoshany/thread-pool/pull/62).
* Added a new helper class, `BS::blocks`, which is used by `parallelize_loop()` and `push_loop()` to divide a range into blocks. This class is not documented in `README.md`, as it most likely will not be of interest to most users, but it is still publicly available, in case you want to parallelize something manually but still benefit from the built-in algorithm for splitting a range into blocks.
* `BS_thread_pool_test.cpp`:
* Added plenty of new tests for the new features described above.
* Fixed a bug in `count_unique_threads()` that caused it to get stuck on certain systems.
* `dual_println()` now also flushes the stream using `BS::endl`, so that if the test gets stuck, the log file will still contain everything up to that point. (Note: It is a common misconception that `std::endl` and `'\n'` are interchangeable. `std::endl` not only prints a newline character, it also flushes the stream, which is not always desirable, as it may reduce performance.)
* The performance test has been modified as follows:
* Instead of generating random vectors using `std::mersenne_twister_engine`, which proved to be inconsistent across different compilers and systems, the test now generates each element via an arbitrarily-chosen numerical operation. In my testing, this provided much more consistent results.
* Instead of using a hard-coded vector size, a suitable vector size is now determined dynamically at runtime.
* Instead of using `parallelize_loop()`, the test now uses the new `push_loop()` function to squeeze out a bit more performance.
* Instead of setting the test parameters to achieve a fixed single-threaded mean execution time of 300 ms, the test now aims to achieve a fixed multi-threaded mean execution time of 50 ms when the number of blocks is equal to the number of threads. This allows for more reliable results on very fast CPUs with a very large number of threads, where the mean execution time when using all the threads could previously be below a statistically significant value.
* The number of vectors is now restricted to be a multiple of the number of threads, so that the blocks are always all of the same size.
* `README.md`:
* Added instructions and examples for the new features described above.
* Rewrote the documentation for `parallelize_loop()` to make it clearer.
### v3.1.0 (2022-07-13)
* `BS_thread_pool.hpp`:
+1 -1
View File
@@ -1,6 +1,6 @@
MIT License
Copyright (c) 2022 Barak Shoshany
Copyright (c) 2023 Barak Shoshany
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
+553 -330
View File
File diff suppressed because it is too large Load Diff
+819
View File
@@ -0,0 +1,819 @@
#pragma once
/**
* @file BS_thread_pool.hpp
* @author Barak Shoshany (baraksh@gmail.com) (http://baraksh.com)
* @version 3.5.0
* @date 2023-05-25
* @copyright Copyright (c) 2023 Barak Shoshany. Licensed under the MIT license. If you found this project useful, please consider starring it on GitHub! If you use this library in software of any kind, please provide a link to the GitHub repository https://github.com/bshoshany/thread-pool in the source code and documentation. If you use this library in published research, please cite it as follows: Barak Shoshany, "A C++17 Thread Pool for High-Performance Scientific Computing", doi:10.5281/zenodo.4742687, arXiv:2105.00613 (May 2021)
*
* @brief BS::thread_pool: a fast, lightweight, and easy-to-use C++17 thread pool library. This header file contains the entire library, including the main BS::thread_pool class and the helper classes BS::multi_future, BS::blocks, BS:synced_stream, and BS::timer.
*/
#define BS_THREAD_POOL_VERSION "v3.5.0 (2023-05-25)"
#include <chrono> // std::chrono
#include <condition_variable> // std::condition_variable
#include <exception> // std::current_exception
#include <functional> // std::bind, std::function, std::invoke
#include <future> // std::future, std::promise
#include <iostream> // std::cout, std::endl, std::flush, std::ostream
#include <memory> // std::make_shared, std::make_unique, std::shared_ptr, std::unique_ptr
#include <mutex> // std::mutex, std::scoped_lock, std::unique_lock
#include <queue> // std::queue
#include <thread> // std::thread
#include <type_traits> // std::common_type_t, std::conditional_t, std::decay_t, std::invoke_result_t, std::is_void_v
#include <utility> // std::forward, std::move, std::swap
#include <vector> // std::vector
namespace BS
{
/**
* @brief A convenient shorthand for the type of std::thread::hardware_concurrency(). Should evaluate to unsigned int.
*/
using concurrency_t = std::invoke_result_t<decltype(std::thread::hardware_concurrency)>;
// ============================================================================================= //
// Begin class multi_future //
/**
* @brief A helper class to facilitate waiting for and/or getting the results of multiple futures at once.
*
* @tparam T The return type of the futures.
*/
template <typename T>
class [[nodiscard]] multi_future
{
public:
/**
* @brief Construct a multi_future object with the given number of futures.
*
* @param num_futures_ The desired number of futures to store.
*/
multi_future(const size_t num_futures_ = 0) : futures(num_futures_) {}
/**
* @brief Get the results from all the futures stored in this multi_future object, rethrowing any stored exceptions.
*
* @return If the futures return void, this function returns void as well. Otherwise, it returns a vector containing the results.
*/
[[nodiscard]] std::conditional_t<std::is_void_v<T>, void, std::vector<T>> get()
{
if constexpr (std::is_void_v<T>)
{
for (size_t i = 0; i < futures.size(); ++i)
futures[i].get();
return;
}
else
{
std::vector<T> results(futures.size());
for (size_t i = 0; i < futures.size(); ++i)
results[i] = futures[i].get();
return results;
}
}
/**
* @brief Get a reference to one of the futures stored in this multi_future object.
*
* @param i The index of the desired future.
* @return The future.
*/
[[nodiscard]] std::future<T>& operator[](const size_t i)
{
return futures[i];
}
/**
* @brief Append a future to this multi_future object.
*
* @param future The future to append.
*/
void push_back(std::future<T> future)
{
futures.push_back(std::move(future));
}
/**
* @brief Get the number of futures stored in this multi_future object.
*
* @return The number of futures.
*/
[[nodiscard]] size_t size() const
{
return futures.size();
}
/**
* @brief Wait for all the futures stored in this multi_future object.
*/
void wait() const
{
for (size_t i = 0; i < futures.size(); ++i)
futures[i].wait();
}
private:
/**
* @brief A vector to store the futures.
*/
std::vector<std::future<T>> futures;
};
// End class multi_future //
// ============================================================================================= //
// ============================================================================================= //
// Begin class blocks //
/**
* @brief A helper class to divide a range into blocks. Used by parallelize_loop() and push_loop().
*
* @tparam T1 The type of the first index in the range. Should be a signed or unsigned integer.
* @tparam T2 The type of the index after the last index in the range. Should be a signed or unsigned integer. If T1 is not the same as T2, a common type will be automatically inferred.
* @tparam T The common type of T1 and T2.
*/
template <typename T1, typename T2, typename T = std::common_type_t<T1, T2>>
class [[nodiscard]] blocks
{
public:
/**
* @brief Construct a blocks object with the given specifications.
*
* @param first_index_ The first index in the range.
* @param index_after_last_ The index after the last index in the range.
* @param num_blocks_ The desired number of blocks to divide the range into.
*/
blocks(const T1 first_index_, const T2 index_after_last_, const size_t num_blocks_) : first_index(static_cast<T>(first_index_)), index_after_last(static_cast<T>(index_after_last_)), num_blocks(num_blocks_)
{
if (index_after_last < first_index)
std::swap(index_after_last, first_index);
total_size = static_cast<size_t>(index_after_last - first_index);
block_size = static_cast<size_t>(total_size / num_blocks);
if (block_size == 0)
{
block_size = 1;
num_blocks = (total_size > 1) ? total_size : 1;
}
}
/**
* @brief Get the first index of a block.
*
* @param i The block number.
* @return The first index.
*/
[[nodiscard]] T start(const size_t i) const
{
return static_cast<T>(i * block_size) + first_index;
}
/**
* @brief Get the index after the last index of a block.
*
* @param i The block number.
* @return The index after the last index.
*/
[[nodiscard]] T end(const size_t i) const
{
return (i == num_blocks - 1) ? index_after_last : (static_cast<T>((i + 1) * block_size) + first_index);
}
/**
* @brief Get the number of blocks. Note that this may be different than the desired number of blocks that was passed to the constructor.
*
* @return The number of blocks.
*/
[[nodiscard]] size_t get_num_blocks() const
{
return num_blocks;
}
/**
* @brief Get the total number of indices in the range.
*
* @return The total number of indices.
*/
[[nodiscard]] size_t get_total_size() const
{
return total_size;
}
private:
/**
* @brief The size of each block (except possibly the last block).
*/
size_t block_size = 0;
/**
* @brief The first index in the range.
*/
T first_index = 0;
/**
* @brief The index after the last index in the range.
*/
T index_after_last = 0;
/**
* @brief The number of blocks.
*/
size_t num_blocks = 0;
/**
* @brief The total number of indices in the range.
*/
size_t total_size = 0;
};
// End class blocks //
// ============================================================================================= //
// ============================================================================================= //
// Begin class thread_pool //
/**
* @brief A fast, lightweight, and easy-to-use C++17 thread pool class.
*/
class [[nodiscard]] thread_pool
{
public:
// ============================
// Constructors and destructors
// ============================
/**
* @brief Construct a new thread pool.
*
* @param thread_count_ The number of threads to use. The default value is the total number of hardware threads available, as reported by the implementation. This is usually determined by the number of cores in the CPU. If a core is hyperthreaded, it will count as two threads.
*/
thread_pool(const concurrency_t thread_count_ = 0) : thread_count(determine_thread_count(thread_count_)), threads(std::make_unique<std::thread[]>(determine_thread_count(thread_count_)))
{
create_threads();
}
/**
* @brief Destruct the thread pool. Waits for all tasks to complete, then destroys all threads. Note that if the pool is paused, then any tasks still in the queue will never be executed.
*/
~thread_pool()
{
wait_for_tasks();
destroy_threads();
}
// =======================
// Public member functions
// =======================
/**
* @brief Get the number of tasks currently waiting in the queue to be executed by the threads.
*
* @return The number of queued tasks.
*/
[[nodiscard]] size_t get_tasks_queued() const
{
const std::scoped_lock tasks_lock(tasks_mutex);
return tasks.size();
}
/**
* @brief Get the number of tasks currently being executed by the threads.
*
* @return The number of running tasks.
*/
[[nodiscard]] size_t get_tasks_running() const
{
const std::scoped_lock tasks_lock(tasks_mutex);
return tasks_running;
}
/**
* @brief Get the total number of unfinished tasks: either still waiting in the queue, or running in a thread. Note that get_tasks_total() == get_tasks_queued() + get_tasks_running().
*
* @return The total number of tasks.
*/
[[nodiscard]] size_t get_tasks_total() const
{
const std::scoped_lock tasks_lock(tasks_mutex);
return tasks_running + tasks.size();
}
/**
* @brief Get the number of threads in the pool.
*
* @return The number of threads.
*/
[[nodiscard]] concurrency_t get_thread_count() const
{
return thread_count;
}
/**
* @brief Check whether the pool is currently paused.
*
* @return true if the pool is paused, false if it is not paused.
*/
[[nodiscard]] bool is_paused() const
{
const std::scoped_lock tasks_lock(tasks_mutex);
return paused;
}
/**
* @brief Parallelize a loop by automatically splitting it into blocks and submitting each block separately to the queue. Returns a multi_future object that contains the futures for all of the blocks.
*
* @tparam F The type of the function to loop through.
* @tparam T1 The type of the first index in the loop. Should be a signed or unsigned integer.
* @tparam T2 The type of the index after the last index in the loop. Should be a signed or unsigned integer. If T1 is not the same as T2, a common type will be automatically inferred.
* @tparam T The common type of T1 and T2.
* @tparam R The return value of the loop function F (can be void).
* @param first_index The first index in the loop.
* @param index_after_last The index after the last index in the loop. The loop will iterate from first_index to (index_after_last - 1) inclusive. In other words, it will be equivalent to "for (T i = first_index; i < index_after_last; ++i)". Note that if index_after_last == first_index, no blocks will be submitted.
* @param loop The function to loop through. Will be called once per block. Should take exactly two arguments: the first index in the block and the index after the last index in the block. loop(start, end) should typically involve a loop of the form "for (T i = start; i < end; ++i)".
* @param num_blocks The maximum number of blocks to split the loop into. The default is to use the number of threads in the pool.
* @return A multi_future object that can be used to wait for all the blocks to finish. If the loop function returns a value, the multi_future object can also be used to obtain the values returned by each block.
*/
template <typename F, typename T1, typename T2, typename T = std::common_type_t<T1, T2>, typename R = std::invoke_result_t<std::decay_t<F>, T, T>>
[[nodiscard]] multi_future<R> parallelize_loop(const T1 first_index, const T2 index_after_last, F&& loop, const size_t num_blocks = 0)
{
blocks blks(first_index, index_after_last, num_blocks ? num_blocks : thread_count);
if (blks.get_total_size() > 0)
{
multi_future<R> mf(blks.get_num_blocks());
for (size_t i = 0; i < blks.get_num_blocks(); ++i)
mf[i] = submit(std::forward<F>(loop), blks.start(i), blks.end(i));
return mf;
}
else
{
return multi_future<R>();
}
}
/**
* @brief Parallelize a loop by automatically splitting it into blocks and submitting each block separately to the queue. Returns a multi_future object that contains the futures for all of the blocks. This overload is used for the special case where the first index is 0.
*
* @tparam F The type of the function to loop through.
* @tparam T The type of the loop indices. Should be a signed or unsigned integer.
* @tparam R The return value of the loop function F (can be void).
* @param index_after_last The index after the last index in the loop. The loop will iterate from 0 to (index_after_last - 1) inclusive. In other words, it will be equivalent to "for (T i = 0; i < index_after_last; ++i)". Note that if index_after_last == 0, no blocks will be submitted.
* @param loop The function to loop through. Will be called once per block. Should take exactly two arguments: the first index in the block and the index after the last index in the block. loop(start, end) should typically involve a loop of the form "for (T i = start; i < end; ++i)".
* @param num_blocks The maximum number of blocks to split the loop into. The default is to use the number of threads in the pool.
* @return A multi_future object that can be used to wait for all the blocks to finish. If the loop function returns a value, the multi_future object can also be used to obtain the values returned by each block.
*/
template <typename F, typename T, typename R = std::invoke_result_t<std::decay_t<F>, T, T>>
[[nodiscard]] multi_future<R> parallelize_loop(const T index_after_last, F&& loop, const size_t num_blocks = 0)
{
return parallelize_loop(0, index_after_last, std::forward<F>(loop), num_blocks);
}
/**
* @brief Pause the pool. The workers will temporarily stop retrieving new tasks out of the queue, although any tasks already executed will keep running until they are finished.
*/
void pause()
{
const std::scoped_lock tasks_lock(tasks_mutex);
paused = true;
}
/**
* @brief Purge all the tasks waiting in the queue. Tasks that are currently running will not be affected, but any tasks still waiting in the queue will be discarded, and will never be executed by the threads. Please note that there is no way to restore the purged tasks.
*/
void purge()
{
const std::scoped_lock tasks_lock(tasks_mutex);
while (!tasks.empty())
tasks.pop();
}
/**
* @brief Parallelize a loop by automatically splitting it into blocks and submitting each block separately to the queue. Does not return a multi_future, so the user must use wait_for_tasks() or some other method to ensure that the loop finishes executing, otherwise bad things will happen.
*
* @tparam F The type of the function to loop through.
* @tparam T1 The type of the first index in the loop. Should be a signed or unsigned integer.
* @tparam T2 The type of the index after the last index in the loop. Should be a signed or unsigned integer. If T1 is not the same as T2, a common type will be automatically inferred.
* @tparam T The common type of T1 and T2.
* @param first_index The first index in the loop.
* @param index_after_last The index after the last index in the loop. The loop will iterate from first_index to (index_after_last - 1) inclusive. In other words, it will be equivalent to "for (T i = first_index; i < index_after_last; ++i)". Note that if index_after_last == first_index, no blocks will be submitted.
* @param loop The function to loop through. Will be called once per block. Should take exactly two arguments: the first index in the block and the index after the last index in the block. loop(start, end) should typically involve a loop of the form "for (T i = start; i < end; ++i)".
* @param num_blocks The maximum number of blocks to split the loop into. The default is to use the number of threads in the pool.
*/
template <typename F, typename T1, typename T2, typename T = std::common_type_t<T1, T2>>
void push_loop(const T1 first_index, const T2 index_after_last, F&& loop, const size_t num_blocks = 0)
{
blocks blks(first_index, index_after_last, num_blocks ? num_blocks : thread_count);
if (blks.get_total_size() > 0)
{
for (size_t i = 0; i < blks.get_num_blocks(); ++i)
push_task(std::forward<F>(loop), blks.start(i), blks.end(i));
}
}
/**
* @brief Parallelize a loop by automatically splitting it into blocks and submitting each block separately to the queue. Does not return a multi_future, so the user must use wait_for_tasks() or some other method to ensure that the loop finishes executing, otherwise bad things will happen. This overload is used for the special case where the first index is 0.
*
* @tparam F The type of the function to loop through.
* @tparam T The type of the loop indices. Should be a signed or unsigned integer.
* @param index_after_last The index after the last index in the loop. The loop will iterate from 0 to (index_after_last - 1) inclusive. In other words, it will be equivalent to "for (T i = 0; i < index_after_last; ++i)". Note that if index_after_last == 0, no blocks will be submitted.
* @param loop The function to loop through. Will be called once per block. Should take exactly two arguments: the first index in the block and the index after the last index in the block. loop(start, end) should typically involve a loop of the form "for (T i = start; i < end; ++i)".
* @param num_blocks The maximum number of blocks to split the loop into. The default is to use the number of threads in the pool.
*/
template <typename F, typename T>
void push_loop(const T index_after_last, F&& loop, const size_t num_blocks = 0)
{
push_loop(0, index_after_last, std::forward<F>(loop), num_blocks);
}
/**
* @brief Push a function with zero or more arguments, but no return value, into the task queue. Does not return a future, so the user must use wait_for_tasks() or some other method to ensure that the task finishes executing, otherwise bad things will happen.
*
* @tparam F The type of the function.
* @tparam A The types of the arguments.
* @param task The function to push.
* @param args The zero or more arguments to pass to the function. Note that if the task is a class member function, the first argument must be a pointer to the object, i.e. &object (or this), followed by the actual arguments.
*/
template <typename F, typename... A>
void push_task(F&& task, A&&... args)
{
{
const std::scoped_lock tasks_lock(tasks_mutex);
tasks.push(std::bind(std::forward<F>(task), std::forward<A>(args)...)); // cppcheck-suppress ignoredReturnValue
}
task_available_cv.notify_one();
}
/**
* @brief Reset the number of threads in the pool. Waits for all currently running tasks to be completed, then destroys all threads in the pool and creates a new thread pool with the new number of threads. Any tasks that were waiting in the queue before the pool was reset will then be executed by the new threads. If the pool was paused before resetting it, the new pool will be paused as well.
*
* @param thread_count_ The number of threads to use. The default value is the total number of hardware threads available, as reported by the implementation. This is usually determined by the number of cores in the CPU. If a core is hyperthreaded, it will count as two threads.
*/
void reset(const concurrency_t thread_count_ = 0)
{
std::unique_lock tasks_lock(tasks_mutex);
const bool was_paused = paused;
paused = true;
tasks_lock.unlock();
wait_for_tasks();
destroy_threads();
thread_count = determine_thread_count(thread_count_);
threads = std::make_unique<std::thread[]>(thread_count);
paused = was_paused;
create_threads();
}
/**
* @brief Submit a function with zero or more arguments into the task queue. If the function has a return value, get a future for the eventual returned value. If the function has no return value, get an std::future<void> which can be used to wait until the task finishes.
*
* @tparam F The type of the function.
* @tparam A The types of the zero or more arguments to pass to the function.
* @tparam R The return type of the function (can be void).
* @param task The function to submit.
* @param args The zero or more arguments to pass to the function. Note that if the task is a class member function, the first argument must be a pointer to the object, i.e. &object (or this), followed by the actual arguments.
* @return A future to be used later to wait for the function to finish executing and/or obtain its returned value if it has one.
*/
template <typename F, typename... A, typename R = std::invoke_result_t<std::decay_t<F>, std::decay_t<A>...>>
[[nodiscard]] std::future<R> submit(F&& task, A&&... args)
{
std::shared_ptr<std::promise<R>> task_promise = std::make_shared<std::promise<R>>();
push_task(
[task_function = std::bind(std::forward<F>(task), std::forward<A>(args)...), task_promise]
{
try
{
if constexpr (std::is_void_v<R>)
{
std::invoke(task_function);
task_promise->set_value();
}
else
{
task_promise->set_value(std::invoke(task_function));
}
}
catch (...)
{
try
{
task_promise->set_exception(std::current_exception());
}
catch (...)
{
}
}
});
return task_promise->get_future();
}
/**
* @brief Unpause the pool. The workers will resume retrieving new tasks out of the queue.
*/
void unpause()
{
const std::scoped_lock tasks_lock(tasks_mutex);
paused = false;
}
/**
* @brief Wait for tasks to be completed. Normally, this function waits for all tasks, both those that are currently running in the threads and those that are still waiting in the queue. However, if the pool is paused, this function only waits for the currently running tasks (otherwise it would wait forever). Note: To wait for just one specific task, use submit() instead, and call the wait() member function of the generated future.
*/
void wait_for_tasks()
{
std::unique_lock tasks_lock(tasks_mutex);
waiting = true;
tasks_done_cv.wait(tasks_lock, [this] { return !tasks_running && (paused || tasks.empty()); });
waiting = false;
}
/**
* @brief Wait for tasks to be completed, but stop waiting after the specified duration has passed.
*
* @tparam R An arithmetic type representing the number of ticks to wait.
* @tparam P An std::ratio representing the length of each tick in seconds.
* @param duration The time duration to wait.
* @return true if all tasks finished running, false if the duration expired but some tasks are still running.
*/
template <typename R, typename P>
bool wait_for_tasks_duration(const std::chrono::duration<R, P>& duration)
{
std::unique_lock tasks_lock(tasks_mutex);
waiting = true;
const bool status = tasks_done_cv.wait_for(tasks_lock, duration, [this] { return !tasks_running && (paused || tasks.empty()); });
waiting = false;
return status;
}
/**
* @brief Wait for tasks to be completed, but stop waiting after the specified time point has been reached.
*
* @tparam C The type of the clock used to measure time.
* @tparam D An std::chrono::duration type used to indicate the time point.
* @param timeout_time The time point at which to stop waiting.
* @return true if all tasks finished running, false if the time point was reached but some tasks are still running.
*/
template <typename C, typename D>
bool wait_for_tasks_until(const std::chrono::time_point<C, D>& timeout_time)
{
std::unique_lock tasks_lock(tasks_mutex);
waiting = true;
const bool status = tasks_done_cv.wait_until(tasks_lock, timeout_time, [this] { return !tasks_running && (paused || tasks.empty()); });
waiting = false;
return status;
}
private:
// ========================
// Private member functions
// ========================
/**
* @brief Create the threads in the pool and assign a worker to each thread.
*/
void create_threads()
{
{
const std::scoped_lock tasks_lock(tasks_mutex);
workers_running = true;
}
for (concurrency_t i = 0; i < thread_count; ++i)
{
threads[i] = std::thread(&thread_pool::worker, this);
}
}
/**
* @brief Destroy the threads in the pool.
*/
void destroy_threads()
{
{
const std::scoped_lock tasks_lock(tasks_mutex);
workers_running = false;
}
task_available_cv.notify_all();
for (concurrency_t i = 0; i < thread_count; ++i)
{
threads[i].join();
}
}
/**
* @brief Determine how many threads the pool should have, based on the parameter passed to the constructor or reset().
*
* @param thread_count_ The parameter passed to the constructor or reset(). If the parameter is a positive number, then the pool will be created with this number of threads. If the parameter is non-positive, or a parameter was not supplied (in which case it will have the default value of 0), then the pool will be created with the total number of hardware threads available, as obtained from std::thread::hardware_concurrency(). If the latter returns a non-positive number for some reason, then the pool will be created with just one thread.
* @return The number of threads to use for constructing the pool.
*/
[[nodiscard]] concurrency_t determine_thread_count(const concurrency_t thread_count_) const
{
if (thread_count_ > 0)
return thread_count_;
else
{
if (std::thread::hardware_concurrency() > 0)
return std::thread::hardware_concurrency();
else
return 1;
}
}
/**
* @brief A worker function to be assigned to each thread in the pool. Waits until it is notified by push_task() that a task is available, and then retrieves the task from the queue and executes it. Once the task finishes, the worker notifies wait_for_tasks() in case it is waiting.
*/
void worker()
{
std::function<void()> task;
while (true)
{
std::unique_lock tasks_lock(tasks_mutex);
task_available_cv.wait(tasks_lock, [this] { return !tasks.empty() || !workers_running; });
if (!workers_running)
break;
if (paused)
continue;
task = std::move(tasks.front());
tasks.pop();
++tasks_running;
tasks_lock.unlock();
task();
tasks_lock.lock();
--tasks_running;
if (waiting && !tasks_running && (paused || tasks.empty()))
tasks_done_cv.notify_all();
}
}
// ============
// Private data
// ============
/**
* @brief A flag indicating whether the workers should pause. When set to true, the workers temporarily stop retrieving new tasks out of the queue, although any tasks already executed will keep running until they are finished. When set to false again, the workers resume retrieving tasks.
*/
bool paused = false;
/**
* @brief A condition variable to notify worker() that a new task has become available.
*/
std::condition_variable task_available_cv = {};
/**
* @brief A condition variable to notify wait_for_tasks() that the tasks are done.
*/
std::condition_variable tasks_done_cv = {};
/**
* @brief A queue of tasks to be executed by the threads.
*/
std::queue<std::function<void()>> tasks = {};
/**
* @brief A counter for the total number of currently running tasks.
*/
size_t tasks_running = 0;
/**
* @brief A mutex to synchronize access to the task queue by different threads.
*/
mutable std::mutex tasks_mutex = {};
/**
* @brief The number of threads in the pool.
*/
concurrency_t thread_count = 0;
/**
* @brief A smart pointer to manage the memory allocated for the threads.
*/
std::unique_ptr<std::thread[]> threads = nullptr;
/**
* @brief A flag indicating that wait_for_tasks() is active and expects to be notified whenever a task is done.
*/
bool waiting = false;
/**
* @brief A flag indicating to the workers to keep running. When set to false, the workers terminate permanently.
*/
bool workers_running = false;
};
// End class thread_pool //
// ============================================================================================= //
// ============================================================================================= //
// Begin class synced_stream //
/**
* @brief A helper class to synchronize printing to an output stream by different threads.
*/
class [[nodiscard]] synced_stream
{
public:
/**
* @brief Construct a new synced stream.
*
* @param out_stream_ The output stream to print to. The default value is std::cout.
*/
synced_stream(std::ostream& out_stream_ = std::cout) : out_stream(out_stream_) {}
/**
* @brief Print any number of items into the output stream. Ensures that no other threads print to this stream simultaneously, as long as they all exclusively use the same synced_stream object to print.
*
* @tparam T The types of the items
* @param items The items to print.
*/
template <typename... T>
void print(T&&... items)
{
const std::scoped_lock lock(stream_mutex);
(out_stream << ... << std::forward<T>(items));
}
/**
* @brief Print any number of items into the output stream, followed by a newline character. Ensures that no other threads print to this stream simultaneously, as long as they all exclusively use the same synced_stream object to print.
*
* @tparam T The types of the items
* @param items The items to print.
*/
template <typename... T>
void println(T&&... items)
{
print(std::forward<T>(items)..., '\n');
}
/**
* @brief A stream manipulator to pass to a synced_stream (an explicit cast of std::endl). Prints a newline character to the stream, and then flushes it. Should only be used if flushing is desired, otherwise '\n' should be used instead.
*/
inline static std::ostream& (&endl)(std::ostream&) = static_cast<std::ostream& (&)(std::ostream&)>(std::endl);
/**
* @brief A stream manipulator to pass to a synced_stream (an explicit cast of std::flush). Used to flush the stream.
*/
inline static std::ostream& (&flush)(std::ostream&) = static_cast<std::ostream& (&)(std::ostream&)>(std::flush);
private:
/**
* @brief The output stream to print to.
*/
std::ostream& out_stream;
/**
* @brief A mutex to synchronize printing.
*/
mutable std::mutex stream_mutex = {};
};
// End class synced_stream //
// ============================================================================================= //
// ============================================================================================= //
// Begin class timer //
/**
* @brief A helper class to measure execution time for benchmarking purposes.
*/
class [[nodiscard]] timer
{
public:
/**
* @brief Start (or restart) measuring time.
*/
void start()
{
start_time = std::chrono::steady_clock::now();
}
/**
* @brief Stop measuring time and store the elapsed time since start().
*/
void stop()
{
elapsed_time = std::chrono::steady_clock::now() - start_time;
}
/**
* @brief Get the number of milliseconds that have elapsed between start() and stop().
*
* @return The number of milliseconds.
*/
[[nodiscard]] std::chrono::milliseconds::rep ms() const
{
return (std::chrono::duration_cast<std::chrono::milliseconds>(elapsed_time)).count();
}
private:
/**
* @brief The time point when measuring started.
*/
std::chrono::time_point<std::chrono::steady_clock> start_time = std::chrono::steady_clock::now();
/**
* @brief The duration that has elapsed between start() and stop().
*/
std::chrono::duration<double> elapsed_time = std::chrono::duration<double>::zero();
};
// End class timer //
// ============================================================================================= //
} // namespace BS
+327
View File
@@ -0,0 +1,327 @@
#pragma once
/**
* @file BS_thread_pool_light.hpp
* @author Barak Shoshany (baraksh@gmail.com) (http://baraksh.com)
* @version 3.5.0
* @date 2023-05-25
* @copyright Copyright (c) 2023 Barak Shoshany. Licensed under the MIT license. If you found this project useful, please consider starring it on GitHub! If you use this library in software of any kind, please provide a link to the GitHub repository https://github.com/bshoshany/thread-pool in the source code and documentation. If you use this library in published research, please cite it as follows: Barak Shoshany, "A C++17 Thread Pool for High-Performance Scientific Computing", doi:10.5281/zenodo.4742687, arXiv:2105.00613 (May 2021)
*
* @brief BS::thread_pool_light: a fast, lightweight, and easy-to-use C++17 thread pool library. This header file contains a light version of the main library, for use when advanced features are not needed.
*/
#define BS_THREAD_POOL_LIGHT_VERSION "v3.5.0 (2023-05-25)"
#include <condition_variable> // std::condition_variable
#include <exception> // std::current_exception
#include <functional> // std::bind, std::function, std::invoke
#include <future> // std::future, std::promise
#include <memory> // std::make_shared, std::make_unique, std::shared_ptr, std::unique_ptr
#include <mutex> // std::mutex, std::scoped_lock, std::unique_lock
#include <queue> // std::queue
#include <thread> // std::thread
#include <type_traits> // std::common_type_t, std::decay_t, std::invoke_result_t, std::is_void_v
#include <utility> // std::forward, std::move, std::swap
namespace BS
{
/**
* @brief A convenient shorthand for the type of std::thread::hardware_concurrency(). Should evaluate to unsigned int.
*/
using concurrency_t = std::invoke_result_t<decltype(std::thread::hardware_concurrency)>;
/**
* @brief A fast, lightweight, and easy-to-use C++17 thread pool class. This is a lighter version of the main thread pool class.
*/
class [[nodiscard]] thread_pool_light
{
public:
// ============================
// Constructors and destructors
// ============================
/**
* @brief Construct a new thread pool.
*
* @param thread_count_ The number of threads to use. The default value is the total number of hardware threads available, as reported by the implementation. This is usually determined by the number of cores in the CPU. If a core is hyperthreaded, it will count as two threads.
*/
thread_pool_light(const concurrency_t thread_count_ = 0) : thread_count(determine_thread_count(thread_count_)), threads(std::make_unique<std::thread[]>(determine_thread_count(thread_count_)))
{
create_threads();
}
/**
* @brief Destruct the thread pool. Waits for all tasks to complete, then destroys all threads.
*/
~thread_pool_light()
{
wait_for_tasks();
destroy_threads();
}
// =======================
// Public member functions
// =======================
/**
* @brief Get the number of threads in the pool.
*
* @return The number of threads.
*/
[[nodiscard]] concurrency_t get_thread_count() const
{
return thread_count;
}
/**
* @brief Parallelize a loop by automatically splitting it into blocks and submitting each block separately to the queue. The user must use wait_for_tasks() or some other method to ensure that the loop finishes executing, otherwise bad things will happen.
*
* @tparam F The type of the function to loop through.
* @tparam T1 The type of the first index in the loop. Should be a signed or unsigned integer.
* @tparam T2 The type of the index after the last index in the loop. Should be a signed or unsigned integer. If T1 is not the same as T2, a common type will be automatically inferred.
* @tparam T The common type of T1 and T2.
* @param first_index The first index in the loop.
* @param index_after_last The index after the last index in the loop. The loop will iterate from first_index to (index_after_last - 1) inclusive. In other words, it will be equivalent to "for (T i = first_index; i < index_after_last; ++i)". Note that if index_after_last == first_index, no blocks will be submitted.
* @param loop The function to loop through. Will be called once per block. Should take exactly two arguments: the first index in the block and the index after the last index in the block. loop(start, end) should typically involve a loop of the form "for (T i = start; i < end; ++i)".
* @param num_blocks The maximum number of blocks to split the loop into. The default is to use the number of threads in the pool.
*/
template <typename F, typename T1, typename T2, typename T = std::common_type_t<T1, T2>>
void push_loop(T1 first_index_, T2 index_after_last_, F&& loop, size_t num_blocks = 0)
{
T first_index = static_cast<T>(first_index_);
T index_after_last = static_cast<T>(index_after_last_);
if (num_blocks == 0)
num_blocks = thread_count;
if (index_after_last < first_index)
std::swap(index_after_last, first_index);
size_t total_size = static_cast<size_t>(index_after_last - first_index);
size_t block_size = static_cast<size_t>(total_size / num_blocks);
if (block_size == 0)
{
block_size = 1;
num_blocks = (total_size > 1) ? total_size : 1;
}
if (total_size > 0)
{
for (size_t i = 0; i < num_blocks; ++i)
push_task(std::forward<F>(loop), static_cast<T>(i * block_size) + first_index, (i == num_blocks - 1) ? index_after_last : (static_cast<T>((i + 1) * block_size) + first_index));
}
}
/**
* @brief Parallelize a loop by automatically splitting it into blocks and submitting each block separately to the queue. The user must use wait_for_tasks() or some other method to ensure that the loop finishes executing, otherwise bad things will happen. This overload is used for the special case where the first index is 0.
*
* @tparam F The type of the function to loop through.
* @tparam T The type of the loop indices. Should be a signed or unsigned integer.
* @param index_after_last The index after the last index in the loop. The loop will iterate from 0 to (index_after_last - 1) inclusive. In other words, it will be equivalent to "for (T i = 0; i < index_after_last; ++i)". Note that if index_after_last == 0, no blocks will be submitted.
* @param loop The function to loop through. Will be called once per block. Should take exactly two arguments: the first index in the block and the index after the last index in the block. loop(start, end) should typically involve a loop of the form "for (T i = start; i < end; ++i)".
* @param num_blocks The maximum number of blocks to split the loop into. The default is to use the number of threads in the pool.
*/
template <typename F, typename T>
void push_loop(const T index_after_last, F&& loop, const size_t num_blocks = 0)
{
push_loop(0, index_after_last, std::forward<F>(loop), num_blocks);
}
/**
* @brief Push a function with zero or more arguments, but no return value, into the task queue. Does not return a future, so the user must use wait_for_tasks() or some other method to ensure that the task finishes executing, otherwise bad things will happen.
*
* @tparam F The type of the function.
* @tparam A The types of the arguments.
* @param task The function to push.
* @param args The zero or more arguments to pass to the function. Note that if the task is a class member function, the first argument must be a pointer to the object, i.e. &object (or this), followed by the actual arguments.
*/
template <typename F, typename... A>
void push_task(F&& task, A&&... args)
{
{
const std::scoped_lock tasks_lock(tasks_mutex);
tasks.push(std::bind(std::forward<F>(task), std::forward<A>(args)...)); // cppcheck-suppress ignoredReturnValue
}
task_available_cv.notify_one();
}
/**
* @brief Submit a function with zero or more arguments into the task queue. If the function has a return value, get a future for the eventual returned value. If the function has no return value, get an std::future<void> which can be used to wait until the task finishes.
*
* @tparam F The type of the function.
* @tparam A The types of the zero or more arguments to pass to the function.
* @tparam R The return type of the function (can be void).
* @param task The function to submit.
* @param args The zero or more arguments to pass to the function. Note that if the task is a class member function, the first argument must be a pointer to the object, i.e. &object (or this), followed by the actual arguments.
* @return A future to be used later to wait for the function to finish executing and/or obtain its returned value if it has one.
*/
template <typename F, typename... A, typename R = std::invoke_result_t<std::decay_t<F>, std::decay_t<A>...>>
[[nodiscard]] std::future<R> submit(F&& task, A&&... args)
{
std::shared_ptr<std::promise<R>> task_promise = std::make_shared<std::promise<R>>();
push_task(
[task_function = std::bind(std::forward<F>(task), std::forward<A>(args)...), task_promise]
{
try
{
if constexpr (std::is_void_v<R>)
{
std::invoke(task_function);
task_promise->set_value();
}
else
{
task_promise->set_value(std::invoke(task_function));
}
}
catch (...)
{
try
{
task_promise->set_exception(std::current_exception());
}
catch (...)
{
}
}
});
return task_promise->get_future();
}
/**
* @brief Wait for tasks to be completed, both those that are currently running in the threads and those that are still waiting in the queue. Note: To wait for just one specific task, use submit() instead, and call the wait() member function of the generated future.
*/
void wait_for_tasks()
{
std::unique_lock tasks_lock(tasks_mutex);
waiting = true;
tasks_done_cv.wait(tasks_lock, [this] { return !tasks_running && tasks.empty(); });
waiting = false;
}
private:
// ========================
// Private member functions
// ========================
/**
* @brief Create the threads in the pool and assign a worker to each thread.
*/
void create_threads()
{
{
const std::scoped_lock tasks_lock(tasks_mutex);
workers_running = true;
}
for (concurrency_t i = 0; i < thread_count; ++i)
{
threads[i] = std::thread(&thread_pool_light::worker, this);
}
}
/**
* @brief Destroy the threads in the pool.
*/
void destroy_threads()
{
{
const std::scoped_lock tasks_lock(tasks_mutex);
workers_running = false;
}
task_available_cv.notify_all();
for (concurrency_t i = 0; i < thread_count; ++i)
{
threads[i].join();
}
}
/**
* @brief Determine how many threads the pool should have, based on the parameter passed to the constructor.
*
* @param thread_count_ The parameter passed to the constructor. If the parameter is a positive number, then the pool will be created with this number of threads. If the parameter is non-positive, or a parameter was not supplied (in which case it will have the default value of 0), then the pool will be created with the total number of hardware threads available, as obtained from std::thread::hardware_concurrency(). If the latter returns a non-positive number for some reason, then the pool will be created with just one thread.
* @return The number of threads to use for constructing the pool.
*/
[[nodiscard]] concurrency_t determine_thread_count(const concurrency_t thread_count_) const
{
if (thread_count_ > 0)
return thread_count_;
else
{
if (std::thread::hardware_concurrency() > 0)
return std::thread::hardware_concurrency();
else
return 1;
}
}
/**
* @brief A worker function to be assigned to each thread in the pool. Waits until it is notified by push_task() that a task is available, and then retrieves the task from the queue and executes it. Once the task finishes, the worker notifies wait_for_tasks() in case it is waiting.
*/
void worker()
{
std::function<void()> task;
while (true)
{
std::unique_lock tasks_lock(tasks_mutex);
task_available_cv.wait(tasks_lock, [this] { return !tasks.empty() || !workers_running; });
if (!workers_running)
break;
task = std::move(tasks.front());
tasks.pop();
++tasks_running;
tasks_lock.unlock();
task();
tasks_lock.lock();
--tasks_running;
if (waiting && !tasks_running && tasks.empty())
tasks_done_cv.notify_all();
}
}
// ============
// Private data
// ============
/**
* @brief A condition variable to notify worker() that a new task has become available.
*/
std::condition_variable task_available_cv = {};
/**
* @brief A condition variable to notify wait_for_tasks() that the tasks are done.
*/
std::condition_variable tasks_done_cv = {};
/**
* @brief A queue of tasks to be executed by the threads.
*/
std::queue<std::function<void()>> tasks = {};
/**
* @brief A counter for the total number of currently running tasks.
*/
size_t tasks_running = 0;
/**
* @brief A mutex to synchronize access to the task queue by different threads.
*/
mutable std::mutex tasks_mutex = {};
/**
* @brief The number of threads in the pool.
*/
concurrency_t thread_count = 0;
/**
* @brief A smart pointer to manage the memory allocated for the threads.
*/
std::unique_ptr<std::thread[]> threads = nullptr;
/**
* @brief A flag indicating that wait_for_tasks() is active and expects to be notified whenever a task is done.
*/
bool waiting = false;
/**
* @brief A flag indicating to the workers to keep running. When set to false, the workers terminate permanently.
*/
bool workers_running = false;
};
} // namespace BS
File diff suppressed because it is too large Load Diff
+224
View File
@@ -0,0 +1,224 @@
#!/usr/bin/env pwsh
$Host.UI.RawUI.WindowTitle = 'BS::thread_pool Test Script'
$TitleColor = 'Green'
$TextColor = 'Yellow'
$ErrorColor = 'Red'
$CommandColor = 'Blue'
Function Write-Title([String] $Title)
{
If ($Title.Length -gt 0)
{
$Separator = '=' * $Title.Length
Write-Host
Write-Host $Separator -ForegroundColor $TitleColor
Write-Host $Title -ForegroundColor $TitleColor
Write-Host $Separator -ForegroundColor $TitleColor
Write-Host
}
}
Function Write-Text([String] $Text)
{
Write-Host $Text -ForegroundColor $TextColor
}
Function Write-Error([String] $Text)
{
Write-Host $Text -ForegroundColor $ErrorColor
}
Function Write-Command([String] $Text)
{
Write-Host $Text -ForegroundColor $CommandColor
}
Function Exit-Script([Int] $Code)
{
Set-Location $CurrentDir
Exit $Code
}
$CurrentDir = Get-Location
Write-Title '=== BS::thread_pool test script ==='
$SourceFile = 'BS_thread_pool_test.cpp'
If (Test-Path -Path $SourceFile)
{
Write-Text "Found source file $SourceFile."
}
Else
{
Write-Error "Source file $SourceFile not found, aborting script!"
Exit-Script 1
}
$BuildFolder = Join-Path '..' 'build'
If (Test-Path -Path $BuildFolder)
{
Write-Text 'Cleaning up build folder...'
Remove-Item (Join-Path $BuildFolder '*')
}
Else
{
Write-Text 'Creating build folder...'
$Null = New-Item $BuildFolder -ItemType 'Directory'
}
Write-Text 'Done.'
Write-Title 'Compiling...'
If ($IsWindows)
{
$Extension = '.exe'
$PThread = ''
}
Else
{
$Extension = ''
$PThread = ' -pthread'
}
$ClangExe = 'BS_thread_pool_test_clang' + $Extension
$GCCExe = 'BS_thread_pool_test_gcc' + $Extension
$MSVCName = 'BS_thread_pool_test_msvc'
$MSVCExe = $MSVCName + $Extension
$MSVCObj = $MSVCName + '.obj'
If (Get-Command 'clang++' -ErrorAction SilentlyContinue)
{
$Clang = $True
$FullClangExe = Join-Path $BuildFolder $ClangExe
Write-Text 'Compiling with Clang...'
$ClangCommand = "clang++ $SourceFile$PThread -std=c++17 -O3 -Wall -Wextra -Wconversion -Wsign-conversion -Wpedantic -Weffc++ -Wshadow -o $FullClangExe"
Write-Command $ClangCommand
Invoke-Expression $ClangCommand
If ($LASTEXITCODE)
{
Write-Error "Failed to compile, aborting script! (Exit code: $LASTEXITCODE)"
Exit-Script $LASTEXITCODE
}
Else
{
Write-Text "Successfully compiled to $FullClangExe."
}
}
Else
{
$Clang = $False
Write-Error 'Clang not found, skipping it!'
}
Write-Host
If (Get-Command 'g++' -ErrorAction SilentlyContinue)
{
$GCC = $True
$FullGCCExe = Join-Path $BuildFolder $GCCExe
Write-Text 'Compiling with GCC...'
$GCCCommand = "g++ $SourceFile$PThread -std=c++17 -O3 -Wall -Wextra -Wconversion -Wsign-conversion -Wpedantic -Weffc++ -Wshadow -o $FullGCCExe"
Write-Command $GCCCommand
Invoke-Expression $GCCCommand
If ($LASTEXITCODE)
{
Write-Error "Failed to compile, aborting script! (Exit code: $LASTEXITCODE)"
Exit-Script $LASTEXITCODE
}
Else
{
Write-Text "Successfully compiled to $FullGCCExe."
}
}
Else
{
$GCC = $False
Write-Error 'GCC not found, skipping it!'
}
Write-Host
If ($IsWindows)
{
$MSVCEnv = 'C:\Program Files\Microsoft Visual Studio\2022\Community\Common7\Tools\Launch-VsDevShell.ps1'
If (Test-Path $MSVCEnv)
{
$MSVC = $True
$FullMSVCExe = Join-Path $BuildFolder $MSVCExe
$FullMSVCObj = Join-Path $BuildFolder $MSVCObj
Write-Text 'Compiling with MSVC...'
$Env:BS_THREAD_POOL_MSVC_COMMAND = "cl $SourceFile /std:c++17 /permissive- /O2 /W4 /EHsc /Fe:$FullMSVCExe /Fo:$FullMSVCObj"
Write-Command $Env:BS_THREAD_POOL_MSVC_COMMAND
pwsh -Command {
$CurrentDir = Get-Location
& 'C:\Program Files\Microsoft Visual Studio\2022\Community\Common7\Tools\Launch-VsDevShell.ps1'
Set-Location $CurrentDir
Invoke-Expression $Env:BS_THREAD_POOL_MSVC_COMMAND
Exit $LASTEXITCODE
}
$Env:BS_THREAD_POOL_MSVC_COMMAND = $Null
If ($LASTEXITCODE)
{
Write-Error "Failed to compile, aborting script! (Exit code: $LASTEXITCODE)"
Exit-Script $LASTEXITCODE
}
Else
{
Remove-Item $FullMSVCObj
Write-Text "Successfully compiled to $FullMSVCExe."
}
}
Else
{
$MSVC = $False
Write-Error 'MSVC not found, skipping it!'
}
}
Else
{
$MSVC = $False
}
Write-Title 'Starting tests...'
Set-Location $BuildFolder
$Repeats = 5;
Write-Text "Each test will be repeated $Repeats times. Outputs can be found in the generated log files."
Function Invoke-Test([String] $Compiler, [String] $Executable)
{
Write-Title "Starting $Compiler tests..."
For ($i = 1; $i -Le $Repeats; $i++)
{
Write-Text "Running $Compiler test #$i of $Repeats..."
Invoke-Expression $Executable | Out-Null
if ($LASTEXITCODE)
{
Write-Error "Test Failed, aborting script! (Exit code: $LASTEXITCODE)"
Exit-Script $LASTEXITCODE
}
Write-Text 'Test finished successfully!'
Write-Host
}
Write-Text "$Compiler tests done."
}
if ($Clang)
{
Invoke-Test 'Clang' (Join-Path '.' $ClangExe)
}
if ($GCC)
{
Invoke-Test 'GCC' (Join-Path '.' $GCCExe)
}
if ($MSVC)
{
Invoke-Test 'MSVC' (Join-Path '.' $MSVCExe)
}
Write-Title '=== All tests completed successfully! ==='
Exit-Script 0