diff --git a/.clang-format b/.clang-format
index 53dfbad..9084f79 100644
--- a/.clang-format
+++ b/.clang-format
@@ -25,7 +25,6 @@ AllowShortLambdasOnASingleLine: Empty
AllowShortLoopsOnASingleLine: false
AlwaysBreakAfterReturnType: None
AlwaysBreakBeforeMultilineStrings: false
-AlwaysBreakTemplateDeclarations: Yes
AttributeMacros: []
BinPackArguments: true
BinPackParameters: true
@@ -45,7 +44,7 @@ BraceWrapping:
BeforeLambdaBody: true
BeforeWhile: false
IndentBraces: false
- SplitEmptyFunction: true
+ SplitEmptyFunction: false
SplitEmptyNamespace: true
SplitEmptyRecord: true
BracedInitializerIndentWidth: 4
@@ -57,12 +56,11 @@ BreakBeforeConceptDeclarations: true
BreakBeforeInheritanceComma: false
BreakBeforeTernaryOperators: true
BreakConstructorInitializers: BeforeColon
-BreakConstructorInitializersBeforeComma: false
BreakInheritanceList: BeforeColon
BreakStringLiterals: true
-ColumnLimit: 1024
+BreakTemplateDeclarations: No
+ColumnLimit: 0
CompactNamespaces: false
-ConstructorInitializerAllOnOneLineOrOnePerLine: false
ConstructorInitializerIndentWidth: 4
ContinuationIndentWidth: 4
Cpp11BracedListStyle: true
@@ -99,7 +97,7 @@ ObjCBreakBeforeNestedBlockParam: true
ObjCSpaceAfterProperty: false
ObjCSpaceBeforeProtocolList: true
PPIndentWidth: -1
-PackConstructorInitializers: BinPack
+PackConstructorInitializers: CurrentLine
PenaltyBreakAssignment: 0
PenaltyBreakBeforeFirstCallParameter: 0
PenaltyBreakComment: 0
diff --git a/.clang-tidy b/.clang-tidy
index ea4b7ac..032b1eb 100644
--- a/.clang-tidy
+++ b/.clang-tidy
@@ -1,7 +1,8 @@
CheckOptions:
+ cppcoreguidelines-pro-type-member-init.IgnoreArrays: true
+ cppcoreguidelines-special-member-functions.AllowSoleDefaultDtor: true
misc-const-correctness.WarnPointersAsValues: true
misc-non-private-member-variables-in-classes.IgnoreClassesWithAllMemberVariablesBeingPublic: true
- readability-magic-numbers.IgnoredIntegerValues: 0; 1; 2; 3; 4; 5; 6; 7; 8; 9; 10
Checks: >
*,
-abseil-*,
@@ -11,6 +12,10 @@ Checks: >
-bugprone-easily-swappable-parameters,
-bugprone-empty-catch,
-cert-err58-cpp,
+ -clang-analyzer-alpha.*,
+ -clang-analyzer-debug.*,
+ -clang-analyzer-fuchsia.*,
+ -clang-analyzer-webkit.*,
-cppcoreguidelines-avoid-c-arrays,
-cppcoreguidelines-avoid-do-while,
-cppcoreguidelines-avoid-magic-numbers,
@@ -26,15 +31,16 @@ Checks: >
-google-*,
-hicpp-avoid-c-arrays,
-hicpp-braces-around-statements,
+ -hicpp-member-init,
-hicpp-no-array-decay,
-hicpp-signed-bitwise,
+ -hicpp-special-member-functions,
-hicpp-use-auto,
-hicpp-vararg,
-linuxkernel-*,
-llvm-*,
-llvmlibc-*,
-misc-definitions-in-headers,
- -misc-use-internal-linkage,
-modernize-avoid-bind,
-modernize-avoid-c-arrays,
-modernize-use-auto,
@@ -51,6 +57,8 @@ Checks: >
-readability-braces-around-statements,
-readability-function-cognitive-complexity,
-readability-identifier-length,
+ -readability-magic-numbers,
+ -readability-use-concise-preprocessor-directives,
-zircon-*,
HeaderFileExtensions: [h, hpp, cppm]
HeaderFilterRegex: .*
diff --git a/.github/ISSUE_TEMPLATE/bug_report.md b/.github/ISSUE_TEMPLATE/bug_report.md
index 1fd9cab..480b5c4 100644
--- a/.github/ISSUE_TEMPLATE/bug_report.md
+++ b/.github/ISSUE_TEMPLATE/bug_report.md
@@ -32,4 +32,4 @@ What behavior did you expect to get? What actually happened? If the code failed
**Additional information**
-Include any additional information here.
+Include any additional information here.
diff --git a/.github/ISSUE_TEMPLATE/failed-tests.md b/.github/ISSUE_TEMPLATE/failed-tests.md
index f6e59b9..a4ff3f9 100644
--- a/.github/ISSUE_TEMPLATE/failed-tests.md
+++ b/.github/ISSUE_TEMPLATE/failed-tests.md
@@ -21,4 +21,4 @@ Please attach the log file generated by the automated test program to this issue
**Additional information**
-Include any additional information here.
+Include any additional information here.
diff --git a/.github/ISSUE_TEMPLATE/feature_request.md b/.github/ISSUE_TEMPLATE/feature_request.md
index ac7e0a2..2c719cc 100644
--- a/.github/ISSUE_TEMPLATE/feature_request.md
+++ b/.github/ISSUE_TEMPLATE/feature_request.md
@@ -18,4 +18,4 @@ An example of code that utilizes the suggested feature. Paste or write it betwee
**Additional information**
-Include any additional information here.
+Include any additional information here.
diff --git a/.github/pull_request_template.md b/.github/pull_request_template.md
index 0e18f48..36e35fb 100644
--- a/.github/pull_request_template.md
+++ b/.github/pull_request_template.md
@@ -27,4 +27,4 @@ If so, please provide information about the test system(s):
**Additional information**
-Include any additional information here.
+Include any additional information here.
diff --git a/.gitignore b/.gitignore
index c6adf5c..0b7dd2e 100644
--- a/.gitignore
+++ b/.gitignore
@@ -1,2 +1,3 @@
build
temp
+default_args.txt
diff --git a/.vscode-linux/c_cpp_properties.json b/.vscode-linux/c_cpp_properties.json
index b86215e..7b65c25 100644
--- a/.vscode-linux/c_cpp_properties.json
+++ b/.vscode-linux/c_cpp_properties.json
@@ -14,7 +14,7 @@
"BS_THREAD_POOL_NATIVE_EXTENSIONS"
],
"includePath": [
- "${workspaceFolder}/**"
+ "${workspaceFolder}/include"
],
"intelliSenseMode": "linux-clang-x64",
"name": "Clang C++17"
@@ -33,7 +33,7 @@
"BS_THREAD_POOL_NATIVE_EXTENSIONS"
],
"includePath": [
- "${workspaceFolder}/**"
+ "${workspaceFolder}/include"
],
"intelliSenseMode": "linux-clang-x64",
"name": "Clang C++20"
@@ -52,7 +52,7 @@
"BS_THREAD_POOL_NATIVE_EXTENSIONS"
],
"includePath": [
- "${workspaceFolder}/**"
+ "${workspaceFolder}/include"
],
"intelliSenseMode": "linux-clang-x64",
"name": "Clang C++23"
@@ -68,7 +68,7 @@
"BS_THREAD_POOL_NATIVE_EXTENSIONS"
],
"includePath": [
- "${workspaceFolder}/**"
+ "${workspaceFolder}/include"
],
"intelliSenseMode": "linux-gcc-x64",
"name": "GCC C++17"
@@ -84,7 +84,7 @@
"BS_THREAD_POOL_NATIVE_EXTENSIONS"
],
"includePath": [
- "${workspaceFolder}/**"
+ "${workspaceFolder}/include"
],
"intelliSenseMode": "linux-gcc-x64",
"name": "GCC C++20"
@@ -100,7 +100,7 @@
"BS_THREAD_POOL_NATIVE_EXTENSIONS"
],
"includePath": [
- "${workspaceFolder}/**"
+ "${workspaceFolder}/include"
],
"intelliSenseMode": "linux-gcc-x64",
"name": "GCC C++23"
diff --git a/.vscode-linux/launch.json b/.vscode-linux/launch.json
index afe98e5..42186ce 100644
--- a/.vscode-linux/launch.json
+++ b/.vscode-linux/launch.json
@@ -1,59 +1,59 @@
-{
- "configurations": [
- {
- "args": [],
- "cwd": "${workspaceFolder}${/}build",
- "name": "Build and debug (Clang C++17)",
- "preLaunchTask": "Build for debugging (Clang C++17)",
- "program": "${workspaceFolder}${/}build${/}${fileBasenameNoExtension}_debug-clang-cpp17",
- "request": "launch",
- "type": "lldb"
- },
- {
- "args": [],
- "cwd": "${workspaceFolder}${/}build",
- "name": "Build and debug (Clang C++20)",
- "preLaunchTask": "Build for debugging (Clang C++20)",
- "program": "${workspaceFolder}${/}build${/}${fileBasenameNoExtension}_debug-clang-cpp20",
- "request": "launch",
- "type": "lldb"
- },
- {
- "args": [],
- "cwd": "${workspaceFolder}${/}build",
- "name": "Build and debug (Clang C++23)",
- "preLaunchTask": "Build for debugging (Clang C++23)",
- "program": "${workspaceFolder}${/}build${/}${fileBasenameNoExtension}_debug-clang-cpp23",
- "request": "launch",
- "type": "lldb"
- },
- {
- "args": [],
- "cwd": "${workspaceFolder}${/}build",
- "name": "Build and debug (GCC C++17)",
- "preLaunchTask": "Build for debugging (GCC C++17)",
- "program": "${workspaceFolder}${/}build${/}${fileBasenameNoExtension}_debug-gcc-cpp17",
- "request": "launch",
- "type": "cppdbg"
- },
- {
- "args": [],
- "cwd": "${workspaceFolder}${/}build",
- "name": "Build and debug (GCC C++20)",
- "preLaunchTask": "Build for debugging (GCC C++20)",
- "program": "${workspaceFolder}${/}build${/}${fileBasenameNoExtension}_debug-gcc-cpp20",
- "request": "launch",
- "type": "cppdbg"
- },
- {
- "args": [],
- "cwd": "${workspaceFolder}${/}build",
- "name": "Build and debug (GCC C++23)",
- "preLaunchTask": "Build for debugging (GCC C++23)",
- "program": "${workspaceFolder}${/}build${/}${fileBasenameNoExtension}_debug-gcc-cpp23",
- "request": "launch",
- "type": "cppdbg"
- }
- ],
- "version": "0.2.0"
-}
+{
+ "configurations": [
+ {
+ "args": [],
+ "cwd": "${workspaceFolder}${/}build",
+ "name": "Build and debug (Clang C++17)",
+ "preLaunchTask": "Build for debugging (Clang C++17)",
+ "program": "${workspaceFolder}${/}build${/}${fileBasenameNoExtension}_debug-clang-cpp17",
+ "request": "launch",
+ "type": "lldb"
+ },
+ {
+ "args": [],
+ "cwd": "${workspaceFolder}${/}build",
+ "name": "Build and debug (Clang C++20)",
+ "preLaunchTask": "Build for debugging (Clang C++20)",
+ "program": "${workspaceFolder}${/}build${/}${fileBasenameNoExtension}_debug-clang-cpp20",
+ "request": "launch",
+ "type": "lldb"
+ },
+ {
+ "args": [],
+ "cwd": "${workspaceFolder}${/}build",
+ "name": "Build and debug (Clang C++23)",
+ "preLaunchTask": "Build for debugging (Clang C++23)",
+ "program": "${workspaceFolder}${/}build${/}${fileBasenameNoExtension}_debug-clang-cpp23",
+ "request": "launch",
+ "type": "lldb"
+ },
+ {
+ "args": [],
+ "cwd": "${workspaceFolder}${/}build",
+ "name": "Build and debug (GCC C++17)",
+ "preLaunchTask": "Build for debugging (GCC C++17)",
+ "program": "${workspaceFolder}${/}build${/}${fileBasenameNoExtension}_debug-gcc-cpp17",
+ "request": "launch",
+ "type": "cppdbg"
+ },
+ {
+ "args": [],
+ "cwd": "${workspaceFolder}${/}build",
+ "name": "Build and debug (GCC C++20)",
+ "preLaunchTask": "Build for debugging (GCC C++20)",
+ "program": "${workspaceFolder}${/}build${/}${fileBasenameNoExtension}_debug-gcc-cpp20",
+ "request": "launch",
+ "type": "cppdbg"
+ },
+ {
+ "args": [],
+ "cwd": "${workspaceFolder}${/}build",
+ "name": "Build and debug (GCC C++23)",
+ "preLaunchTask": "Build for debugging (GCC C++23)",
+ "program": "${workspaceFolder}${/}build${/}${fileBasenameNoExtension}_debug-gcc-cpp23",
+ "request": "launch",
+ "type": "cppdbg"
+ }
+ ],
+ "version": "0.2.0"
+}
diff --git a/.vscode-linux/settings.json b/.vscode-linux/settings.json
new file mode 100644
index 0000000..f7f9824
--- /dev/null
+++ b/.vscode-linux/settings.json
@@ -0,0 +1,6 @@
+{
+ "C_Cpp.codeAnalysis.exclude": {
+ "misc/**": true,
+ "temp/**": true
+ }
+}
diff --git a/.vscode-linux/tasks.json b/.vscode-linux/tasks.json
index dc945a2..211e95f 100644
--- a/.vscode-linux/tasks.json
+++ b/.vscode-linux/tasks.json
@@ -470,8 +470,9 @@
},
{
"args": [
- "scripts/clear_folder.py",
- "../build"
+ "scripts/compile_cpp.py",
+ "-b",
+ "-v"
],
"command": "python3",
"detail": "Delete all files in the build folder.",
@@ -490,13 +491,16 @@
},
{
"args": [
- "scripts/clear_folder.py",
- "../temp"
+ "scripts/compile_cpp.py",
+ "${file}",
+ "-t=release",
+ "-y",
+ "-v"
],
"command": "python3",
- "detail": "Delete all files in the temp folder.",
+ "detail": "Compile active file using all available compilers and all relevant C++ standards with warning and optimization flags.",
"group": "test",
- "label": "Clear temp folder",
+ "label": "Build all optimized (all compilers and standards)",
"presentation": {
"clear": false,
"echo": true,
@@ -510,12 +514,17 @@
},
{
"args": [
- "scripts/test_all.py"
+ "scripts/compile_cpp.py",
+ "${file}",
+ "-t=release",
+ "-y",
+ "-r",
+ "-v"
],
"command": "python3",
- "detail": "Compile and run the test program with all available compilers and all relevant C++ standards.",
+ "detail": "Compile active file using all available compilers and all relevant C++ standards with warning and optimization flags and run the program.",
"group": "test",
- "label": "Run all tests",
+ "label": "Build all optimized and run (all compilers and standards)",
"presentation": {
"clear": false,
"echo": true,
diff --git a/.vscode-macos/c_cpp_properties.json b/.vscode-macos/c_cpp_properties.json
index c5c0821..1be5f25 100644
--- a/.vscode-macos/c_cpp_properties.json
+++ b/.vscode-macos/c_cpp_properties.json
@@ -8,7 +8,7 @@
"BS_THREAD_POOL_NATIVE_EXTENSIONS"
],
"includePath": [
- "${workspaceFolder}/**"
+ "${workspaceFolder}/include"
],
"intelliSenseMode": "macos-clang-x64",
"name": "Clang C++17"
@@ -21,7 +21,7 @@
"BS_THREAD_POOL_NATIVE_EXTENSIONS"
],
"includePath": [
- "${workspaceFolder}/**"
+ "${workspaceFolder}/include"
],
"intelliSenseMode": "macos-clang-x64",
"name": "Clang C++20"
@@ -34,7 +34,7 @@
"BS_THREAD_POOL_NATIVE_EXTENSIONS"
],
"includePath": [
- "${workspaceFolder}/**"
+ "${workspaceFolder}/include"
],
"intelliSenseMode": "macos-clang-x64",
"name": "Clang C++23"
diff --git a/.vscode-macos/launch.json b/.vscode-macos/launch.json
index e26fabc..b671279 100644
--- a/.vscode-macos/launch.json
+++ b/.vscode-macos/launch.json
@@ -1,32 +1,32 @@
-{
- "configurations": [
- {
- "args": [],
- "cwd": "${workspaceFolder}${/}build",
- "name": "Build and debug (Clang C++17)",
- "preLaunchTask": "Build for debugging (Clang C++17)",
- "program": "${workspaceFolder}${/}build${/}${fileBasenameNoExtension}_debug-clang-cpp17",
- "request": "launch",
- "type": "lldb"
- },
- {
- "args": [],
- "cwd": "${workspaceFolder}${/}build",
- "name": "Build and debug (Clang C++20)",
- "preLaunchTask": "Build for debugging (Clang C++20)",
- "program": "${workspaceFolder}${/}build${/}${fileBasenameNoExtension}_debug-clang-cpp20",
- "request": "launch",
- "type": "lldb"
- },
- {
- "args": [],
- "cwd": "${workspaceFolder}${/}build",
- "name": "Build and debug (Clang C++23)",
- "preLaunchTask": "Build for debugging (Clang C++23)",
- "program": "${workspaceFolder}${/}build${/}${fileBasenameNoExtension}_debug-clang-cpp23",
- "request": "launch",
- "type": "lldb"
- }
- ],
- "version": "0.2.0"
-}
+{
+ "configurations": [
+ {
+ "args": [],
+ "cwd": "${workspaceFolder}${/}build",
+ "name": "Build and debug (Clang C++17)",
+ "preLaunchTask": "Build for debugging (Clang C++17)",
+ "program": "${workspaceFolder}${/}build${/}${fileBasenameNoExtension}_debug-clang-cpp17",
+ "request": "launch",
+ "type": "lldb"
+ },
+ {
+ "args": [],
+ "cwd": "${workspaceFolder}${/}build",
+ "name": "Build and debug (Clang C++20)",
+ "preLaunchTask": "Build for debugging (Clang C++20)",
+ "program": "${workspaceFolder}${/}build${/}${fileBasenameNoExtension}_debug-clang-cpp20",
+ "request": "launch",
+ "type": "lldb"
+ },
+ {
+ "args": [],
+ "cwd": "${workspaceFolder}${/}build",
+ "name": "Build and debug (Clang C++23)",
+ "preLaunchTask": "Build for debugging (Clang C++23)",
+ "program": "${workspaceFolder}${/}build${/}${fileBasenameNoExtension}_debug-clang-cpp23",
+ "request": "launch",
+ "type": "lldb"
+ }
+ ],
+ "version": "0.2.0"
+}
diff --git a/.vscode-macos/settings.json b/.vscode-macos/settings.json
new file mode 100644
index 0000000..f7f9824
--- /dev/null
+++ b/.vscode-macos/settings.json
@@ -0,0 +1,6 @@
+{
+ "C_Cpp.codeAnalysis.exclude": {
+ "misc/**": true,
+ "temp/**": true
+ }
+}
diff --git a/.vscode-macos/tasks.json b/.vscode-macos/tasks.json
index dd5d118..753ddd8 100644
--- a/.vscode-macos/tasks.json
+++ b/.vscode-macos/tasks.json
@@ -236,8 +236,9 @@
},
{
"args": [
- "scripts/clear_folder.py",
- "../build"
+ "scripts/compile_cpp.py",
+ "-b",
+ "-v"
],
"command": "python3",
"detail": "Delete all files in the build folder.",
@@ -256,13 +257,16 @@
},
{
"args": [
- "scripts/clear_folder.py",
- "../temp"
+ "scripts/compile_cpp.py",
+ "${file}",
+ "-t=release",
+ "-y",
+ "-v"
],
"command": "python3",
- "detail": "Delete all files in the temp folder.",
+ "detail": "Compile active file using all available compilers and all relevant C++ standards with warning and optimization flags.",
"group": "test",
- "label": "Clear temp folder",
+ "label": "Build all optimized (all compilers and standards)",
"presentation": {
"clear": false,
"echo": true,
@@ -276,12 +280,17 @@
},
{
"args": [
- "scripts/test_all.py"
+ "scripts/compile_cpp.py",
+ "${file}",
+ "-t=release",
+ "-y",
+ "-r",
+ "-v"
],
"command": "python3",
- "detail": "Compile and run the test program with all available compilers and all relevant C++ standards.",
+ "detail": "Compile active file using all available compilers and all relevant C++ standards with warning and optimization flags and run the program.",
"group": "test",
- "label": "Run all tests",
+ "label": "Build all optimized and run (all compilers and standards)",
"presentation": {
"clear": false,
"echo": true,
diff --git a/.vscode-windows/c_cpp_properties.json b/.vscode-windows/c_cpp_properties.json
index 9e79264..a12fe30 100644
--- a/.vscode-windows/c_cpp_properties.json
+++ b/.vscode-windows/c_cpp_properties.json
@@ -14,7 +14,7 @@
"BS_THREAD_POOL_NATIVE_EXTENSIONS"
],
"includePath": [
- "${workspaceFolder}/**"
+ "${workspaceFolder}/include"
],
"intelliSenseMode": "windows-clang-x64",
"name": "Clang C++17"
@@ -33,7 +33,7 @@
"BS_THREAD_POOL_NATIVE_EXTENSIONS"
],
"includePath": [
- "${workspaceFolder}/**"
+ "${workspaceFolder}/include"
],
"intelliSenseMode": "windows-clang-x64",
"name": "Clang C++20"
@@ -52,7 +52,7 @@
"BS_THREAD_POOL_NATIVE_EXTENSIONS"
],
"includePath": [
- "${workspaceFolder}/**"
+ "${workspaceFolder}/include"
],
"intelliSenseMode": "windows-clang-x64",
"name": "Clang C++23"
@@ -68,7 +68,7 @@
"BS_THREAD_POOL_NATIVE_EXTENSIONS"
],
"includePath": [
- "${workspaceFolder}/**"
+ "${workspaceFolder}/include"
],
"intelliSenseMode": "windows-gcc-x64",
"name": "GCC C++17"
@@ -84,7 +84,7 @@
"BS_THREAD_POOL_NATIVE_EXTENSIONS"
],
"includePath": [
- "${workspaceFolder}/**"
+ "${workspaceFolder}/include"
],
"intelliSenseMode": "windows-gcc-x64",
"name": "GCC C++20"
@@ -100,7 +100,7 @@
"BS_THREAD_POOL_NATIVE_EXTENSIONS"
],
"includePath": [
- "${workspaceFolder}/**"
+ "${workspaceFolder}/include"
],
"intelliSenseMode": "windows-gcc-x64",
"name": "GCC C++23"
@@ -116,7 +116,7 @@
"BS_THREAD_POOL_NATIVE_EXTENSIONS"
],
"includePath": [
- "${workspaceFolder}/**"
+ "${workspaceFolder}/include"
],
"intelliSenseMode": "windows-msvc-x64",
"name": "MSVC C++17"
@@ -132,7 +132,7 @@
"BS_THREAD_POOL_NATIVE_EXTENSIONS"
],
"includePath": [
- "${workspaceFolder}/**"
+ "${workspaceFolder}/include"
],
"intelliSenseMode": "windows-msvc-x64",
"name": "MSVC C++20"
@@ -148,7 +148,7 @@
"BS_THREAD_POOL_NATIVE_EXTENSIONS"
],
"includePath": [
- "${workspaceFolder}/**"
+ "${workspaceFolder}/include"
],
"intelliSenseMode": "windows-msvc-x64",
"name": "MSVC C++23"
diff --git a/.vscode-windows/launch.json b/.vscode-windows/launch.json
index a869852..f03b556 100644
--- a/.vscode-windows/launch.json
+++ b/.vscode-windows/launch.json
@@ -1,89 +1,89 @@
-{
- "configurations": [
- {
- "args": [],
- "cwd": "${workspaceFolder}${/}build",
- "name": "Build and debug (Clang C++17)",
- "preLaunchTask": "Build for debugging (Clang C++17)",
- "program": "${workspaceFolder}${/}build${/}${fileBasenameNoExtension}_debug-clang-cpp17",
- "request": "launch",
- "type": "lldb"
- },
- {
- "args": [],
- "cwd": "${workspaceFolder}${/}build",
- "name": "Build and debug (Clang C++20)",
- "preLaunchTask": "Build for debugging (Clang C++20)",
- "program": "${workspaceFolder}${/}build${/}${fileBasenameNoExtension}_debug-clang-cpp20",
- "request": "launch",
- "type": "lldb"
- },
- {
- "args": [],
- "cwd": "${workspaceFolder}${/}build",
- "name": "Build and debug (Clang C++23)",
- "preLaunchTask": "Build for debugging (Clang C++23)",
- "program": "${workspaceFolder}${/}build${/}${fileBasenameNoExtension}_debug-clang-cpp23",
- "request": "launch",
- "type": "lldb"
- },
- {
- "args": [],
- "cwd": "${workspaceFolder}${/}build",
- "name": "Build and debug (GCC C++17)",
- "preLaunchTask": "Build for debugging (GCC C++17)",
- "program": "${workspaceFolder}${/}build${/}${fileBasenameNoExtension}_debug-gcc-cpp17",
- "request": "launch",
- "type": "cppdbg"
- },
- {
- "args": [],
- "cwd": "${workspaceFolder}${/}build",
- "name": "Build and debug (GCC C++20)",
- "preLaunchTask": "Build for debugging (GCC C++20)",
- "program": "${workspaceFolder}${/}build${/}${fileBasenameNoExtension}_debug-gcc-cpp20",
- "request": "launch",
- "type": "cppdbg"
- },
- {
- "args": [],
- "cwd": "${workspaceFolder}${/}build",
- "name": "Build and debug (GCC C++23)",
- "preLaunchTask": "Build for debugging (GCC C++23)",
- "program": "${workspaceFolder}${/}build${/}${fileBasenameNoExtension}_debug-gcc-cpp23",
- "request": "launch",
- "type": "cppdbg"
- },
- {
- "args": [],
- "console": "integratedTerminal",
- "cwd": "${workspaceFolder}${/}build",
- "name": "Build and debug (MSVC C++17)",
- "preLaunchTask": "Build for debugging (MSVC C++17)",
- "program": "${workspaceFolder}${/}build${/}${fileBasenameNoExtension}_debug-msvc-cpp17",
- "request": "launch",
- "type": "cppvsdbg"
- },
- {
- "args": [],
- "console": "integratedTerminal",
- "cwd": "${workspaceFolder}${/}build",
- "name": "Build and debug (MSVC C++20)",
- "preLaunchTask": "Build for debugging (MSVC C++20)",
- "program": "${workspaceFolder}${/}build${/}${fileBasenameNoExtension}_debug-msvc-cpp20",
- "request": "launch",
- "type": "cppvsdbg"
- },
- {
- "args": [],
- "console": "integratedTerminal",
- "cwd": "${workspaceFolder}${/}build",
- "name": "Build and debug (MSVC C++23)",
- "preLaunchTask": "Build for debugging (MSVC C++23)",
- "program": "${workspaceFolder}${/}build${/}${fileBasenameNoExtension}_debug-msvc-cpp23",
- "request": "launch",
- "type": "cppvsdbg"
- }
- ],
- "version": "0.2.0"
-}
+{
+ "configurations": [
+ {
+ "args": [],
+ "cwd": "${workspaceFolder}${/}build",
+ "name": "Build and debug (Clang C++17)",
+ "preLaunchTask": "Build for debugging (Clang C++17)",
+ "program": "${workspaceFolder}${/}build${/}${fileBasenameNoExtension}_debug-clang-cpp17",
+ "request": "launch",
+ "type": "lldb"
+ },
+ {
+ "args": [],
+ "cwd": "${workspaceFolder}${/}build",
+ "name": "Build and debug (Clang C++20)",
+ "preLaunchTask": "Build for debugging (Clang C++20)",
+ "program": "${workspaceFolder}${/}build${/}${fileBasenameNoExtension}_debug-clang-cpp20",
+ "request": "launch",
+ "type": "lldb"
+ },
+ {
+ "args": [],
+ "cwd": "${workspaceFolder}${/}build",
+ "name": "Build and debug (Clang C++23)",
+ "preLaunchTask": "Build for debugging (Clang C++23)",
+ "program": "${workspaceFolder}${/}build${/}${fileBasenameNoExtension}_debug-clang-cpp23",
+ "request": "launch",
+ "type": "lldb"
+ },
+ {
+ "args": [],
+ "cwd": "${workspaceFolder}${/}build",
+ "name": "Build and debug (GCC C++17)",
+ "preLaunchTask": "Build for debugging (GCC C++17)",
+ "program": "${workspaceFolder}${/}build${/}${fileBasenameNoExtension}_debug-gcc-cpp17",
+ "request": "launch",
+ "type": "cppdbg"
+ },
+ {
+ "args": [],
+ "cwd": "${workspaceFolder}${/}build",
+ "name": "Build and debug (GCC C++20)",
+ "preLaunchTask": "Build for debugging (GCC C++20)",
+ "program": "${workspaceFolder}${/}build${/}${fileBasenameNoExtension}_debug-gcc-cpp20",
+ "request": "launch",
+ "type": "cppdbg"
+ },
+ {
+ "args": [],
+ "cwd": "${workspaceFolder}${/}build",
+ "name": "Build and debug (GCC C++23)",
+ "preLaunchTask": "Build for debugging (GCC C++23)",
+ "program": "${workspaceFolder}${/}build${/}${fileBasenameNoExtension}_debug-gcc-cpp23",
+ "request": "launch",
+ "type": "cppdbg"
+ },
+ {
+ "args": [],
+ "console": "integratedTerminal",
+ "cwd": "${workspaceFolder}${/}build",
+ "name": "Build and debug (MSVC C++17)",
+ "preLaunchTask": "Build for debugging (MSVC C++17)",
+ "program": "${workspaceFolder}${/}build${/}${fileBasenameNoExtension}_debug-msvc-cpp17",
+ "request": "launch",
+ "type": "cppvsdbg"
+ },
+ {
+ "args": [],
+ "console": "integratedTerminal",
+ "cwd": "${workspaceFolder}${/}build",
+ "name": "Build and debug (MSVC C++20)",
+ "preLaunchTask": "Build for debugging (MSVC C++20)",
+ "program": "${workspaceFolder}${/}build${/}${fileBasenameNoExtension}_debug-msvc-cpp20",
+ "request": "launch",
+ "type": "cppvsdbg"
+ },
+ {
+ "args": [],
+ "console": "integratedTerminal",
+ "cwd": "${workspaceFolder}${/}build",
+ "name": "Build and debug (MSVC C++23)",
+ "preLaunchTask": "Build for debugging (MSVC C++23)",
+ "program": "${workspaceFolder}${/}build${/}${fileBasenameNoExtension}_debug-msvc-cpp23",
+ "request": "launch",
+ "type": "cppvsdbg"
+ }
+ ],
+ "version": "0.2.0"
+}
diff --git a/.vscode-windows/settings.json b/.vscode-windows/settings.json
new file mode 100644
index 0000000..76817cb
--- /dev/null
+++ b/.vscode-windows/settings.json
@@ -0,0 +1,9 @@
+{
+ "C_Cpp.codeAnalysis.clangTidy.args": [
+ "--extra-arg-before=--target=x86_64-pc-windows-msvc",
+ ],
+ "C_Cpp.codeAnalysis.exclude": {
+ "misc/**": true,
+ "temp/**": true
+ }
+}
diff --git a/.vscode-windows/tasks.json b/.vscode-windows/tasks.json
index ee2e307..6c9d901 100644
--- a/.vscode-windows/tasks.json
+++ b/.vscode-windows/tasks.json
@@ -704,8 +704,9 @@
},
{
"args": [
- "scripts/clear_folder.py",
- "../build"
+ "scripts/compile_cpp.py",
+ "-b",
+ "-v"
],
"command": "python",
"detail": "Delete all files in the build folder.",
@@ -724,13 +725,16 @@
},
{
"args": [
- "scripts/clear_folder.py",
- "../temp"
+ "scripts/compile_cpp.py",
+ "${file}",
+ "-t=release",
+ "-y",
+ "-v"
],
"command": "python",
- "detail": "Delete all files in the temp folder.",
+ "detail": "Compile active file using all available compilers and all relevant C++ standards with warning and optimization flags.",
"group": "test",
- "label": "Clear temp folder",
+ "label": "Build all optimized (all compilers and standards)",
"presentation": {
"clear": false,
"echo": true,
@@ -744,12 +748,17 @@
},
{
"args": [
- "scripts/test_all.py"
+ "scripts/compile_cpp.py",
+ "${file}",
+ "-t=release",
+ "-y",
+ "-r",
+ "-v"
],
"command": "python",
- "detail": "Compile and run the test program with all available compilers and all relevant C++ standards.",
+ "detail": "Compile active file using all available compilers and all relevant C++ standards with warning and optimization flags and run the program.",
"group": "test",
- "label": "Run all tests",
+ "label": "Build all optimized and run (all compilers and standards)",
"presentation": {
"clear": false,
"echo": true,
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 0141d89..90d6147 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -6,6 +6,7 @@ Website: \
GitHub:
* [Version history](#version-history)
+ * [v5.1.0 (2026-01-03)](#v510-2026-01-03)
* [v5.0.0 (2024-12-19)](#v500-2024-12-19)
* [v4.1.0 (2024-03-22)](#v410-2024-03-22)
* [v4.0.1 (2023-12-28)](#v401-2023-12-28)
@@ -30,6 +31,50 @@ GitHub:
## Version history
+### v5.1.0 (2026-01-03)
+
+* New/changed features:
+ * Added `detach_bulk()` and `submit_bulk()` member functions to submit tasks in bulk. You can pass either a range of iterators or a container. The mutex protecting the task queue is locked only once for the entire bulk submission, which should improve performance when submitting a large number of tasks; if the tasks were submitted using individual calls to `detach_task()` or `submit_task()` instead, the mutex would need to be locked and unlocked for each task.
+ * `detach_blocks()`/`detach_loop()`/`detach_sequence()` and `submit_blocks()`/`submit_loop()`/`submit_sequence()` now use `detach_bulk()` and `submit_bulk()`, respectively, under the hood for increased performance (the API remains the same). They have also been refactored using helper functions and custom function object classes to reduce code duplication.
+ * All `submit_*` member functions now use a C++17/20 polyfill for `std::move_only_function` when C++23 is not available (or when using libc++, which at the time of this release has not implemented it yet). This allows them to work without using `std::shared_ptr`, which should increase performance.
+ * If the native extensions are enabled, a pool created with the default constructor will now only use the number of threads available to the process, as obtained from `BS::get_os_process_affinity()`, which can be less than the number of hardware threads. See [#161](https://github.com/bshoshany/thread-pool/issues/161).
+ * Since importing the C++ Standard Library using `import std` is now supported by all 3 major compilers, the library (and test program) will now use `import std` whenever the macro `BS_THREAD_POOL_IMPORT_STD` is defined, as long as C++23 is enabled, without performing any additional checks for compiler or standard library support (aside from the workaround for GCC mentioned below).
+ * The `BS::tp` enumeration is now properly defined as an `enum class` with the appropriate bitwise operators.
+ * Removed the polyfills for `std::counting_semaphore` and `std::binary_semaphore` from `BS_thread_pool.hpp`, as they are not used by the library itself, to reduce the size of the header file. If you need them, you can copy them from the test program `BS_thread_pool_test.cpp`.
+ * On Windows, if the native extensions are enabled, `WIN32_LEAN_AND_MEAN` is now defined before including `` to reduce compilation time.
+* Bug fixes:
+ * The system macros `major` and `minor` (from `` on Linux) or `min` and `max` (from `` on Windows) are now automatically undefined if they are detected, to prevent compilation errors. This was also done previously, but only under certain conditions; now it is done unconditionally, as some users reported issues. On Windows, `NOMINMAX` is now defined before including ``, but the `min` and `max` macros are still undefined independently.
+ * `BS::wait_deadlock` is now only exported by the module if exceptions are enabled, preventing a compiler error. See [#160](https://github.com/bshoshany/thread-pool/pull/160).
+ * Fixed a typo in `BS::thread_pool::submit_sequence()` which caused the wrong number of futures to be reserved, potentially resulting in unnecessary reallocations.
+ * `BS::multi_future::wait_until` now correctly waits using the specific clock type passed in the template parameter.
+ * Fixed a bug where `reset()` failed to notify worker threads if the pool was unpaused before resetting.
+ * `get_os_thread_affinity()` and `set_os_thread_affinity()` now return `std::nullopt` and `false` (respectively) on Android, as the API is not supported. See [#163](https://github.com/bshoshany/thread-pool/pull/163).
+* Tests:
+ * The test program `BS_thread_pool_test.cpp` now prints colored output for better readability. This can be disabled by setting the `NO_COLOR` environment variable.
+ * The test program now prints out the Mandelbrot set it generates, downsampled to fit in a terminal window (at 120 character width). This will be in 24-bit color in the terminal, and in monochrome using Unicode blocks in the log file. (If `NO_COLOR` is set, the terminal output will also be in monochrome.)
+ * The test program now looks for `default_args.txt` in both the current folder and the parent folder when reading default command line arguments.
+* Documentation:
+ * Added an example in `README.md` for getting and setting process affinity.
+ * Removed the suggestion in `README.md` to use the `-pthread` flag on Linux/macOS, as it does not seem to be necessary in order to use the library, at least on the systems I tested with. If you are using a system that requires it, then you probably already know about it.
+ * Updated the instructions in `README.md` for compiling with GCC using `import BS.thread_pool`, and added instructions on how to compile the `std` module with GNU libstdc++.
+ * Fixed many typos and inconsistencies in `README.md`.
+* Known issues:
+ * At the time of this release, there is a bug in Clang with libc++ where using `std::jthread` in a C++20 module causes a compilation error. As a workaround, until the bug is fixed, the thread pool library automatically falls back to `std::thread` if it detects that Clang and libc++ are being used together with C++20 modules. This workaround can be disabled by defining `BS_THREAD_POOL_DISABLE_WORKAROUNDS` when compiling the module.
+ * At the time of this release, there is a bug when using GCC with libstdc++ on Windows via MSYS2 where the `BS.thread_pool` module doesn't compile if both native extensions and `import std` are enabled. As a workaround, until the bug is fixed, the thread pool library automatically falls back to header files if it detects that GCC and libstdc++ are being used together with the C++23 `std` module on Windows. This workaround can be disabled by defining `BS_THREAD_POOL_DISABLE_WORKAROUNDS` when compiling the module.
+* Development:
+ * The Python script I use for compiling the test program, `compile_cpp.py`, has received numerous improvements:
+ * The script now supports `import std` with GCC in addition to Clang and MSVC.
+ * The script now only recompiles the program if the source file(s), module(s), and optional additional dependencies (added using the flag `-n`/`--deps` or the `deps` field in `compile_cpp.yaml`) have changed since the binary was created. Use `-e`/`--force` to force recompilation.
+ * The script now allows disabling exceptions by either defining `disable_exceptions: true` in `compile_cpp.yaml` or using the flag `-x=true`/`--disable-exceptions=true` (the flag overrides the YAML file).
+ * The script can now compile modules independently using the `-l`/`--as-module` flag.
+ * The script can now clear the output folder using the `-b`/`--clear-output` flag (replaces the `clear_folder.py` script from the previous release).
+ * The script can now test compilation using all possible combinations of compilers and C++ standards available in the system using the `-y`/`--try-all` flag (replaces the `test_all.py` script from the previous release).
+ * The script now automatically detects the Visual Studio installation path on Windows.
+ * The script now implements a more robust mechanism for finding the `std` module.
+ * The script now prints colored output for better readability. This can be disabled by setting the `NO_COLOR` environment variable.
+ * The script no longer disables optimizations when compiling with GCC and modules (since that bug is fixed in recent versions of GCC).
+ * Added a VS Code task to compile the test program (or the active file) with all available compilers and all relevant C++ standards, but without running it, to quickly check for compiler compatibility issues.
+
### v5.0.0 (2024-12-19)
* A major new release with many new features, improvements, bug fixes, and performance optimizations! Please note that code written using previous releases may 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.
@@ -172,7 +217,7 @@ GitHub:
* **Development:**
* A Python script `compile_cpp.py` has been added to the repository, in the `scripts` folder. It can be used to compile any C++ source file with different compilers on different platforms. The compilation parameters can be configured using command line arguments and/or via an optional YAML configuration file `compile_cpp.yaml` which specifies defined macros, extra compiler flags (per compiler), include folders, modules, and the output folder.
* I wrote this script to make it easier for me to test the library with different combinations of compilers, standards, and platforms using the built-in Visual Studio Code tasks. I also included three `.vscode` folders (one for each OS) in the repository, with appropriate `c_cpp_properties.json`, `launch.json`, and `tasks.json` files that utilize this script, in case you want to use it in your own projects. However, note that this script is not meant to replace CMake or any full-fledged build system, it's just a convenient script for developing single-header libraries like this one or other small projects.
- * The `compile_cpp.py` script also transparently handles C++20 modules and importing the C++ Standard Library as a module in C++23. Therefore, users of this library who wish to import it as a C+20 module may find this script particularly useful.
+ * The `compile_cpp.py` script also transparently handles C++20 modules and importing the C++ Standard Library as a module in C++23. Therefore, users of this library who wish to import it as a C++20 module may find this script particularly useful.
* Another Python script `test_all.py` in the `scripts` folder replaces the old PowerShell test script. Tests are now performed in C++17, C++20, and C++23 modes, using all compilers available in the system (Clang, GCC, and/or MSVC). Since there are so many tests, the test script now no longer performs the benchmarks, as that would take too long.
* A final Python script `clear_folder.py` in the `scripts` folder is used to clean up output and temporary folders, and integrates with VS Code tasks.
diff --git a/CITATION.bib b/CITATION.bib
index bbba157..652b177 100644
--- a/CITATION.bib
+++ b/CITATION.bib
@@ -9,4 +9,4 @@
url = {https://www.sciencedirect.com/science/article/pii/S235271102400058X},
volume = {26},
year = {2024}
-}
+}
diff --git a/CITATION.cff b/CITATION.cff
index 05e3a98..df3f96a 100644
--- a/CITATION.cff
+++ b/CITATION.cff
@@ -22,4 +22,4 @@ preferred-citation:
repository-code: https://github.com/bshoshany/thread-pool
title: A C++17 Thread Pool for High-Performance Scientific Computing
type: software
-url: https://github.com/bshoshany/thread-pool
+url: https://github.com/bshoshany/thread-pool
diff --git a/LICENSE.txt b/LICENSE.txt
index 5a7c645..ea7aa26 100644
--- a/LICENSE.txt
+++ b/LICENSE.txt
@@ -1,6 +1,6 @@
MIT License
-Copyright (c) 2024 Barak Shoshany
+Copyright (c) 2021-2026 Barak Shoshany
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
diff --git a/README.md b/README.md
index 4794b5a..55315d6 100644
--- a/README.md
+++ b/README.md
@@ -18,7 +18,7 @@ Email: \
Website: \
GitHub:
-This is the complete documentation for **v5.0.0** of the library, released on **2024-12-19**.
+This is the complete documentation for **v5.1.0** of the library, released on **2026-01-03**.
* [Introduction](#introduction)
* [Motivation](#motivation)
@@ -43,9 +43,9 @@ This is the complete documentation for **v5.0.0** of the library, released on **
* [Loops with return values](#loops-with-return-values)
* [Parallelizing sequences](#parallelizing-sequences)
* [More about `BS::multi_future`](#more-about-bsmulti_future)
+ * [Submitting tasks in bulk without a loop](#submitting-tasks-in-bulk-without-a-loop)
* [Utility classes](#utility-classes)
* [Synchronizing printing to a stream with `BS::synced_stream`](#synchronizing-printing-to-a-stream-with-bssynced_stream)
- * [Synchronizing tasks with `BS::counting_semaphore` and `BS::binary_semaphore`](#synchronizing-tasks-with-bscounting_semaphore-and-bsbinary_semaphore)
* [Managing tasks](#managing-tasks)
* [Monitoring the tasks](#monitoring-the-tasks)
* [Purging tasks](#purging-tasks)
@@ -82,12 +82,13 @@ This is the complete documentation for **v5.0.0** of the library, released on **
* [Enabling `import std`](#enabling-import-std)
* [Compiling with `compile_cpp.py` using `import std`](#compiling-with-compile_cpppy-using-import-std)
* [Compiling with Clang and LLVM libc++ using `import std`](#compiling-with-clang-and-llvm-libc-using-import-std)
+ * [Compiling with GCC and GNU libstdc++ using `import std`](#compiling-with-gcc-and-gnu-libstdc-using-import-std)
* [Compiling with MSVC and Microsoft STL using `import std`](#compiling-with-msvc-and-microsoft-stl-using-import-std)
* [Compiling with CMake using `import std`](#compiling-with-cmake-using-import-std)
* [Installing the library using package managers](#installing-the-library-using-package-managers)
* [Installing using vcpkg](#installing-using-vcpkg)
- * [Installing using Conan](#installing-using-conan)
* [Installing using Meson](#installing-using-meson)
+ * [Installing using Conan](#installing-using-conan)
* [Installing using CMake with CPM](#installing-using-cmake-with-cpm)
* [Installing using CMake with `FetchContent`](#installing-using-cmake-with-fetchcontent)
* [Complete library reference](#complete-library-reference)
@@ -102,7 +103,7 @@ This is the complete documentation for **v5.0.0** of the library, released on **
* [All names exported by the C++20 module](#all-names-exported-by-the-c20-module)
* [Development tools](#development-tools)
* [The `compile_cpp.py` script](#the-compile_cpppy-script)
- * [Other included tools](#other-included-tools)
+ * [Visual Studio Code tasks](#visual-studio-code-tasks)
* [About the project](#about-the-project)
* [Bug reports and feature requests](#bug-reports-and-feature-requests)
* [Contribution and pull request policy](#contribution-and-pull-request-policy)
@@ -144,10 +145,10 @@ Obtaining the library is quick and easy; it can be downloaded manually from [the
* Header-only: no need to install or build the library.
* Self-contained: no external requirements or dependencies.
* Portable: uses only the C++ standard library, and works with any C++17-compliant compiler on any platform.
- * Only 487 lines of code, including all optional features and utility classes (excluding comments, blank lines, lines containing only a single brace, C++17 polyfills, and native extensions).
+ * Only 536 lines of code, including all optional features and utility classes (excluding comments, blank lines, lines containing only a single brace, C++17/20 polyfills, and native extensions).
* **Modern:**
* Fully supports C++17, C++20, and C++23, taking advantage of the latest language features when available for maximum performance, reliability, and usability.
- * In C++20, the library can an be imported as a C++20 module using [`import BS.thread_pool`](#importing-the-library-as-a-c20-module), with many benefits, such as faster compilation times and avoiding namespace pollution.
+ * In C++20, the library can be imported as a C++20 module using [`import BS.thread_pool`](#importing-the-library-as-a-c20-module), with many benefits, such as faster compilation times and avoiding namespace pollution.
* In C++23, the library can import the C++ Standard Library as a module using [`import std`](#importing-the-c23-standard-library-as-a-module) on supported compilers and platforms.
* Makes use of modern C++ programming practices for readability, maintainability, performance, safety, portability, and reliability.
* **Easy to use:**
@@ -155,7 +156,7 @@ Obtaining the library is quick and easy; it can be downloaded manually from [the
* Every task submitted to the queue using [`submit_task()`](#submitting-tasks-to-the-queue) automatically generates an `std::future`, which can be used to wait for the task to finish executing, obtain its eventual return value, and/or catch any thrown exceptions.
* Loops can be automatically parallelized into any number of tasks using [`submit_loop()`](#parallelizing-loops), which returns a [`BS::multi_future`](#more-about-bsmulti_future) that can be used to track the execution of all parallel tasks at once.
* If futures are not needed, tasks may be submitted using [`detach_task()`](#detaching-and-waiting-for-tasks), and loops can be parallelized using [`detach_loop()`](#parallelizing-loops-without-futures) - sacrificing convenience for even greater performance. In that case, `wait()`, `wait_for()`, and `wait_until()` can be used to wait for all the tasks in the queue to complete.
- * Extremely thorough and detailed documentation, with numerous examples, is available in the library's [`README.md` file](https://github.com/bshoshany/thread-pool/blob/master/README.md), with a total of 3,359 lines and 25,506 words!
+ * Extremely thorough and detailed documentation, with numerous examples, is available in the library's [`README.md` file](https://github.com/bshoshany/thread-pool/blob/master/README.md), with a total of 3,486 lines and 26,700 words!
* The code is thoroughly documented using Doxygen comments - not only the interface, but also the implementation, in case the user would like to make modifications.
* Optionally, the included Python script [`compile_cpp.py`](#the-compile_cpppy-script) can be used to easily compile any programs that are using the library, with full support for C++20 modules and C++23 Standard Library modules where applicable.
* **Additional features:**
@@ -167,10 +168,10 @@ Obtaining the library is quick and easy; it can be downloaded manually from [the
* Run a cleanup function in each thread right before it is destroyed, using [`set_cleanup_func()`](#thread-cleanup-functions).
* Assume lower-level control of parallelized loops using [`detach_blocks()` and `submit_blocks()`](#parallelizing-individual-indices-vs-blocks).
* Parallelize a sequence of tasks enumerated by indices to the queue using [`detach_sequence()` and `submit_sequence()`](#parallelizing-sequences).
+ * Submit tasks in bulk from a container or iterator range using [`detach_bulk()` and `submit_bulk()`](#submitting-tasks-in-bulk-without-a-loop).
* Get [information about the current thread](#getting-information-about-the-current-thread): the pool index using `BS::this_thread::get_index()` and a pointer to the owning pool using `BS::this_thread::get_pool()`.
* Get the unique thread IDs for all threads in the pool using [`get_thread_ids()`](#getting-and-resetting-the-number-of-threads-in-the-pool).
* Synchronize output to one or more streams from multiple threads in parallel using the [`BS::synced_stream`](#synchronizing-printing-to-a-stream-with-bssynced_stream) utility class.
- * Access C++20 semaphores in C++17 using the [`BS::binary_semaphore` and `BS::counting_semaphore`](#synchronizing-tasks-with-bscounting_semaphore-and-bsbinary_semaphore) polyfill classes.
* **Optional features:**
* [Optional features](#enabling-features) can be enabled by passing a bitmask template parameter to the `BS::thread_pool` class template.
* Assign a priority to each task using the optional [task priority](#setting-task-priority) feature. The priority, in the range -128 to +127, is passed as the last argument to all `submit` and `detach` member functions. Tasks with higher priorities will be executed first.
@@ -185,9 +186,9 @@ Obtaining the library is quick and easy; it can be downloaded manually from [the
* Use [`BS::get_os_process_affinity()` and `BS::set_os_process_affinity()`](#setting-process-affinity) to get and set the processor affinity of the current process.
* Get the implementation-defined thread handles for all threads in the pool using [`get_native_handles()`](#accessing-native-thread-handles).
* **Well-tested:**
- * The included test program [`BS_thread_pool_test.cpp`](#automated-tests) performs hundreds of automated tests, and also serves as a comprehensive example of how to properly use the library.
+ * The included test program [`BS_thread_pool_test.cpp`](#testing-the-library) performs hundreds of automated tests, and also serves as a comprehensive example of how to properly use the library.
* The test program also performs [benchmarks](#performance-tests) using a highly-optimized multithreaded algorithm which generates a plot of the Mandelbrot set.
- * The included Python script `test_all.py` provides a portable way to easily run the tests with multiple compilers.
+ * The included Python script [`compile_cpp.py`](#the-compile_cpppy-script) provides a portable way to automatically run the tests with all available compilers with one command.
* [Compatibility](#compiling-and-compatibility) is comprehensively tested on the latest versions of Windows, Ubuntu, and macOS, using Clang, GCC, and MSVC.
* Under continuous and active development. Bug reports and feature requests are welcome, and should be made via [GitHub issues](https://github.com/bshoshany/thread-pool/issues).
@@ -203,7 +204,7 @@ To install `BS::thread_pool`, simply download the [latest release](https://githu
The thread pool will now be accessible via the `BS::thread_pool` class. For an even quicker installation, you can download the header file itself directly [at this URL](https://raw.githubusercontent.com/bshoshany/thread-pool/master/include/BS_thread_pool.hpp); no additional files are required, as the library is a single-header library.
-This library is also available on various package managers and build system, including [vcpkg](https://vcpkg.io/), [Conan](https://conan.io/), [Meson](https://mesonbuild.com/), and [CMake](https://cmake.org/). Please [see below](#installing-the-library-using-package-managers) for more details.
+This library is also available on various package managers and build systems, including [vcpkg](https://vcpkg.io/), [Conan](https://conan.io/), [Meson](https://mesonbuild.com/), and [CMake](https://cmake.org/). Please [see below](#installing-the-library-using-package-managers) for more details.
If C++20 features are available, the library can also be imported as a C++20 module, in which case `#include "BS_thread_pool.hpp"` should be replaced with `import BS.thread_pool;`. This requires one additional file, and the module must be compiled before it can be used; please see detailed instructions [below](#importing-the-library-as-a-c20-module).
@@ -211,22 +212,22 @@ If C++20 features are available, the library can also be imported as a
This library officially supports C++17, C++20, and C++23. If compiled with C++20 and/or C++23 support, the library will make use of newly available features for maximum performance and usability. However, the library is fully compatible with C++17, and should successfully compile on any C++17 standard-compliant compiler, on all operating systems and architectures for which such a compiler is available.
-Compatibility was verified using the bundled test program `BS_thread_pool_test.cpp`, compiled using the bundled Python scripts `test_all.py` and `compile_cpp.py` with native extensions enabled, importing the library [as a C++20 module](#importing-the-library-as-a-c20-module) where applicable, and importing the [C++23 Standard Library as a module](#importing-the-c23-standard-library-as-a-module) where applicable, on a 24-core (8P+16E) / 32-thread Intel i9-13900K CPU, using the following compilers, C++ standard libraries, and platforms:
+Compatibility was verified using the bundled test program [`BS_thread_pool_test.cpp`](#testing-the-library), compiled using the bundled Python script [`compile_cpp.py`](#the-compile_cpppy-script) with native extensions enabled, importing the library [as a C++20 module](#importing-the-library-as-a-c20-module) where applicable, and importing the [C++23 Standard Library as a module](#importing-the-c23-standard-library-as-a-module) where applicable, on a 24-core (8P+16E) / 32-thread Intel i9-13900K CPU, using the following compilers, C++ standard libraries, and platforms:
-* Windows 11 23H2 build 22631.4602:
- * [Clang](https://clang.llvm.org/) v19.1.4 with LLVM libc++ v19.1.4 ([MSYS2 build](https://www.msys2.org/))
- * [GCC](https://gcc.gnu.org/) v14.2.0 with GNU libstdc++ v14 (20240801) ([MSYS2 build](https://www.msys2.org/))
- * [MSVC](https://docs.microsoft.com/en-us/cpp/) v19.42.34435 with Microsoft STL v143 (202408).
-* Ubuntu 24.10:
- * [Clang](https://clang.llvm.org/) v19.1.6 with LLVM libc++ v19.1.6
- * [GCC](https://gcc.gnu.org/) v14.2.0 with GNU libstdc++ v14 (20240908)
+* Windows 11 25H2 build 26200.7462:
+ * [Clang](https://clang.llvm.org/) v21.1.8 with LLVM libc++ v21.1.8 ([MSYS2 build](https://www.msys2.org/))
+ * [GCC](https://gcc.gnu.org/) v15.2.0 with GNU libstdc++ v15 (20250808) ([MSYS2 build](https://www.msys2.org/))
+ * [MSVC](https://docs.microsoft.com/en-us/cpp/) v19.50.35721 with Microsoft STL v145 (202508).
+* Ubuntu 25.10:
+ * [Clang](https://clang.llvm.org/) v21.1.8 with LLVM libc++ v21.1.8
+ * [GCC](https://gcc.gnu.org/) v15.2.0 with GNU libstdc++ v15 (20250917)
* macOS 15.1 build 24B83:
- * [Clang](https://clang.llvm.org/) v19.1.6 with LLVM libc++ v19.1.6 ([Homebrew build](https://formulae.brew.sh/formula/llvm))
+ * [Clang](https://clang.llvm.org/) v21.1.8 with LLVM libc++ v21.1.8 ([Homebrew build](https://formulae.brew.sh/formula/llvm))
* Note: Apple Clang is currently not officially supported, as it does not support C++20 modules.
As this library requires C++17 features, the code must be compiled with C++17 support:
-* For Clang or GCC, use the `-std=c++17` flag. On Linux, you will also need to use the `-pthread` flag to enable the POSIX threads library.
+* For Clang or GCC, use the `-std=c++17` flag.
* For MSVC, use `/std:c++17`, and also `/permissive-` to ensure standards conformance.
For maximum performance, it is recommended to compile with all available compiler optimizations:
@@ -234,17 +235,17 @@ For maximum performance, it is recommended to compile with all available compile
* For Clang or GCC, use the `-O3` flag.
* For MSVC, use `/O2`.
-As an example, to compile the test program `BS_thread_pool_test.cpp` with compiler optimizations, it is recommended to use the following commands:
+As an example, to compile the test program `BS_thread_pool_test.cpp` with compiler optimizations, first create the `build` folder using `mkdir build`, and then run the following command in the root folder of the repository:
* Windows:
- * GCC: `g++ BS_thread_pool_test.cpp -std=c++17 -O3 -o BS_thread_pool_test.exe`
- * Clang: `clang++ BS_thread_pool_test.cpp -std=c++17 -O3 -o BS_thread_pool_test.exe`
- * MSVC: `cl BS_thread_pool_test.cpp /std:c++17 /permissive- /O2 /EHsc /Fo:BS_thread_pool_test.obj /Fe:BS_thread_pool_test.exe`
+ * GCC: `g++ -std=c++17 -O3 -I include tests/BS_thread_pool_test.cpp -o build/BS_thread_pool_test.exe`
+ * Clang: `clang++ -std=c++17 -O3 -I include tests/BS_thread_pool_test.cpp -o build/BS_thread_pool_test.exe`
+ * MSVC: `cl /std:c++17 /permissive- /O2 /EHsc /I include tests/BS_thread_pool_test.cpp /Fo:build/BS_thread_pool_test.obj /Fe:build/BS_thread_pool_test.exe` (in the Visual Studio Developer PowerShell for your CPU architecture)
* Linux/macOS:
- * GCC: `g++ BS_thread_pool_test.cpp -std=c++17 -O3 -pthread -o BS_thread_pool_test`
- * Clang: `clang++ BS_thread_pool_test.cpp -std=c++17 -O3 -pthread -o BS_thread_pool_test`
+ * GCC: `g++ -std=c++17 -O3 -I include tests/BS_thread_pool_test.cpp -o build/BS_thread_pool_test`
+ * Clang: `clang++ -std=c++17 -O3 -I include tests/BS_thread_pool_test.cpp -o build/BS_thread_pool_test`
-If your compiler and codebase support C++20 and/or C++23, it is recommended to enable them in order to allow the library access to the latest features:
+If your compiler and codebase support C++20 and/or C++23, it is recommended to enable them in order to allow the thread pool library access to the latest features:
* For Clang or GCC, use the `-std=c++20` or `-std=c++23` flag.
* For MSVC, use `/std:c++20` for C++20 or `/std:c++latest` for C++23.
@@ -269,15 +270,19 @@ BS::thread_pool pool(12);
Usually, when the thread pool is used, a program's main thread should only submit tasks to the thread pool and wait for them to finish, and should not perform any computationally intensive tasks on its own. If this is the case, it is recommended to use the default value for the number of threads. This ensures that all the threads available in the hardware will be put to work while the main thread waits.
-However, if the main thread also performs computationally intensive tasks, it may be beneficial to use one fewer thread than the hardware concurrency, leaving one hardware thread available for the main thread. Furthermore, if more than one thread pool is used in the program simultaneously, the total number of thread across all pools should not exceed the hardware concurrency.
+However, if the main thread also performs computationally intensive tasks, it may be beneficial to use one fewer thread than the hardware concurrency, leaving one hardware thread available for the main thread. Furthermore, if more than one thread pool is used in the program simultaneously, the total number of threads across all pools should not exceed the hardware concurrency.
+
+Note: If the [native extensions](#native-extensions) are enabled, a pool created with the default constructor will only use the number of threads available to the process, as obtained from [`BS::get_os_process_affinity()`](#setting-process-affinity), which can be less than the number of hardware threads.
### Getting and resetting the number of threads in the pool
-The member function `get_thread_count()` returns the number of threads in the pool. This will be equal to `std::thread::hardware_concurrency()` if the default constructor was used.
+The member function `get_thread_count()` returns the number of threads in the pool. This will be equal to `std::thread::hardware_concurrency()` if the default constructor was used (or to [`BS::get_os_process_affinity()`](#setting-process-affinity) if the [native extensions](#native-extensions) are enabled).
It is generally unnecessary to change the number of threads in the pool after it has been created, since the whole point of a thread pool is that you only create the threads once. However, if needed, this can be done, safely and on-the-fly, using the `reset()` member function.
-`reset()` will wait for all currently running tasks to be completed, but will leave the rest of the tasks in the queue. Then it will destroy the thread pool and create a new one with the desired new number of threads, as specified in the function's argument (or the hardware concurrency if no argument is given). The new thread pool will then resume executing the tasks that remained in the queue and any newly submitted tasks.
+`reset()` will wait for all tasks to be completed, both those that are currently running in the threads and those that are still waiting in the queue. Then it will destroy the thread pool and create a new one with the desired new number of threads, as specified in the function's argument (if no argument is given, it behaves like the default constructor), with an empty task queue.
+
+If pausing is enabled ([see below](#pausing-the-pool)), `reset()` will only wait for tasks that are currently running before destroying the pool; once the pool is reset, it will then resume executing the tasks that remained in the queue and any newly submitted tasks. If the pool was paused before resetting it, the new pool will be paused as well. `reset()` can also be used to change the thread initialization function ([see below](#thread-initialization-functions)).
The member function `get_thread_ids()` returns a vector containing the unique identifiers for each of the pool's threads, as obtained by `std::thread::get_id()`. These values are not so useful on their own, but can be used to identify and distinguish between threads, or for allocating resources.
@@ -313,7 +318,7 @@ int main()
}
```
-In this example we submitted the function `the_answer()`, which returns an `int`. The member function `submit_task()` of the pool therefore returned an `std::future`. We then used used the `get()` member function of the future to get the return value, and printed it out.
+In this example we submitted the function `the_answer()`, which returns an `int`. The member function `submit_task()` of the pool therefore returned an `std::future`. We then used the `get()` member function of the future to get the return value, and printed it out.
In addition to submitting a pre-defined function, we can also use a [lambda expression](https://en.cppreference.com/w/cpp/language/lambda) to quickly define the task on-the-fly. Rewriting the previous example in terms of a lambda expression, we get:
@@ -364,7 +369,7 @@ Here we split the lambda into multiple lines to make it more readable. The comma
### Submitting tasks with arguments and receiving a future
-As stated in the previous section, tasks submitted using `submit_task()` cannot have any arguments. However, it is easy to submit tasks with argument either by wrapping the function in a lambda or using lambda captures directly. The following is an example of submitting a pre-defined function with arguments by wrapping it in a lambda:
+As stated in the previous section, tasks submitted using `submit_task()` cannot have any arguments. However, it is easy to submit tasks with arguments either by wrapping the function in a lambda or using lambda captures directly. The following is an example of submitting a pre-defined function with arguments by wrapping it in a lambda:
```cpp
#include "BS_thread_pool.hpp" // BS::thread_pool
@@ -545,7 +550,7 @@ Sorry, the task is not done yet.
Task done!
```
-For detached tasks, since we do not have futures for them, we cannot use this method. However, `BS::thread_pool` has two member functions, also named `wait_for()` and `wait_until()`, which similarly wait for a specified duration or until a specified time point, but do so for **all** tasks (whether submitted or detached). Instead of an `std::future_status`, the thread pool's wait functions returns `true` if all tasks finished running, or `false` if the duration expired or the time point was reached but some tasks are still running.
+For detached tasks, since we do not have futures for them, we cannot use this method. However, `BS::thread_pool` has two member functions, also named `wait_for()` and `wait_until()`, which similarly wait for a specified duration or until a specified time point, but do so for **all** tasks (whether submitted or detached). Instead of an `std::future_status`, the thread pool's wait functions return `true` if all tasks finished running, or `false` if the duration expired or the time point was reached but some tasks are still running.
Here is the same example as above, using `detach_task()` and `pool.wait_for()`:
@@ -715,7 +720,7 @@ where:
* The loop is over the range `[start, end)`, i.e. inclusive of `start` but exclusive of `end`.
* `loop()` is an operation performed for each loop index `i`, such as modifying an array with `end - start` elements.
-This loop may be automatically parallelized and submitted to the thread pool's queue using the member function `submit_loop()`, which has the follows syntax:
+This loop may be automatically parallelized and submitted to the thread pool's queue using the member function `submit_loop()`, which has the following syntax:
```cpp
pool.submit_loop(start, end, loop, num_blocks);
@@ -1022,6 +1027,44 @@ However, `BS::multi_future` also has additional member functions that are aim
Aside from using `BS::multi_future` to track the execution of parallelized loops, it can also be used, for example, whenever you have several different groups of tasks and you want to track the execution of each group individually.
+### Submitting tasks in bulk without a loop
+
+Sometimes, you may have a large number of tasks to submit to the thread pool, which are not part of a loop or sequence. In such cases, you can use `detach_bulk()` or `submit_bulk()` to submit all the tasks at once. As usual, `detach_bulk()` simply detaches the tasks, while `submit_bulk()` returns a `BS::multi_future`. The two functions can be used in one of two ways:
+
+1. By passing a container of callable objects. They must have no arguments; to submit functions with arguments, enclose them in lambda expressions. In the case of `submit_bulk()`, the callables may have return values, which will be stored in the returned `BS::multi_future`, but they must all return the same type.
+2. By passing an iterator range, similarly to the standard library algorithms. This can be used, for example, to submit only a subset of tasks from a larger container.
+
+The following example demonstrates how to use `submit_bulk()` with a container:
+
+```cpp
+#include "BS_thread_pool.hpp" // BS::multi_future, BS::thread_pool
+#include // std::function
+#include // std::cout
+#include // std::string
+#include // std::vector
+
+int main()
+{
+ BS::thread_pool pool;
+ std::vector> tasks;
+ tasks.emplace_back([]
+ {
+ return "Do something.";
+ });
+ tasks.emplace_back([]
+ {
+ return "Do something else.";
+ });
+ tasks.emplace_back([]
+ {
+ return "Do another thing.";
+ });
+ BS::multi_future results = pool.submit_bulk(tasks);
+ for (const std::string& result : results.get())
+ std::cout << result << '\n';
+}
+```
+
## Utility classes
### Synchronizing printing to a stream with `BS::synced_stream`
@@ -1150,7 +1193,7 @@ int main()
Note that we must wait on the future before the `main()` function ends, as otherwise the log file may be destructed before the tasks finish executing. If we used `detach_sequence()`, which does not return a future, we would have to call `pool.wait()` in the last line.
-In this example we did not create the `BS::synced_stream` as a global object, since we wanted to pass the log file as a stream to the constructor. However, it is also possible to add streams to or remove streams from an existing `BS::synced_stream` object using the member functions `add_stream()` and `remove_stream()`. For example, in the following program, we create a `BS::synced_stream` global object with the default constructor, so that it prints to `std::cout`, but then we change out minds, remove `std::cout` from the list of streams, and add a log file instead:
+In this example we did not create the `BS::synced_stream` as a global object, since we wanted to pass the log file as a stream to the constructor. However, it is also possible to add streams to or remove streams from an existing `BS::synced_stream` object using the member functions `add_stream()` and `remove_stream()`. For example, in the following program, we create a `BS::synced_stream` global object with the default constructor, so that it prints to `std::cout`, but then we change our minds, remove `std::cout` from the list of streams, and add a log file instead:
```cpp
#include "BS_thread_pool.hpp" // BS::synced_stream, BS::thread_pool
@@ -1178,12 +1221,6 @@ It is common practice to create a global `BS::synced_stream` object, so that it
Internally, `BS::synced_stream` keeps the streams in an `std::vector`. The order in which the streams are added is also the order in which they will be printed to. For more precise control, you can use the member function `get_streams()` to get a reference to this vector, and manipulate it directly as you see fit.
-### Synchronizing tasks with `BS::counting_semaphore` and `BS::binary_semaphore`
-
-The thread pool library provides two utility classes, `BS::counting_semaphore` and `BS::binary_semaphore`, which offer versatile synchronization primitives that can be used to synchronize tasks in a variety of ways. These classes are equivalent to the C++20 `std::counting_semaphore` and `std::binary_semaphore`, respectively, but are offered in the library as convenience polyfills for projects based on C++17. If C++20 features are available, the polyfills are not used, and instead are just aliases for the standard library classes.
-
-Since `BS::counting_semaphore` and `BS::binary_semaphore` are identical in functionality to their standard library counterparts, we will not explain how to use them here. Instead, the user is referred to [cppreference.com](https://en.cppreference.com/w/cpp/thread/counting_semaphore).
-
## Managing tasks
### Monitoring the tasks
@@ -1285,7 +1322,7 @@ int main()
}
```
-The program submit 8 tasks to the queue. Each task waits 100 milliseconds and then prints a message. The thread pool has 4 threads, so it will execute the first 4 tasks in parallel, and then the remaining 4. We wait 50 milliseconds, to ensure that the first 4 tasks have all started running. Then we call `purge()` to purge the remaining 4 tasks. As a result, these tasks never get executed. However, since the first 4 tasks are still running when `purge()` is called, they will finish uninterrupted; `purge()` only discards tasks that have not yet started running. The output of the program therefore only contains the messages from the first 4 tasks:
+The program submits 8 tasks to the queue. Each task waits 100 milliseconds and then prints a message. The thread pool has 4 threads, so it will execute the first 4 tasks in parallel, and then the remaining 4. We wait 50 milliseconds, to ensure that the first 4 tasks have all started running. Then we call `purge()` to purge the remaining 4 tasks. As a result, these tasks never get executed. However, since the first 4 tasks are still running when `purge()` is called, they will finish uninterrupted; `purge()` only discards tasks that have not yet started running. The output of the program therefore only contains the messages from the first 4 tasks:
```none
Task 0 done.
@@ -1591,7 +1628,7 @@ In this example, we create a `thread_local` Mersenne twister engine, meaning tha
Note that the lambda function we passed to `submit_sequence()` has the signature `[](int)`, with an unnamed `int` argument, as it does not make use of the sequence index, which will be a number in the range `[0, 4)`. This is an easy way to simply submit the same task multiple times.
-**Warning:** Exceptions thrown by thread initialization functions must not throw any exceptions, as that will result in program termination. Any exceptions must be handled explicitly within the function.
+**Warning:** Thread initialization functions must not throw any exceptions, as that will result in program termination. Any exceptions must be handled explicitly within the function.
### Thread cleanup functions
@@ -1635,7 +1672,7 @@ In this example, we create 4 threads, each of which has a separate thread-local
We submit 40 tasks to the queue using `submit_sequence()`, each of which prints a message to the log file indicating which thread it is running on. When the `main()` function exits and `pool` is destroyed, the cleanup function is called for each thread, ensuring that the log files are closed properly.
-**Warning:** As with initialization functions, exceptions thrown by thread cleanup functions must not throw any exceptions, as that will result in program termination. Any exceptions must be handled explicitly within the function.
+**Warning:** As with initialization functions, thread cleanup functions must not throw any exceptions, as that will result in program termination. Any exceptions must be handled explicitly within the function.
### Passing task arguments by constant reference
@@ -1686,7 +1723,7 @@ Generally, it is not really necessary to pass arguments by constant reference, b
### Enabling features
-The thread pool has some optional features, which are disabled by default to minimize overhead. They can be enabled by passing the appropriate template parameter to the `BS::thread_pool` class when creating the pool. The template parameter is a bitmask, so you can enable several features at once by combining them with the bitwise OR operator `|`. The bitmask flags are members of the `BS::tp` enumeration:
+The thread pool has some optional features, which are disabled by default to minimize overhead. They can be enabled by passing the appropriate template parameter to the `BS::thread_pool` class when creating the pool. The template parameter is a bitmask, so you can enable several features at once by combining them with the bitwise OR operator `|`. The bitmask flags are members of the `BS::tp` enumeration class:
* `BS::tp::priority` enables [task priority](#setting-task-priority).
* `BS::tp::pause` enables [pausing the pool](#pausing-the-pool).
@@ -1714,7 +1751,7 @@ Note that, since optional features are enabled separately for each `BS::thread_p
Turning on the `BS::tp::priority` flag in the template parameter to `BS::thread_pool` enables task priority. In addition, the library defines the convenience alias `BS::priority_thread_pool`, which is equivalent to `BS::thread_pool`. When this feature is enabled, the static member `priority_enabled` will be set to `true`.
-The priority of a task or group of tasks may then be specified as an additional argument (at the end of the argument list) to `detach_task()`, `submit_task()`, `detach_blocks()`, `submit_blocks()`, `detach_loop()`, `submit_loop()`, `detach_sequence()`, and `submit_sequence()`. If the priority is not specified, the default value will be 0.
+The priority of a task or group of tasks may then be specified as an additional argument (at the end of the argument list) to `detach_task()`, `submit_task()`, `detach_blocks()`, `submit_blocks()`, `detach_loop()`, `submit_loop()`, `detach_sequence()`, `submit_sequence()`, `detach_bulk()`, and `submit_bulk()`. If the priority is not specified, the default value will be 0.
The priority is a number of type `BS::priority_t`, which is a signed 8-bit integer, so it can have any value between -128 and +127. The tasks will be executed in priority order from highest to lowest. If priority is assigned to the block/loop/sequence parallelization functions, which submit multiple tasks, then all of these tasks will have the same priority.
@@ -1777,7 +1814,7 @@ Lastly, please note that when using the priority queue, tasks will not necessari
Turning on the `BS::tp::pause` flag in the template parameter to `BS::thread_pool` enables pausing the pool. In addition, the library defines the convenience alias `BS::pause_thread_pool`, which is equivalent to `BS::thread_pool`. When this feature is enabled, the static member `pause_enabled` will be set to `true`.
-This feature enables the member functions `pause()`, `unpause()`, and `is_paused()`. When you call `pause()`, the workers will temporarily stop retrieving new tasks out of the queue. However, any tasks already executed will keep running until they are done, since the thread pool has no control over the internal code of your tasks. If you need to pause a task in the middle of its execution, you must do that manually by programming your own pause mechanism into the task itself. To resume retrieving tasks, call `unpause()`. To check whether the pool is currently paused, call `is_paused()`.
+This feature enables the member functions `pause()`, `unpause()`, and `is_paused()`. When you call `pause()`, the workers will temporarily stop retrieving new tasks out of the queue. However, any tasks already executing will keep running until they are done, since the thread pool has no control over the internal code of your tasks. If you need to pause a task in the middle of its execution, you must do that manually by programming your own pause mechanism into the task itself. To resume retrieving tasks, call `unpause()`. To check whether the pool is currently paused, call `is_paused()`.
Here is an example:
@@ -2000,7 +2037,7 @@ Wait deadlock checks are disabled by default because wait deadlocks are not some
### Enabling the native extensions
-While portability is one of the guiding principle for developing this library, non-portable features such as setting the thread priority using the operating system's native API can be very useful. Therefore, the library includes native extensions - which are disabled by default, as they are not portable.
+While portability is one of the guiding principle for developing this library, non-portable features such as setting the thread priority using the operating system's native API can be very useful. Therefore, the library includes native extensions - which are disabled by default, as they are not portable. (Note that as long as the native extensions are disabled, the library is 100% standard C++.)
The native extensions may be enabled by defining the macro `BS_THREAD_POOL_NATIVE_EXTENSIONS` at compilation time. If including the library as a header file, the macro must be defined before `#include "BS_thread_pool.hpp"`. Note that even if the macro is defined, the native extensions are disabled automatically if a supported operating system (Windows, Linux, or macOS) is not detected.
@@ -2010,7 +2047,7 @@ If importing the library [as a C++20 module](#importing-the-library-as
The `constexpr` flag `BS::thread_pool_native_extensions` indicates whether the thread pool library was compiled with native extensions enabled. Note that the flag will be `false` if `BS_THREAD_POOL_NATIVE_EXTENSIONS` is defined but the operating system is unsupported.
-**Warning:** Please note that, as of v5.0.0 of the thread pool library, the native extensions have only been tested on **Windows 11 23H2, Ubuntu 24.10, and macOS 15.1**. They have not been tested on older versions of these operating systems, other Linux distributions, or any other operating systems, and are therefore not guaranteed to work on every system. If you encounter any issues, please report them on [the GitHub repository](https://github.com/bshoshany/thread-pool).
+**Warning:** Please note that the native extensions have only been tested on the operating systems listed above under [compiling and compatibility](#compiling-and-compatibility). They have not been tested on older versions of these operating systems, other Linux distributions, or any other operating systems, and are therefore not guaranteed to work on every system. If you encounter any issues, please report them on [the GitHub repository](https://github.com/bshoshany/thread-pool).
### Setting thread priority
@@ -2085,12 +2122,12 @@ The thread pool's native extensions allow the user to set a thread's processor a
This can be useful for performance optimization, as it can reduce cache misses. However, it can also degrade performance, sometimes severely, since the thread will not run at all until its assigned cores are available. Therefore, it is usually better to let the operating system's scheduler manage thread affinities on its own, except in very specific cases.
-Please note that setting thread affinity works on Windows and Linux, but not on macOS, as the native API does not allow it. As affinity is handled differently on different operating systems, the thread pool library provides an abstraction layer over the native APIs. In this abstraction layer, affinity is controlled using an `std::vector` where each element corresponds to a logical processor.
+Please note that setting thread affinity works on Windows and Linux, but not on macOS and Android, as the native API does not allow it. As affinity is handled differently on different operating systems, the thread pool library provides an abstraction layer over the native APIs. In this abstraction layer, affinity is controlled using an `std::vector` where each element corresponds to a logical processor.
Thread affinity is managed using two static member functions of the `BS::this_thread` class:
-* `BS::this_thread::get_os_thread_affinity()` gets the current thread's affinity. It returns an object of type `std::optional>`. If the returned object does not contain a value, then the affinity could not be determined. On macOS, this function always returns `std::nullopt`.
-* `BS::this_thread::set_os_thread_affinity()` sets the current thread's affinity. It returns `true` if the affinity was set successfully, or `false` otherwise. On macOS, this function always returns `false`.
+* `BS::this_thread::get_os_thread_affinity()` gets the current thread's affinity. It returns an object of type `std::optional>`. If the returned object does not contain a value, then the affinity could not be determined. On macOS and Android, this function always returns `std::nullopt`.
+* `BS::this_thread::set_os_thread_affinity()` sets the current thread's affinity. It returns `true` if the affinity was set successfully, or `false` otherwise. On macOS and Android, this function always returns `false`.
Note that the thread affinity must be a subset of the process affinity (as obtained using [`BS::get_os_process_affinity()`](#setting-process-affinity)) for the containing process of a thread.
@@ -2258,8 +2295,51 @@ The thread pool's native extensions also allow the user to set the entire proces
Process affinity is managed using two functions:
-* `BS::this_thread::get_os_process_affinity()` gets the process's affinity. It returns an object of type `std::optional>`. If the returned object does not contain a value, then the affinity could not be determined. On macOS, this function always returns `std::nullopt`.
-* `BS::this_thread::set_os_process_affinity()` sets the process's affinity. It returns `true` if the affinity was set successfully, or `false` otherwise. On macOS, this function always returns `false`.
+* `BS::get_os_process_affinity()` gets the process's affinity. It returns an object of type `std::optional>`. If the returned object does not contain a value, then the affinity could not be determined. On macOS, this function always returns `std::nullopt`.
+* `BS::set_os_process_affinity()` sets the process's affinity. It returns `true` if the affinity was set successfully, or `false` otherwise. On macOS, this function always returns `false`.
+
+Note that by counting the number of elements set to `true` in `BS::get_os_process_affinity()`, you can determine how many logical processors are available to the process. If the native extensions are enabled, a pool created with the default constructor will use this method to determine the number of threads available to the process, which can be less than the number of hardware threads, and use this as the default number of pool threads. This is demonstrated by the following program:
+
+```cpp
+#define BS_THREAD_POOL_NATIVE_EXTENSIONS
+#include "BS_thread_pool.hpp" // BS::get_os_process_affinity(), BS::set_os_process_affinity, BS::synced_stream, BS::thread_pool
+#include // std::count
+#include // std::optional
+#include // std::thread
+#include // std::vector
+
+BS::synced_stream sync_out;
+
+int main()
+{
+ sync_out.println("Total hardware threads: ", std::thread::hardware_concurrency());
+ BS::thread_pool pool1;
+ sync_out.println("Threads in first pool: ", pool1.get_thread_count());
+
+ const bool success = BS::set_os_process_affinity({true, true, true});
+ if (success)
+ {
+ const std::optional> affinity = BS::get_os_process_affinity();
+ if (affinity)
+ {
+ sync_out.println("Total threads now available to the process: ", std::count(affinity->begin(), affinity->end(), true));
+ BS::thread_pool pool2;
+ sync_out.println("Threads in second pool: ", pool2.get_thread_count());
+ return 0;
+ }
+ }
+ sync_out.println("ERROR: Failed to set or get process affinity.");
+}
+```
+
+Assuming that the program was executed without setting the affinity of the process beforehand (e.g. using `taskset` on Linux), `pool1` will be created with the total number of hardware threads. However, we then manually set the affinity of the process so that only the first 3 logical processors are enabled (by passing a vector with 3 `true` elements and all other elements `false`). Therefore, `pool2` will be created with only 3 threads. If, for example, 32 hardware threads are available in total, the output will be:
+
+```none
+Total hardware threads: 32
+Threads in first pool: 32
+Total threads now available to the process: 3
+Threads in second pool: 3
+```
### Accessing native thread handles
@@ -2308,24 +2388,26 @@ The test program also takes the following command line arguments:
* `log`: Print to a log file. It will have the same name as the executable, with a suffix `-yyyy-mm-dd_hh.mm.ss.log` based on the current date and time.
* `tests`: Perform standard tests.
* `deadlock`: Perform long deadlock tests.
-* `benchmarks`: Perform full Mandelbrot plot benchmarks.
-* `plot`: Perform quick Mandelbrot plot benchmarks.
-* `save`: Save the Mandelbrot plot to a file.
+* `benchmarks`: Perform full Mandelbrot set benchmarks.
+* `plot`: Perform quick Mandelbrot set benchmarks.
+* `save`: Save the Mandelbrot set image to a file.
-If no options are entered, the default is `benchmarks log stdout tests`. If the file `default_args.txt` exists in the same folder, the test program reads the default arguments from it (space separated in a single line). Command line arguments can still override these defaults. This is useful when debugging.
+If no options are entered, the default is `benchmarks log stdout tests`. If the file `default_args.txt` exists in the same folder or the parent folder, the test program reads the default arguments from it (space separated in a single line). Command line arguments can still override these defaults. This is useful when debugging.
The following macros can be defined during compilation (using the `-D` flag in Clang and GCC or `/D` in MSVC) to enable additional features:
* `BS_THREAD_POOL_TEST_IMPORT_MODULE`: Import the thread pool library [as a C++20 module](#importing-the-library-as-a-c20-module). Note that the module must be compiled beforehand, as explained in the relevant section.
* `BS_THREAD_POOL_NATIVE_EXTENSIONS`: Test the [native extensions](#native-extensions). If importing the library as a C++20 module, ensure that the library was compiled with the same macro.
-A Python script, `test_all.py`, is provided for convenience in the `scripts` folder. This script makes use of the bundled [`compile_cpp.py` script](#the-compile_cpppy-script), and requires Python 3.12 or later. The script will automatically detect if Clang, GCC, and/or MSVC are available, and compile and run the test program using each available compiler 3 times:
+The bundled [`compile_cpp.py` script](#the-compile_cpppy-script), if run with `python scripts/compile_cpp.py tests/BS_thread_pool_test.cpp --run --try-all --type=release --verbose`, will automatically detect if Clang, GCC, and/or MSVC are available, and compile and run the test program using each available compiler 3 times:
1. With C++17 support.
2. With C++20 support, using `import BS.thread_pool`.
-3. With C++23 support, using `import BS.thread_pool`, and using `import std` on supported compilers.
+3. With C++23 support, using `import BS.thread_pool`, and using `import std`.
-If any of the tests fail, please [submit a bug report](https://github.com/bshoshany/thread-pool/issues) including the exact specifications of your system (OS, CPU, compiler, etc.) and the generated log file. However, please note that only the latest versions of each compiler are supported.
+If any of the tests fail, please [submit a bug report](https://github.com/bshoshany/thread-pool/issues) including the exact specifications of your system (OS, CPU, compiler, etc.) and the generated log file. However, please note that **only the latest versions of each compiler are supported**.
+
+By default, the test program prints colored output using ANSI escape codes for better readability. This can be disabled by setting the `NO_COLOR` environment variable.
### Performance tests
@@ -2335,7 +2417,9 @@ These benchmarks are heavily CPU-intensive, which results in a high speedup fact
The full benchmarks are enabled using the command line argument `benchmarks`, which is enabled by default. The command line argument `plot` can be used to just plot the Mandelbrot set once, either instead of or in addition to doing the full benchmarks. This will plot the largest possible image that can be plotted in 5 seconds, and only measure the performance in pixels/ms for the entire plot.
-If you want to see the actual plot, pass the `save` command line argument. The plot is saved to a BMP file, to avoid having to depend on 3rd-party libraries. This is off by default, since that file can get quite large.
+The test program prints out the Mandelbrot set it generates, downsampled to fit in a terminal window (at 120 character width). This will be in 24-bit color in the terminal, and in monochrome using Unicode blocks in the log file. If the `NO_COLOR` environment variable is set, the terminal output will also be in monochrome. (Note: On Windows Terminal, ensure that `adjustIndistinguishableColors` is disabled in the settings, otherwise the plot will not be displayed correctly.)
+
+If you want to see the plot in full resolution, pass the `save` command line argument, and the plot will be saved to `BS_thread_pool_benchmark_mandelbrot.bmp` (it's a BMP file to avoid having to depend on 3rd-party libraries). This is off by default, since that file can get quite large.
The program determines the optimal resolution of the Mandelbrot plot by testing how many pixels are needed to reach a certain target duration when parallelizing the loop using a number of tasks equal to the number of threads. This ensures that the benchmarks take approximately the same amount of time (per thread) on all systems, and are thus more consistent and portable.
@@ -2348,40 +2432,40 @@ If the [native extensions](#native-extensions) are enabled, the program will try
As an example, here are the results of the benchmarks running on a 24-core (8P+16E) / 32-thread Intel i9-13900K CPU. The tests were compiled using MSVC in C++23 mode, to obtain maximum performance using the latest C++23 features. Compiler optimizations were enabled using the `/O2` flag. The benchmarks were run 5 times, and the result with the median speedup was as follows:
```none
-Generating a 3965x3965 plot of the Mandelbrot set...
+Generating a 3927x3927 plot of the Mandelbrot set...
Each test will be repeated 30 times to collect reliable statistics.
1 task: [..............................] (single-threaded)
--> Mean: 510.5 ms, standard deviation: 0.5 ms, speed: 1026.5 pixels/ms.
+-> Mean: 500.8 ms, standard deviation: 1.3 ms, speed: 1026.5 pixels/ms.
8 tasks: [..............................]
--> Mean: 149.1 ms, standard deviation: 0.6 ms, speed: 3514.7 pixels/ms.
+-> Mean: 146.0 ms, standard deviation: 0.3 ms, speed: 3520.9 pixels/ms.
16 tasks: [..............................]
--> Mean: 85.4 ms, standard deviation: 2.5 ms, speed: 6133.9 pixels/ms.
+-> Mean: 82.2 ms, standard deviation: 1.5 ms, speed: 6256.1 pixels/ms.
32 tasks: [..............................]
--> Mean: 48.3 ms, standard deviation: 1.8 ms, speed: 10849.7 pixels/ms.
+-> Mean: 49.8 ms, standard deviation: 1.2 ms, speed: 10322.2 pixels/ms.
64 tasks: [..............................]
--> Mean: 29.1 ms, standard deviation: 1.0 ms, speed: 17987.7 pixels/ms.
+-> Mean: 26.9 ms, standard deviation: 1.2 ms, speed: 19109.5 pixels/ms.
128 tasks: [..............................]
--> Mean: 23.6 ms, standard deviation: 0.7 ms, speed: 22173.8 pixels/ms.
+-> Mean: 22.8 ms, standard deviation: 0.9 ms, speed: 22545.8 pixels/ms.
256 tasks: [..............................]
--> Mean: 22.5 ms, standard deviation: 0.6 ms, speed: 23325.3 pixels/ms.
+-> Mean: 21.4 ms, standard deviation: 0.5 ms, speed: 24058.2 pixels/ms.
512 tasks: [..............................]
--> Mean: 21.8 ms, standard deviation: 0.5 ms, speed: 24075.4 pixels/ms.
+-> Mean: 20.7 ms, standard deviation: 0.6 ms, speed: 24833.1 pixels/ms.
1024 tasks: [..............................]
--> Mean: 21.9 ms, standard deviation: 0.7 ms, speed: 23892.4 pixels/ms.
-Maximum speedup obtained by multithreading vs. single-threading: 23.5x, using 512 tasks.
+-> Mean: 21.0 ms, standard deviation: 0.4 ms, speed: 24478.3 pixels/ms.
+Maximum speedup obtained by multithreading vs. single-threading: 24.2x, using 512 tasks.
```
This CPU has 24 cores, of which 8 are fast (5.40 GHz max) performance cores with hyperthreading (thus providing 16 threads in total), and 16 are slower (4.30 GHz max) efficiency cores without hyperthreading, for a total of 32 threads.
Due to the hybrid architecture, it is not trivial to calculate the theoretical maximum speedup. However, we can get a rough estimate by noticing that the E-cores are about 20% slower than the P-cores, and that hyperthreading is generally known to provide around a 30% speedup. Thus, the estimated theoretical speedup (compared to a single P-core) is 8 × 1.3 + 16 × 0.8 = 23.2x.
-The actual median speedup obtained, 23.5x, is slightly above this estimate, which indicates that the thread pool provides optimal performance and allows the Mandelbrot plot algorithm to take full advantage of the CPU's capabilities.
+The actual median speedup obtained, 24.2x, is 4.3% above this estimate, which indicates that the thread pool provides optimal performance and allows the Mandelbrot plot algorithm to take full advantage of the CPU's capabilities.
It should also be noted that even though the available number of hardware threads is 32, the maximum possible speedup is achieved not with 32 tasks, but with 512 tasks - half the square of the number of hardware threads. The reason for this is that splitting the job into more tasks than threads eliminates thread idle time, as explained [above](#optimizing-the-number-of-blocks). However, at 1024 tasks we encounter diminishing returns, as the overhead of submitting the tasks to the pool starts to outweigh the benefits of parallelization.
### Finding the version of the library
-Starting with v5.0.0, the thread pool library defines the `constexpr` object `BS::thread_pool_version`, which can be used to check the version of the library at compilation time. This object is of type `BS::version`, with members `major`, `minor`, and `patch`, and all comparison operators defined as `constexpr`. It also has a `to_string()` member function and an `operator<<` overload for easy printing at runtime.
+Starting with v5.0.0, the thread pool library defines the `constexpr` object `BS::thread_pool_version`, which can be used to check the version of the library at compilation time. This object is of type `BS::version`, with members `major`, `minor`, and `patch`, and all comparison operators defined as `constexpr`. It also has a `to_string()` member function and an `operator<<` overload for easy printing at runtime (used by the [test program](#testing-the-library)).
Since `BS::thread_pool_version` is a `constexpr` object, it can be used in any context where a `constexpr` object is allowed, such as `static_assert()` and `if constexpr`. For example, the following program will fail to compile if the version is not 5.1.0 or higher:
@@ -2418,9 +2502,7 @@ int main()
}
```
-Currently, both the examples above are of pedagogical value only, because `BS::thread_pool_version` was only introduced in v5.0.0, and that is also the latest version at the time of writing, so there are no other versions to compare to. However, once future versions of the library are released, this object will be the preferred way to do version checking.
-
-For backwards compatibility, if you are not sure if you are going to get v4 or v5 of the library, you can check the version using the following preprocessor macros, which were introduced in v4.0.1:
+`BS::thread_pool_version` was introduced in v5.0.0, and it is the preferred way to do version checking. However, for backwards compatibility, if you are not sure if you are going to get v4 or v5 of the library, you can check the version using the following preprocessor macros, which were introduced in v4.0.1:
* `BS_THREAD_POOL_VERSION_MAJOR` - indicates the major version.
* `BS_THREAD_POOL_VERSION_MINOR` - indicates the minor version.
@@ -2495,7 +2577,7 @@ Below we will provide the commands for compiling the library as a module and the
│ └── BS_thread_pool.hpp <- the header file
├── modules
│ └── BS.thread_pool.cppm <- the module file
-├── tasks
+├── scripts
│ └── compile_cpp.py <- the compile script (optional)
└── tests
└── BS_thread_pool_test.cpp <- the test program
@@ -2519,11 +2601,11 @@ Since we used `-t=release`, optimization flags will be added automatically. If y
Thread pool library imported using: import BS.thread_pool (C++20 modules).
```
-For further customization, it is recommend to create a `compile_cpp.yaml` file as explained [below](#the-compile_cpppy-script).
+For further customization, it is recommended to create a `compile_cpp.yaml` file as explained [below](#the-compile_cpppy-script).
### Compiling with Clang using `import BS.thread_pool`
-Note: The following instructions have only been tested using Clang v19.1.6, the latest version at the time of writing, and may not work with older versions of the compiler.
+Note: The following instructions have only been tested using Clang v21.1.8, the latest version at the time of writing, and may not work with older versions of the compiler.
To compile the module file `BS.thread_pool.cppm` with Clang, first create the `build` folder using `mkdir build`, and then run the following command in the root folder of the repository:
@@ -2563,16 +2645,18 @@ Thread pool library imported using: import BS.thread_pool (C++20 modules).
Of course, you should add warning, debugging, optimization, and other compiler flags to the commands above as needed. For more information about using C++20 modules with Clang, please see [the official documentation](https://clang.llvm.org/docs/StandardCPlusPlusModules.html).
-**Note:** On macOS, Apple Clang v16.0.0 (the latest version at the time of writing) does not support C++20 modules. Please either install the latest version of LLVM Clang using [Homebrew](https://formulae.brew.sh/formula/llvm), or include the library as a header file.
+**Note:** At the time of writing, there is a bug in Clang with libc++ where using `std::jthread` in a C++20 module causes a compilation error. As a workaround, until the bug is fixed, the thread pool library automatically falls back to `std::thread` if it detects that Clang and libc++ are being used together with C++20 modules. This workaround can be disabled by defining `BS_THREAD_POOL_DISABLE_WORKAROUNDS` when compiling the module.
+
+**Note:** On macOS, Apple Clang does not support C++20 modules. Please either install the latest version of LLVM Clang using [Homebrew](https://formulae.brew.sh/formula/llvm), or include the library as a header file.
### Compiling with GCC using `import BS.thread_pool`
-Note: The following instructions have only been tested using GCC v14.2.0, the latest version at the time of writing, and may not work with older versions of the compiler.
+Note: The following instructions have only been tested using GCC v15.2.0, the latest version at the time of writing, and may not work with older versions of the compiler.
To compile the module file `BS.thread_pool.cppm` with GCC, first create the `build` folder using `mkdir build`, and then run the following command in the root folder of the repository:
```bash
-g++ -x c++ modules/BS.thread_pool.cppm -c "-fmodule-mapper=|@g++-mapper-server -r build" -fmodule-only -fmodules-ts -std=c++20 -I include
+g++ -x c++ modules/BS.thread_pool.cppm -c "-fmodule-mapper=|@g++-mapper-server -r build" -fmodule-only -fmodules -std=c++20 -I include
```
Here is a breakdown of the compiler arguments:
@@ -2582,7 +2666,7 @@ Here is a breakdown of the compiler arguments:
* `-c`: Do not run the linker, only compile the module.
* `"-fmodule-mapper=|@g++-mapper-server -r build"`: Specify to the module mapper that the compiled module should be placed in the `build` folder. This will create a file `build/BS.thread_pool.gcm`. The extension `.gcm` is used by GCC for compiled modules.
* `-fmodule-only`: Do not create an object file for the module.
-* `-fmodules-ts`: Enable C++20 modules.
+* `-fmodules`: Enable C++20 modules.
* `-std=c++20`: Use the C++20 standard. For C++23, use `-std=c++23`.
* `-I include`: Add the `include` folder to the include path, so that the module can find the header file `BS_thread_pool.hpp`.
@@ -2591,14 +2675,14 @@ Note that to enable the [native extensions](#native-extensions), you should add
Once the module is compiled, you can compile the test program as follows:
```bash
-g++ tests/BS_thread_pool_test.cpp "-fmodule-mapper=|@g++-mapper-server -r build" -fmodules-ts -std=c++20 -o build/BS_thread_pool_test -D BS_THREAD_POOL_TEST_IMPORT_MODULE
+g++ tests/BS_thread_pool_test.cpp "-fmodule-mapper=|@g++-mapper-server -r build" -fmodules -std=c++20 -o build/BS_thread_pool_test -D BS_THREAD_POOL_TEST_IMPORT_MODULE
```
Here is a breakdown of the compiler arguments:
* `tests/BS_thread_pool_test.cpp`: The program to compile.
* `"-fmodule-mapper=|@g++-mapper-server -r build"`: Specify to the module mapper that the compiled module can be found in the `build` folder. It will look for the file `build/BS.thread_pool.gcm`.
-* `-fmodules-ts`, `-std=c++20`: Same as above.
+* `-fmodules`, `-std=c++20`: Same as above.
* `-o build/BS_thread_pool_test`: Output the compiled program to `build/BS_thread_pool_test` (or `build/BS_thread_pool_test.exe` on Windows).
* `-D BS_THREAD_POOL_TEST_IMPORT_MODULE`: Define the macro `BS_THREAD_POOL_TEST_IMPORT_MODULE`, which is used to indicate to the test program that it needs to import the library as a module instead of including the header file. **Note that this macro is only used by the test program; it is not needed when you compile your own programs.**
@@ -2610,21 +2694,19 @@ Thread pool library imported using: import BS.thread_pool (C++20 modules).
Of course, you should add warning, debugging, optimization, and other compiler flags to the commands above as needed. For more information about using C++20 modules with GCC, please see [the official documentation](https://gcc.gnu.org/onlinedocs/gcc/C_002b_002b-Modules.html).
-**Note:** GCC v14.2.0 (latest version at the time of writing) appears to have an internal compiler error when compiling programs containing modules (or at least, this particular module) with any optimization flags other than `-Og` enabled. Until this is fixed, if you wish to use compiler optimizations, please either include the library as a header file or use a different compiler.
-
### Compiling with MSVC using `import BS.thread_pool`
-Note: The following instructions have only been tested using MSVC v19.42.34435, the latest version at the time of writing, and may not work with older versions of the compiler.
+Note: The following instructions have only been tested using MSVC v19.50.35721, the latest version at the time of writing, and may not work with older versions of the compiler.
-To compile the module file `BS.thread_pool.cppm` with MSVC, first open the Visual Studio Developer PowerShell for the appropriate CPU architecture. For example, for x64, execute the following command in PowerShell:
+To compile the module file `BS.thread_pool.cppm` with MSVC, first open the Visual Studio Developer PowerShell for the appropriate CPU architecture. For example, on Visual Studio 2026, for x64 architecture, execute the following command in PowerShell in the root folder of the repository:
```pwsh
-& 'C:\Program Files\Microsoft Visual Studio\2022\Community\Common7\Tools\Launch-VsDevShell.ps1' -Arch amd64 -HostArch amd64
+& 'C:\Program Files\Microsoft Visual Studio\18\Community\Common7\Tools\Launch-VsDevShell.ps1' -Arch amd64 -HostArch amd64 -SkipAutomaticLocation
```
-For ARM64, replace `amd64` with `arm64`. (Do not use the "Developer PowerShell for VS 2022" Start Menu shortcut, as it may not use the correct CPU architecture by default.)
+For ARM64, replace `amd64` with `arm64`. (Do not use the "Developer PowerShell for VS" Start Menu shortcut, as it may not use the correct CPU architecture by default.)
-Navigate to the repository folder, create the `build` folder using `mkdir build`, and then run the following command in the root folder of the repository:
+Create the `build` folder using `mkdir build`, and then run the following command in the root folder of the repository:
```pwsh
cl modules/BS.thread_pool.cppm /c /EHsc /interface /nologo /permissive- /std:c++20 /TP /Zc:__cplusplus /I include /ifcOutput build/BS.thread_pool.ifc /Fo:build/BS.thread_pool.obj
@@ -2673,12 +2755,12 @@ Of course, you should add warning, debugging, optimization, and other compiler f
### Compiling with CMake using `import BS.thread_pool`
-Note: The following instructions have only been tested using CMake v3.31.2, the latest version at the time of writing, and may not work with older versions. Also, modules are currently only supported by CMake with the [`Ninja`](https://ninja-build.org/) and `Visual Studio 17 2022` generators.
+Note: The following instructions have only been tested using CMake v4.2.1, the latest version at the time of writing, and may not work with older versions. Also, modules are currently not supported by CMake with all generators; please see the CMake documentation for more information.
If you are using [CMake](https://cmake.org/), you can use `target_sources()` with `CXX_MODULES` to include the module file `BS.thread_pool.cppm`. CMake will then automatically compile the module and link it to your program. Here is an example of a `CMakeLists.txt` file that can be used to build the test program and import the thread pool library as a module:
```cmake
-cmake_minimum_required(VERSION 3.31)
+cmake_minimum_required(VERSION 4.2.1)
project(BS_thread_pool_test LANGUAGES CXX)
set(CMAKE_CXX_STANDARD 20)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
@@ -2727,10 +2809,9 @@ If C++23 features are available, the thread pool library can import th
At the time of writing, importing the C++ Standard Library as a module is only officially supported by the following combinations of compilers and standard libraries:
-* Recent versions of MSVC with Microsoft STL.
* Recent versions of LLVM Clang (**not** Apple Clang) with LLVM libc++.
-
-It is not supported by GCC with any standard library, Clang with any standard library other than libc++, any compiler with GNU libstdc++, or any other compiler or standard library.
+* Recent versions of GCC with libstdc++.
+* Recent versions of MSVC with Microsoft STL.
If `BS_THREAD_POOL_IMPORT_STD` is defined, then you must also import the thread pool library itself as a module. If the library is included as a header file, this will force the program that included the header file to also import `std`, which is not desirable and can lead to compilation errors if the program `#include`s any Standard Library header files.
@@ -2738,7 +2819,7 @@ Defining the macro before importing the module will not work, as modules cannot
[The test program](#testing-the-library) will also import the `std` module if the macro `BS_THREAD_POOL_IMPORT_STD` is defined at compilation time. In that case, you should also enable the macro `BS_THREAD_POOL_TEST_IMPORT_MODULE` to import the thread pool library as a module.
-The `constexpr` flag `BS::thread_pool_import_std` indicates whether the thread pool library was compiled with `import std`. Note that the flag will be `false` if `BS_THREAD_POOL_IMPORT_STD` is defined but the compiler or standard library does not support importing the C++ Standard Library as a module.
+The `constexpr` flag `BS::thread_pool_import_std` indicates whether the thread pool library was compiled with `import std`. Note that the flag will be `false` if `BS_THREAD_POOL_IMPORT_STD` is defined but C++23 support is not enabled in the compiler.
At the time of writing, importing the `std` module requires compiling it first. As explained in the [previous section](#importing-the-library-as-a-c20-module), using the bundled `compile_cpp.py` script is the easiest way to do this, as we show in the [next section](#compiling-with-compile_cpppy-using-import-std). However, for those who wish to compile manually, in the following sections we will explain how to do it with both Clang and MSVC, as well as with CMake. It is assumed that the reader has already read the section about importing the `BS.thread_pool` library as a module, so we omit some details here.
@@ -2764,17 +2845,17 @@ C++ Standard Library imported using:
* Test program: import std (C++23 std module).
```
-For further customization, it is recommend to create a `compile_cpp.yaml` file as explained [below](#the-compile_cpppy-script).
+For further customization, it is recommended to create a `compile_cpp.yaml` file as explained [below](#the-compile_cpppy-script).
### Compiling with Clang and LLVM libc++ using `import std`
-Note: The following instructions have only been tested using Clang v19.1.6 and LLVM libc++ v19.1.6, the latest versions at the time of writing, and may not work with older versions.
+Note: The following instructions have only been tested using Clang v21.1.8 and LLVM libc++ v21.1.8, the latest versions at the time of writing, and may not work with older versions.
Before compiling the `std` module, you must find the file `std.cppm`:
-* On Windows, libc++ is most likely installed via [MSYS2](https://www.msys2.org/), so the `std` module should be at `C:\msys64\clang64\share\libc++\v1\std.cppm`. If you did not install MSYS2 in `C:\msys64`, replace that with the correct path. If you installed libc++ without MSYS2, locate `std.cppm` manually in the installation folder.
-* On Linux, the `std` module should be at `/usr/lib/llvm-/share/libc++/v1/std.cppm`. Replace `` with the major version number of libc++, e.g. `19`. If you installed libc++ in a different folder, locate `std.cppm` manually in that folder.
-* On macOS, the `std` module should be at `/usr/local/Cellar/llvm//share/libc++/v1/std.cppm`. Replace `` with the full version number of libc++, e.g. `19.1.6`. If you installed libc++ in a different folder, locate `std.cppm` manually in that folder.
+* On Windows, libc++ is most likely installed via [MSYS2](https://www.msys2.org/), so the `std` module should be at `C:\msys64\clang64\share\libc++\v1\std.cppm`. If you did not install MSYS2 in `C:\msys64`, replace that with the correct path. If you installed libc++ without MSYS2, locate `std.cppm` manually in the installation folder.
+* On Linux, the `std` module should be at `/usr/lib/llvm-/share/libc++/v1/std.cppm`. Replace `` with the major version number of libc++. If you installed libc++ in a different folder, locate `std.cppm` manually in that folder.
+* On macOS with the ([Homebrew build](https://formulae.brew.sh/formula/llvm)), the `std` module should be at `/usr/local/Cellar/llvm//share/libc++/v1/std.cppm`. Replace `` with the full version number of libc++. If you installed libc++ in a different folder, locate `std.cppm` manually in that folder.
To compile the module file `std.cppm` with Clang, first create the `build` folder using `mkdir build`, and then run the following command in the root folder of the repository:
@@ -2784,7 +2865,7 @@ clang++ "path to std.cppm" --precompile -std=c++23 -o build/std.pcm -Wno-reserve
Of course, you should replace `"path to std.cppm"` with the actual path. The compiler arguments are explained [above](#compiling-with-clang-using-import-bsthread_pool). The additional argument `-Wno-reserved-module-identifier` is needed to silence a false-positive warning.
-Next, compile the `BS.thread_pool` module as [above](#compiling-with-clang-using-import-bsthread_pool), but with the following additional flags:
+Next, compile the `BS.thread_pool` module as [above](#compiling-with-clang-using-import-bsthread_pool), but with `-std=c++23` and the following additional flags:
* `-fmodule-file="std=build/std.pcm"`: Specify that the module `std` is located in the file `build/std.pcm`.
* `-D BS_THREAD_POOL_IMPORT_STD`: Instruct the library to import the `std` module.
@@ -2807,11 +2888,47 @@ C++ Standard Library imported using:
* Test program: import std (C++23 std module).
```
+### Compiling with GCC and GNU libstdc++ using `import std`
+
+Note: The following instructions have only been tested using GCC v15.2.0 and GNU libstdc++ v15 (20250917), the latest versions at the time of writing, and may not work with older versions.
+
+With GNU libstdc++, the `std` module file is always available as the system module `bits/std.cc`. To compile this module file with GCC, first create the `build` folder using `mkdir build`, and then run the following command in the root folder of the repository:
+
+```bash
+g++ -fsearch-include-path bits/std.cc -c "-fmodule-mapper=|@g++-mapper-server -r build" -fmodule-only -fmodules -std=c++23 -I include
+```
+
+The compiler arguments are explained [above](#compiling-with-gcc-using-import-bsthread_pool). The additional argument `-fsearch-include-path` is needed to tell the compiler to look for `bits/std.cc` in the include path (otherwise it will assume it is in the current directory).
+
+Next, compile the `BS.thread_pool` module as [above](#compiling-with-gcc-using-import-bsthread_pool), but with `-std=c++23` and the following additional flags:
+
+* `-D BS_THREAD_POOL_IMPORT_STD`: Instruct the library to import the `std` module.
+
+```bash
+g++ -x c++ modules/BS.thread_pool.cppm -c "-fmodule-mapper=|@g++-mapper-server -r build" -fmodule-only -fmodules -std=c++23 -I include -D BS_THREAD_POOL_IMPORT_STD
+```
+
+Add `-D BS_THREAD_POOL_NATIVE_EXTENSIONS` if you wish to enable the [native extensions](#native-extensions). Once the module is compiled, you can compile the test program as follows:
+
+```bash
+g++ tests/BS_thread_pool_test.cpp "-fmodule-mapper=|@g++-mapper-server -r build" -fmodules -std=c++23 -o build/BS_thread_pool_test -D BS_THREAD_POOL_TEST_IMPORT_MODULE -D BS_THREAD_POOL_IMPORT_STD
+```
+
+Again, you should add `-D BS_THREAD_POOL_NATIVE_EXTENSIONS` if you wish to test the native extensions. If you now type `build/BS_thread_pool_test`, the test program will run. If the `std` module was successfully imported, the test program will print the message:
+
+```none
+C++ Standard Library imported using:
+* Thread pool library: import std (C++23 std module).
+* Test program: import std (C++23 std module).
+```
+
+**NOTE:** At the time of writing, there is a bug when using GCC with libstdc++ on Windows via MSYS2 where the `BS.thread_pool` module doesn't compile if both native extensions and `import std` are enabled. As a workaround, until the bug is fixed, the thread pool library automatically falls back to header files if it detects that GCC and libstdc++ are being used together with the C++23 `std` module on Windows. This workaround can be disabled by defining `BS_THREAD_POOL_DISABLE_WORKAROUNDS` when compiling the module.
+
### Compiling with MSVC and Microsoft STL using `import std`
-Note: The following instructions have only been tested using MSVC v19.42.34435 and Microsoft STL v143 (202408), the latest versions at the time of writing, and may not work with older versions.
+Note: The following instructions have only been tested using MSVC v19.50.35721 and Microsoft STL v145 (202508), the latest versions at the time of writing, and may not work with older versions.
-Before compiling the `std` module, you must find the file `std.ixx`. It should be located in the folder `C:\Program Files\Microsoft Visual Studio\2022\Community\VC\Tools\MSVC\\modules`. Replace `` with the full version number of the MSVC runtime library, e.g. `14.42.34433`. If you installed Visual Studio in a different folder, locate `std.ixx` manually in that folder.
+Before compiling the `std` module, you must find the file `std.ixx`. If you have Visual Studio 2026, it should be located in the folder `C:\Program Files\Microsoft Visual Studio\18\Community\VC\Tools\MSVC\\modules`. Replace `` with the full version number of the MSVC runtime library; the latest is `14.50.35717` at the time of writing. If you installed Visual Studio in a different folder, locate `std.ixx` manually in that folder.
To compile the module file `std.ixx` with MSVC, first open the Visual Studio Developer PowerShell for the appropriate CPU architecture as explained [above](#compiling-with-msvc-using-import-bsthread_pool). Navigate to the repository folder, create the `build` folder using `mkdir build`, and then run the following command in the root folder of the repository:
@@ -2846,12 +2963,12 @@ C++ Standard Library imported using:
### Compiling with CMake using `import std`
-Note: The following instructions have only been tested using CMake v3.31.2, the latest version at the time of writing, and may not work with older versions. Also, modules are currently only supported by CMake with the [`Ninja`](https://ninja-build.org/) and `Visual Studio 17 2022` generators.
+Note: The following instructions have only been tested using CMake v4.2.1, the latest version at the time of writing, and may not work with older versions. Also, modules are currently not supported by CMake with all generators; please see the CMake documentation for more information.
If you are using [CMake](https://cmake.org/), you can enable `CMAKE_EXPERIMENTAL_CXX_IMPORT_STD` to automatically compile the `std` module, provided the compiler and standard library support it. Here is an example of a `CMakeLists.txt` file that can be used to build the test program, import the thread pool library as a module, and import the C++ Standard Library as a module:
```cmake
-cmake_minimum_required(VERSION 3.31)
+cmake_minimum_required(VERSION 4.2.1)
project(BS_thread_pool_test LANGUAGES CXX)
set(CMAKE_CXX_STANDARD 23)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
@@ -2911,17 +3028,6 @@ vcpkg upgrade
Please refer to [this package's page on vcpkg.io](https://vcpkg.io/en/package/bshoshany-thread-pool) for more information.
-### Installing using Conan
-
-If you are using the [Conan](https://conan.io/) C/C++ package manager, you can easily integrate `BS::thread_pool` into your project by adding the following lines to your `conanfile.txt`:
-
-```ini
-[requires]
-bshoshany-thread-pool/5.0.0
-```
-
-To update the package to the latest version, simply change the version number. Please refer to [this package's page on ConanCenter](https://conan.io/center/recipes/bshoshany-thread-pool) for more information.
-
### Installing using Meson
If you are using the [Meson](https://mesonbuild.com/) build system, you can install `BS::thread_pool` from [WrapDB](https://mesonbuild.com/Wrapdb-projects.html). To do so, create a `subprojects` folder in your project (if it does not already exist) and run the following command:
@@ -2936,9 +3042,20 @@ Then, use `dependency('bshoshany-thread-pool')` in your `meson.build` file to in
meson wrap update bshoshany-thread-pool
```
+### Installing using Conan
+
+If you are using the [Conan](https://conan.io/) C/C++ package manager, you can easily integrate `BS::thread_pool` into your project by adding the following lines to your `conanfile.txt`:
+
+```ini
+[requires]
+bshoshany-thread-pool/5.1.0
+```
+
+To update the package to the latest version, simply change the version number. Please refer to [this package's page on ConanCenter](https://conan.io/center/recipes/bshoshany-thread-pool) for more information.
+
### Installing using CMake with CPM
-Note: The following instructions have only been tested using CMake v3.31.2 and CPM v0.40.2, the latest versions at the time of writing, and may not work with older versions.
+Note: The following instructions have only been tested using CMake v4.2.1 and CPM v0.42.0, the latest versions at the time of writing, and may not work with older versions.
If you are using [CMake](https://cmake.org/), you can install `BS::thread_pool` most easily with [CPM](https://github.com/cpm-cmake/CPM.cmake). If CPM is already installed, simply add the following to your project's `CMakeLists.txt`:
@@ -2946,7 +3063,7 @@ If you are using [CMake](https://cmake.org/), you can install `BS::thread_pool`
CPMAddPackage(
NAME BS_thread_pool
GITHUB_REPOSITORY bshoshany/thread-pool
- VERSION 5.0.0
+ VERSION 5.1.0
EXCLUDE_FROM_ALL
SYSTEM
)
@@ -2959,7 +3076,7 @@ This will automatically download the indicated version of the package from [the
A convenient shorthand for GitHub packages also exists, in which case `CPMAddPackage()` can be called with a single argument of the form `"gh:user/name@version"`. After that, `CPM_LAST_PACKAGE_NAME` will be set to the name of the package, so we need to use this variable to define the include folder. This results in a more compact configuration:
```cmake
-CPMAddPackage("gh:bshoshany/thread-pool@5.0.0")
+CPMAddPackage("gh:bshoshany/thread-pool@5.1.0")
add_library(BS_thread_pool INTERFACE)
target_include_directories(BS_thread_pool INTERFACE ${${CPM_LAST_PACKAGE_NAME}_SOURCE_DIR}/include)
```
@@ -2974,10 +3091,10 @@ endif()
include(${CPM_DOWNLOAD_LOCATION})
```
-Here is an example of a complete `CMakeLists.txt` which automatically downloads and compiles the test program [`BS_thread_pool_test.cpp`](#automated-tests):
+Here is an example of a complete `CMakeLists.txt` which automatically downloads and compiles the test program [`BS_thread_pool_test.cpp`](#testing-the-library):
```cmake
-cmake_minimum_required(VERSION 3.31)
+cmake_minimum_required(VERSION 4.2.1)
project(BS_thread_pool_test LANGUAGES CXX)
set(CMAKE_CXX_STANDARD 17)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
@@ -2993,7 +3110,7 @@ if(NOT(EXISTS ${CPM_DOWNLOAD_LOCATION}))
endif()
include(${CPM_DOWNLOAD_LOCATION})
-CPMAddPackage("gh:bshoshany/thread-pool@5.0.0")
+CPMAddPackage("gh:bshoshany/thread-pool@5.1.0")
add_library(BS_thread_pool INTERFACE)
target_include_directories(BS_thread_pool INTERFACE ${${CPM_LAST_PACKAGE_NAME}_SOURCE_DIR}/include)
@@ -3001,9 +3118,9 @@ add_executable(${PROJECT_NAME} ${${CPM_LAST_PACKAGE_NAME}_SOURCE_DIR}/tests/BS_t
target_link_libraries(${PROJECT_NAME} PRIVATE BS_thread_pool)
```
-Note that for MSVC we have to add the `/permissive-` flag to enforce strict C++ standard conformance, otherwise the test program will not compile, and `/Zc:__cplusplus`, otherwise the test program cannot detect the correct C++ version. This is handled automatically by the `if(MSVC)` block.
+The `if(MSVC)` block is explained [above](#compiling-with-msvc-using-import-bsthread_pool). To enable the [native extensions](#native-extensions), add the line `add_compile_definitions(BS_THREAD_POOL_NATIVE_EXTENSIONS)`.
-To enable the [native extensions](#native-extensions), add the line `add_compile_definitions(BS_THREAD_POOL_NATIVE_EXTENSIONS)`. Replace `CMAKE_CXX_STANDARD 17` with `20` or `23` if you wish to use C++20 or C++23 features, respectively. Of course, you should add warning, debugging, optimization, and other compiler flags to the configuration above as needed.
+Replace `CMAKE_CXX_STANDARD 17` with `20` or `23` if you wish to use C++20 or C++23 features, respectively. Of course, you should add warning, debugging, optimization, and other compiler flags to the configuration above as needed.
With this `CMakeLists.txt` in an empty folder, type the following commands to build and run the project:
@@ -3017,12 +3134,12 @@ For MSVC, replace the last command with `build/Debug/BS_thread_pool_test`. Pleas
### Installing using CMake with `FetchContent`
-Note: The following instructions have only been tested using CMake v3.31.2, the latest version at the time of writing, and may not work with older versions.
+Note: The following instructions have only been tested using CMake v4.2.1, the latest version at the time of writing, and may not work with older versions.
If you are using [CMake](https://cmake.org/) but do not wish to use 3rd-party tools, you can also install `BS::thread_pool` using the built-in [`FetchContent`](https://cmake.org/cmake/help/latest/module/FetchContent.html) module. Here is an example of a complete `CMakeLists.txt` which automatically downloads and compiles the test program, as in the previous section, but this time using `FetchContent` directly:
```cmake
-cmake_minimum_required(VERSION 3.31)
+cmake_minimum_required(VERSION 4.2.1)
project(BS_thread_pool_test LANGUAGES CXX)
set(CMAKE_CXX_STANDARD 17)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
@@ -3037,7 +3154,7 @@ set(FETCHCONTENT_UPDATES_DISCONNECTED ON)
FetchContent_Declare(
bshoshany_thread_pool
GIT_REPOSITORY https://github.com/bshoshany/thread-pool.git
- GIT_TAG v5.0.0
+ GIT_TAG v5.1.0
DOWNLOAD_EXTRACT_TIMESTAMP TRUE
EXCLUDE_FROM_ALL
SYSTEM
@@ -3061,14 +3178,14 @@ Descriptions of each item can also be found in the [Doxygen](https://www.doxygen
`BS::thread_pool` is the main thread pool class. It is used to create a pool of threads that continuously execute tasks submitted to a queue. It can take template parameters, which enable optional features as described [below](#optional-features-and-the-template-parameter). The member functions that are available by default, when no template parameters are used, are:
* Constructors:
- * `thread_pool()`: Construct a new thread pool with a number of threads equal to `std::thread::hardware_concurrency()`.
+ * `thread_pool()`: Construct a new thread pool with a number of threads equal to `std::thread::hardware_concurrency()`, or if the native extensions are enabled, the number of threads available to the process as obtained from `BS::get_os_process_affinity()`.
* `thread_pool(std::size_t num_threads)`: Construct a new thread pool with the specified number of threads.
- * `thread_pool(F&& init)`: Construct a new thread pool with a number of threads equal to `std::thread::hardware_concurrency()` and the specified initialization function. `F` is a template parameter.
+ * `thread_pool(F&& init)`: Construct a new thread pool with the default number of threads and the specified initialization function. `F` is a template parameter.
* `thread_pool(std::size_t num_threads, F&& init)`: Construct a new thread pool with the specified number of threads and the specified initialization function.
* Resetters:
- * `void reset()`: Reset the pool with a number of threads equal to `std::thread::hardware_concurrency()`, waiting for running tasks first, and preserving submitted tasks after the reset.
+ * `void reset()`: Reset the pool with the default number of threads (as if constructed with the default constructor). Waits for all tasks first; if pausing is enabled, waits only for running tasks, and queued tasks resume after the pool is reset. If the pool was paused before resetting it, the new pool will be paused as well.
* `void reset(std::size_t num_threads)`: Reset the pool with a new number of threads.
- * `void reset(F&& init)` Reset the pool with a number of threads equal to `std::thread::hardware_concurrency()` and a new initialization function. `F` is a template parameter.
+ * `void reset(F&& init)`: Reset the pool with the default number of threads and a new initialization function. `F` is a template parameter.
* `void reset(std::size_t num_threads, F&& init)`: Reset the pool with a new number of threads and a new initialization function.
* Setters:
* `void set_cleanup_func(F&& cleanup)`: Set the thread pool's cleanup function. `F` is a template parameter.
@@ -3078,16 +3195,20 @@ Descriptions of each item can also be found in the [Doxygen](https://www.doxygen
* `std::size_t get_tasks_total()`: Get the total number of unfinished tasks: either still waiting in the queue, or running in a thread. Note that `get_tasks_total() == get_tasks_queued() + get_tasks_running()`.
* `std::size_t get_thread_count()`: Get the number of threads in the pool.
* `std::vector get_thread_ids()`: Get a vector containing the unique identifiers for each of the pool's threads, as obtained by `std::thread::get_id()` (or `std::jthread::get_id()` in C++20 and later).
-* Task submission without futures (`T1`, `T2`, and `F` are template parameters):
+* Task submission without futures (`T1`, `T2`, `F`, `C`, and `I` are template parameters):
* `void detach_task(F&& task)`: Submit a function with no arguments and no return value into the task queue. To submit a function with arguments, enclose it in a lambda expression.
- * `void detach_blocks(T1 first_index, T2 index_after_last, F&& block, std::size_t num_blocks = 0)`: Parallelize a loop by automatically splitting it into blocks. The block function takes two arguments, the start and end of the block, so that it is only called once per block, but it is up to the user make sure the block function correctly deals with all the indices in each block.
+ * `void detach_blocks(T1 first_index, T2 index_after_last, F&& block, std::size_t num_blocks = 0)`: Parallelize a loop by automatically splitting it into blocks. The block function takes two arguments, the start and end of the block, so that it is only called once per block, but it is up to the user to make sure the block function correctly deals with all the indices in each block.
* `void detach_loop(T1 first_index, T2 index_after_last, F&& loop, std::size_t num_blocks = 0)`: Parallelize a loop by automatically splitting it into blocks. The loop function takes one argument, the loop index, so that it is called many times per block.
- * `void detach_sequence(1T first_index, T2 index_after_last, F&& sequence)`: Submit a sequence of tasks enumerated by indices to the queue. The sequence function takes one argument, the task index, and will be called once per index.
-* Task submission with futures (`T1`, `T2`, `F`, and `R` are template parameters):
+ * `void detach_sequence(T1 first_index, T2 index_after_last, F&& sequence)`: Submit a sequence of tasks enumerated by indices to the queue. The sequence function takes one argument, the task index, and will be called once per index.
+ * `void detach_bulk(C& container)`: Submit a container of functions with no arguments and no return values to the queue.
+ * `void detach_bulk(I first, I last)`: Submit an iterator range containing functions with no arguments and no return values to the queue.
+* Task submission with futures (`T1`, `T2`, `F`, `R`, `C`, and `I` are template parameters):
* `std::future submit_task(F&& task)`: Submit a function with no arguments into the task queue. To submit a function with arguments, enclose it in a lambda expression.
- * `BS::multi_future submit_blocks(T1 first_index, T2 index_after_last, F&& block, std::size_t num_blocks = 0)`: Parallelize a loop by automatically splitting it into blocks. The block function takes two arguments, the start and end of the block, so that it is only called once per block, but it is up to the user make sure the block function correctly deals with all the indices in each block. Returns a `BS::multi_future` that contains the futures for all of the blocks.
- * `BS::multi_future submit_loop(T1 first_index, T2 index_after_last, F&& loop, std::size_t num_blocks = 0)`: Parallelize a loop by automatically splitting it into blocks. The loop function takes one argument, the loop index, so that it is called many times per block. It must have no return value. Returns a `BS::multi_future` that contains the futures for all of the blocks.
- * `BS::multi_future submit_sequence(T1 first_index, T2 index_after_last, F&& sequence)`: Submit a sequence of tasks enumerated by indices to the queue. The sequence function takes one argument, the task index, and will be called once per index. Returns a `BS::multi_future` that contains the futures for all of the tasks.
+ * `BS::multi_future submit_blocks(T1 first_index, T2 index_after_last, F&& block, std::size_t num_blocks = 0)`: Parallelize a loop by automatically splitting it into blocks. The block function takes two arguments, the start and end of the block, so that it is only called once per block, but it is up to the user to make sure the block function correctly deals with all the indices in each block. Returns a `BS::multi_future` that contains the futures for all the blocks.
+ * `BS::multi_future submit_loop(T1 first_index, T2 index_after_last, F&& loop, std::size_t num_blocks = 0)`: Parallelize a loop by automatically splitting it into blocks. The loop function takes one argument, the loop index, so that it is called many times per block. It must have no return value. Returns a `BS::multi_future` that contains the futures for all the blocks.
+ * `BS::multi_future submit_sequence(T1 first_index, T2 index_after_last, F&& sequence)`: Submit a sequence of tasks enumerated by indices to the queue. The sequence function takes one argument, the task index, and will be called once per index. Returns a `BS::multi_future` that contains the futures for all the tasks.
+ * `BS::multi_future submit_bulk(C& container)`: Submit a container of functions with no arguments to the queue. Returns a `BS::multi_future` that contains the futures for all the tasks.
+ * `BS::multi_future submit_bulk(I first, I last)`: Submit an iterator range containing functions with no arguments to the queue. Returns a `BS::multi_future` that contains the futures for all the tasks.
* Task management:
* `void purge()`: Purge all the tasks waiting in the queue. Please note that there is no way to restore the purged tasks.
* Waiting for tasks (`R`, `P`, `C`, and `D` are template parameters):
@@ -3099,14 +3220,14 @@ Descriptions of each item can also be found in the [Doxygen](https://www.doxygen
### Optional features and the template parameter
-The thread pool has several optional features that must be explicitly enabled by passing a template parameter. The template parameter is a bitmask, so you can enable several features at once by combining them with the bitwise OR operator `|`. The bitmask flags are members of the `BS::tp` enumeration.
+The thread pool has several optional features that must be explicitly enabled by passing a template parameter. The template parameter is a bitmask, so you can enable several features at once by combining them with the bitwise OR operator `|`. The bitmask flags are members of the `BS::tp` enumeration class.
* **Task priority:** Enabled by turning on the `BS::tp::priority` flag in the template parameter. When enabled, the static member `priority_enabled` will be set to `true`.
* When enabled, the priority of a task or group of tasks may be specified as an additional argument (at the end of the argument list) to all detach and submit functions. If the priority is not specified, the default value will be 0.
* The priority is of type `BS::priority_t`, a signed 8-bit integer, with values between -128 and +127. The tasks will be executed in priority order from highest to lowest. Groups of parallelized tasks will all have the same priority.
* The enumeration `BS::pr` contains some pre-defined priorities: `BS::pr::highest`, `BS::pr::high`, `BS::pr::normal`, `BS::pr::low`, and `BS::pr::lowest`.
* **Pausing:** Enabled by turning on the `BS::tp::pause` flag in the template parameter. When enabled, the static member `pause_enabled` will be set to `true`. Adds the following member functions:
- * `void pause()`: 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()`: Pause the pool. The workers will temporarily stop retrieving new tasks out of the queue, although any tasks already executing will keep running until they are finished.
* `void unpause()`: Unpause the pool. The workers will resume retrieving new tasks out of the queue.
* `bool is_paused()`: Check whether the pool is currently paused.
* **Wait deadlock checks:** Enabled by turning on the `BS::tp::wait_deadlock_checks` flag in the template parameter. When enabled, the static member `wait_deadlock_checks_enabled` will be set to `true`.
@@ -3135,19 +3256,19 @@ The native extensions may be enabled by defining the macro `BS_THREAD_POOL_NATIV
The native extensions add the following functions to the `BS` namespace:
-* `bool set_os_process_affinity(std::vector& affinity)`: Set the processor affinity of the current process. The argument is an `std::vector` where each element corresponds to a logical processor. Returns `true` if the affinity was set successfully, `false` otherwise. Does not work on macOS.
+* `bool BS::set_os_process_affinity(std::vector& affinity)`: Set the processor affinity of the current process. The argument is an `std::vector` where each element corresponds to a logical processor. Returns `true` if the affinity was set successfully, `false` otherwise. Does not work on macOS.
* `std::optional> BS::get_os_process_affinity()`: Get the processor affinity of the current process. The optional object will not have a value if the affinity could not be determined. Does not work on macOS.
* `bool BS::set_os_process_priority(BS::os_process_priority priority)`: Set the priority of the current process. The argument must be a member of the `BS::os_process_priority` enumeration, which contains the options `idle`, `below_normal`, `normal`, `above_normal`, `high`, and `realtime`. Returns `true` if the priority was set successfully, or `false` otherwise.
* `std::optional BS::get_os_process_priority()`: Get the priority of the current process. The optional object will not have a value if the priority could not be determined, or it is not one of the pre-defined values in the `BS::os_process_priority` enumeration.
The native extensions also add the following static member functions to `BS::this_thread`:
-* `bool set_os_thread_affinity(std::vector& affinity)`: Set the processor affinity of the current thread. The argument is an `std::vector` where each element corresponds to a logical processor. Note that the thread affinity must be a subset of the process affinity for the containing process of a thread. Does not work on macOS.
-* `std::optional> get_os_thread_affinity()`: Get the processor affinity of the current thread. The optional object will not have a value if the affinity could not be determined. Does not work on macOS.
-* `bool set_os_thread_name(std::string& name)`: Set the name of the current thread. Note that on Linux thread names are limited to 16 characters, including the null terminator. Returns `true` if the name was set successfully, `false` otherwise.
-* `std::optional get_os_thread_name()`: Get the name of the current thread. The optional object will not have a value if the name could not be determined.
-* `bool set_os_thread_priority(BS::os_thread_priority priority)`: Set the priority of the current thread. The argument must be a member of the `BS::os_thread_priority` enumeration, which contains the options `idle`, `lowest`, `below_normal`, `normal`, `above_normal`, `highest`, and `realtime`. Returns `true` if the priority was set successfully, or `false` otherwise.
-* `std::optional get_os_thread_priority()`: Get the priority of the current thread. The optional object will not have a value if the priority could not be determined, or it is not one of the pre-defined values in the `BS::os_thread_priority` enumeration.
+* `bool BS::this_thread::set_os_thread_affinity(std::vector& affinity)`: Set the processor affinity of the current thread. The argument is an `std::vector` where each element corresponds to a logical processor. Note that the thread affinity must be a subset of the process affinity for the containing process of a thread. Does not work on macOS and Android.
+* `std::optional> BS::this_thread::get_os_thread_affinity()`: Get the processor affinity of the current thread. The optional object will not have a value if the affinity could not be determined. Does not work on macOS and Android.
+* `bool BS::this_thread::set_os_thread_name(std::string& name)`: Set the name of the current thread. Note that on Linux thread names are limited to 16 characters, including the null terminator. Returns `true` if the name was set successfully, `false` otherwise.
+* `std::optional BS::this_thread::get_os_thread_name()`: Get the name of the current thread. The optional object will not have a value if the name could not be determined.
+* `bool BS::this_thread::set_os_thread_priority(BS::os_thread_priority priority)`: Set the priority of the current thread. The argument must be a member of the `BS::os_thread_priority` enumeration, which contains the options `idle`, `lowest`, `below_normal`, `normal`, `above_normal`, `highest`, and `realtime`. Returns `true` if the priority was set successfully, or `false` otherwise.
+* `std::optional BS::this_thread::get_os_thread_priority()`: Get the priority of the current thread. The optional object will not have a value if the priority could not be determined, or it is not one of the pre-defined values in the `BS::os_thread_priority` enumeration.
Finally, the native extensions add the following member function to `BS::thread_pool`:
@@ -3208,9 +3329,7 @@ The library defines the following `constexpr` variables:
When the library is imported as a C++20 module using `import BS.thread_pool`, it exports the following names, in alphabetical order:
-* `BS::binary_semaphore`
* `BS::common_index_type_t`
-* `BS::counting_semaphore`
* `BS::light_thread_pool`
* `BS::multi_future`
* `BS::pause_thread_pool`
@@ -3224,11 +3343,14 @@ When the library is imported as a C++20 module using `import BS.thread
* `BS::thread_pool_module`
* `BS::thread_pool_native_extensions`
* `BS::thread_pool_version`
-* `BS::tp`
+* `BS::tp` (plus related bitwise operators)
* `BS::version`
-* `BS::wait_deadlock`
* `BS::wdc_thread_pool`
+If exceptions are enabled, the following names are also exported:
+
+* `BS::wait_deadlock`
+
If the native extensions are enabled, the following names are also exported:
* `BS::get_os_process_affinity`
@@ -3242,7 +3364,7 @@ If the native extensions are enabled, the following names are also exported:
### The `compile_cpp.py` script
-The Python script `compile_cpp.py`, in the `scripts` folder of [the GitHub repository](https://github.com/bshoshany/thread-pool), can be used to compile any C++ source file with different compilers on different platforms. It requires Python 3.12 or later.
+The Python script `compile_cpp.py`, in the `scripts` folder of [the GitHub repository](https://github.com/bshoshany/thread-pool), can be used to compile any C++ source file with different compilers on different platforms. It has only been tested using Python v3.14.2, the latest version at the time of writing, and may not work with older versions.
The script was written by the author of the library to make it easier to test the library with different combinations of compilers, standards, and platforms using the built-in Visual Studio Code tasks. However, note that this script is not meant to replace CMake or any full-fledged build system, it's just a convenient script for developing single-header libraries like this one or other small projects.
@@ -3253,51 +3375,56 @@ The compilation parameters can be configured using the command line arguments an
* Positional argument(s): the source file(s) to compile.
* `-h` or `--help`: Show the help message and exit.
* `-a` or `--arch`: The target architecture (MSVC only). Must be one of `[amd64, arm64]`, default is `amd64`.
+* `-b` or `--clear-output`: Clear the output folder before compiling. If no source files are specified, just clear and exit. The outcome is always an empty output folder.
* `-c` or `--compiler`: Which compiler to use. Must be one of `[cl, clang++, g++]`. The default is to determine it automatically based on the platform.
* `-d` or `--define`: Macros to define. Use this argument multiple times to define more than one macro. Additional macros can be defined in `compile_cpp.yaml`.
+* `-e` or `--force`: Force recompilation even if the executable is up to date.
* `-f` or `--flag`: Extra compiler flags to add. Use this argument multiple times to add more than one flag. Additional flags can be specified in `compile_cpp.yaml`.
+* `-g` or `--ignore-config`: Ignore the `compile_cpp.yaml` configuration file, if it exists.
* `-i` or `--include`: The include folder to use. Use this argument multiple times to use more than one include folder. Additional include folders can be specified in `compile_cpp.yaml`.
* `-l` or `--as-module`: Enable this flag to compile the file as a C++20 module.
-* `-m` or `--module`: C++20 module files to use if desired, in the format `module_name=module_file,dependent_files,...`. Use this argument multiple times to use more than one module. Additional modules can be specified in `compile_cpp.yaml`. The dependent files are only used to determine whether the module needs to be recompiled.
-* `-o` or `--output`: The output folder and/or executable name. End with `/` to create the folder if it doesn't already exist. If not specified, the folder defined in `compile_cpp.yaml` will be used. If the executable name is not specified, it will be determined automatically in the format `source_[module_]type-compiler-standard` where:
+* `-m` or `--module`: C++20 module files to use if desired, in the format `module_name=module_file,dependencies,...`. Use this argument multiple times to use more than one module. Additional modules can be specified in `compile_cpp.yaml`. The dependencies are only used to determine whether the module needs to be recompiled.
+* `-n` or `--deps`: Dependencies used to detect if recompilation is needed. If these files are modified, then the executable is recompiled even if the source files have not been modified. Use this argument multiple times to add more than one dependency. Additional dependencies can be specified in `compile_cpp.yaml`. Note that this is not used for C++20 modules, which have their own dependencies, listed when using `-m`.
+* `-o` or `--output`: The output folder and/or executable name. End with `/` to create the folder if it doesn't already exist. If not specified, the folder defined in `compile_cpp.yaml` will be used. If the executable name is not specified, it will be determined automatically in the format `{source}_[module_]{type}-{compiler}-{standard}` where:
* `source` is the name of the first source file (without the extension).
- * `module_`, if present, indicates that the file is a C++20 module.
+ * `module_`, if present, indicates that the file is a C++20 module (if `-l`/`--as-module` is enabled)
* `type` is one of `[debug, release]`.
* `compiler` is one of `[clang, gcc, msvc]`.
- * `standard` is one of `[c++17, c++20, c++23]`.
-* `-p` or `--pass`: Pass command line arguments to the compiled program when running it, if `-r` is specified. Use this argument multiple times to pass more than one argument to the program. Additional arguments can be specified in `compile_cpp.yaml`.
+ * `standard` is one of `[cpp17, cpp20, cpp23]`.
+* `-p` or `--pass`: Pass command line arguments to the compiled program when running it, if `-r`/`--run` is specified. Use this argument multiple times to pass more than one argument to the program. Additional arguments can be specified in `compile_cpp.yaml`.
* `-r` or `--run`: Enable this flag to run the program after compiling it.
* `-s` or `--std`: Which C++ standard to use. Must be one of `[c++17, c++20, c++23]`. The default is `c++23`.
* `-t` or `--type`: Which mode to compile in. Must be one of `[debug, release]`. The default is `debug`.
* `-u` or `--std-module`: Specify the path to the standard library module (C++23 only). Taken from `compile_cpp.yaml` if not specified. Use `auto` to auto-detect or `disable` to explicitly disable.
* `-v` or `--verbose`: Enable this flag to print the script's diagnostic messages.
+* `-x` or `--disable-exceptions`: If set to `true`, disables exceptions in the compiler flags. If set to `false`, exceptions will be enabled. If not specified, the setting will be taken from `compile_cpp.yaml`.
+* `-y` or `--try-all`: Test compilation using all possible combinations of compilers and C++ standards available in the system. Also runs each compiled program if `-r`/`--run` is specified. All other arguments are passed to all compilation attempts. Cannot be used together with `-c`/`--compiler` or `-s`/`--std`.
The `compile_cpp.yaml` file includes the following fields:
* `defines`: A list of macros to define when compiling the source files.
+* `deps`: A list of dependencies, such as header files or libraries. All source files compiled using this script will be recompiled if any of these files change.
+* `disable_exceptions`: Whether to disable exceptions in the compiler flags. Defaults to `false` if not specified.
* `flags`: A map of flags to pass to each compiler. The compiler should be one of `[cl, clang++, g++]`. The flags should be a list of strings.
* `includes`: A list of include folders.
-* `modules`: A map of C++20 modules in the format `module_name: [module_path, dependent files, ...]`. Will only be used in C++20 or C++23 mode. The dependent files are only used to determine whether the module needs to be recompiled.
+* `modules`: A map of C++20 modules in the format `module_name: [module_path, dependencies, ...]`. Will only be used in C++20 or C++23 mode. The dependencies are only used to determine whether the module needs to be recompiled.
* `output`: The output folder for the compiled files.
* `pass_args`: A list of arguments to pass to the program if running it after compilation.
-* `std_module`: A map of paths to the standard library modules for each OS and compiler combination (C++23 only). The OS should be one of `[Windows, Linux, Darwin]`. Use `Automatic` to determine the path automatically if possible.
+* `std_module`: A map of paths to the standard library modules for each OS and compiler combination (C++23 only). The OS should be one of `[Windows, Linux, Darwin]`. Use `auto` to determine the path automatically if possible.
Please see the `compile_cpp.yaml` file in the GitHub repository for an example of how to use it.
-### Other included tools
+By default, the script prints colored output using ANSI escape codes for better readability. This can be disabled by setting the `NO_COLOR` environment variable.
-The `scripts` folder of [the GitHub repository](https://github.com/bshoshany/thread-pool) contains two other Python scripts that are used in the development of the library:
+### Visual Studio Code tasks
-* `test_all.py` performs the [automated tests](#automated-tests) in C++17, C++20, and C++23 modes, using all compilers available in the system (Clang, GCC, and/or MSVC). Since there are so many tests, the test script does not perform the benchmarks, as that would take too long. Pass the optional argument `--compile-only` to only check that the program compiles successfully with all compilers, without running it.
-* `clear_folder.py` is used to clean up output and temporary folders. It will create the folder if it does not already exist, so the outcome is always an empty folder.
-
-In addition, for Visual Studio Code users, the GitHub repository includes three `.vscode` folders:
+For Visual Studio Code users, the GitHub repository includes three `.vscode` folders:
* `.vscode-windows`, to be used in Windows with Clang, GCC, and MSVC.
* `.vscode-linux`, to be used in Linux with Clang and GCC.
* `.vscode-macos`, to be used in macOS with LLVM Clang (not Apple Clang).
-Each folder contains appropriate `c_cpp_properties.json`, `launch.json`, and `tasks.json` files that utilize the included Python scripts. Users are welcome to use these files in their own projects, but they may require some modifications to work on specific systems.
+Each folder contains appropriate `c_cpp_properties.json`, `launch.json`, and `tasks.json` files that utilize the included Python script [`compile_cpp.py`](#the-compile_cpppy-script). Users are welcome to use these files in their own projects, but they may require some modifications to work on specific systems.
## About the project
@@ -3319,7 +3446,7 @@ Many GitHub users have helped improve this project, directly or indirectly, via
### Copyright and citing
-Copyright (c) 2024 [Barak Shoshany](https://baraksh.com/). Licensed under the [MIT license](https://github.com/bshoshany/thread-pool/blob/master/LICENSE.txt).
+Copyright (c) 2021-2026 [Barak Shoshany](https://baraksh.com/). Licensed under the [MIT license](https://github.com/bshoshany/thread-pool/blob/master/LICENSE.txt).
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.
diff --git a/compile_cpp.yaml b/compile_cpp.yaml
index e7970c7..19d7b57 100644
--- a/compile_cpp.yaml
+++ b/compile_cpp.yaml
@@ -1,25 +1,31 @@
# A list of macros to define when compiling the source files.
defines: [BS_THREAD_POOL_TEST_IMPORT_MODULE, BS_THREAD_POOL_IMPORT_STD, BS_THREAD_POOL_NATIVE_EXTENSIONS]
+# A list of dependencies, such as header files or libraries. All source files compiled using this script will be recompiled if any of these files change. (Note that this is not used for C++20 modules, which have their own dependencies, listed in the modules map.)
+deps: [include/BS_thread_pool.hpp]
+# Whether to disable exceptions.
+disable_exceptions: false
# A map of flags to pass to each compiler. The compiler should be one of [cl, clang++, g++]. The flags should be a list of strings.
flags:
- cl: [/W4]
- clang++: [-Wall, -Wextra, -Wconversion, -Wsign-conversion, -Wpedantic, -Wshadow, -Weffc++, -march=native, -fcolor-diagnostics, -fansi-escape-codes, -stdlib=libc++]
- g++: [-Wall, -Wextra, -Wconversion, -Wpedantic, -Wshadow, -Wuseless-cast, -march=native, -fdiagnostics-color=always]
+ cl: [/W4, /D_CRT_SECURE_NO_WARNINGS]
+ clang++: [-Wall, -Wextra, -Wconversion, -Wsign-conversion, -Wpedantic, -Wshadow, -Weffc++, -Wdocumentation, -march=native, -fcolor-diagnostics, -fansi-escape-codes, -stdlib=libc++]
+ g++: [-Wall, -Wextra, -Wconversion, -Wsign-conversion, -Wpedantic, -Wshadow, -Wuseless-cast, -march=native, -fdiagnostics-color=always, -Wnrvo]
# A list of include folders.
includes: [include]
-# A map of C++20 modules in the format "module_name: [module_path, dependent files, ...]". Will only be used in C++20 or C++23 mode. The dependent files are any files that the module depends on, and are only used to determine whether the module needs to be recompiled.
+# A map of C++20 modules in the format "module_name: [module_path, dependencies, ...]". Will only be used in C++20 or C++23 mode. The dependencies are any files that the module depends on, and are only used to determine whether the module needs to be recompiled.
modules:
BS.thread_pool: [modules/BS.thread_pool.cppm, include/BS_thread_pool.hpp]
# The output folder for the compiled files.
output: build/
# A list of arguments to pass to the program if running it after compilation.
pass_args: []
-# A map of paths to the standard library modules for each OS and compiler combination (C++23 only). The OS should be one of [Darwin, Linux, Windows]. This is currently only officially supported by MSVC with Microsoft STL and LLVM Clang (NOT Apple Clang) with LLVM libc++. It is not supported by GCC with any standard library, or any compiler with GNU libstdc++. Use "auto" to determine the path automatically if possible.
+# A map of paths to the standard library modules for each OS and compiler combination (C++23 only). The OS should be one of [Darwin, Linux, Windows]. Use "auto" to determine the path automatically if possible.
std_module:
Darwin:
clang++: auto
Linux:
clang++: auto
+ g++: auto
Windows:
cl: auto
clang++: auto
+ g++: auto
diff --git a/include/BS_thread_pool.hpp b/include/BS_thread_pool.hpp
index e9bb7ce..e6a129f 100644
--- a/include/BS_thread_pool.hpp
+++ b/include/BS_thread_pool.hpp
@@ -7,9 +7,9 @@
*
* @file BS_thread_pool.hpp
* @author Barak Shoshany (baraksh@gmail.com) (https://baraksh.com/)
- * @version 5.0.0
- * @date 2024-12-19
- * @copyright Copyright (c) 2024 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.1016/j.softx.2024.101687, SoftwareX 26 (2024) 101687, arXiv:2105.00613
+ * @version 5.1.0
+ * @date 2026-01-03
+ * @copyright Copyright (c) 2021-2026 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.1016/j.softx.2024.101687, SoftwareX 26 (2024) 101687, arXiv:2105.00613
*
* @brief `BS::thread_pool`: a fast, lightweight, modern, and easy-to-use C++17/C++20/C++23 thread pool library. This header file contains the entire library, and is the only file needed to use the library.
*/
@@ -17,20 +17,58 @@
#ifndef BS_THREAD_POOL_HPP
#define BS_THREAD_POOL_HPP
-// We need to include since if we're using `import std` it will not define any feature-test macros, including `__cpp_lib_modules`, which we need to check if `import std` is supported in the first place.
+// We need to include since if we're using `import std` it will not define any feature-test macros.
#ifdef __has_include
#if __has_include()
#include // NOLINT(misc-include-cleaner)
#endif
#endif
-// If the macro `BS_THREAD_POOL_IMPORT_STD` is defined, import the C++ Standard Library as a module. Otherwise, include the relevant Standard Library header files. This is currently only officially supported by MSVC with Microsoft STL and LLVM Clang (NOT Apple Clang) with LLVM libc++. It is not supported by GCC with any standard library, or any compiler with GNU libstdc++. We also check that the feature is enabled by checking `__cpp_lib_modules`. However, MSVC defines this macro even in C++20 mode, which is not standards-compliant, so we check that we are in C++23 mode; MSVC currently reports `__cplusplus` as `202004L` for C++23 mode, so we use that value.
-#if defined(BS_THREAD_POOL_IMPORT_STD) && defined(__cpp_lib_modules) && (__cplusplus >= 202004L) && (defined(_MSC_VER) || (defined(__clang__) && defined(_LIBCPP_VERSION) && !defined(__apple_build_version__)))
+// At the time of this release, there is a bug in Clang with libc++ where using `std::jthread` in a C++20 module causes a compilation error. As a workaround, until the bug is fixed, the thread pool library automatically falls back to `std::thread` if it detects that Clang and libc++ are being used together with C++20 modules. This workaround can be disabled by defining `BS_THREAD_POOL_DISABLE_WORKAROUNDS` when compiling the module. TODO: Remove this workaround when the bug is fixed.
+#if defined(__clang__) && defined(_LIBCPP_VERSION) && defined(BS_THREAD_POOL_MODULE) && (__cplusplus >= 202002L) && !defined(BS_THREAD_POOL_DISABLE_WORKAROUNDS)
+ #ifdef __cpp_lib_jthread
+ #undef __cpp_lib_jthread
+ #endif
+#endif
+
+// At the time of this release, there is a bug when using GCC with libstdc++ on Windows via MSYS2 where the `BS.thread_pool` module doesn't compile if both native extensions and `import std` are enabled. As a workaround, until the bug is fixed, the thread pool library automatically falls back to header files if it detects that GCC and libstdc++ are being used together with the C++23 `std` module on Windows. This workaround can be disabled by defining `BS_THREAD_POOL_DISABLE_WORKAROUNDS` when compiling the module. TODO: Remove this workaround when the bug is fixed.
+#if (defined(__GNUC__) && defined(_GLIBCXX_RELEASE) && defined(_WIN32)) && !defined(BS_THREAD_POOL_DISABLE_WORKAROUNDS)
+ #ifdef BS_THREAD_POOL_IMPORT_STD
+ #undef BS_THREAD_POOL_IMPORT_STD
+ #endif
+#endif
+
+// In GCC with libstdc++ on Linux, loading the system headers after `import std` causes compilation errors, so we load them first.
+#ifdef BS_THREAD_POOL_NATIVE_EXTENSIONS
+ #if defined(_WIN32)
+ #ifndef WIN32_LEAN_AND_MEAN
+ #define WIN32_LEAN_AND_MEAN
+ #endif
+ #ifndef NOMINMAX
+ #define NOMINMAX
+ #endif
+ #include
+ #elif defined(__linux__) || defined(__APPLE__)
+ #include
+ #include
+ #include
+ #include
+ #if defined(__linux__)
+ #include
+ #include
+ #endif
+ #else
+ #undef BS_THREAD_POOL_NATIVE_EXTENSIONS
+ #endif
+#endif
+
+// If the macro `BS_THREAD_POOL_IMPORT_STD` is defined, import the C++ Standard Library as a module. Otherwise, include the relevant Standard Library header files.
+#if defined(BS_THREAD_POOL_IMPORT_STD) && (__cplusplus >= 202004L)
// Only allow importing the `std` module if the library itself is imported as a module. If the library is included as a header file, this will force the program that included the header file to also import `std`, which is not desirable and can lead to compilation errors if the program `#include`s any Standard Library header files.
#ifdef BS_THREAD_POOL_MODULE
import std;
#else
- #error "The thread pool library cannot import the C++ Standard Library as a module using `import std` if the library itself is not imported as a module. Either use `import BS.thread_pool` to import the libary, or remove the `BS_THREAD_POOL_IMPORT_STD` macro. Aborting compilation."
+ #error "The thread pool library cannot import the C++ Standard Library as a module using `import std` if the library itself is not imported as a module. Either use `import BS.thread_pool` to import the library, or remove the `BS_THREAD_POOL_IMPORT_STD` macro. Aborting compilation."
#endif
#else
#undef BS_THREAD_POOL_IMPORT_STD
@@ -69,41 +107,25 @@ import std;
#ifdef __cpp_lib_int_pow2
#include
#endif
- #ifdef __cpp_lib_semaphore
- #include
- #endif
#ifdef __cpp_lib_jthread
#include
#endif
#endif
-#ifdef BS_THREAD_POOL_NATIVE_EXTENSIONS
- #if defined(_WIN32)
- #include
- #undef min
- #undef max
- #elif defined(__linux__) || defined(__APPLE__)
- #include
- #include
- #include
- #include
- #if defined(__linux__)
- #include
- #include
- #endif
- #else
- #undef BS_THREAD_POOL_NATIVE_EXTENSIONS
- #endif
+// On Linux, defines macros called `major` and `minor`, which we undefine here to prevent conflicts.
+#ifdef major
+ #undef major
+#endif
+#ifdef minor
+ #undef minor
#endif
-#if defined(__linux__)
- // On Linux, defines macros called `major` and `minor`. We undefine them here so the `version` struct can work.
- #ifdef major
- #undef major
- #endif
- #ifdef minor
- #undef minor
- #endif
+// On Windows, defines macros called `min` and `max`, which we undefine here to prevent conflicts.
+#ifdef min
+ #undef min
+#endif
+#ifdef max
+ #undef max
#endif
/**
@@ -112,13 +134,13 @@ import std;
namespace BS {
// Macros indicating the version of the thread pool library.
#define BS_THREAD_POOL_VERSION_MAJOR 5
-#define BS_THREAD_POOL_VERSION_MINOR 0
+#define BS_THREAD_POOL_VERSION_MINOR 1
#define BS_THREAD_POOL_VERSION_PATCH 0
/**
* @brief A struct used to store a version number, which can be checked and compared at compilation time.
*/
-struct version
+struct [[nodiscard]] version
{
constexpr version(const std::uint64_t major_, const std::uint64_t minor_, const std::uint64_t patch_) noexcept : major(major_), minor(minor_), patch(patch_) {}
@@ -221,27 +243,126 @@ inline constexpr bool thread_pool_native_extensions = false;
*/
using opt_t = std::uint8_t;
-template
+/**
+ * @brief An enumeration class of flags to be used in the bitmask template parameter of `BS::thread_pool` to enable optional features.
+ */
+enum class tp : opt_t
+{
+ /**
+ * @brief No optional features enabled.
+ */
+ none = 0,
+
+ /**
+ * @brief Enable task priority.
+ */
+ priority = 1 << 0,
+
+ /**
+ * @brief Enable pausing.
+ */
+ pause = 1 << 1,
+
+ /**
+ * @brief Enable wait deadlock checks.
+ */
+ wait_deadlock_checks = 1 << 2
+};
+
+// NOLINTBEGIN(bugprone-macro-parentheses)
+#define BS_THREAD_POOL_DEFINE_BITWISE_OPERATOR(ENUM, OP) \
+ constexpr ENUM operator OP(const ENUM lhs, const ENUM rhs) noexcept \
+ { \
+ return static_cast(static_cast>(lhs) OP static_cast>(rhs)); \
+ } \
+ constexpr ENUM& operator OP##=(ENUM& lhs, const ENUM rhs) noexcept \
+ { \
+ return lhs = lhs OP rhs; \
+ }
+// NOLINTEND(bugprone-macro-parentheses)
+
+BS_THREAD_POOL_DEFINE_BITWISE_OPERATOR(tp, &)
+BS_THREAD_POOL_DEFINE_BITWISE_OPERATOR(tp, |)
+BS_THREAD_POOL_DEFINE_BITWISE_OPERATOR(tp, ^)
+
+constexpr tp operator~(const tp value) noexcept
+{
+ return static_cast(~static_cast>(value));
+}
+
+template
class thread_pool;
#ifdef __cpp_lib_move_only_function
/**
* @brief The template to use to store functions in the task queue and other places. In C++23 and later we use `std::move_only_function`.
*/
-template
-using function_t = std::move_only_function;
+using std::move_only_function;
#else
+template
+class move_only_function;
+
/**
- * @brief The template to use to store functions in the task queue and other places. In C++17 we use `std::function`.
+ * @brief A simple polyfill for `std::move_only_function`, to be used if C++23 features are not available. Note that it does not have all the features of `std::move_only_function`, only the minimum needed for the thread pool library.
+ *
+ * @tparam R The return type of the function.
+ * @tparam Args The argument types of the function.
*/
-template
-using function_t = std::function;
+template
+class move_only_function
+{
+public:
+ move_only_function() = default;
+ move_only_function(move_only_function&&) noexcept = default;
+ move_only_function& operator=(move_only_function&&) noexcept = default;
+ move_only_function(const move_only_function&) = delete;
+ move_only_function& operator=(const move_only_function&) = delete;
+ ~move_only_function() = default;
+
+ template , move_only_function> && std::is_invocable_r_v>>
+ move_only_function(F&& func) : ptr(std::make_unique>>(std::forward(func))) {} // NOLINT(hicpp-explicit-conversions)
+
+ R operator()(Args... args)
+ {
+ return ptr->call(std::forward(args)...);
+ }
+
+private:
+ struct func_concept
+ {
+ virtual ~func_concept() = default;
+ virtual R call(Args... args) = 0;
+ };
+
+ template
+ struct func_model final : func_concept
+ {
+ template , func_model>>>
+ explicit func_model(T&& func) : stored_func(std::forward(func)) {}
+
+ R call(Args... args) override
+ {
+ if constexpr (std::is_void_v)
+ {
+ std::invoke(stored_func, std::forward(args)...);
+ }
+ else
+ {
+ return std::invoke(stored_func, std::forward(args)...);
+ }
+ }
+
+ F stored_func;
+ };
+
+ std::unique_ptr ptr = nullptr;
+};
#endif
/**
* @brief The type of tasks in the task queue.
*/
-using task_t = function_t;
+using task_t = move_only_function;
#ifdef __cpp_lib_jthread
/**
@@ -255,7 +376,7 @@ using thread_t = std::jthread;
#define BS_THREAD_POOL_OR_STOP_CONDITION
#else
/**
- * @brief The type of threads to use. In C++17 we use`std::thread`.
+ * @brief The type of threads to use. In C++17 we use `std::thread`.
*/
using thread_t = std::thread;
// The following macros are used to determine how to stop the workers. In C++17 we use a manual flag `workers_running`.
@@ -273,7 +394,7 @@ using priority_t = std::int8_t;
/**
* @brief An enum containing some pre-defined priorities for convenience.
*/
-enum pr : priority_t
+enum pr : priority_t // NOLINT(cppcoreguidelines-use-enum-class) This cannot be an `enum class` because we need the numerical values.
{
lowest = -128,
low = -64,
@@ -308,9 +429,9 @@ struct [[nodiscard]] pr_task
}
/**
- * @brief The task.
+ * @brief The task. It is `mutable` so it can be moved out of the `const` reference returned by `std::priority_queue::top()`.
*/
- task_t task;
+ mutable task_t task;
/**
* @brief The priority of the task.
@@ -437,7 +558,7 @@ public:
for (const std::future& future : *this)
{
future.wait_until(timeout_time);
- if (timeout_time < std::chrono::steady_clock::now())
+ if (timeout_time < C::now())
return false;
}
return true;
@@ -460,7 +581,7 @@ public:
* @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 T first_index_, const T index_after_last_, const std::size_t num_blocks_) noexcept : first_index(first_index_), index_after_last(index_after_last_), num_blocks(num_blocks_)
+ blocks(const T first_index_, const T index_after_last_, const std::size_t num_blocks_) noexcept : num_blocks(num_blocks_), first_index(first_index_), index_after_last(index_after_last_)
{
if (index_after_last > first_index)
{
@@ -518,16 +639,6 @@ private:
*/
std::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.
*/
@@ -537,13 +648,130 @@ private:
* @brief The remainder obtained after dividing the total size by the number of blocks.
*/
std::size_t remainder = 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;
}; // class blocks
+/**
+ * @brief A function object class used by `detach_blocks()` and `submit_blocks()` to execute a block function over a specified range of indices.
+ *
+ * @tparam T The type of the indices.
+ * @tparam F The type of the function.
+ * @tparam R The return type of the function (can be `void`).
+ */
+template
+struct block_task
+{
+ R operator()()
+ {
+ return (*block_ptr)(start, end);
+ }
+
+ std::shared_ptr> block_ptr;
+ T start;
+ T end;
+}; // struct block_task
+
+/**
+ * @brief A function object class used by `detach_loop()` and `submit_loop()` to execute a loop function over a specified range of indices.
+ *
+ * @tparam T The type of the indices.
+ * @tparam F The type of the function.
+ */
+template
+struct loop_task
+{
+ void operator()()
+ {
+ for (T i = start; i < end; ++i)
+ (*loop_ptr)(i);
+ }
+
+ std::shared_ptr> loop_ptr;
+ T start;
+ T end;
+}; // struct loop_task
+
+/**
+ * @brief A function object class used by `detach_sequence()` and `submit_sequence()` to execute a sequence function over a specified index.
+ *
+ * @tparam T The type of the index.
+ * @tparam F The type of the function.
+ * @tparam R The return type of the function (can be `void`).
+ */
+template
+struct sequence_task
+{
+ R operator()()
+ {
+ return (*sequence_ptr)(i);
+ }
+
+ std::shared_ptr> sequence_ptr;
+ T i;
+}; // struct sequence_task
+
+/**
+ * @brief A class that takes a function with a return value (but no arguments), and constructs a task with no return value along with a future used to retrieve the function's return value once the task is executed. Used by `submit_task()` and `submit_bulk()`.
+ *
+ * @tparam R The return type of the function (can be `void`).
+ */
+template
+struct task_and_future
+{
+ template , task_and_future>>>
+ explicit task_and_future(F&& func)
+ {
+ std::promise promise;
+ future = promise.get_future();
+ task = [task = std::forward(func), promise = std::move(promise)]() mutable
+ {
+#ifdef __cpp_exceptions
+ try
+ {
+#endif
+ if constexpr (std::is_void_v)
+ {
+ task();
+ promise.set_value();
+ }
+ else
+ {
+ promise.set_value(task());
+ }
+#ifdef __cpp_exceptions
+ }
+ catch (...)
+ {
+ try
+ {
+ promise.set_exception(std::current_exception());
+ }
+ catch (...)
+ {
+ }
+ }
+#endif
+ };
+ }
+
+ std::future future;
+ task_t task;
+}; // struct task_and_future
+
#ifdef __cpp_exceptions
/**
- * @brief An exception that will be thrown by `wait()`, `wait_for()`, and `wait_until()` if the user tries to call them from within a thread of the same pool, which would result in a deadlock. Only used if the flag `BS:tp::wait_deadlock_checks` is enabled in the template parameter of `BS::thread_pool`.
+ * @brief An exception that will be thrown by `wait()`, `wait_for()`, and `wait_until()` if the user tries to call them from within a thread of the same pool, which would result in a deadlock. Only used if the flag `BS::tp::wait_deadlock_checks` is enabled in the template parameter of `BS::thread_pool`.
*/
-struct wait_deadlock : public std::runtime_error
+struct [[nodiscard]] wait_deadlock : public std::runtime_error
{
wait_deadlock() : std::runtime_error("BS::wait_deadlock") {};
};
@@ -656,7 +884,7 @@ enum class os_thread_priority
* @param affinity The processor affinity to set, as an `std::vector` where each element corresponds to a logical processor.
* @return `true` if the affinity was set successfully, `false` otherwise. On macOS, this function always returns `false`.
*/
-inline bool set_os_process_affinity(const std::vector& affinity)
+inline bool set_os_process_affinity([[maybe_unused]] const std::vector& affinity)
{
#if defined(_WIN32)
DWORD_PTR process_mask = 0;
@@ -673,7 +901,7 @@ inline bool set_os_process_affinity(const std::vector& affinity)
}
return sched_setaffinity(getpid(), sizeof(cpu_set_t), &cpu_set) == 0;
#elif defined(__APPLE__)
- return affinity[0] && false; // NOLINT(readability-simplify-boolean-expr) // Using `affinity` to suppress unused parameter warning.
+ return false;
#endif
}
@@ -733,11 +961,11 @@ inline bool set_os_process_priority(const os_process_priority priority)
#endif
/**
- * @brief A class used to obtain information about the current thread and, if native extensions are enabled, set its priority and affinity.
+ * @brief A class used to obtain information about the current thread and, if native extensions are enabled, get/set its priority, affinity, or name.
*/
class [[nodiscard]] this_thread
{
- template
+ template
friend class thread_pool;
public:
@@ -763,9 +991,9 @@ public:
#ifdef BS_THREAD_POOL_NATIVE_EXTENSIONS
/**
- * @brief Get the processor affinity of the current thread using the current platform's native API. This should work on Windows and Linux, but is not possible on macOS as the native API does not allow it.
+ * @brief Get the processor affinity of the current thread using the current platform's native API. This should work on Windows and Linux, but is not possible on macOS and Android as the native API does not allow it.
*
- * @return An `std::optional` object, optionally containing the processor affinity of the current thread as an `std::vector` where each element corresponds to a logical processor. If the returned object does not contain a value, then the affinity could not be determined. On macOS, this function always returns `std::nullopt`.
+ * @return An `std::optional` object, optionally containing the processor affinity of the current thread as an `std::vector` where each element corresponds to a logical processor. If the returned object does not contain a value, then the affinity could not be determined. On macOS and Android, this function always returns `std::nullopt`.
*/
[[nodiscard]] static std::optional> get_os_thread_affinity()
{
@@ -794,7 +1022,7 @@ public:
for (std::size_t i = 0; i < num_cpus; ++i)
affinity[i] = ((previous_mask & (1ULL << i)) != 0ULL);
return affinity;
- #elif defined(__linux__)
+ #elif defined(__linux__) && !defined(__ANDROID__)
cpu_set_t cpu_set;
CPU_ZERO(&cpu_set);
if (pthread_getaffinity_np(pthread_self(), sizeof(cpu_set_t), &cpu_set) != 0)
@@ -806,25 +1034,25 @@ public:
for (std::size_t i = 0; i < affinity.size(); ++i)
affinity[i] = CPU_ISSET(i, &cpu_set);
return affinity;
- #elif defined(__APPLE__)
+ #else
return std::nullopt;
#endif
}
/**
- * @brief Set the processor affinity of the current thread using the current platform's native API. This should work on Windows and Linux, but is not possible on macOS as the native API does not allow it. Note that the thread affinity must be a subset of the process affinity (as obtained using `BS::get_os_process_affinity()`) for the containing process of a thread.
+ * @brief Set the processor affinity of the current thread using the current platform's native API. This should work on Windows and Linux, but is not possible on macOS and Android as the native API does not allow it. Note that the thread affinity must be a subset of the process affinity (as obtained using `BS::get_os_process_affinity()`) for the containing process of a thread.
*
* @param affinity The processor affinity to set, as an `std::vector` where each element corresponds to a logical processor.
- * @return `true` if the affinity was set successfully, `false` otherwise. On macOS, this function always returns `false`.
+ * @return `true` if the affinity was set successfully, `false` otherwise. On macOS and Android, this function always returns `false`.
*/
- static bool set_os_thread_affinity(const std::vector& affinity)
+ static bool set_os_thread_affinity([[maybe_unused]] const std::vector& affinity)
{
#if defined(_WIN32)
DWORD_PTR thread_mask = 0;
for (std::size_t i = 0; i < std::min(affinity.size(), sizeof(DWORD_PTR) * 8); ++i)
thread_mask |= (affinity[i] ? (1ULL << i) : 0ULL);
return SetThreadAffinityMask(GetCurrentThread(), thread_mask) != 0;
- #elif defined(__linux__)
+ #elif defined(__linux__) && !defined(__ANDROID__)
cpu_set_t cpu_set;
CPU_ZERO(&cpu_set);
for (std::size_t i = 0; i < std::min(affinity.size(), CPU_SETSIZE); ++i)
@@ -833,8 +1061,8 @@ public:
CPU_SET(i, &cpu_set);
}
return pthread_setaffinity_np(pthread_self(), sizeof(cpu_set_t), &cpu_set) == 0;
- #elif defined(__APPLE__)
- return affinity[0] && false; // NOLINT(readability-simplify-boolean-expr) // Using `affinity` to suppress unused parameter warning.
+ #else
+ return false;
#endif
}
@@ -931,7 +1159,7 @@ public:
// The only pre-defined priority that uses SCHED_FIFO and the maximum available priority value is the "realtime" priority.
return os_thread_priority::realtime;
}
- if (policy == SCHED_RR && param.sched_priority == sched_get_priority_min(SCHED_RR) + (sched_get_priority_max(SCHED_RR) - sched_get_priority_min(SCHED_RR)) / 2)
+ if (policy == SCHED_RR && param.sched_priority == sched_get_priority_min(SCHED_RR) + ((sched_get_priority_max(SCHED_RR) - sched_get_priority_min(SCHED_RR)) / 2))
{
// The only pre-defined priority that uses SCHED_RR and a priority in the middle of the available range is the "highest" priority.
return os_thread_priority::highest;
@@ -1028,7 +1256,7 @@ public:
case os_thread_priority::highest:
// "Highest" pre-defined priority: We use the policy `SCHED_RR` ("round-robin") with a priority in the middle of the available range.
policy = SCHED_RR;
- param.sched_priority = sched_get_priority_min(SCHED_RR) + (sched_get_priority_max(SCHED_RR) - sched_get_priority_min(SCHED_RR)) / 2;
+ param.sched_priority = sched_get_priority_min(SCHED_RR) + ((sched_get_priority_max(SCHED_RR) - sched_get_priority_min(SCHED_RR)) / 2);
break;
case os_thread_priority::above_normal:
// "Above normal" pre-defined priority: We use the policy `SCHED_OTHER` (the default). This policy does not accept a priority value, so priority must be 0. However, we set the "nice" value to the minimum value as given by `PRIO_MIN`, plus 2 (which should evaluate to -18). The usual range is -20 to 19 or 20, with higher values corresponding to lower priorities.
@@ -1171,32 +1399,6 @@ struct common_index_type && std::
template
using common_index_type_t = typename common_index_type::type;
-/**
- * @brief An enumeration of flags to be used in the bitmask template parameter of `BS::thread_pool` to enable optional features.
- */
-enum tp : opt_t
-{
- /**
- * @brief No optional features enabled.
- */
- none = 0,
-
- /**
- * @brief Enable task priority.
- */
- priority = 1 << 0,
-
- /**
- * @brief Enable pausing.
- */
- pause = 1 << 2,
-
- /**
- * @brief Enable wait deadlock checks.
- */
- wait_deadlock_checks = 1 << 3
-};
-
/**
* @brief A fast, lightweight, modern, and easy-to-use C++17/C++20/C++23 thread pool class. This alias defines a thread pool with all optional features disabled.
*/
@@ -1222,24 +1424,24 @@ using wdc_thread_pool = thread_pool;
*
* @tparam OptFlags A bitmask of flags which can be used to enable optional features. The flags are members of the `BS::tp` enumeration: `BS::tp::priority`, `BS::tp::pause`, and `BS::tp::wait_deadlock_checks`. The default is `BS::tp::none`, which disables all optional features. To enable multiple features, use the bitwise OR operator `|`, e.g. `BS::tp::priority | BS::tp::pause`.
*/
-template
+template
class [[nodiscard]] thread_pool
{
public:
/**
* @brief A flag indicating whether task priority is enabled.
*/
- static constexpr bool priority_enabled = (OptFlags & tp::priority) != 0;
+ static constexpr bool priority_enabled = (OptFlags & tp::priority) != tp::none;
/**
* @brief A flag indicating whether pausing is enabled.
*/
- static constexpr bool pause_enabled = (OptFlags & tp::pause) != 0;
+ static constexpr bool pause_enabled = (OptFlags & tp::pause) != tp::none;
/**
* @brief A flag indicating whether wait deadlock checks are enabled.
*/
- static constexpr bool wait_deadlock_checks_enabled = (OptFlags & tp::wait_deadlock_checks) != 0;
+ static constexpr bool wait_deadlock_checks_enabled = (OptFlags & tp::wait_deadlock_checks) != tp::none;
#ifndef __cpp_exceptions
static_assert(!wait_deadlock_checks_enabled, "Wait deadlock checks cannot be enabled if exception handling is disabled.");
@@ -1250,7 +1452,7 @@ public:
// ============================
/**
- * @brief Construct a new thread pool. The number of threads will be 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.
+ * @brief Construct a new thread pool. The number of threads will be 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. If the native extensions are enabled, the pool will instead use the number of threads available to the process, as obtained from `BS::get_os_process_affinity()`, which can be less than the number of hardware threads.
*/
thread_pool() : thread_pool(0, [] {}) {}
@@ -1262,14 +1464,12 @@ public:
explicit thread_pool(const std::size_t num_threads) : thread_pool(num_threads, [] {}) {}
/**
- * @brief Construct a new thread pool with the specified initialization function.
+ * @brief Construct a new thread pool with the specified initialization function and the default number of threads.
*
* @param init An initialization function to run in each thread before it starts executing any submitted tasks. The function must have no return value, and can either take one argument, the thread index of type `std::size_t`, or zero arguments. It will be executed exactly once per thread, when the thread is first constructed. The initialization function must not throw any exceptions, as that will result in program termination. Any exceptions must be handled explicitly within the function.
*/
template
- explicit thread_pool(F&& init) : thread_pool(0, std::forward(init))
- {
- }
+ explicit thread_pool(F&& init) : thread_pool(0, std::forward(init)) {}
/**
* @brief Construct a new thread pool with the specified number of threads and initialization function.
@@ -1315,66 +1515,87 @@ public:
// =======================
/**
- * @brief Parallelize a loop by automatically splitting it into blocks and submitting each block separately to the queue, with the specified priority. The block function takes two arguments, the start and end of the block, so that it is only called once per block, but it is up to the user make sure the block function correctly deals with all the indices in each block. Does not return a `BS::multi_future`, so the user must use `wait()` or some other method to ensure that the loop finishes executing, otherwise bad things will happen.
+ * @brief Parallelize a loop by automatically splitting it into blocks and submitting each block separately to the queue, with the specified priority. The block function takes two arguments, the start and end of the block, so that it is only called once per block, but it is up to the user to make sure the block function correctly deals with all the indices in each block. Does not return a `BS::multi_future`, so the user must use `wait()` or some other method to ensure that the loop finishes executing, otherwise bad things will happen.
*
* @tparam T1 The type of the first index. Should be a signed or unsigned integer.
* @tparam T2 The type of the index after the last index. Should be a signed or unsigned integer.
- * @tparam F The type of the function to loop through.
+ * @tparam T The common type of the indices, as determined by `BS::common_index_type_t`.
+ * @tparam F The type of the block function.
* @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 block A function that 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. `block(start, end)` should typically involve a loop of the form `for (T i = start; i < end; ++i)`.
+ * @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 tasks will be submitted.
+ * @param block A function that 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. `block(start, end)` should typically involve a loop of the form `for (T i = start; i < end; ++i)`. Must not return a value.
* @param num_blocks The maximum number of blocks to split the loop into. The default is 0, which means the number of blocks will be equal to the number of threads in the pool.
- * @param priority The priority of the tasks. Should be between -128 and +127 (a signed 8-bit integer). The default is 0. Only taken into account if the flag `BS:tp::priority` is enabled in the template parameter, otherwise has no effect.
+ * @param priority The priority of the tasks. Should be between -128 and +127 (a signed 8-bit integer). The default is 0. Only taken into account if the flag `BS::tp::priority` is enabled in the template parameter, otherwise has no effect.
*/
template , typename F>
void detach_blocks(const T1 first_index, const T2 index_after_last, F&& block, const std::size_t num_blocks = 0, const priority_t priority = 0)
{
- if (static_cast(index_after_last) > static_cast(first_index))
+ enqueue_blocks(static_cast(first_index), static_cast(index_after_last), std::forward(block), num_blocks, priority);
+ }
+
+ /**
+ * @brief Submit an iterator range containing functions with no arguments and no return values into the task queue, with the specified priority. To submit functions with arguments, enclose them in lambda expressions. Does not return a `BS::multi_future`, so the user must use `wait()` or some other method to ensure that the loop finishes executing, otherwise bad things will happen.
+ *
+ * @tparam I The type of the iterators.
+ * @param first An iterator to the first function.
+ * @param last An iterator to one past the last function.
+ * @param priority The priority of the tasks. Should be between -128 and +127 (a signed 8-bit integer). The default is 0. Only taken into account if the flag `BS::tp::priority` is enabled in the template parameter, otherwise has no effect.
+ */
+ template
+ void detach_bulk(const I first, const I last, const priority_t priority = 0)
+ {
+ if (first != last)
{
- const std::shared_ptr> block_ptr = std::make_shared>(std::forward(block));
- const blocks blks(static_cast(first_index), static_cast(index_after_last), num_blocks ? num_blocks : thread_count);
- for (std::size_t blk = 0; blk < blks.get_num_blocks(); ++blk)
+ bool notify = false;
{
- detach_task(
- [block_ptr, start = blks.start(blk), end = blks.end(blk)]
- {
- (*block_ptr)(start, end);
- },
- priority);
+ const std::scoped_lock tasks_lock(tasks_mutex);
+ if constexpr (pause_enabled)
+ notify = tasks.empty() && !paused;
+ else
+ notify = tasks.empty();
+ for (I it = first; it != last; ++it)
+ {
+ if constexpr (priority_enabled)
+ tasks.emplace(std::move(*it), priority);
+ else
+ tasks.emplace(std::move(*it));
+ }
}
+ if (notify)
+ task_available_cv.notify_all();
}
}
/**
- * @brief Parallelize a loop by automatically splitting it into blocks and submitting each block separately to the queue, with the specified priority. The loop function takes one argument, the loop index, so that it is called many times per block. Does not return a `BS::multi_future`, so the user must use `wait()` or some other method to ensure that the loop finishes executing, otherwise bad things will happen.
+ * @brief Submit a container of functions with no arguments and no return values into the task queue, with the specified priority. To submit functions with arguments, enclose them in lambda expressions. Does not return a `BS::multi_future`, so the user must use `wait()` or some other method to ensure that the loop finishes executing, otherwise bad things will happen.
+ *
+ * @tparam C The type of the container. Must either be an array or have `begin()` and `end()` member functions.
+ * @param container The container.
+ * @param priority The priority of the tasks. Should be between -128 and +127 (a signed 8-bit integer). The default is 0. Only taken into account if the flag `BS::tp::priority` is enabled in the template parameter, otherwise has no effect.
+ */
+ template
+ void detach_bulk(C& container, const priority_t priority = 0)
+ {
+ detach_bulk(std::begin(container), std::end(container), priority);
+ }
+
+ /**
+ * @brief Parallelize a loop by automatically splitting it into blocks and submitting each block separately to the queue, with the specified priority. The loop function takes one argument, the loop index, and it is called exactly once per index, but many times per block. Does not return a `BS::multi_future`, so the user must use `wait()` or some other method to ensure that the loop finishes executing, otherwise bad things will happen.
*
* @tparam T1 The type of the first index. Should be a signed or unsigned integer.
* @tparam T2 The type of the index after the last index. Should be a signed or unsigned integer.
- * @tparam F The type of the function to loop through.
+ * @tparam T The common type of the indices, as determined by `BS::common_index_type_t`.
+ * @tparam F The type of the loop function.
* @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 index, many times per block. Should take exactly one argument: the loop index.
+ * @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 tasks will be submitted.
+ * @param loop A function that will be called once per index, many times per block. Should take exactly one argument: the loop index. Must not return a value.
* @param num_blocks The maximum number of blocks to split the loop into. The default is 0, which means the number of blocks will be equal to the number of threads in the pool.
- * @param priority The priority of the tasks. Should be between -128 and +127 (a signed 8-bit integer). The default is 0. Only taken into account if the flag `BS:tp::priority` is enabled in the template parameter, otherwise has no effect.
+ * @param priority The priority of the tasks. Should be between -128 and +127 (a signed 8-bit integer). The default is 0. Only taken into account if the flag `BS::tp::priority` is enabled in the template parameter, otherwise has no effect.
*/
template , typename F>
void detach_loop(const T1 first_index, const T2 index_after_last, F&& loop, const std::size_t num_blocks = 0, const priority_t priority = 0)
{
- if (static_cast(index_after_last) > static_cast(first_index))
- {
- const std::shared_ptr> loop_ptr = std::make_shared>(std::forward(loop));
- const blocks blks(static_cast(first_index), static_cast(index_after_last), num_blocks ? num_blocks : thread_count);
- for (std::size_t blk = 0; blk < blks.get_num_blocks(); ++blk)
- {
- detach_task(
- [loop_ptr, start = blks.start(blk), end = blks.end(blk)]
- {
- for (T i = start; i < end; ++i)
- (*loop_ptr)(i);
- },
- priority);
- }
- }
+ enqueue_loop(static_cast(first_index), static_cast(index_after_last), std::forward(loop), num_blocks, priority);
}
/**
@@ -1382,28 +1603,17 @@ public:
*
* @tparam T1 The type of the first index. Should be a signed or unsigned integer.
* @tparam T2 The type of the index after the last index. Should be a signed or unsigned integer.
- * @tparam F The type of the function used to define the sequence.
+ * @tparam T The common type of the indices, as determined by `BS::common_index_type_t`.
+ * @tparam F The type of the sequence function.
* @param first_index The first index in the sequence.
* @param index_after_last The index after the last index in the sequence. The sequence 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 tasks will be submitted.
- * @param sequence The function used to define the sequence. Will be called once per index. Should take exactly one argument, the index.
- * @param priority The priority of the tasks. Should be between -128 and +127 (a signed 8-bit integer). The default is 0. Only taken into account if the flag `BS:tp::priority` is enabled in the template parameter, otherwise has no effect.
+ * @param sequence A function that will be called once per index. Should take exactly one argument, the index. Must not return a value.
+ * @param priority The priority of the tasks. Should be between -128 and +127 (a signed 8-bit integer). The default is 0. Only taken into account if the flag `BS::tp::priority` is enabled in the template parameter, otherwise has no effect.
*/
template , typename F>
void detach_sequence(const T1 first_index, const T2 index_after_last, F&& sequence, const priority_t priority = 0)
{
- if (static_cast(index_after_last) > static_cast(first_index))
- {
- const std::shared_ptr> sequence_ptr = std::make_shared>(std::forward(sequence));
- for (T i = static_cast(first_index); i < static_cast(index_after_last); ++i)
- {
- detach_task(
- [sequence_ptr, i]
- {
- (*sequence_ptr)(i);
- },
- priority);
- }
- }
+ return enqueue_sequence(static_cast(first_index), static_cast(index_after_last), std::forward(sequence), priority);
}
/**
@@ -1411,7 +1621,7 @@ public:
*
* @tparam F The type of the function.
* @param task The function to submit.
- * @param priority The priority of the task. Should be between -128 and +127 (a signed 8-bit integer). The default is 0. Only taken into account if the flag `BS:tp::priority` is enabled in the template parameter, otherwise has no effect.
+ * @param priority The priority of the task. Should be between -128 and +127 (a signed 8-bit integer). The default is 0. Only taken into account if the flag `BS::tp::priority` is enabled in the template parameter, otherwise has no effect.
*/
template
void detach_task(F&& task, const priority_t priority = 0)
@@ -1498,7 +1708,7 @@ public:
}
/**
- * @brief Check whether the pool is currently paused. Only enabled if the flag `BS:tp::pause` is enabled in the template parameter.
+ * @brief Check whether the pool is currently paused. Only enabled if the flag `BS::tp::pause` is enabled in the template parameter.
*
* @return `true` if the pool is paused, `false` if it is not paused.
*/
@@ -1510,7 +1720,7 @@ public:
}
/**
- * @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. Only enabled if the flag `BS:tp::pause` is enabled in the template parameter.
+ * @brief Pause the pool. The workers will temporarily stop retrieving new tasks out of the queue, although any tasks already executing will keep running until they are finished. Only enabled if the flag `BS::tp::pause` is enabled in the template parameter.
*/
BS_THREAD_POOL_IF_PAUSE_ENABLED
void pause()
@@ -1529,7 +1739,7 @@ public:
}
/**
- * @brief Reset the pool with the total number of hardware threads available, as reported by the implementation. 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.
+ * @brief Reset the pool with the default number of threads (as if constructed with the default constructor). Waits for all tasks to be completed, both running and queued, then destroys the thread pool and creates a new one with an empty task queue. If pausing is enabled, only waits for tasks that are currently running before destroying the pool; once the pool is reset, it will then resume executing the tasks that remained in the queue and any newly submitted tasks. If the pool was paused before resetting it, the new pool will be paused as well.
*/
void reset()
{
@@ -1537,7 +1747,7 @@ public:
}
/**
- * @brief Reset the pool with a new number of threads. 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.
+ * @brief Reset the pool with a new number of threads. Waits for all tasks to be completed, both running and queued, then destroys the thread pool and creates a new one with an empty task queue. If pausing is enabled, only waits for tasks that are currently running before destroying the pool; once the pool is reset, it will then resume executing the tasks that remained in the queue and any newly submitted tasks. If the pool was paused before resetting it, the new pool will be paused as well.
*
* @param num_threads The number of threads to use.
*/
@@ -1547,7 +1757,7 @@ public:
}
/**
- * @brief Reset the pool with the total number of hardware threads available, as reported by the implementation, and a new initialization function. 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 and initialization function. 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.
+ * @brief Reset the pool with the default number of threads and a new initialization function. Waits for all tasks to be completed, both running and queued, then destroys the thread pool and creates a new one with an empty task queue. If pausing is enabled, only waits for tasks that are currently running before destroying the pool; once the pool is reset, it will then resume executing the tasks that remained in the queue and any newly submitted tasks. If the pool was paused before resetting it, the new pool will be paused as well.
*
* @param init An initialization function to run in each thread before it starts executing any submitted tasks. The function must have no return value, and can either take one argument, the thread index of type `std::size_t`, or zero arguments. It will be executed exactly once per thread, when the thread is first constructed. The initialization function must not throw any exceptions, as that will result in program termination. Any exceptions must be handled explicitly within the function.
*/
@@ -1558,7 +1768,7 @@ public:
}
/**
- * @brief Reset the pool with a new number of threads and a new initialization function. 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 and initialization function. 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.
+ * @brief Reset the pool with a new number of threads and a new initialization function. Waits for all tasks to be completed, both running and queued, then destroys the thread pool and creates a new one with an empty task queue. If pausing is enabled, only waits for tasks that are currently running before destroying the pool; once the pool is reset, it will then resume executing the tasks that remained in the queue and any newly submitted tasks. If the pool was paused before resetting it, the new pool will be paused as well.
*
* @param num_threads The number of threads to use.
* @param init An initialization function to run in each thread before it starts executing any submitted tasks. The function must have no return value, and can either take one argument, the thread index of type `std::size_t`, or zero arguments. It will be executed exactly once per thread, when the thread is first constructed. The initialization function must not throw any exceptions, as that will result in program termination. Any exceptions must be handled explicitly within the function.
@@ -1575,6 +1785,9 @@ public:
reset_pool(num_threads, std::forward(init));
tasks_lock.lock();
paused = was_paused;
+ tasks_lock.unlock();
+ if (!was_paused)
+ task_available_cv.notify_all();
}
else
{
@@ -1604,112 +1817,113 @@ public:
}
/**
- * @brief Parallelize a loop by automatically splitting it into blocks and submitting each block separately to the queue, with the specified priority. The block function takes two arguments, the start and end of the block, so that it is only called once per block, but it is up to the user make sure the block function correctly deals with all the indices in each block. Returns a `BS::multi_future` that contains the futures for all of the blocks.
+ * @brief Parallelize a loop by automatically splitting it into blocks and submitting each block separately to the queue, with the specified priority. The block function takes two arguments, the start and end of the block, so that it is only called once per block, but it is up to the user to make sure the block function correctly deals with all the indices in each block. If the block function has a return value, get a `BS::multi_future` for the eventual returned values. If the block function has no return value, get a `BS::multi_future` which can be used to wait until all the tasks finish.
*
* @tparam T1 The type of the first index. Should be a signed or unsigned integer.
* @tparam T2 The type of the index after the last index. Should be a signed or unsigned integer.
- * @tparam F The type of the function to loop through.
- * @tparam R The return type of the function to loop through (can be `void`).
+ * @tparam T The common type of the indices, as determined by `BS::common_index_type_t`.
+ * @tparam F The type of the block function.
+ * @tparam R The return type of the block function (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, and an empty `BS::multi_future` will be returned.
- * @param block A function that 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. `block(start, end)` should typically involve a loop of the form `for (T i = start; i < end; ++i)`.
+ * @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 tasks will be submitted, and an empty `BS::multi_future` will be returned.
+ * @param block A function that 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. `block(start, end)` should typically involve a loop of the form `for (T i = start; i < end; ++i)`. Can return a value.
* @param num_blocks The maximum number of blocks to split the loop into. The default is 0, which means the number of blocks will be equal to the number of threads in the pool.
- * @param priority The priority of the tasks. Should be between -128 and +127 (a signed 8-bit integer). The default is 0. Only taken into account if the flag `BS:tp::priority` is enabled in the template parameter, otherwise has no effect.
- * @return A `BS::multi_future` that can be used to wait for all the blocks to finish. If the block function returns a value, the `BS::multi_future` can also be used to obtain the values returned by each block.
+ * @param priority The priority of the tasks. Should be between -128 and +127 (a signed 8-bit integer). The default is 0. Only taken into account if the flag `BS::tp::priority` is enabled in the template parameter, otherwise has no effect.
+ * @return A `BS::multi_future` that can be used to wait for all the tasks to finish. If the block function returns a value, the `BS::multi_future` can also be used to obtain the values returned by each block.
*/
template , typename F, typename R = std::invoke_result_t, T, T>>
[[nodiscard]] multi_future submit_blocks(const T1 first_index, const T2 index_after_last, F&& block, const std::size_t num_blocks = 0, const priority_t priority = 0)
{
- if (static_cast(index_after_last) > static_cast(first_index))
+ return enqueue_blocks(static_cast(first_index), static_cast(index_after_last), std::forward(block), num_blocks, priority);
+ }
+
+ /**
+ * @brief Submit an iterator range containing functions with no arguments into the task queue, with the specified priority. To submit functions with arguments, enclose them in lambda expressions. If the functions have return values, get a `BS::multi_future` for the eventual returned values. If the functions have no return values, get a `BS::multi_future` which can be used to wait until all the tasks finish.
+ *
+ * @tparam I The type of the iterators.
+ * @tparam F The type of the functions.
+ * @tparam R The return type of the functions (can be `void`, but must be the same for all the functions).
+ * @param first An iterator to the first function.
+ * @param last An iterator to one past the last function.
+ * @param priority The priority of the tasks. Should be between -128 and +127 (a signed 8-bit integer). The default is 0. Only taken into account if the flag `BS::tp::priority` is enabled in the template parameter, otherwise has no effect.
+ * @return A `BS::multi_future` that can be used to wait for all the tasks to finish. If the functions return values, the `BS::multi_future` can also be used to obtain the values returned by each task.
+ */
+ template ()), typename R = std::invoke_result_t>>
+ [[nodiscard]] multi_future submit_bulk(const I first, const I last, const priority_t priority = 0)
+ {
+ if (first != last)
{
- const std::shared_ptr> block_ptr = std::make_shared>(std::forward(block));
- const blocks blks(static_cast(first_index), static_cast(index_after_last), num_blocks ? num_blocks : thread_count);
- multi_future future;
- future.reserve(blks.get_num_blocks());
- for (std::size_t blk = 0; blk < blks.get_num_blocks(); ++blk)
+ const std::size_t num_tasks = static_cast(std::distance(first, last));
+ multi_future all_futures;
+ all_futures.reserve(num_tasks);
+ std::vector all_tasks;
+ all_tasks.reserve(num_tasks);
+ for (I it = first; it != last; ++it)
{
- future.push_back(submit_task(
- [block_ptr, start = blks.start(blk), end = blks.end(blk)]
- {
- return (*block_ptr)(start, end);
- },
- priority));
+ task_and_future ft(std::move(*it));
+ all_futures.emplace_back(std::move(ft.future));
+ all_tasks.emplace_back(std::move(ft.task));
}
- return future;
+ detach_bulk(all_tasks, priority);
+ return all_futures;
}
return {};
}
/**
- * @brief Parallelize a loop by automatically splitting it into blocks and submitting each block separately to the queue, with the specified priority. The loop function takes one argument, the loop index, so that it is called many times per block. It must have no return value. Returns a `BS::multi_future` that contains the futures for all of the blocks.
+ * @brief Submit a container of functions with no arguments into the task queue, with the specified priority. To submit functions with arguments, enclose them in lambda expressions. If the functions have return values, get a `BS::multi_future` for the eventual returned values. If the functions have no return values, get a `BS::multi_future` which can be used to wait until all the tasks finish.
+ *
+ * @tparam C The type of the container. Must either be an array or have `begin()` and `end()` member functions.
+ * @tparam F The type of the functions.
+ * @tparam R The return type of the functions (can be `void`, but must be the same for all the functions).
+ * @param container The container.
+ * @param priority The priority of the tasks. Should be between -128 and +127 (a signed 8-bit integer). The default is 0. Only taken into account if the flag `BS::tp::priority` is enabled in the template parameter, otherwise has no effect.
+ * @return A `BS::multi_future` that can be used to wait for all the tasks to finish. If the functions return values, the `BS::multi_future` can also be used to obtain the values returned by each task.
+ */
+ template ().begin()), typename R = std::invoke_result_t>>
+ [[nodiscard]] multi_future submit_bulk(C& container, const priority_t priority = 0)
+ {
+ return submit_bulk(std::begin(container), std::end(container), priority);
+ }
+
+ /**
+ * @brief Parallelize a loop by automatically splitting it into blocks and submitting each block separately to the queue, with the specified priority. The loop function takes one argument, the loop index, and it is called exactly once per index, but many times per block. Returns a `BS::multi_future` which can be used to wait until all the tasks finish.
*
* @tparam T1 The type of the first index. Should be a signed or unsigned integer.
* @tparam T2 The type of the index after the last index. Should be a signed or unsigned integer.
- * @tparam F The type of the function to loop through.
+ * @tparam T The common type of the indices, as determined by `BS::common_index_type_t`.
+ * @tparam F The type of the loop function.
* @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 tasks will be submitted, and an empty `BS::multi_future` will be returned.
- * @param loop The function to loop through. Will be called once per index, many times per block. Should take exactly one argument: the loop index. It cannot have a return value.
+ * @param loop A function that will be called once per index, many times per block. Should take exactly one argument: the loop index. Must not return a value.
* @param num_blocks The maximum number of blocks to split the loop into. The default is 0, which means the number of blocks will be equal to the number of threads in the pool.
- * @param priority The priority of the tasks. Should be between -128 and +127 (a signed 8-bit integer). The default is 0. Only taken into account if the flag `BS:tp::priority` is enabled in the template parameter, otherwise has no effect.
- * @return A `BS::multi_future` that can be used to wait for all the blocks to finish.
+ * @param priority The priority of the tasks. Should be between -128 and +127 (a signed 8-bit integer). The default is 0. Only taken into account if the flag `BS::tp::priority` is enabled in the template parameter, otherwise has no effect.
+ * @return A `BS::multi_future` that can be used to wait for all the tasks to finish.
*/
template , typename F>
[[nodiscard]] multi_future submit_loop(const T1 first_index, const T2 index_after_last, F&& loop, const std::size_t num_blocks = 0, const priority_t priority = 0)
{
- if (static_cast(index_after_last) > static_cast(first_index))
- {
- const std::shared_ptr> loop_ptr = std::make_shared>(std::forward(loop));
- const blocks blks(static_cast(first_index), static_cast(index_after_last), num_blocks ? num_blocks : thread_count);
- multi_future future;
- future.reserve(blks.get_num_blocks());
- for (std::size_t blk = 0; blk < blks.get_num_blocks(); ++blk)
- {
- future.push_back(submit_task(
- [loop_ptr, start = blks.start(blk), end = blks.end(blk)]
- {
- for (T i = start; i < end; ++i)
- (*loop_ptr)(i);
- },
- priority));
- }
- return future;
- }
- return {};
+ return enqueue_loop(static_cast(first_index), static_cast(index_after_last), std::forward(loop), num_blocks, priority);
}
/**
- * @brief Submit a sequence of tasks enumerated by indices to the queue, with the specified priority. The sequence function takes one argument, the task index, and will be called once per index. Returns a `BS::multi_future` that contains the futures for all of the tasks.
+ * @brief Submit a sequence of tasks enumerated by indices to the queue, with the specified priority. The sequence function takes one argument, the task index, and will be called once per index. If the sequence function has a return value, get a `BS::multi_future` for the eventual returned values. If the sequence function has no return value, get a `BS::multi_future` which can be used to wait until all the tasks finish.
*
* @tparam T1 The type of the first index. Should be a signed or unsigned integer.
* @tparam T2 The type of the index after the last index. Should be a signed or unsigned integer.
- * @tparam F The type of the function used to define the sequence.
- * @tparam R The return type of the function used to define the sequence (can be `void`).
+ * @tparam T The common type of the indices, as determined by `BS::common_index_type_t`.
+ * @tparam F The type of the sequence function.
+ * @tparam R The return type of the sequence function (can be `void`).
* @param first_index The first index in the sequence.
* @param index_after_last The index after the last index in the sequence. The sequence 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 tasks will be submitted, and an empty `BS::multi_future` will be returned.
- * @param sequence The function used to define the sequence. Will be called once per index. Should take exactly one argument, the index.
- * @param priority The priority of the tasks. Should be between -128 and +127 (a signed 8-bit integer). The default is 0. Only taken into account if the flag `BS:tp::priority` is enabled in the template parameter, otherwise has no effect.
+ * @param sequence A function that will be called once per index. Should take exactly one argument, the index. Can return a value.
+ * @param priority The priority of the tasks. Should be between -128 and +127 (a signed 8-bit integer). The default is 0. Only taken into account if the flag `BS::tp::priority` is enabled in the template parameter, otherwise has no effect.
* @return A `BS::multi_future` that can be used to wait for all the tasks to finish. If the sequence function returns a value, the `BS::multi_future` can also be used to obtain the values returned by each task.
*/
template , typename F, typename R = std::invoke_result_t, T>>
[[nodiscard]] multi_future submit_sequence(const T1 first_index, const T2 index_after_last, F&& sequence, const priority_t priority = 0)
{
- if (static_cast(index_after_last) > static_cast