mirror of
https://github.com/bshoshany/thread-pool.git
synced 2026-07-22 19:43:00 +04:00
Compare commits
2 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| ff95929999 | |||
| cabb3df587 |
+159
@@ -0,0 +1,159 @@
|
||||
---
|
||||
AccessModifierOffset: -4
|
||||
AlignAfterOpenBracket: DontAlign
|
||||
AlignArrayOfStructures: None
|
||||
AlignConsecutiveAssignments: None
|
||||
AlignConsecutiveBitFields: None
|
||||
AlignConsecutiveDeclarations: None
|
||||
AlignConsecutiveMacros: None
|
||||
AlignConsecutiveShortCaseStatements:
|
||||
Enabled: false
|
||||
AlignEscapedNewlines: Left
|
||||
AlignOperands: DontAlign
|
||||
AlignTrailingComments:
|
||||
Kind: Always
|
||||
OverEmptyLines: 1
|
||||
AllowAllArgumentsOnNextLine: false
|
||||
AllowAllParametersOfDeclarationOnNextLine: false
|
||||
AllowBreakBeforeNoexceptSpecifier: Never
|
||||
AllowShortBlocksOnASingleLine: Empty
|
||||
AllowShortCaseLabelsOnASingleLine: false
|
||||
AllowShortCompoundRequirementOnASingleLine: true
|
||||
AllowShortEnumsOnASingleLine: false
|
||||
AllowShortFunctionsOnASingleLine: Empty
|
||||
AllowShortIfStatementsOnASingleLine: Never
|
||||
AllowShortLambdasOnASingleLine: Empty
|
||||
AllowShortLoopsOnASingleLine: false
|
||||
AlwaysBreakAfterReturnType: None
|
||||
AlwaysBreakBeforeMultilineStrings: false
|
||||
AlwaysBreakTemplateDeclarations: "Yes"
|
||||
AttributeMacros: []
|
||||
BinPackArguments: true
|
||||
BinPackParameters: true
|
||||
BitFieldColonSpacing: Both
|
||||
BraceWrapping:
|
||||
AfterCaseLabel: true
|
||||
AfterClass: true
|
||||
AfterControlStatement: Always
|
||||
AfterEnum: true
|
||||
AfterExternBlock: true
|
||||
AfterFunction: true
|
||||
AfterNamespace: false
|
||||
AfterStruct: true
|
||||
AfterUnion: true
|
||||
BeforeCatch: true
|
||||
BeforeElse: true
|
||||
BeforeLambdaBody: true
|
||||
BeforeWhile: false
|
||||
IndentBraces: false
|
||||
SplitEmptyFunction: true
|
||||
SplitEmptyNamespace: true
|
||||
SplitEmptyRecord: true
|
||||
BracedInitializerIndentWidth: 4
|
||||
BreakAdjacentStringLiterals: false
|
||||
BreakAfterAttributes: Never
|
||||
BreakBeforeBinaryOperators: None
|
||||
BreakBeforeBraces: Custom
|
||||
BreakBeforeConceptDeclarations: true
|
||||
BreakBeforeInheritanceComma: false
|
||||
BreakBeforeTernaryOperators: true
|
||||
BreakConstructorInitializers: BeforeColon
|
||||
BreakConstructorInitializersBeforeComma: false
|
||||
BreakInheritanceList: BeforeColon
|
||||
BreakStringLiterals: true
|
||||
ColumnLimit: 1024
|
||||
CompactNamespaces: false
|
||||
ConstructorInitializerAllOnOneLineOrOnePerLine: false
|
||||
ConstructorInitializerIndentWidth: 4
|
||||
ContinuationIndentWidth: 4
|
||||
Cpp11BracedListStyle: true
|
||||
DeriveLineEnding: true
|
||||
DerivePointerAlignment: false
|
||||
DisableFormat: false
|
||||
EmptyLineAfterAccessModifier: Never
|
||||
EmptyLineBeforeAccessModifier: LogicalBlock
|
||||
ExperimentalAutoDetectBinPacking: false
|
||||
FixNamespaceComments: true
|
||||
IncludeBlocks: Preserve
|
||||
IncludeIsMainSourceRegex: ""
|
||||
IndentAccessModifiers: false
|
||||
IndentCaseBlocks: false
|
||||
IndentCaseLabels: false
|
||||
IndentExternBlock: AfterExternBlock
|
||||
IndentGotoLabels: true
|
||||
IndentPPDirectives: None
|
||||
IndentRequires: false
|
||||
IndentWidth: 4
|
||||
IndentWrappedFunctionNames: false
|
||||
JavaScriptQuotes: Leave
|
||||
JavaScriptWrapImports: true
|
||||
KeepEmptyLinesAtTheStartOfBlocks: true
|
||||
LambdaBodyIndentation: Signature
|
||||
Language: Cpp
|
||||
MacroBlockBegin: ""
|
||||
MacroBlockEnd: ""
|
||||
MaxEmptyLinesToKeep: 1
|
||||
NamespaceIndentation: Inner
|
||||
ObjCBinPackProtocolList: Auto
|
||||
ObjCBlockIndentWidth: 4
|
||||
ObjCBreakBeforeNestedBlockParam: true
|
||||
ObjCSpaceAfterProperty: false
|
||||
ObjCSpaceBeforeProtocolList: true
|
||||
PPIndentWidth: -1
|
||||
PackConstructorInitializers: BinPack
|
||||
PenaltyBreakAssignment: 0
|
||||
PenaltyBreakBeforeFirstCallParameter: 0
|
||||
PenaltyBreakComment: 0
|
||||
PenaltyBreakFirstLessLess: 0
|
||||
PenaltyBreakOpenParenthesis: 0
|
||||
PenaltyBreakString: 0
|
||||
PenaltyBreakTemplateDeclaration: 0
|
||||
PenaltyExcessCharacter: 0
|
||||
PenaltyIndentedWhitespace: 0
|
||||
PenaltyReturnTypeOnItsOwnLine: 0
|
||||
PointerAlignment: Left
|
||||
QualifierAlignment: Leave
|
||||
ReferenceAlignment: Pointer
|
||||
ReflowComments: true
|
||||
RemoveBracesLLVM: false
|
||||
SeparateDefinitionBlocks: Always
|
||||
ShortNamespaceLines: 1
|
||||
SortIncludes: CaseSensitive
|
||||
SortJavaStaticImport: Before
|
||||
SortUsingDeclarations: true
|
||||
SpaceAfterCStyleCast: false
|
||||
SpaceAfterLogicalNot: false
|
||||
SpaceAfterTemplateKeyword: true
|
||||
SpaceAroundPointerQualifiers: Default
|
||||
SpaceBeforeAssignmentOperators: true
|
||||
SpaceBeforeCaseColon: false
|
||||
SpaceBeforeCpp11BracedList: false
|
||||
SpaceBeforeCtorInitializerColon: true
|
||||
SpaceBeforeInheritanceColon: true
|
||||
SpaceBeforeParens: ControlStatements
|
||||
SpaceBeforeParensOptions:
|
||||
AfterControlStatements: true
|
||||
AfterForeachMacros: true
|
||||
AfterFunctionDeclarationName: false
|
||||
AfterFunctionDefinitionName: false
|
||||
AfterIfMacros: true
|
||||
AfterOverloadedOperator: false
|
||||
BeforeNonEmptyParentheses: false
|
||||
SpaceBeforeRangeBasedForLoopColon: true
|
||||
SpaceBeforeSquareBrackets: false
|
||||
SpaceInEmptyBlock: false
|
||||
SpaceInEmptyParentheses: false
|
||||
SpacesBeforeTrailingComments: 1
|
||||
SpacesInAngles: Never
|
||||
SpacesInCStyleCastParentheses: false
|
||||
SpacesInConditionalStatement: false
|
||||
SpacesInContainerLiterals: true
|
||||
SpacesInLineCommentPrefix:
|
||||
Maximum: 1
|
||||
Minimum: 1
|
||||
SpacesInParentheses: false
|
||||
SpacesInSquareBrackets: false
|
||||
Standard: c++17
|
||||
TabWidth: 4
|
||||
UseCRLF: false
|
||||
UseTab: Never
|
||||
+45
@@ -0,0 +1,45 @@
|
||||
---
|
||||
CheckOptions:
|
||||
misc-const-correctness.WarnPointersAsValues: true
|
||||
misc-include-cleaner.IgnoreHeaders: time.h
|
||||
Checks: >
|
||||
-*,
|
||||
bugprone-*,
|
||||
-bugprone-easily-swappable-parameters,
|
||||
-bugprone-empty-catch,
|
||||
-bugprone-exception-escape,
|
||||
cert-*,
|
||||
-cert-err58-cpp,
|
||||
concurrency-*,
|
||||
-concurrency-mt-unsafe,
|
||||
cppcoreguidelines-*,
|
||||
-cppcoreguidelines-avoid-c-arrays,
|
||||
-cppcoreguidelines-avoid-do-while,
|
||||
-cppcoreguidelines-avoid-non-const-global-variables,
|
||||
-cppcoreguidelines-interfaces-global-init,
|
||||
-cppcoreguidelines-macro-usage,
|
||||
-cppcoreguidelines-missing-std-forward,
|
||||
-cppcoreguidelines-pro-bounds-array-to-pointer-decay,
|
||||
-cppcoreguidelines-special-member-functions,
|
||||
hicpp-*,
|
||||
-hicpp-avoid-c-arrays,
|
||||
-hicpp-braces-around-statements,
|
||||
-hicpp-named-parameter,
|
||||
-hicpp-no-array-decay,
|
||||
-hicpp-special-member-functions,
|
||||
-hicpp-use-auto,
|
||||
misc-*,
|
||||
-misc-definitions-in-headers,
|
||||
modernize-*,
|
||||
-modernize-avoid-c-arrays,
|
||||
-modernize-use-auto,
|
||||
-modernize-use-trailing-return-type,
|
||||
performance-*,
|
||||
portability-*,
|
||||
readability-*,
|
||||
-readability-braces-around-statements,
|
||||
-readability-const-return-type,
|
||||
-readability-named-parameter,
|
||||
-readability-redundant-member-init,
|
||||
-readability-use-anyofallof,
|
||||
HeaderFilterRegex: .*
|
||||
@@ -6,9 +6,19 @@
|
||||
|
||||
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?
|
||||
|
||||
**Linting**
|
||||
|
||||
Have you linted your code using the `.clang-tidy` 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:
|
||||
|
||||
@@ -0,0 +1,2 @@
|
||||
build
|
||||
temp
|
||||
@@ -1,813 +0,0 @@
|
||||
#pragma once
|
||||
|
||||
/**
|
||||
* @file BS_thread_pool.hpp
|
||||
* @author Barak Shoshany (baraksh@gmail.com) (http://baraksh.com)
|
||||
* @version 3.4.0
|
||||
* @date 2023-05-12
|
||||
* @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.4.0 (2023-05-12)"
|
||||
|
||||
#include <atomic> // std::atomic
|
||||
#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_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 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
|
||||
{
|
||||
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()
|
||||
{
|
||||
paused = true;
|
||||
}
|
||||
|
||||
/**
|
||||
* @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)
|
||||
{
|
||||
std::function<void()> task_function = std::bind(std::forward<F>(task), std::forward<A>(args)...);
|
||||
{
|
||||
const std::scoped_lock tasks_lock(tasks_mutex);
|
||||
tasks.push(task_function);
|
||||
++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. 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::function<R()> task_function = std::bind(std::forward<F>(task), std::forward<A>(args)...);
|
||||
std::shared_ptr<std::promise<R>> task_promise = std::make_shared<std::promise<R>>();
|
||||
push_task(
|
||||
[task_function, 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()
|
||||
{
|
||||
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()
|
||||
{
|
||||
if (!waiting)
|
||||
{
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @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 finished waiting before the duration expired, false if timed out or the pool is already waiting. In other words, returns false if and only if tasks are still running.
|
||||
*/
|
||||
template <typename R, typename P>
|
||||
bool wait_for_tasks_duration(const std::chrono::duration<R, P>& duration)
|
||||
{
|
||||
if (!waiting)
|
||||
{
|
||||
waiting = true;
|
||||
std::unique_lock<std::mutex> tasks_lock(tasks_mutex);
|
||||
const bool status = task_done_cv.wait_for(tasks_lock, duration, [this] { return (tasks_total == (paused ? tasks.size() : 0)); });
|
||||
waiting = false;
|
||||
return status;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* @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 finished waiting before the time point was reached, false if timed out or the pool is already waiting. In other words, returns false if and only if tasks are still running.
|
||||
*/
|
||||
template <typename C, typename D>
|
||||
bool wait_for_tasks_until(const std::chrono::time_point<C, D>& timeout_time)
|
||||
{
|
||||
if (!waiting)
|
||||
{
|
||||
waiting = true;
|
||||
std::unique_lock<std::mutex> tasks_lock(tasks_mutex);
|
||||
const bool status = task_done_cv.wait_until(tasks_lock, timeout_time, [this] { return (tasks_total == (paused ? tasks.size() : 0)); });
|
||||
waiting = false;
|
||||
return status;
|
||||
}
|
||||
return 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;
|
||||
{
|
||||
const std::scoped_lock tasks_lock(tasks_mutex);
|
||||
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, [this] { 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 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.
|
||||
*/
|
||||
std::atomic<bool> paused = false;
|
||||
|
||||
/**
|
||||
* @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(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
|
||||
@@ -1,331 +0,0 @@
|
||||
#pragma once
|
||||
|
||||
/**
|
||||
* @file BS_thread_pool_light.hpp
|
||||
* @author Barak Shoshany (baraksh@gmail.com) (http://baraksh.com)
|
||||
* @version 3.4.0
|
||||
* @date 2023-05-12
|
||||
* @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.4.0 (2023-05-12)"
|
||||
|
||||
#include <atomic> // std::atomic
|
||||
#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)
|
||||
{
|
||||
std::function<void()> task_function = std::bind(std::forward<F>(task), std::forward<A>(args)...);
|
||||
{
|
||||
const std::scoped_lock tasks_lock(tasks_mutex);
|
||||
tasks.push(task_function);
|
||||
++tasks_total;
|
||||
}
|
||||
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::function<R()> task_function = std::bind(std::forward<F>(task), std::forward<A>(args)...);
|
||||
std::shared_ptr<std::promise<R>> task_promise = std::make_shared<std::promise<R>>();
|
||||
push_task(
|
||||
[task_function, 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. 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. 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()
|
||||
{
|
||||
if (!waiting)
|
||||
{
|
||||
waiting = true;
|
||||
std::unique_lock<std::mutex> tasks_lock(tasks_mutex);
|
||||
task_done_cv.wait(tasks_lock, [this] { return (tasks_total == 0); });
|
||||
waiting = 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_light::worker, this);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Destroy the threads in the pool.
|
||||
*/
|
||||
void destroy_threads()
|
||||
{
|
||||
running = false;
|
||||
{
|
||||
const std::scoped_lock tasks_lock(tasks_mutex);
|
||||
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_)
|
||||
{
|
||||
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, [this] { return !tasks.empty() || !running; });
|
||||
if (running)
|
||||
{
|
||||
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;
|
||||
};
|
||||
|
||||
} // namespace BS
|
||||
@@ -1,657 +0,0 @@
|
||||
/**
|
||||
* @file BS_thread_pool_light_test.cpp
|
||||
* @author Barak Shoshany (baraksh@gmail.com) (http://baraksh.com)
|
||||
* @version 3.4.0
|
||||
* @date 2023-05-12
|
||||
* @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 program tests all aspects of the light version of the main library, but is not needed in order to use the library.
|
||||
*/
|
||||
|
||||
#include <algorithm> // std::min, std::sort, std::unique
|
||||
#include <atomic> // std::atomic
|
||||
#include <chrono> // std::chrono
|
||||
#include <cmath> // std::abs
|
||||
#include <condition_variable> // std::condition_variable
|
||||
#include <cstdlib> // std::quick_exit
|
||||
#include <exception> // std::exception
|
||||
#include <future> // std::future
|
||||
#include <iostream> // std::cout
|
||||
#include <memory> // std::make_unique, std::unique_ptr
|
||||
#include <mutex> // std::mutex, std::scoped_lock, std::unique_lock
|
||||
#include <random> // std::mt19937_64, std::random_device, std::uniform_int_distribution
|
||||
#include <stdexcept> // std::runtime_error
|
||||
#include <string> // std::string, std::to_string
|
||||
#include <thread> // std::this_thread, std::thread
|
||||
#include <utility> // std::forward
|
||||
#include <vector> // std::vector
|
||||
|
||||
// Include the header file for the thread pool library.
|
||||
#include "BS_thread_pool_light.hpp"
|
||||
|
||||
// ================
|
||||
// Global variables
|
||||
// ================
|
||||
|
||||
// A global thread pool object to be used throughout the test.
|
||||
BS::thread_pool_light pool;
|
||||
|
||||
// A global random_device object to be used to seed some random number generators.
|
||||
std::random_device rd;
|
||||
|
||||
// A global variable to measure how many checks succeeded.
|
||||
size_t tests_succeeded = 0;
|
||||
|
||||
// A global variable to measure how many checks failed.
|
||||
size_t tests_failed = 0;
|
||||
|
||||
// ================
|
||||
// Helper functions
|
||||
// ================
|
||||
|
||||
/**
|
||||
* @brief Print any number of items into std::cout.
|
||||
*
|
||||
* @tparam T The types of the items.
|
||||
* @param items The items to print.
|
||||
*/
|
||||
template <typename... T>
|
||||
void print(T&&... items)
|
||||
{
|
||||
(std::cout << ... << std::forward<T>(items));
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Print any number of items into std::cout, followed by a newline character.
|
||||
*
|
||||
* @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 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 = '=')
|
||||
{
|
||||
println();
|
||||
println(std::string(text.length(), symbol));
|
||||
println(text);
|
||||
println(std::string(text.length(), symbol));
|
||||
}
|
||||
|
||||
/**
|
||||
* @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)
|
||||
{
|
||||
println("-> PASSED!");
|
||||
++tests_succeeded;
|
||||
}
|
||||
else
|
||||
{
|
||||
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)
|
||||
{
|
||||
print("Expected: ", expected, ", obtained: ", obtained);
|
||||
if (expected == obtained)
|
||||
{
|
||||
println(" -> PASSED!");
|
||||
++tests_succeeded;
|
||||
}
|
||||
else
|
||||
{
|
||||
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()
|
||||
{
|
||||
std::condition_variable ID_cv, total_cv;
|
||||
std::mutex ID_mutex, total_mutex;
|
||||
{
|
||||
const BS::concurrency_t num_tasks = pool.get_thread_count() * 2;
|
||||
std::vector<std::thread::id> thread_IDs(num_tasks);
|
||||
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(
|
||||
[&total_count, &id, &ID_release, &ID_cv, &total_cv, &ID_mutex, &total_mutex]
|
||||
{
|
||||
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, [&ID_release] { return ID_release; });
|
||||
});
|
||||
total_cv.wait(total_lock, [&total_count] { 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(total_lock, [&total_count, &num_tasks] { return total_count == num_tasks; });
|
||||
pool.wait_for_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()
|
||||
{
|
||||
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());
|
||||
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());
|
||||
}
|
||||
|
||||
// =======================================
|
||||
// Functions to verify submission of tasks
|
||||
// =======================================
|
||||
|
||||
/**
|
||||
* @brief Check that push_task() works.
|
||||
*/
|
||||
void check_push_task()
|
||||
{
|
||||
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);
|
||||
}
|
||||
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);
|
||||
}
|
||||
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()
|
||||
{
|
||||
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);
|
||||
}
|
||||
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);
|
||||
}
|
||||
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);
|
||||
}
|
||||
println("Checking that submit() works for a function with no arguments and a return value...");
|
||||
{
|
||||
bool flag = false;
|
||||
std::future<int> flag_future = pool.submit(
|
||||
[&flag]
|
||||
{
|
||||
flag = true;
|
||||
return 42;
|
||||
});
|
||||
check(flag_future.get() == 42 && flag);
|
||||
}
|
||||
println("Checking that submit() works for a function with one argument and a return value...");
|
||||
{
|
||||
bool flag = false;
|
||||
std::future<int> flag_future = pool.submit(
|
||||
[](bool* flag_)
|
||||
{
|
||||
*flag_ = true;
|
||||
return 42;
|
||||
},
|
||||
&flag);
|
||||
check(flag_future.get() == 42 && flag);
|
||||
}
|
||||
println("Checking that submit() works for a function with two arguments and a return value...");
|
||||
{
|
||||
bool flag1 = false;
|
||||
bool flag2 = false;
|
||||
std::future<int> flag_future = pool.submit(
|
||||
[](bool* flag1_, bool* flag2_)
|
||||
{
|
||||
*flag1_ = *flag2_ = true;
|
||||
return 42;
|
||||
},
|
||||
&flag1, &flag2);
|
||||
check(flag_future.get() == 42 && flag1 && flag2);
|
||||
}
|
||||
}
|
||||
|
||||
class flag_class
|
||||
{
|
||||
public:
|
||||
void set_flag_no_args()
|
||||
{
|
||||
flag = true;
|
||||
}
|
||||
|
||||
void set_flag_one_arg(const bool arg)
|
||||
{
|
||||
flag = arg;
|
||||
}
|
||||
|
||||
int set_flag_no_args_return()
|
||||
{
|
||||
flag = true;
|
||||
return 42;
|
||||
}
|
||||
|
||||
int set_flag_one_arg_return(const bool arg)
|
||||
{
|
||||
flag = arg;
|
||||
return 42;
|
||||
}
|
||||
|
||||
bool get_flag() const
|
||||
{
|
||||
return flag;
|
||||
}
|
||||
|
||||
void push_test_flag_no_args()
|
||||
{
|
||||
pool.push_task(&flag_class::set_flag_no_args, this);
|
||||
pool.wait_for_tasks();
|
||||
check(get_flag());
|
||||
}
|
||||
|
||||
void push_test_flag_one_arg()
|
||||
{
|
||||
pool.push_task(&flag_class::set_flag_one_arg, this, true);
|
||||
pool.wait_for_tasks();
|
||||
check(get_flag());
|
||||
}
|
||||
|
||||
void submit_test_flag_no_args()
|
||||
{
|
||||
pool.submit(&flag_class::set_flag_no_args, this).wait();
|
||||
check(get_flag());
|
||||
}
|
||||
|
||||
void submit_test_flag_one_arg()
|
||||
{
|
||||
pool.submit(&flag_class::set_flag_one_arg, this, true).wait();
|
||||
check(get_flag());
|
||||
}
|
||||
|
||||
void submit_test_flag_no_args_return()
|
||||
{
|
||||
std::future<int> flag_future = pool.submit(&flag_class::set_flag_no_args_return, this);
|
||||
check(flag_future.get() == 42 && get_flag());
|
||||
}
|
||||
|
||||
void submit_test_flag_one_arg_return()
|
||||
{
|
||||
std::future<int> flag_future = pool.submit(&flag_class::set_flag_one_arg_return, this, true);
|
||||
check(flag_future.get() == 42 && get_flag());
|
||||
}
|
||||
|
||||
private:
|
||||
bool flag = false;
|
||||
};
|
||||
|
||||
/**
|
||||
* @brief Check that submitting member functions works.
|
||||
*/
|
||||
void check_member_function()
|
||||
{
|
||||
println("Checking that push_task() works for a member function with no arguments or return value...");
|
||||
{
|
||||
flag_class flag;
|
||||
pool.push_task(&flag_class::set_flag_no_args, &flag);
|
||||
pool.wait_for_tasks();
|
||||
check(flag.get_flag());
|
||||
}
|
||||
println("Checking that push_task() works for a member function with one argument and no return value...");
|
||||
{
|
||||
flag_class flag;
|
||||
pool.push_task(&flag_class::set_flag_one_arg, &flag, true);
|
||||
pool.wait_for_tasks();
|
||||
check(flag.get_flag());
|
||||
}
|
||||
println("Checking that submit() works for a member function with no arguments or return value...");
|
||||
{
|
||||
flag_class flag;
|
||||
pool.submit(&flag_class::set_flag_no_args, &flag).wait();
|
||||
check(flag.get_flag());
|
||||
}
|
||||
println("Checking that submit() works for a member function with one argument and no return value...");
|
||||
{
|
||||
flag_class flag;
|
||||
pool.submit(&flag_class::set_flag_one_arg, &flag, true).wait();
|
||||
check(flag.get_flag());
|
||||
}
|
||||
println("Checking that submit() works for a member function with no arguments and a return value...");
|
||||
{
|
||||
flag_class flag;
|
||||
std::future<int> flag_future = pool.submit(&flag_class::set_flag_no_args_return, &flag);
|
||||
check(flag_future.get() == 42 && flag.get_flag());
|
||||
}
|
||||
println("Checking that submit() works for a member function with one argument and a return value...");
|
||||
{
|
||||
flag_class flag;
|
||||
std::future<int> flag_future = pool.submit(&flag_class::set_flag_one_arg_return, &flag, true);
|
||||
check(flag_future.get() == 42 && flag.get_flag());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Check that submitting member functions within an object works.
|
||||
*/
|
||||
void check_member_function_within_object()
|
||||
{
|
||||
println("Checking that push_task() works within an object for a member function with no arguments or return value...");
|
||||
{
|
||||
flag_class flag;
|
||||
flag.push_test_flag_no_args();
|
||||
}
|
||||
println("Checking that push_task() works within an object for a member function with one argument and no return value...");
|
||||
{
|
||||
flag_class flag;
|
||||
flag.push_test_flag_one_arg();
|
||||
}
|
||||
println("Checking that submit() works within an object for a member function with no arguments or return value...");
|
||||
{
|
||||
flag_class flag;
|
||||
flag.submit_test_flag_no_args();
|
||||
}
|
||||
println("Checking that submit() works within an object for a member function with one argument and no return value...");
|
||||
{
|
||||
flag_class flag;
|
||||
flag.submit_test_flag_one_arg();
|
||||
}
|
||||
println("Checking that submit() works within an object for a member function with no arguments and a return value...");
|
||||
{
|
||||
flag_class flag;
|
||||
flag.submit_test_flag_no_args_return();
|
||||
}
|
||||
println("Checking that submit() works within an object for a member function with one argument and a return value...");
|
||||
{
|
||||
flag_class flag;
|
||||
flag.submit_test_flag_one_arg_return();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @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;
|
||||
});
|
||||
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 push_loop() works for a specific range of indices split over a specific number of tasks, with no return value.
|
||||
*
|
||||
* @param random_start The first index in the loop.
|
||||
* @param random_end The last index in the loop plus 1.
|
||||
* @param num_tasks The number of tasks.
|
||||
*/
|
||||
template <typename T>
|
||||
void check_push_loop_no_return(const int64_t random_start, T random_end, const BS::concurrency_t num_tasks)
|
||||
{
|
||||
if (random_start == random_end)
|
||||
++random_end;
|
||||
println("Verifying that push_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<int64_t>(random_start, static_cast<int64_t>(random_end));
|
||||
std::unique_ptr<std::atomic<bool>[]> flags = std::make_unique<std::atomic<bool>[]>(num_indices);
|
||||
const auto loop = [&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;
|
||||
};
|
||||
if (random_start == 0)
|
||||
pool.push_loop(random_end, loop, num_tasks);
|
||||
else
|
||||
pool.push_loop(random_start, random_end, loop, num_tasks);
|
||||
pool.wait_for_tasks();
|
||||
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 push_loop() works using several different random values for the range of indices and number of tasks.
|
||||
*/
|
||||
void check_push_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_push_loop_no_return(index_dist(mt), index_dist(mt), task_dist(mt));
|
||||
println("Verifying that push_loop() with identical start and end indices does nothing...");
|
||||
bool flag = true;
|
||||
const int64_t index = index_dist(mt);
|
||||
pool.push_loop(index, index, [&flag](const int64_t, const int64_t) { flag = false; });
|
||||
pool.wait_for_tasks();
|
||||
check(flag);
|
||||
println("Trying push_loop() with start and end indices of different types:");
|
||||
const int64_t start = index_dist(mt);
|
||||
const uint32_t end = static_cast<uint32_t>(std::abs(index_dist(mt)));
|
||||
check_push_loop_no_return(start, end, task_dist(mt));
|
||||
println("Trying the overload for push_loop() for the case where the first index is equal to 0:");
|
||||
check_push_loop_no_return(0, index_dist(mt), task_dist(mt));
|
||||
}
|
||||
|
||||
// ======================================
|
||||
// Functions to verify exception handling
|
||||
// ======================================
|
||||
|
||||
/**
|
||||
* @brief Check that exception handling works.
|
||||
*/
|
||||
void check_exceptions()
|
||||
{
|
||||
println("Checking that exceptions are forwarded correctly by submit()...");
|
||||
bool caught = false;
|
||||
auto throws = []
|
||||
{
|
||||
println("Throwing exception...");
|
||||
throw std::runtime_error("Exception thrown!");
|
||||
};
|
||||
std::future<void> my_future = pool.submit(throws);
|
||||
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);
|
||||
}
|
||||
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.push_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);
|
||||
pool.wait_for_tasks();
|
||||
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()
|
||||
{
|
||||
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 push_task() works:");
|
||||
check_push_task();
|
||||
|
||||
print_header("Checking that submit() works:");
|
||||
check_submit();
|
||||
|
||||
print_header("Checking that submitting member functions works:");
|
||||
check_member_function();
|
||||
|
||||
print_header("Checking that submitting member functions from within an object works:");
|
||||
check_member_function_within_object();
|
||||
|
||||
print_header("Checking that wait_for_tasks() works...");
|
||||
check_wait_for_tasks();
|
||||
|
||||
print_header("Checking that push_loop() works:");
|
||||
check_push_loop();
|
||||
|
||||
print_header("Checking that exception handling works:");
|
||||
check_exceptions();
|
||||
|
||||
print_header("Testing that vector operations produce the expected results:");
|
||||
check_vectors();
|
||||
}
|
||||
|
||||
int main()
|
||||
{
|
||||
println("BS::thread_pool_light: a fast, lightweight, and easy-to-use C++17 thread pool library");
|
||||
println("(c) 2023 Barak Shoshany (baraksh@gmail.com) (http://baraksh.com)");
|
||||
println("GitHub: https://github.com/bshoshany/thread-pool\n");
|
||||
|
||||
println("Thread pool library version is ", BS_THREAD_POOL_LIGHT_VERSION, ".");
|
||||
println("Hardware concurrency is ", std::thread::hardware_concurrency(), ".");
|
||||
|
||||
println("Important: Please do not run any other applications, especially multithreaded applications, in parallel with this test!");
|
||||
|
||||
do_tests();
|
||||
|
||||
if (tests_failed == 0)
|
||||
{
|
||||
print_header("SUCCESS: Passed all " + std::to_string(tests_succeeded) + " checks!", '+');
|
||||
return 0;
|
||||
}
|
||||
else
|
||||
{
|
||||
print_header("FAILURE: Passed " + std::to_string(tests_succeeded) + " checks, but failed " + std::to_string(tests_failed) + "!", '+');
|
||||
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.");
|
||||
std::quick_exit(static_cast<int>(tests_failed));
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
+172
-15
@@ -1,13 +1,3 @@
|
||||
[](https://doi.org/10.5281/zenodo.4742687)
|
||||
[](https://arxiv.org/abs/2105.00613)
|
||||
[](https://github.com/bshoshany/thread-pool/blob/master/LICENSE.txt)
|
||||

|
||||

|
||||

|
||||
[](https://github.com/bshoshany/thread-pool)
|
||||
[](https://twitter.com/BarakShoshany)
|
||||
[](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\
|
||||
@@ -16,6 +6,8 @@ Website: <https://baraksh.com/>\
|
||||
GitHub: <https://github.com/bshoshany>
|
||||
|
||||
* [Version history](#version-history)
|
||||
* [v4.0.0 (2023-12-27)](#v400-2023-12-27)
|
||||
* [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)
|
||||
@@ -35,6 +27,171 @@ GitHub: <https://github.com/bshoshany>
|
||||
|
||||
## Version history
|
||||
|
||||
### v4.0.0 (2023-12-27)
|
||||
|
||||
* A major new release with numerous changes, additions, fixes, and improvements. Many frequently requested features have been added, and performance has been optimized. Please note that code written using previous releases will need to be modified to work with the new release. The changes needed to migrate to the new API are explicitly indicated below for your convenience.
|
||||
* Highlights:
|
||||
* The light thread pool has been removed. However, by default, the thread pool is in "light mode". Optional features that may affect performance must be enabled by defining suitable macros.
|
||||
* This library now ships with two stand-alone header files:
|
||||
* `BS_thread_pool.hpp` contains the main `BS::thread_pool` class and the `BS::multi_future` helper classes, and is the only file needed to use the thread pool itself.
|
||||
* `BS_thread_pool_utils.hpp` contains the additional utility classes `BS::signaller`, `BS::synced_stream`, and `BS::timer`, which are fully independent of the thread pool itself and can be used either with or without it.
|
||||
* It is now possible to assign priorities to tasks. Tasks with higher priorities will be executed first.
|
||||
* Member functions for submitting tasks and loops have been renamed for consistency, e.g. `detach_task()` and `submit_task()`, where the prefix `detach` means no future will be returned and `submit` means a future or `BS::multi_future` will be returned.
|
||||
* There are now two ways to parallelize loops into blocks:
|
||||
* `detach_blocks()` and `submit_blocks()` behave the same as loop parallelization in previous releases, running the loop function once per block.
|
||||
* `detach_loop()` and `submit_loop()` have a simpler syntax, where the loop function is run once per index, so the user doesn't have to manually run the internal loop for each block.
|
||||
* The new member functions `detach_sequence()` and `submit_sequence()` allow submitting a sequence of tasks enumerated by indices.
|
||||
* It is now possible to run an initialization function in each thread before it starts to execute any submitted tasks.
|
||||
* Tasks submitted with `detach_task()` or `submit_task()` can no longer have arguments. Task with arguments must be enclosed inside lambda expressions. This simplifies the API and provides better readability. Tasks can still have return values.
|
||||
* Various ways to obtain information about the threads in the pool have been introduced:
|
||||
* The member function `get_thread_ids()` obtains the unique thread identifiers, and `get_native_handles()` obtains the underlying implementation-defined thread handles.
|
||||
* The new namespace `BS::this_thread` allows obtaining the thread's index in the pool using `BS::this_thread::get_index()` and a pointer to the pool that owns the thread using `BS::this_thread::get_pool()`.
|
||||
* Member functions for waiting for tasks have been renamed for brevity: `wait()`/`wait_for()`/`wait_until()`. In addition, these functions can now optionally throw an exception if the user tries to call them from within a thread of the same pool, which would result in a deadlock.
|
||||
* The first index must now be specified explicitly when parallelizing blocks, loops, and sequences, and it must not be greater than the last index. Also, both indices must now have the same type, or the template parameter should be explicitly specified.
|
||||
* Optimized the way `detach_blocks()`, `submit_blocks()`, `detach_loop()`, and `submit_loop()` split the range of the loop into blocks.
|
||||
* Added a utility class `BS::signaller` to allow simple signalling between threads.
|
||||
* `BS::multi_future<T>` is now a specialization of `std::vector<std::future<T>>` with additional member functions.
|
||||
* Breaking changes:
|
||||
* The light thread pool has been removed. The original idea was that the light thread pool will allow the user to sacrifice functionality for increased performance. However, in my testing I found that there was no actual performance benefit to the light thread pool. Therefore, there is no reason to keep it.
|
||||
* However, by default, the thread pool is in "light mode". Optional features that may affect performance due to additional checks or more complicated algorithms must be enabled by defining suitable macros before including the library:
|
||||
* `BS_THREAD_POOL_ENABLE_PAUSE` to enable pausing.
|
||||
* `BS_THREAD_POOL_ENABLE_PRIORITY` to enable task priority.
|
||||
* `BS_THREAD_POOL_ENABLE_WAIT_DEADLOCK_CHECK` to enable wait deadlock checks.
|
||||
* **API migration:**
|
||||
* If you previously used `BS_thread_pool_light.hpp`, simply use `BS_thread_pool.hpp` instead.
|
||||
* If you previously used the pausing feature, define the macro `BS_THREAD_POOL_ENABLE_PAUSE` before including `BS_thread_pool.hpp` to enable it.
|
||||
* Member functions have been renamed for better consistency. Each function has a `detach` variant which does not return a future, and a `submit` variant which does return a future (or a `BS::multi_future`):
|
||||
* `detach_task()` and `submit_task()` for single tasks.
|
||||
* `detach_blocks()` and `submit_blocks()` for loops to be split into blocks, where the loop function is executed once per block and must have an internal loop, as in previous releases.
|
||||
* `detach_loop()` and `submit_loop()` for loops to be split into blocks, where the loop function is executed once per index and the pool takes care of the internal loop.
|
||||
* `detach_sequence()` and `submit_sequence()` for sequences of enumerated tasks.
|
||||
* **API migration:** Use the new names of the functions:
|
||||
* `push_task()` -> `detach_task()`
|
||||
* `submit()` -> `submit_task()`
|
||||
* `push_loop()` -> `detach_blocks()`
|
||||
* `parallelize_loop()` -> `submit_blocks()`
|
||||
* `wait_for_tasks()`, `wait_for_tasks_duration()`, and `wait_for_tasks_until()` have been renamed to `wait()`, `wait_for()`, and `wait_until()` respectively.
|
||||
* **API migration:** Use the new names of the functions:
|
||||
* `wait_for_tasks()` -> `wait()`
|
||||
* `wait_for_tasks_duration()` -> `wait_for()`
|
||||
* `wait_for_tasks_until()` -> `wait_until()`
|
||||
* Functions for parallelizing loops no longer have dedicated overloads for the special case where the first index is 0. These overloads essentially amount to giving the first function argument a default value, which is not allowed in C++, and can be confusing. In addition, indicating the first index explicitly is better for readability.
|
||||
* **API migration:** Add the first index 0 manually as the first argument if it was omitted.
|
||||
* Functions for parallelizing loops no longer allow the last index to be smaller than the first index. Previously, e.g. `detach_blocks(5, 0, ...)` was equivalent to `detach_blocks(0, 5, ...)`. However, this led to confusing results. Since the first argument is the first index and the second argument is the index *after* the last index (i.e. 0 to 5 actually means 0, 1, 2, 3, 4), the user might get the wrong impression that `detach_blocks(5, 0, ...)` will count 5, 4, 3, 2, 1 instead. This option was removed to avoid this confusion.
|
||||
* Sometimes the user might actually want to make a loop that counts down instead of up. This cannot be done by flipping the order of the arguments to e.g. `detach_blocks()` (nor could it be done in previous releases). However, it can be done by simply defining a suitable loop function. For example, if you call `detach_blocks(0, 10, loop, 2)` and define the loop function as `for (T i = 9 - start; i > 9 - end; --i)`, then the first block will count 9, 8, 7, 6, 5 and the second block will count 4, 3, 2, 1, 0.
|
||||
* `detach_loop()`, `submit_loop()`, `detach_sequence()`, and `submit_sequence()` work the same way. The first index must be smaller than the last index, but you can count down by writing a suitable loop or sequence function.
|
||||
* **API migration:** Any loop parallelization that used a first index greater than the last index will work exactly the same after switching the first and second arguments so that the smaller index appears first.
|
||||
* Functions for parallelizing loops no longer accept first and last indices of different types. The reason for allowing this previously was that otherwise, writing something like `detach_blocks(0, x, ...)` where `x` is not an `int` would result in a compilation error, since `0` is by default an `int` and therefore the arguments `0` and `x` have different types. However, this behavior, which used [`std::common_type`](https://en.cppreference.com/w/cpp/types/common_type) to determine the common type of the two indices, sometimes completely messed up the range of the loop. For example, the `std::common_type` of `int` and `unsigned int` is `unsigned int`, which means the loop will only use non-negative indices even if the `int` start index was negative, resulting in an integer overflow.
|
||||
* **API migration:** If you want to invoke e.g. `detach_blocks(0, x, ...)` where `x` is not an `int`, you can either:
|
||||
* Make the `0` have the desired type using a cast or a suffix. For example, if `x` is an `unsigned int`, write `(unsigned int)0` or `0U` instead of `0`.
|
||||
* Specify the template parameter explicitly. For example, if `x` is a `size_t`, write `detach_blocks<size_t>(0, x, ...)`.
|
||||
* `detach_task()` and `submit_task()` no longer accept arguments for the submitted task. Instead, you must enclose the function in a [lambda expression](https://en.cppreference.com/w/cpp/language/lambda). In other words, instead of `detach_task(task, args...)` you should write `detach_task([] { task(args...); })`, indicating in the capture list `[]` whether to capture the task itself, and each of the arguments, by value or reference. Please see `README.md` for examples. This was changed for the following reasons:
|
||||
1. Consistency with `detach_blocks()` and `submit_blocks()`, as well as the new `detach_loop()`, `submit_loop()`, `detach_sequence()`, and `submit_sequence()`, which do not accept function arguments either.
|
||||
2. In my own multithreaded projects, I find that I almost always need the task to have access to variables in the local scope. This is much simpler, easier, and more concise to do with a lambda capture list, especially an implicit capture `[=]` or `[&]`, than by defining a function that takes arguments and then passing these arguments.
|
||||
3. Similarly, I find that I mostly submit tasks defined as a lambda on the spot, rather than creating them as separate functions, because it's faster to code and makes it clear exactly what the task does without having to look elsewhere.
|
||||
4. When users post issues to this repository asking for help with their own code that uses the thread pool, the solution often turns out to be "just wrap that in a lambda". Such issues can be avoided if lambdas must be used to begin with.
|
||||
5. Submitting member functions, which previously required the awkward syntax `detach_task(&class::function, &object, args...)`, can now be achieved with the much simpler and more readable syntax `detach_task([] { object.function(args...); })` with the appropriate captures.
|
||||
6. Passing arguments by reference, which previously required using [`std::ref`](https://en.cppreference.com/w/cpp/utility/functional/ref), e.g. `detach_task(task, std::ref(arg))`, can now be achieved with the much simpler and more readable syntax `detach_task([&arg] { task(arg); })`.
|
||||
7. The new syntax allows specifying the priority of the task easily, as the second argument - otherwise, it would have been hard to distinguish the priority from a task argument, making the API more complicated and confusing. This syntax will also permit adding additional arguments to the member functions as needed in the future.
|
||||
* **API migration:** Enclose all tasks with arguments inside a lambda expression. All submitted tasks must have no arguments, but they can still have return values.
|
||||
* Alternatively, [`std::bind`](https://en.cppreference.com/w/cpp/utility/functional/bind) can also be used, if the old syntax is preferred to a lambda. Just wrap it around the task and its arguments: instead of `detach_task(task, args...)`, write `detach_task(std::bind(task, args...))`. This achieves the same effect, and can be used to easily convert v3.x.x code to v4.0.0 using a simple regular expression search and replace:
|
||||
* `push_task\((.*?)\)` -> `detach_task(std::bind($1))`
|
||||
* `submit\((.*?)\)` -> `submit_task(std::bind($1))`
|
||||
* `BS::synced_stream` and `BS::timer` have been moved to `BS_thread_pool_utils.hpp`.
|
||||
* **API migration:** Include the new header file if either of these utility classes are used.
|
||||
* `BS_thread_pool.hpp` new features:
|
||||
* A new optional feature, enabled by defining the macro `BS_THREAD_POOL_ENABLE_PRIORITY`, allows assigning priority to tasks. The priority is a number of type `BS::priority_t`, which is a signed 16-bit integer, so it can have any value between -32,768 and 32,767. The tasks will be executed in priority order from highest to lowest.
|
||||
* To assign a priority to a task, add the priority as the last argument to any of the `detach` or `submit` functions. If the priority is not specified, the default value will be 0.
|
||||
* The namespace `BS::pr` contains some pre-defined priorities for users who wish to avoid magic numbers and enjoy better future-proofing. In order of decreasing priority, the pre-defined priorities are: `BS::pr::highest`, `BS::pr::high`, `BS::pr::normal`, `BS::pr::low`, and `BS::pr::lowest`.
|
||||
* Please see `README.md` for more information, including performance considerations.
|
||||
* The new member functions `detach_loop()` and `submit_loop()` facilitate loop parallelization without having to worry about internal loops in the loop function. In previous releases, the loop function had to be of the form `[](T start, T end) { for (T i = start; i < end; ++i) loop(i); }`. This behavior has been preserved in `detach_blocks()` and `submit_blocks()`. However, the new `detach_loop()` and `submit_loop()` allow much simpler loop functions of the form `[](T i) { loop(i) }`, greatly simplifying the interface.
|
||||
* Performance-wise, due to fewer function calls, `detach_blocks()` and `submit_blocks()` are generally faster. However, the difference is usually not significant, and with compiler optimizations there may be no difference at all. In any case, `detach_loop()` and `submit_loop()` are provided as convenience functions, but performance-critical applications can stick with `detach_blocks()` and `submit_blocks()`.
|
||||
* The new member functions `detach_sequence()` and `submit_sequence()` facilitate submitting a sequence of tasks enumerated by indices. This is a bit similar to `detach_loop()` and `submit_loop()`, except that the range of indices is not split into blocks with each block containing a smaller range of indices. Instead, there is exactly one task per index. This can be used, for example, to submit a sequence of tasks with each one independently processing a single array element. `detach_sequence()` does not return a future, while `submit_sequence()` returns a `BS::multi_future`.
|
||||
* It is now possible to run an initialization function in each thread before it starts to execute any submitted tasks. The function must take no arguments and have no return value. It will only be executed exactly once, when the thread is first constructed. It can be passed as an argument to the constructor or to `reset()`. See [#104](https://github.com/bshoshany/thread-pool/issues/104), [#105](https://github.com/bshoshany/thread-pool/pull/105), [#113](https://github.com/bshoshany/thread-pool/issues/113), and [#119](https://github.com/bshoshany/thread-pool/issues/119).
|
||||
* Added a member function `get_thread_ids()` which returns a vector containing the unique identifiers for each of the pool's threads, as obtained by [`std::thread::get_id()`](https://en.cppreference.com/w/cpp/thread/get_id). See [#126](https://github.com/bshoshany/thread-pool/issues/126).
|
||||
* A new optional feature, enabled by defining the macro `BS_THREAD_POOL_ENABLE_NATIVE_HANDLES`, adds a member function `get_native_handles()` which returns a vector containing the underlying implementation-defined thread handles for each of the pool's threads. These can then be used in an implementation-specific way to manage the threads at the OS level; however, note that this will generally **not** be portable code. See [#122](https://github.com/bshoshany/thread-pool/issues/122).
|
||||
* This feature is disabled by default since it uses [std::thread::native_handle()](https://en.cppreference.com/w/cpp/thread/thread/native_handle), which is in the C++ standard library, but is **not** guaranteed to be present on all systems.
|
||||
* A new namespace `BS::this_thread` was created to provide functionality similar to `std::this_thread`.
|
||||
* `BS::this_thread::get_index()` can be used to get the index of the current thread. If this thread belongs to a `BS::thread_pool` object, it will have an index from 0 to `BS::thread_pool::get_thread_count() - 1`. Otherwise, for example if this thread is the main thread or an independent [`std::thread`](https://en.cppreference.com/w/cpp/thread/thread), [`std::nullopt`](https://en.cppreference.com/w/cpp/utility/optional/nullopt) will be returned.
|
||||
* `BS::this_thread::get_pool()` can be used to get the pointer to the thread pool that owns the current thread. If this thread belongs to a `BS::thread_pool` object, a pointer to that object will be returned. Otherwise, `std::nullopt` will be returned.
|
||||
* Note that both functions return an [`std::optional`](https://en.cppreference.com/w/cpp/utility/optional) object.
|
||||
* `BS::multi_future<T>` is now defined as a specialization of `std::vector<std::future<T>>`. This means that all of the member functions that can be used on an [`std::vector`](https://en.cppreference.com/w/cpp/container/vector) can also be used on a `BS::multi_future`. For example, it is now possible to use a range-based `for` loop with a `BS::multi_future` object, since it has iterators.
|
||||
* In addition to inherited member functions, `BS::multi_future` has the following specialized member functions, most of which are new in this release: `get()`, `ready_count()`, `valid()`, `wait()`, `wait_for()`, and `wait_until()`. Please see `README.md` for more information. See also [#128](https://github.com/bshoshany/thread-pool/issues/128).
|
||||
* A new optional feature, enabled by defining the macro `BS_THREAD_POOL_ENABLE_WAIT_DEADLOCK_CHECK`, allows `wait()`, `wait_for()`, and `wait_until()` to check whether the user tried to call them from within a thread of the same pool, which would result in a deadlock. If so, they will throw the exception `BS::thread_pool::wait_deadlock` instead of waiting.
|
||||
* `BS_thread_pool_utils.hpp`:
|
||||
* The utility classes `BS::synced_stream` and `BS::timer` now reside in this header file instead of the main one.
|
||||
* `BS::timer` has a new member function, `current_ms()`, which can be used to obtain the number of milliseconds that have elapsed so far, but keep the timer ticking.
|
||||
* The new utility class `BS::signaller` allows simple signalling between threads. It can be used to make one or more threads wait, using the `wait()` member function. When another thread uses the `ready()` member function, all waiting threads stop waiting. This class is really just a convenient wrapper around [`std::promise`](https://en.cppreference.com/w/cpp/thread/promise), which contains both the promise and its future.
|
||||
* `BS_thread_pool.hpp` bug fixes and minor changes:
|
||||
* Optimized locking in the worker function. This should result in increased performance.
|
||||
* Optimized the way `detach_blocks()`, `submit_blocks()`, `detach_loop()`, and `submit_loop()` split the range of the loop into blocks. All blocks are now guaranteed to have one of two sizes, differing by 1, with the larger blocks always first. See [#96](https://github.com/bshoshany/thread-pool/issues/96).
|
||||
* For example, in previous releases, 100 indices were split into 15 blocks as 14 blocks of size 6 and one additional block of size 16, which was suboptimal. Now they are split into 10 blocks of size 7 and 5 blocks of size 6, which means the tasks are as evenly distributed as possible.
|
||||
* Fixed a bug that caused paused pools to have high idle CPU usage if pausing was used. See [#120](https://github.com/bshoshany/thread-pool/issues/120).
|
||||
* The worker now destructs the task object as soon as it finishes executing. See [#124](https://github.com/bshoshany/thread-pool/issues/124) and [#129](https://github.com/bshoshany/thread-pool/pull/129).
|
||||
* Added Markdown inline code formatting in all comments whenever applicable, which makes the comments look nicer when displayed as a tooltip in [Visual Studio Code](https://code.visualstudio.com/) or other supporting IDEs.
|
||||
* The `BS::thread_pool::blocks` helper class has been moved into the main thread pool class, and now returns a degenerate object (zero blocks) if `index_after_last <= first_index`.
|
||||
* `BS_thread_pool_test.cpp`:
|
||||
* Removed tests for the light thread pool.
|
||||
* Added/modified tests for all new/changed features.
|
||||
* Many of the previous tests have been simplified and optimized.
|
||||
* The program now takes command line arguments:
|
||||
* `help`: Show a help message and exit.
|
||||
* `log`: Create a log file.
|
||||
* `tests`: Perform standard tests.
|
||||
* `deadlock` Perform long deadlock tests.
|
||||
* `benchmarks`: Perform benchmarks.
|
||||
* If no options are entered, the default is: `log tests benchmarks`.
|
||||
* By default, the test program enables all the optional features by defining the suitable macros, so it can test them. However, if the macro `BS_THREAD_POOL_LIGHT_TEST` is defined during compilation, the optional features will not be tested.
|
||||
* Instead of using a pre-defined list to specify the number of loop blocks to try in the benchmarks, the program now simply keeps increasing the number of blocks until it finds the optimal value. Often, the optimal number of blocks is much higher than the number of hardware threads, but if the number is too high it will result in diminishing returns.
|
||||
* `check_loop_no_return()` now checks that the loop modifies all the indices exactly once, to detect cases where an index has been modified more than once, e.g. if the same loop index was erroneously placed in more than one block.
|
||||
* Instead of defining `_CRT_SECURE_NO_WARNINGS`, the program now uses [`localtime_s`](https://learn.microsoft.com/en-us/cpp/c-runtime-library/reference/localtime-s-localtime32-s-localtime64-s) instead of [`std::localtime`](https://en.cppreference.com/w/cpp/chrono/c/localtime) if MSVC is detected to avoid generating a warning.
|
||||
* On macOS, the test program will exit with [`std::terminate()`](https://en.cppreference.com/w/cpp/error/terminate) instead of [`std::quick_exit()`](https://en.cppreference.com/w/cpp/utility/program/quick_exit) if any tests failed. This is because macOS does not implement `std::quick_exit()` for some reason. Note that as a result, the number of failed tests cannot be returned by the program on macOS. Unfortunately, [`std::exit()`](https://en.cppreference.com/w/cpp/utility/program/exit) cannot be used here, as it might get stuck if a deadlock occurs. See [#106](https://github.com/bshoshany/thread-pool/pull/106)
|
||||
* The log file now uses the name of the executable file, followed by the date and time, so it's easy to distinguish between log files generated by different builds of the test (since the test script names them based on the compiler used). Also, the program now checks if the log file failed to open for some reason, and writes only to the standard output in that case.
|
||||
* The benchmarks now display a progress bar.
|
||||
* The test program will now detect the OS and compiler used.
|
||||
* `BS_thread_pool_test.ps1`:
|
||||
* The script will compile and run a light version of the test, with no optional features enabled, in addition to the main test, for each compiler.
|
||||
* The source and build folders will now be determined relative to the script folder, to ensure that the script works no matter which folder it is executed from.
|
||||
* The script now checks that the include files `BS_thread_pool.hpp` and `BS_thread_pool_utils.hpp` are present before attempting to compile the test program.
|
||||
* `README.md`:
|
||||
* Added/modified documentation for all new/changed features.
|
||||
* Revised many of the existing examples and explanations.
|
||||
* Added a complete library reference at the end of the documentation.
|
||||
* Added instructions for installing the package using Meson and CMake with CPM. The installation instructions with various package managers and build systems were moved to the end, before the reference.
|
||||
* Miscellaneous:
|
||||
* A `.clang-tidy` file is now included, with all the checks that are enabled in this project. The pull request template has been updated to suggest that authors lint their code using this file before submitting the pull request.
|
||||
* This release is dedicated to my wife (since December 1, 2023), Pauline. Her endless love, support, and encouragement have been a great source of motivation for working on this and other projects. I am so lucky and honored to [`my_future.share()`](https://en.cppreference.com/w/cpp/thread/future/share) with her ❤️
|
||||
|
||||
### 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.
|
||||
* Fixed 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`:
|
||||
@@ -44,7 +201,7 @@ GitHub: <https://github.com/bshoshany>
|
||||
* 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).
|
||||
* 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.
|
||||
@@ -96,7 +253,7 @@ GitHub: <https://github.com/bshoshany>
|
||||
* 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.
|
||||
* 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 multithreaded 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.
|
||||
@@ -108,7 +265,7 @@ GitHub: <https://github.com/bshoshany>
|
||||
* Fixed an issue where `wait_for_tasks()` would sometimes get stuck if `push_task()` was executed immediately before `wait_for_tasks()`.
|
||||
* Both the thread pool constructor and the `reset()` member function now determine the number of threads to use in the pool as follows. 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, 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. See [#51](https://github.com/bshoshany/thread-pool/issues/51) and [#52](https://github.com/bshoshany/thread-pool/issues/52).
|
||||
* Added the `[[nodiscard]]` attribute to classes and class members, in order to warn the user when accidentally discarding an important return value, such as a future or the return value of a function with no useful side-effects. For example, if you use `submit()` and don't save the future it returns, the compiler will now generate a warning. (If a future is not needed, then you should use `push_task()` instead.)
|
||||
* Removed the `explicit` specifier from all constructors, as it prevented the default constructor from being used with static class members. See [#48](https://github.com/bshoshany/thread-pool/issues/48>).
|
||||
* Removed the `explicit` specifier from all constructors, as it prevented the default constructor from being used with static class members. See [#48](https://github.com/bshoshany/thread-pool/issues/48).
|
||||
* `BS_thread_pool_test.cpp`:
|
||||
* Improved `count_unique_threads()` using condition variables, to ensure that each thread in the pool runs at least one task regardless of how fast it takes to run the tasks.
|
||||
* When appropriate, `check()` now explicitly reports what the obtained result was and what it was expected to be.
|
||||
@@ -153,8 +310,8 @@ GitHub: <https://github.com/bshoshany>
|
||||
* Added a new test for `parallelize_loop()` with a return value.
|
||||
* Improved some of the tests to make them more reliable. For example, `count_unique_threads()` now uses futures (stored in a `BS::multi_future<void>` object).
|
||||
* The program now uses `std::vector` instead of matrices, for both consistency checks and benchmarks, in order to simplify the code and considerably reduce its length.
|
||||
* The benchmarks have been simplified. There's now only one test: filling a specific number of vectors of fixed size with random values. This may be replaced with something more practical in a future released, but at least on the systems I've tested on, it does demonstrate a very significant multi-threading speedup.
|
||||
* In addition to multi-threaded tests with different numbers of tasks, the benchmark now also includes a single-threaded test. This allows for more accurate benchmarks compared to previous versions, as the (slight) parallelization overhead is now taken into account when calculating the maximum speedup.
|
||||
* The benchmarks have been simplified. There's now only one test: filling a specific number of vectors of fixed size with random values. This may be replaced with something more practical in a future released, but at least on the systems I've tested on, it does demonstrate a very significant multithreading speedup.
|
||||
* In addition to multithreaded tests with different numbers of tasks, the benchmark now also includes a single-threaded test. This allows for more accurate benchmarks compared to previous versions, as the (slight) parallelization overhead is now taken into account when calculating the maximum speedup.
|
||||
* The program decides how many vectors to use for benchmarking by testing how many are needed to reach a target duration in the single-threaded test. This ensures that the test takes approximately the same amount of time on different systems, and is thus more consistent and portable.
|
||||
* Miscellaneous minor optimizations and style improvements.
|
||||
* Changes to `README.md`:
|
||||
|
||||
+19
-17
@@ -1,24 +1,26 @@
|
||||
---
|
||||
authors:
|
||||
- family-names: "Shoshany"
|
||||
given-names: "Barak"
|
||||
orcid: "https://orcid.org/0000-0003-2222-127X"
|
||||
cff-version: "1.2.0"
|
||||
-
|
||||
family-names: Shoshany
|
||||
given-names: Barak
|
||||
orcid: https://orcid.org/0000-0003-2222-127X
|
||||
cff-version: 1.2.0
|
||||
date-released: "2021-05-03"
|
||||
doi: "10.5281/zenodo.4742687"
|
||||
license: "MIT"
|
||||
message: "If you use this package in published research, please cite it as follows."
|
||||
repository-code: "https://github.com/bshoshany/thread-pool"
|
||||
title: "A C++17 Thread Pool for High-Performance Scientific Computing"
|
||||
doi: 10.5281/zenodo.4742687
|
||||
license: MIT
|
||||
message: If you use this library in published research, please cite it as follows.
|
||||
preferred-citation:
|
||||
type: "article"
|
||||
authors:
|
||||
- family-names: "Shoshany"
|
||||
given-names: "Barak"
|
||||
orcid: "https://orcid.org/0000-0003-2222-127X"
|
||||
doi: "10.5281/zenodo.4742687"
|
||||
journal: "arXiv"
|
||||
-
|
||||
family-names: Shoshany
|
||||
given-names: Barak
|
||||
orcid: https://orcid.org/0000-0003-2222-127X
|
||||
doi: 10.5281/zenodo.4742687
|
||||
journal: arXiv
|
||||
month: 5
|
||||
title: "A C++17 Thread Pool for High-Performance Scientific Computing"
|
||||
url: "https://arxiv.org/abs/2105.00613"
|
||||
title: A C++17 Thread Pool for High-Performance Scientific Computing
|
||||
type: article
|
||||
url: https://arxiv.org/abs/2105.00613
|
||||
year: 2021
|
||||
repository-code: https://github.com/bshoshany/thread-pool
|
||||
title: A C++17 Thread Pool for High-Performance Scientific Computing
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,201 @@
|
||||
#pragma once
|
||||
|
||||
/**
|
||||
* @file BS_thread_pool_utils.hpp
|
||||
* @author Barak Shoshany (baraksh@gmail.com) (http://baraksh.com)
|
||||
* @version 4.0.0
|
||||
* @date 2023-12-27
|
||||
* @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 independent utility classes that are part of the library, but are not needed to use the thread pool itself.
|
||||
*/
|
||||
|
||||
#include <atomic> // std::atomic
|
||||
#include <chrono> // std::chrono
|
||||
#include <future> // std::promise, std::shared_future
|
||||
#include <initializer_list> // std::initializer_list
|
||||
#include <iostream> // std::cout
|
||||
#include <memory> // std::make_unique, std::unique_ptr
|
||||
#include <mutex> // std::mutex, std::scoped_lock
|
||||
#include <ostream> // std::endl, std::flush, std::ostream
|
||||
#include <utility> // std::forward
|
||||
|
||||
/**
|
||||
* @brief A namespace used by Barak Shoshany's projects.
|
||||
*/
|
||||
namespace BS {
|
||||
// A macro containing the version of the thread pool utilities library.
|
||||
#define BS_THREAD_POOL_UTILS_VERSION "v4.0.0 (2023-12-27)"
|
||||
|
||||
/**
|
||||
* @brief A utility class to allow simple signalling between threads.
|
||||
*/
|
||||
class [[nodiscard]] signaller
|
||||
{
|
||||
public:
|
||||
/**
|
||||
* @brief Construct a new signaller.
|
||||
*/
|
||||
signaller() : promise(), future(promise.get_future()) {}
|
||||
|
||||
// The copy constructor and copy assignment operator are deleted. The signaller works using a promise, which cannot be copied.
|
||||
signaller(const signaller&) = delete;
|
||||
signaller& operator=(const signaller&) = delete;
|
||||
|
||||
// The move constructor and move assignment operator are defaulted.
|
||||
signaller(signaller&&) = default;
|
||||
signaller& operator=(signaller&&) = default;
|
||||
|
||||
/**
|
||||
* @brief Inform any waiting threads that the signaller is ready.
|
||||
*/
|
||||
void ready()
|
||||
{
|
||||
promise.set_value();
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Wait until the signaller is ready.
|
||||
*/
|
||||
void wait()
|
||||
{
|
||||
future.wait();
|
||||
}
|
||||
|
||||
private:
|
||||
/**
|
||||
* @brief A promise used to set the state of the signaller.
|
||||
*/
|
||||
std::promise<void> promise;
|
||||
|
||||
/**
|
||||
* @brief A future used to wait for the signaller.
|
||||
*/
|
||||
std::shared_future<void> future;
|
||||
}; // class signaller
|
||||
|
||||
/**
|
||||
* @brief A utility class to synchronize printing to an output stream by different threads.
|
||||
*/
|
||||
class [[nodiscard]] synced_stream
|
||||
{
|
||||
public:
|
||||
/**
|
||||
* @brief Construct a new synced stream.
|
||||
*
|
||||
* @param stream The output stream to print to. The default value is `std::cout`.
|
||||
*/
|
||||
explicit synced_stream(std::ostream& stream = std::cout) : out_stream(stream) {}
|
||||
|
||||
// The copy and move constructors and assignment operators are deleted. The synced stream uses a mutex, which cannot be copied or moved.
|
||||
synced_stream(const synced_stream&) = delete;
|
||||
synced_stream(synced_stream&&) = delete;
|
||||
synced_stream& operator=(const synced_stream&) = delete;
|
||||
synced_stream& operator=(synced_stream&&) = delete;
|
||||
|
||||
/**
|
||||
* @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 stream_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 a newline character 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 = {};
|
||||
}; // class synced_stream
|
||||
|
||||
/**
|
||||
* @brief A utility class to measure execution time for benchmarking purposes.
|
||||
*/
|
||||
class [[nodiscard]] timer
|
||||
{
|
||||
public:
|
||||
/**
|
||||
* @brief Construct a new timer and immediately start measuring time.
|
||||
*/
|
||||
timer() = default;
|
||||
|
||||
/**
|
||||
* @brief Get the number of milliseconds that have elapsed since the object was constructed or since `start()` was last called, but keep the timer ticking.
|
||||
*
|
||||
* @return The number of milliseconds.
|
||||
*/
|
||||
[[nodiscard]] std::chrono::milliseconds::rep current_ms() const
|
||||
{
|
||||
return (std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::steady_clock::now() - start_time)).count();
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Start (or restart) measuring time. Note that the timer starts ticking as soon as the object is created, so this is only necessary if we want to restart the clock later.
|
||||
*/
|
||||
void start()
|
||||
{
|
||||
start_time = std::chrono::steady_clock::now();
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Stop measuring time and store the elapsed time since the object was constructed or since `start()` was last called.
|
||||
*/
|
||||
void stop()
|
||||
{
|
||||
elapsed_time = std::chrono::steady_clock::now() - start_time;
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Get the number of milliseconds stored when `stop()` was last called.
|
||||
*
|
||||
* @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();
|
||||
}; // class timer
|
||||
} // namespace BS
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,228 @@
|
||||
#!/usr/bin/env pwsh
|
||||
|
||||
# BS_thread_pool_test.ps1
|
||||
# By Barak Shoshany (baraksh@gmail.com) (http://baraksh.com)
|
||||
# v4.0.0, 2023-12-27
|
||||
# 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)
|
||||
#
|
||||
# BS::thread_pool: a fast, lightweight, and easy-to-use C++17 thread pool library. This script compiles and runs the bundled test program with different compilers.
|
||||
|
||||
Set-StrictMode -Version Latest
|
||||
|
||||
$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 $StartingLocation
|
||||
Exit $Code
|
||||
}
|
||||
|
||||
Write-Title '=== BS::thread_pool test script ==='
|
||||
|
||||
$StartingLocation = Get-Location
|
||||
|
||||
Set-Location $PSScriptRoot
|
||||
|
||||
$SourceFile = Join-Path $PSScriptRoot '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
|
||||
}
|
||||
|
||||
$IncludeFile = Join-Path (Split-Path -Parent $PSScriptRoot) 'include' 'BS_thread_pool.hpp'
|
||||
If (Test-Path -Path $IncludeFile)
|
||||
{
|
||||
Write-Text "Found main include file $IncludeFile."
|
||||
}
|
||||
Else
|
||||
{
|
||||
Write-Error "Main include file $IncludeFile not found, aborting script!"
|
||||
Exit-Script 1
|
||||
}
|
||||
|
||||
$IncludeFile = Join-Path (Split-Path -Parent $PSScriptRoot) 'include' 'BS_thread_pool_utils.hpp'
|
||||
If (Test-Path -Path $IncludeFile)
|
||||
{
|
||||
Write-Text "Found utilities include file $IncludeFile."
|
||||
}
|
||||
Else
|
||||
{
|
||||
Write-Error "Utilities include file $IncludeFile not found, aborting script!"
|
||||
Exit-Script 1
|
||||
}
|
||||
|
||||
$BuildFolder = Join-Path (Split-Path -Parent $PSScriptRoot) 'build'
|
||||
If (Test-Path -Path $BuildFolder)
|
||||
{
|
||||
Write-Text "Cleaning up build folder $BuildFolder..."
|
||||
Remove-Item (Join-Path $BuildFolder '*')
|
||||
}
|
||||
Else
|
||||
{
|
||||
Write-Text "Creating build folder $BuildFolder..."
|
||||
$Null = New-Item $BuildFolder -ItemType 'Directory'
|
||||
}
|
||||
Write-Text 'Done.'
|
||||
|
||||
Write-Title 'Compiling...'
|
||||
|
||||
If ($IsWindows)
|
||||
{
|
||||
$Extension = '.exe'
|
||||
$PThread = ''
|
||||
}
|
||||
Else
|
||||
{
|
||||
$Extension = ''
|
||||
$PThread = ' -pthread'
|
||||
}
|
||||
|
||||
$ExePrefix = 'BS_thread_pool_test_'
|
||||
|
||||
$Executables = @()
|
||||
|
||||
Function Build-ClangGCC([String] $Compiler, [String] $ExeSuffix, [String] $Macros = '')
|
||||
{
|
||||
$FullExe = Join-Path $BuildFolder "$ExePrefix$ExeSuffix$Extension"
|
||||
$Command = "$Compiler $SourceFile$PThread -I../include -std=c++17 -O3 -march=native -Wall -Wextra -Wconversion -Wsign-conversion -Wpedantic -Weffc++ -Wshadow -o $FullExe $Macros"
|
||||
Write-Command $Command
|
||||
Invoke-Expression $Command
|
||||
If ($LASTEXITCODE)
|
||||
{
|
||||
Write-Error "Failed to compile, aborting script! (Exit code: $LASTEXITCODE)"
|
||||
Exit-Script $LASTEXITCODE
|
||||
}
|
||||
Else
|
||||
{
|
||||
Write-Text "Successfully compiled to $FullExe."
|
||||
$Script:Executables += $FullExe
|
||||
}
|
||||
}
|
||||
|
||||
If (Get-Command 'clang++' -ErrorAction SilentlyContinue)
|
||||
{
|
||||
Write-Text 'Compiling with Clang...'
|
||||
Build-ClangGCC 'clang++' 'clang'
|
||||
Build-ClangGCC 'clang++' 'clang_light' '-DBS_THREAD_POOL_LIGHT_TEST'
|
||||
}
|
||||
Else
|
||||
{
|
||||
Write-Error 'Clang not found, skipping it!'
|
||||
}
|
||||
|
||||
Write-Host
|
||||
|
||||
If (Get-Command 'g++' -ErrorAction SilentlyContinue)
|
||||
{
|
||||
Write-Text 'Compiling with GCC...'
|
||||
Build-ClangGCC 'g++' 'gcc'
|
||||
Build-ClangGCC 'g++' 'gcc_light' '-DBS_THREAD_POOL_LIGHT_TEST'
|
||||
}
|
||||
Else
|
||||
{
|
||||
Write-Error 'GCC not found, skipping it!'
|
||||
}
|
||||
|
||||
Write-Host
|
||||
|
||||
Function Build-MSVC([String] $ExeSuffix, [String] $Macros = '')
|
||||
{
|
||||
$MSVCName = "$ExePrefix$ExeSuffix"
|
||||
$FullExe = Join-Path $BuildFolder "$MSVCName$Extension"
|
||||
$FullObj = Join-Path $BuildFolder "$MSVCName.obj"
|
||||
$Env:BS_THREAD_POOL_MSVC_COMMAND = "cl $SourceFile /I../include /std:c++17 /permissive- /O2 /W4 /EHsc /Fe:$FullExe /Fo:$FullObj $Macros"
|
||||
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 $FullObj
|
||||
Write-Text "Successfully compiled to $FullExe."
|
||||
$Script:Executables += $FullExe
|
||||
}
|
||||
}
|
||||
|
||||
If ($IsWindows)
|
||||
{
|
||||
$MSVCEnv = 'C:\Program Files\Microsoft Visual Studio\2022\Community\Common7\Tools\Launch-VsDevShell.ps1'
|
||||
If (Test-Path $MSVCEnv)
|
||||
{
|
||||
Write-Text 'Compiling with MSVC...'
|
||||
Build-MSVC 'msvc'
|
||||
Build-MSVC 'msvc_light' '/DBS_THREAD_POOL_LIGHT_TEST'
|
||||
}
|
||||
Else
|
||||
{
|
||||
Write-Error 'MSVC not found, skipping it!'
|
||||
}
|
||||
}
|
||||
|
||||
Set-Location $BuildFolder
|
||||
|
||||
Write-Title 'Starting tests. Outputs can be found in the generated log files.'
|
||||
|
||||
ForEach ($Executable in $Executables)
|
||||
{
|
||||
Write-Text "Executing: $Executable"
|
||||
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-Title '=== All tests completed successfully! ==='
|
||||
|
||||
Exit-Script 0
|
||||
Reference in New Issue
Block a user