1
0
mirror of https://github.com/bshoshany/thread-pool.git synced 2026-07-21 19:13:00 +04:00

2 Commits

Author SHA1 Message Date
Barak Shoshany bd4533f1f7 Updated to v5.1.0 2026-01-03 20:03:51 -05:00
Barak Shoshany aa3fbfbe80 Updated to v5.0.0 2024-12-19 21:02:25 -05:00
32 changed files with 10239 additions and 2709 deletions
+7 -8
View File
@@ -11,7 +11,7 @@ AlignEscapedNewlines: Left
AlignOperands: DontAlign
AlignTrailingComments:
Kind: Always
OverEmptyLines: 2
OverEmptyLines: 0
AllowAllArgumentsOnNextLine: false
AllowAllParametersOfDeclarationOnNextLine: false
AllowBreakBeforeNoexceptSpecifier: Never
@@ -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
@@ -117,6 +115,7 @@ ReflowComments: true
RemoveBracesLLVM: false
SeparateDefinitionBlocks: Always
ShortNamespaceLines: 1
SkipMacroDefinitionBody: true
SortIncludes: CaseSensitive
SortJavaStaticImport: Before
SortUsingDeclarations: true
@@ -152,7 +151,7 @@ SpacesInLineCommentPrefix:
Minimum: 1
SpacesInParentheses: false
SpacesInSquareBrackets: false
Standard: c++17
Standard: Latest
TabWidth: 4
UseCRLF: false
UseTab: Never
+43 -24
View File
@@ -1,45 +1,64 @@
---
CheckOptions:
misc-const-correctness.WarnPointersAsValues: true
misc-include-cleaner.IgnoreHeaders: time.h
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
Checks: >
-*,
bugprone-*,
*,
-abseil-*,
-altera-*,
-android-*,
-boost-*,
-bugprone-easily-swappable-parameters,
-bugprone-empty-catch,
-bugprone-exception-escape,
cert-*,
-cert-err58-cpp,
concurrency-*,
-concurrency-mt-unsafe,
cppcoreguidelines-*,
-clang-analyzer-alpha.*,
-clang-analyzer-debug.*,
-clang-analyzer-fuchsia.*,
-clang-analyzer-webkit.*,
-cppcoreguidelines-avoid-c-arrays,
-cppcoreguidelines-avoid-do-while,
-cppcoreguidelines-avoid-magic-numbers,
-cppcoreguidelines-avoid-non-const-global-variables,
-cppcoreguidelines-interfaces-global-init,
-cppcoreguidelines-macro-usage,
-cppcoreguidelines-missing-std-forward,
-cppcoreguidelines-pro-bounds-array-to-pointer-decay,
-cppcoreguidelines-special-member-functions,
hicpp-*,
-cppcoreguidelines-pro-bounds-constant-array-index,
-cppcoreguidelines-pro-bounds-pointer-arithmetic,
-cppcoreguidelines-pro-type-reinterpret-cast,
-cppcoreguidelines-pro-type-vararg,
-darwin-*,
-fuchsia-*,
-google-*,
-hicpp-avoid-c-arrays,
-hicpp-braces-around-statements,
-hicpp-named-parameter,
-hicpp-member-init,
-hicpp-no-array-decay,
-hicpp-signed-bitwise,
-hicpp-special-member-functions,
-hicpp-use-auto,
misc-*,
-hicpp-vararg,
-linuxkernel-*,
-llvm-*,
-llvmlibc-*,
-misc-definitions-in-headers,
modernize-*,
-modernize-avoid-bind,
-modernize-avoid-c-arrays,
-modernize-use-auto,
-modernize-use-constraints,
-modernize-use-designated-initializers,
-modernize-use-ranges,
-modernize-use-std-numbers,
-modernize-use-trailing-return-type,
performance-*,
portability-*,
readability-*,
-mpi-*,
-objc-*,
-openmp-*,
-performance-enum-size,
-readability-avoid-nested-conditional-operator,
-readability-braces-around-statements,
-readability-const-return-type,
-readability-named-parameter,
-readability-redundant-member-init,
-readability-use-anyofallof,
-readability-function-cognitive-complexity,
-readability-identifier-length,
-readability-magic-numbers,
-readability-use-concise-preprocessor-directives,
-zircon-*,
HeaderFileExtensions: [h, hpp, cppm]
HeaderFilterRegex: .*
+1 -3
View File
@@ -3,8 +3,6 @@ name: Bug report
about: Found a bug? Report it here.
title: "[BUG]"
labels: bug
assignees: bshoshany
---
**Describe the bug**
@@ -34,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.
+1 -3
View File
@@ -3,8 +3,6 @@ name: Failed tests
about: The provided automated tests failed on your system? Report it here.
title: "[TEST]"
labels: bug
assignees: bshoshany
---
**System information**
@@ -23,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.
+1 -3
View File
@@ -3,8 +3,6 @@ name: Feature request
about: Want a new feature? Suggest it here.
title: "[REQ]"
labels: enhancement
assignees: bshoshany
---
**Describe the new feature**
@@ -20,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.
+3 -3
View File
@@ -1,6 +1,6 @@
**Pull request policy (please read)**
> Contributions are always welcome. However, I release my projects in cumulative updates after editing and testing them locally on my system, so my policy is not to accept any pull requests. If you open a pull request, and I decide to incorporate your suggestion into the project, I will first modify your code to comply with the project's coding conventions (formatting, syntax, naming, comments, programming practices, etc.), and perform some tests to ensure that the change doesn't break anything. I will then merge it into the next release of the project, possibly together with some other changes. The new release will also include a note in `CHANGELOG.md` with a link to your pull request, and modifications to the documentation in `README.md` as needed.
> Contributions are always welcome. However, I release my projects in cumulative updates after editing and testing them locally on my system, so **my policy is to never accept any pull requests**. If you open a pull request, and I decide to incorporate your suggestion into the project, I will first modify your code to comply with the project's coding conventions (formatting, syntax, naming, comments, programming practices, etc.), and perform some tests to ensure that the change doesn't break anything. I will then merge it into the next release of the project, possibly together with some other changes. The new release will also include a note in `CHANGELOG.md` with a link to your pull request, and modifications to the documentation in `README.md` as needed.
**Describe the changes**
@@ -16,7 +16,7 @@ Have you linted your code using the `.clang-tidy` file attached to this project?
**Testing**
Have you tested the new code using the provided automated test program `BS_thread_pool_test.cpp` (preferably with the provided multi-compiler test script `BS_thread_pool_test.ps1`) and/or performed any other tests to ensure that the new code works correctly?
Have you tested the new code using the provided automated test program `BS_thread_pool_test.cpp` (preferably with the provided test script `test_all.py`) and/or performed any other tests to ensure that the new code works correctly?
If so, please provide information about the test system(s):
@@ -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.
+1
View File
@@ -1,2 +1,3 @@
build
temp
default_args.txt
+110
View File
@@ -0,0 +1,110 @@
{
"configurations": [
{
"browse": {
"limitSymbolsToIncludedHeaders": true
},
"compilerArgs": [
"-stdlib=libc++"
],
"compilerPath": "/usr/bin/clang++",
"cppStandard": "c++17",
"cStandard": "c17",
"defines": [
"BS_THREAD_POOL_NATIVE_EXTENSIONS"
],
"includePath": [
"${workspaceFolder}/include"
],
"intelliSenseMode": "linux-clang-x64",
"name": "Clang C++17"
},
{
"browse": {
"limitSymbolsToIncludedHeaders": true
},
"compilerArgs": [
"-stdlib=libc++"
],
"compilerPath": "/usr/bin/clang++",
"cppStandard": "c++20",
"cStandard": "c17",
"defines": [
"BS_THREAD_POOL_NATIVE_EXTENSIONS"
],
"includePath": [
"${workspaceFolder}/include"
],
"intelliSenseMode": "linux-clang-x64",
"name": "Clang C++20"
},
{
"browse": {
"limitSymbolsToIncludedHeaders": true
},
"compilerArgs": [
"-stdlib=libc++"
],
"compilerPath": "/usr/bin/clang++",
"cppStandard": "c++23",
"cStandard": "c23",
"defines": [
"BS_THREAD_POOL_NATIVE_EXTENSIONS"
],
"includePath": [
"${workspaceFolder}/include"
],
"intelliSenseMode": "linux-clang-x64",
"name": "Clang C++23"
},
{
"browse": {
"limitSymbolsToIncludedHeaders": true
},
"compilerPath": "/usr/bin/g++",
"cppStandard": "c++17",
"cStandard": "c17",
"defines": [
"BS_THREAD_POOL_NATIVE_EXTENSIONS"
],
"includePath": [
"${workspaceFolder}/include"
],
"intelliSenseMode": "linux-gcc-x64",
"name": "GCC C++17"
},
{
"browse": {
"limitSymbolsToIncludedHeaders": true
},
"compilerPath": "/usr/bin/g++",
"cppStandard": "c++20",
"cStandard": "c17",
"defines": [
"BS_THREAD_POOL_NATIVE_EXTENSIONS"
],
"includePath": [
"${workspaceFolder}/include"
],
"intelliSenseMode": "linux-gcc-x64",
"name": "GCC C++20"
},
{
"browse": {
"limitSymbolsToIncludedHeaders": true
},
"compilerPath": "/usr/bin/g++",
"cppStandard": "c++23",
"cStandard": "c23",
"defines": [
"BS_THREAD_POOL_NATIVE_EXTENSIONS"
],
"includePath": [
"${workspaceFolder}/include"
],
"intelliSenseMode": "linux-gcc-x64",
"name": "GCC C++23"
}
],
"version": 4
}
+59
View File
@@ -0,0 +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"
}
+6
View File
@@ -0,0 +1,6 @@
{
"C_Cpp.codeAnalysis.exclude": {
"misc/**": true,
"temp/**": true
}
}
+541
View File
@@ -0,0 +1,541 @@
{
"tasks": [
{
"args": [
"scripts/compile_cpp.py",
"${file}",
"-c=clang++",
"-s=c++17",
"-t=debug",
"-v"
],
"command": "python3",
"detail": "Compile active file using clang++ with warning and debugging flags.",
"group": "build",
"label": "Build for debugging (Clang C++17)",
"presentation": {
"clear": false,
"echo": true,
"focus": false,
"panel": "shared",
"reveal": "always",
"revealProblems": "onProblem",
"showReuseMessage": true
},
"problemMatcher": [
"$gcc"
],
"type": "cppbuild"
},
{
"args": [
"scripts/compile_cpp.py",
"${file}",
"-c=clang++",
"-s=c++20",
"-t=debug",
"-v"
],
"command": "python3",
"detail": "Compile active file using clang++ with warning and debugging flags.",
"group": "build",
"label": "Build for debugging (Clang C++20)",
"presentation": {
"clear": false,
"echo": true,
"focus": false,
"panel": "shared",
"reveal": "always",
"revealProblems": "onProblem",
"showReuseMessage": true
},
"problemMatcher": [
"$gcc"
],
"type": "cppbuild"
},
{
"args": [
"scripts/compile_cpp.py",
"${file}",
"-c=clang++",
"-s=c++23",
"-t=debug",
"-v"
],
"command": "python3",
"detail": "Compile active file using clang++ with warning and debugging flags.",
"group": "build",
"label": "Build for debugging (Clang C++23)",
"presentation": {
"clear": false,
"echo": true,
"focus": false,
"panel": "shared",
"reveal": "always",
"revealProblems": "onProblem",
"showReuseMessage": true
},
"problemMatcher": [
"$gcc"
],
"type": "cppbuild"
},
{
"args": [
"scripts/compile_cpp.py",
"${file}",
"-c=g++",
"-s=c++17",
"-t=debug",
"-v"
],
"command": "python3",
"detail": "Compile active file using g++ with warning and debugging flags.",
"group": "build",
"label": "Build for debugging (GCC C++17)",
"presentation": {
"clear": false,
"echo": true,
"focus": false,
"panel": "shared",
"reveal": "always",
"revealProblems": "onProblem",
"showReuseMessage": true
},
"problemMatcher": [
"$gcc"
],
"type": "cppbuild"
},
{
"args": [
"scripts/compile_cpp.py",
"${file}",
"-c=g++",
"-s=c++20",
"-t=debug",
"-v"
],
"command": "python3",
"detail": "Compile active file using g++ with warning and debugging flags.",
"group": "build",
"label": "Build for debugging (GCC C++20)",
"presentation": {
"clear": false,
"echo": true,
"focus": false,
"panel": "shared",
"reveal": "always",
"revealProblems": "onProblem",
"showReuseMessage": true
},
"problemMatcher": [
"$gcc"
],
"type": "cppbuild"
},
{
"args": [
"scripts/compile_cpp.py",
"${file}",
"-c=g++",
"-s=c++23",
"-t=debug",
"-v"
],
"command": "python3",
"detail": "Compile active file using g++ with warning and debugging flags.",
"group": "build",
"label": "Build for debugging (GCC C++23)",
"presentation": {
"clear": false,
"echo": true,
"focus": false,
"panel": "shared",
"reveal": "always",
"revealProblems": "onProblem",
"showReuseMessage": true
},
"problemMatcher": [
"$gcc"
],
"type": "cppbuild"
},
{
"args": [
"scripts/compile_cpp.py",
"${file}",
"-c=clang++",
"-s=c++17",
"-t=release",
"-v"
],
"command": "python3",
"detail": "Compile active file using clang++ with warning and optimization flags.",
"group": "build",
"label": "Build optimized (Clang C++17)",
"presentation": {
"clear": false,
"echo": true,
"focus": false,
"panel": "shared",
"reveal": "always",
"revealProblems": "onProblem",
"showReuseMessage": true
},
"problemMatcher": [
"$gcc"
],
"type": "cppbuild"
},
{
"args": [
"scripts/compile_cpp.py",
"${file}",
"-c=clang++",
"-s=c++20",
"-t=release",
"-v"
],
"command": "python3",
"detail": "Compile active file using clang++ with warning and optimization flags.",
"group": "build",
"label": "Build optimized (Clang C++20)",
"presentation": {
"clear": false,
"echo": true,
"focus": false,
"panel": "shared",
"reveal": "always",
"revealProblems": "onProblem",
"showReuseMessage": true
},
"problemMatcher": [
"$gcc"
],
"type": "cppbuild"
},
{
"args": [
"scripts/compile_cpp.py",
"${file}",
"-c=clang++",
"-s=c++23",
"-t=release",
"-v"
],
"command": "python3",
"detail": "Compile active file using clang++ with warning and optimization flags.",
"group": "build",
"label": "Build optimized (Clang C++23)",
"presentation": {
"clear": false,
"echo": true,
"focus": false,
"panel": "shared",
"reveal": "always",
"revealProblems": "onProblem",
"showReuseMessage": true
},
"problemMatcher": [
"$gcc"
],
"type": "cppbuild"
},
{
"args": [
"scripts/compile_cpp.py",
"${file}",
"-c=g++",
"-s=c++17",
"-t=release",
"-v"
],
"command": "python3",
"detail": "Compile active file using g++ with warning and optimization flags.",
"group": "build",
"label": "Build optimized (GCC C++17)",
"presentation": {
"clear": false,
"echo": true,
"focus": false,
"panel": "shared",
"reveal": "always",
"revealProblems": "onProblem",
"showReuseMessage": true
},
"problemMatcher": [
"$gcc"
],
"type": "cppbuild"
},
{
"args": [
"scripts/compile_cpp.py",
"${file}",
"-c=g++",
"-s=c++20",
"-t=release",
"-v"
],
"command": "python3",
"detail": "Compile active file using g++ with warning and optimization flags.",
"group": "build",
"label": "Build optimized (GCC C++20)",
"presentation": {
"clear": false,
"echo": true,
"focus": false,
"panel": "shared",
"reveal": "always",
"revealProblems": "onProblem",
"showReuseMessage": true
},
"problemMatcher": [
"$gcc"
],
"type": "cppbuild"
},
{
"args": [
"scripts/compile_cpp.py",
"${file}",
"-c=g++",
"-s=c++23",
"-t=release",
"-v"
],
"command": "python3",
"detail": "Compile active file using g++ with warning and optimization flags.",
"group": "build",
"label": "Build optimized (GCC C++23)",
"presentation": {
"clear": false,
"echo": true,
"focus": false,
"panel": "shared",
"reveal": "always",
"revealProblems": "onProblem",
"showReuseMessage": true
},
"problemMatcher": [
"$gcc"
],
"type": "cppbuild"
},
{
"args": [
"scripts/compile_cpp.py",
"${file}",
"-c=clang++",
"-s=c++17",
"-t=release",
"-r",
"-v"
],
"command": "python3",
"detail": "Compile active file using clang++ with warning and optimization flags and run the program.",
"group": "test",
"label": "Build optimized and run (Clang C++17)",
"presentation": {
"clear": false,
"echo": true,
"focus": false,
"panel": "shared",
"reveal": "always",
"revealProblems": "onProblem",
"showReuseMessage": true
}
},
{
"args": [
"scripts/compile_cpp.py",
"${file}",
"-c=clang++",
"-s=c++20",
"-t=release",
"-r",
"-v"
],
"command": "python3",
"detail": "Compile active file using clang++ with warning and optimization flags and run the program.",
"group": "test",
"label": "Build optimized and run (Clang C++20)",
"presentation": {
"clear": false,
"echo": true,
"focus": false,
"panel": "shared",
"reveal": "always",
"revealProblems": "onProblem",
"showReuseMessage": true
}
},
{
"args": [
"scripts/compile_cpp.py",
"${file}",
"-c=clang++",
"-s=c++23",
"-t=release",
"-r",
"-v"
],
"command": "python3",
"detail": "Compile active file using clang++ with warning and optimization flags and run the program.",
"group": "test",
"label": "Build optimized and run (Clang C++23)",
"presentation": {
"clear": false,
"echo": true,
"focus": false,
"panel": "shared",
"reveal": "always",
"revealProblems": "onProblem",
"showReuseMessage": true
}
},
{
"args": [
"scripts/compile_cpp.py",
"${file}",
"-c=g++",
"-s=c++17",
"-t=release",
"-r",
"-v"
],
"command": "python3",
"detail": "Compile active file using g++ with warning and optimization flags and run the program.",
"group": "test",
"label": "Build optimized and run (GCC C++17)",
"presentation": {
"clear": false,
"echo": true,
"focus": false,
"panel": "shared",
"reveal": "always",
"revealProblems": "onProblem",
"showReuseMessage": true
}
},
{
"args": [
"scripts/compile_cpp.py",
"${file}",
"-c=g++",
"-s=c++20",
"-t=release",
"-r",
"-v"
],
"command": "python3",
"detail": "Compile active file using g++ with warning and optimization flags and run the program.",
"group": "test",
"label": "Build optimized and run (GCC C++20)",
"presentation": {
"clear": false,
"echo": true,
"focus": false,
"panel": "shared",
"reveal": "always",
"revealProblems": "onProblem",
"showReuseMessage": true
}
},
{
"args": [
"scripts/compile_cpp.py",
"${file}",
"-c=g++",
"-s=c++23",
"-t=release",
"-r",
"-v"
],
"command": "python3",
"detail": "Compile active file using g++ with warning and optimization flags and run the program.",
"group": "test",
"label": "Build optimized and run (GCC C++23)",
"presentation": {
"clear": false,
"echo": true,
"focus": false,
"panel": "shared",
"reveal": "always",
"revealProblems": "onProblem",
"showReuseMessage": true
}
},
{
"args": [
"scripts/compile_cpp.py",
"-b",
"-v"
],
"command": "python3",
"detail": "Delete all files in the build folder.",
"group": "test",
"label": "Clear build folder",
"presentation": {
"clear": false,
"echo": true,
"focus": false,
"panel": "shared",
"reveal": "always",
"revealProblems": "onProblem",
"showReuseMessage": true
},
"type": "shell"
},
{
"args": [
"scripts/compile_cpp.py",
"${file}",
"-t=release",
"-y",
"-v"
],
"command": "python3",
"detail": "Compile active file using all available compilers and all relevant C++ standards with warning and optimization flags.",
"group": "test",
"label": "Build all optimized (all compilers and standards)",
"presentation": {
"clear": false,
"echo": true,
"focus": false,
"panel": "shared",
"reveal": "always",
"revealProblems": "onProblem",
"showReuseMessage": true
},
"type": "shell"
},
{
"args": [
"scripts/compile_cpp.py",
"${file}",
"-t=release",
"-y",
"-r",
"-v"
],
"command": "python3",
"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": "Build all optimized and run (all compilers and standards)",
"presentation": {
"clear": false,
"echo": true,
"focus": false,
"panel": "shared",
"reveal": "always",
"revealProblems": "onProblem",
"showReuseMessage": true
},
"type": "shell"
}
],
"version": "2.0.0"
}
+44
View File
@@ -0,0 +1,44 @@
{
"configurations": [
{
"compilerPath": "/usr/local/opt/llvm/bin/clang++",
"cppStandard": "c++17",
"cStandard": "c17",
"defines": [
"BS_THREAD_POOL_NATIVE_EXTENSIONS"
],
"includePath": [
"${workspaceFolder}/include"
],
"intelliSenseMode": "macos-clang-x64",
"name": "Clang C++17"
},
{
"compilerPath": "/usr/local/opt/llvm/bin/clang++",
"cppStandard": "c++20",
"cStandard": "c17",
"defines": [
"BS_THREAD_POOL_NATIVE_EXTENSIONS"
],
"includePath": [
"${workspaceFolder}/include"
],
"intelliSenseMode": "macos-clang-x64",
"name": "Clang C++20"
},
{
"compilerPath": "/usr/local/opt/llvm/bin/clang++",
"cppStandard": "c++23",
"cStandard": "c23",
"defines": [
"BS_THREAD_POOL_NATIVE_EXTENSIONS"
],
"includePath": [
"${workspaceFolder}/include"
],
"intelliSenseMode": "macos-clang-x64",
"name": "Clang C++23"
}
],
"version": 4
}
+32
View File
@@ -0,0 +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"
}
+6
View File
@@ -0,0 +1,6 @@
{
"C_Cpp.codeAnalysis.exclude": {
"misc/**": true,
"temp/**": true
}
}
+307
View File
@@ -0,0 +1,307 @@
{
"tasks": [
{
"args": [
"scripts/compile_cpp.py",
"${file}",
"-c=clang++",
"-s=c++17",
"-t=debug",
"-v"
],
"command": "python3",
"detail": "Compile active file using clang++ with warning and debugging flags.",
"group": "build",
"label": "Build for debugging (Clang C++17)",
"presentation": {
"clear": false,
"echo": true,
"focus": false,
"panel": "shared",
"reveal": "always",
"revealProblems": "onProblem",
"showReuseMessage": true
},
"problemMatcher": [
"$gcc"
],
"type": "cppbuild"
},
{
"args": [
"scripts/compile_cpp.py",
"${file}",
"-c=clang++",
"-s=c++20",
"-t=debug",
"-v"
],
"command": "python3",
"detail": "Compile active file using clang++ with warning and debugging flags.",
"group": "build",
"label": "Build for debugging (Clang C++20)",
"presentation": {
"clear": false,
"echo": true,
"focus": false,
"panel": "shared",
"reveal": "always",
"revealProblems": "onProblem",
"showReuseMessage": true
},
"problemMatcher": [
"$gcc"
],
"type": "cppbuild"
},
{
"args": [
"scripts/compile_cpp.py",
"${file}",
"-c=clang++",
"-s=c++23",
"-t=debug",
"-v"
],
"command": "python3",
"detail": "Compile active file using clang++ with warning and debugging flags.",
"group": "build",
"label": "Build for debugging (Clang C++23)",
"presentation": {
"clear": false,
"echo": true,
"focus": false,
"panel": "shared",
"reveal": "always",
"revealProblems": "onProblem",
"showReuseMessage": true
},
"problemMatcher": [
"$gcc"
],
"type": "cppbuild"
},
{
"args": [
"scripts/compile_cpp.py",
"${file}",
"-c=clang++",
"-s=c++17",
"-t=release",
"-v"
],
"command": "python3",
"detail": "Compile active file using clang++ with warning and optimization flags.",
"group": "build",
"label": "Build optimized (Clang C++17)",
"presentation": {
"clear": false,
"echo": true,
"focus": false,
"panel": "shared",
"reveal": "always",
"revealProblems": "onProblem",
"showReuseMessage": true
},
"problemMatcher": [
"$gcc"
],
"type": "cppbuild"
},
{
"args": [
"scripts/compile_cpp.py",
"${file}",
"-c=clang++",
"-s=c++20",
"-t=release",
"-v"
],
"command": "python3",
"detail": "Compile active file using clang++ with warning and optimization flags.",
"group": "build",
"label": "Build optimized (Clang C++20)",
"presentation": {
"clear": false,
"echo": true,
"focus": false,
"panel": "shared",
"reveal": "always",
"revealProblems": "onProblem",
"showReuseMessage": true
},
"problemMatcher": [
"$gcc"
],
"type": "cppbuild"
},
{
"args": [
"scripts/compile_cpp.py",
"${file}",
"-c=clang++",
"-s=c++23",
"-t=release",
"-v"
],
"command": "python3",
"detail": "Compile active file using clang++ with warning and optimization flags.",
"group": "build",
"label": "Build optimized (Clang C++23)",
"presentation": {
"clear": false,
"echo": true,
"focus": false,
"panel": "shared",
"reveal": "always",
"revealProblems": "onProblem",
"showReuseMessage": true
},
"problemMatcher": [
"$gcc"
],
"type": "cppbuild"
},
{
"args": [
"scripts/compile_cpp.py",
"${file}",
"-c=clang++",
"-s=c++17",
"-t=release",
"-r",
"-v"
],
"command": "python3",
"detail": "Compile active file using clang++ with warning and optimization flags and run the program.",
"group": "test",
"label": "Build optimized and run (Clang C++17)",
"presentation": {
"clear": false,
"echo": true,
"focus": false,
"panel": "shared",
"reveal": "always",
"revealProblems": "onProblem",
"showReuseMessage": true
}
},
{
"args": [
"scripts/compile_cpp.py",
"${file}",
"-c=clang++",
"-s=c++20",
"-t=release",
"-r",
"-v"
],
"command": "python3",
"detail": "Compile active file using clang++ with warning and optimization flags and run the program.",
"group": "test",
"label": "Build optimized and run (Clang C++20)",
"presentation": {
"clear": false,
"echo": true,
"focus": false,
"panel": "shared",
"reveal": "always",
"revealProblems": "onProblem",
"showReuseMessage": true
}
},
{
"args": [
"scripts/compile_cpp.py",
"${file}",
"-c=clang++",
"-s=c++23",
"-t=release",
"-r",
"-v"
],
"command": "python3",
"detail": "Compile active file using clang++ with warning and optimization flags and run the program.",
"group": "test",
"label": "Build optimized and run (Clang C++23)",
"presentation": {
"clear": false,
"echo": true,
"focus": false,
"panel": "shared",
"reveal": "always",
"revealProblems": "onProblem",
"showReuseMessage": true
}
},
{
"args": [
"scripts/compile_cpp.py",
"-b",
"-v"
],
"command": "python3",
"detail": "Delete all files in the build folder.",
"group": "test",
"label": "Clear build folder",
"presentation": {
"clear": false,
"echo": true,
"focus": false,
"panel": "shared",
"reveal": "always",
"revealProblems": "onProblem",
"showReuseMessage": true
},
"type": "shell"
},
{
"args": [
"scripts/compile_cpp.py",
"${file}",
"-t=release",
"-y",
"-v"
],
"command": "python3",
"detail": "Compile active file using all available compilers and all relevant C++ standards with warning and optimization flags.",
"group": "test",
"label": "Build all optimized (all compilers and standards)",
"presentation": {
"clear": false,
"echo": true,
"focus": false,
"panel": "shared",
"reveal": "always",
"revealProblems": "onProblem",
"showReuseMessage": true
},
"type": "shell"
},
{
"args": [
"scripts/compile_cpp.py",
"${file}",
"-t=release",
"-y",
"-r",
"-v"
],
"command": "python3",
"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": "Build all optimized and run (all compilers and standards)",
"presentation": {
"clear": false,
"echo": true,
"focus": false,
"panel": "shared",
"reveal": "always",
"revealProblems": "onProblem",
"showReuseMessage": true
},
"type": "shell"
}
],
"version": "2.0.0"
}
+158
View File
@@ -0,0 +1,158 @@
{
"configurations": [
{
"browse": {
"limitSymbolsToIncludedHeaders": true
},
"compilerArgs": [
"-stdlib=libc++"
],
"compilerPath": "C:/msys64/clang64/bin/clang++.exe",
"cppStandard": "c++17",
"cStandard": "c17",
"defines": [
"BS_THREAD_POOL_NATIVE_EXTENSIONS"
],
"includePath": [
"${workspaceFolder}/include"
],
"intelliSenseMode": "windows-clang-x64",
"name": "Clang C++17"
},
{
"browse": {
"limitSymbolsToIncludedHeaders": true
},
"compilerArgs": [
"-stdlib=libc++"
],
"compilerPath": "C:/msys64/clang64/bin/clang++.exe",
"cppStandard": "c++20",
"cStandard": "c17",
"defines": [
"BS_THREAD_POOL_NATIVE_EXTENSIONS"
],
"includePath": [
"${workspaceFolder}/include"
],
"intelliSenseMode": "windows-clang-x64",
"name": "Clang C++20"
},
{
"browse": {
"limitSymbolsToIncludedHeaders": true
},
"compilerArgs": [
"-stdlib=libc++"
],
"compilerPath": "C:/msys64/clang64/bin/clang++.exe",
"cppStandard": "c++23",
"cStandard": "c23",
"defines": [
"BS_THREAD_POOL_NATIVE_EXTENSIONS"
],
"includePath": [
"${workspaceFolder}/include"
],
"intelliSenseMode": "windows-clang-x64",
"name": "Clang C++23"
},
{
"browse": {
"limitSymbolsToIncludedHeaders": true
},
"compilerPath": "C:/msys64/ucrt64/bin/g++.exe",
"cppStandard": "c++17",
"cStandard": "c17",
"defines": [
"BS_THREAD_POOL_NATIVE_EXTENSIONS"
],
"includePath": [
"${workspaceFolder}/include"
],
"intelliSenseMode": "windows-gcc-x64",
"name": "GCC C++17"
},
{
"browse": {
"limitSymbolsToIncludedHeaders": true
},
"compilerPath": "C:/msys64/ucrt64/bin/g++.exe",
"cppStandard": "c++20",
"cStandard": "c17",
"defines": [
"BS_THREAD_POOL_NATIVE_EXTENSIONS"
],
"includePath": [
"${workspaceFolder}/include"
],
"intelliSenseMode": "windows-gcc-x64",
"name": "GCC C++20"
},
{
"browse": {
"limitSymbolsToIncludedHeaders": true
},
"compilerPath": "C:/msys64/ucrt64/bin/g++.exe",
"cppStandard": "c++23",
"cStandard": "c23",
"defines": [
"BS_THREAD_POOL_NATIVE_EXTENSIONS"
],
"includePath": [
"${workspaceFolder}/include"
],
"intelliSenseMode": "windows-gcc-x64",
"name": "GCC C++23"
},
{
"browse": {
"limitSymbolsToIncludedHeaders": true
},
"compilerPath": "C:/Program Files/Microsoft Visual Studio/2022/Community/VC/Tools/MSVC/14.42.34433/bin/Hostx64/x64/cl.exe",
"cppStandard": "c++17",
"cStandard": "c17",
"defines": [
"BS_THREAD_POOL_NATIVE_EXTENSIONS"
],
"includePath": [
"${workspaceFolder}/include"
],
"intelliSenseMode": "windows-msvc-x64",
"name": "MSVC C++17"
},
{
"browse": {
"limitSymbolsToIncludedHeaders": true
},
"compilerPath": "C:/Program Files/Microsoft Visual Studio/2022/Community/VC/Tools/MSVC/14.42.34433/bin/Hostx64/x64/cl.exe",
"cppStandard": "c++20",
"cStandard": "c17",
"defines": [
"BS_THREAD_POOL_NATIVE_EXTENSIONS"
],
"includePath": [
"${workspaceFolder}/include"
],
"intelliSenseMode": "windows-msvc-x64",
"name": "MSVC C++20"
},
{
"browse": {
"limitSymbolsToIncludedHeaders": true
},
"compilerPath": "C:/Program Files/Microsoft Visual Studio/2022/Community/VC/Tools/MSVC/14.42.34433/bin/Hostx64/x64/cl.exe",
"cppStandard": "c++23",
"cStandard": "c23",
"defines": [
"BS_THREAD_POOL_NATIVE_EXTENSIONS"
],
"includePath": [
"${workspaceFolder}/include"
],
"intelliSenseMode": "windows-msvc-x64",
"name": "MSVC C++23"
}
],
"version": 4
}
+89
View File
@@ -0,0 +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"
}
+9
View File
@@ -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
}
}
+775
View File
@@ -0,0 +1,775 @@
{
"tasks": [
{
"args": [
"scripts/compile_cpp.py",
"${file}",
"-c=clang++",
"-s=c++17",
"-t=debug",
"-v"
],
"command": "python",
"detail": "Compile active file using clang++ with warning and debugging flags.",
"group": "build",
"label": "Build for debugging (Clang C++17)",
"presentation": {
"clear": false,
"echo": true,
"focus": false,
"panel": "shared",
"reveal": "always",
"revealProblems": "onProblem",
"showReuseMessage": true
},
"problemMatcher": [
"$gcc"
],
"type": "cppbuild"
},
{
"args": [
"scripts/compile_cpp.py",
"${file}",
"-c=clang++",
"-s=c++20",
"-t=debug",
"-v"
],
"command": "python",
"detail": "Compile active file using clang++ with warning and debugging flags.",
"group": "build",
"label": "Build for debugging (Clang C++20)",
"presentation": {
"clear": false,
"echo": true,
"focus": false,
"panel": "shared",
"reveal": "always",
"revealProblems": "onProblem",
"showReuseMessage": true
},
"problemMatcher": [
"$gcc"
],
"type": "cppbuild"
},
{
"args": [
"scripts/compile_cpp.py",
"${file}",
"-c=clang++",
"-s=c++23",
"-t=debug",
"-v"
],
"command": "python",
"detail": "Compile active file using clang++ with warning and debugging flags.",
"group": "build",
"label": "Build for debugging (Clang C++23)",
"presentation": {
"clear": false,
"echo": true,
"focus": false,
"panel": "shared",
"reveal": "always",
"revealProblems": "onProblem",
"showReuseMessage": true
},
"problemMatcher": [
"$gcc"
],
"type": "cppbuild"
},
{
"args": [
"scripts/compile_cpp.py",
"${file}",
"-c=g++",
"-s=c++17",
"-t=debug",
"-v"
],
"command": "python",
"detail": "Compile active file using g++ with warning and debugging flags.",
"group": "build",
"label": "Build for debugging (GCC C++17)",
"presentation": {
"clear": false,
"echo": true,
"focus": false,
"panel": "shared",
"reveal": "always",
"revealProblems": "onProblem",
"showReuseMessage": true
},
"problemMatcher": [
"$gcc"
],
"type": "cppbuild"
},
{
"args": [
"scripts/compile_cpp.py",
"${file}",
"-c=g++",
"-s=c++20",
"-t=debug",
"-v"
],
"command": "python",
"detail": "Compile active file using g++ with warning and debugging flags.",
"group": "build",
"label": "Build for debugging (GCC C++20)",
"presentation": {
"clear": false,
"echo": true,
"focus": false,
"panel": "shared",
"reveal": "always",
"revealProblems": "onProblem",
"showReuseMessage": true
},
"problemMatcher": [
"$gcc"
],
"type": "cppbuild"
},
{
"args": [
"scripts/compile_cpp.py",
"${file}",
"-c=g++",
"-s=c++23",
"-t=debug",
"-v"
],
"command": "python",
"detail": "Compile active file using g++ with warning and debugging flags.",
"group": "build",
"label": "Build for debugging (GCC C++23)",
"presentation": {
"clear": false,
"echo": true,
"focus": false,
"panel": "shared",
"reveal": "always",
"revealProblems": "onProblem",
"showReuseMessage": true
},
"problemMatcher": [
"$gcc"
],
"type": "cppbuild"
},
{
"args": [
"scripts/compile_cpp.py",
"${file}",
"-c=cl",
"-s=c++17",
"-t=debug",
"-v"
],
"command": "python",
"detail": "Compile active file using cl with warning and debugging flags.",
"group": "build",
"label": "Build for debugging (MSVC C++17)",
"presentation": {
"clear": false,
"echo": true,
"focus": false,
"panel": "shared",
"reveal": "always",
"revealProblems": "onProblem",
"showReuseMessage": true
},
"problemMatcher": [
"$msCompile"
],
"type": "cppbuild"
},
{
"args": [
"scripts/compile_cpp.py",
"${file}",
"-c=cl",
"-s=c++20",
"-t=debug",
"-v"
],
"command": "python",
"detail": "Compile active file using cl with warning and debugging flags.",
"group": "build",
"label": "Build for debugging (MSVC C++20)",
"presentation": {
"clear": false,
"echo": true,
"focus": false,
"panel": "shared",
"reveal": "always",
"revealProblems": "onProblem",
"showReuseMessage": true
},
"problemMatcher": [
"$msCompile"
],
"type": "cppbuild"
},
{
"args": [
"scripts/compile_cpp.py",
"${file}",
"-c=cl",
"-s=c++23",
"-t=debug",
"-v"
],
"command": "python",
"detail": "Compile active file using cl with warning and debugging flags.",
"group": "build",
"label": "Build for debugging (MSVC C++23)",
"presentation": {
"clear": false,
"echo": true,
"focus": false,
"panel": "shared",
"reveal": "always",
"revealProblems": "onProblem",
"showReuseMessage": true
},
"problemMatcher": [
"$msCompile"
],
"type": "cppbuild"
},
{
"args": [
"scripts/compile_cpp.py",
"${file}",
"-c=clang++",
"-s=c++17",
"-t=release",
"-v"
],
"command": "python",
"detail": "Compile active file using clang++ with warning and optimization flags.",
"group": "build",
"label": "Build optimized (Clang C++17)",
"presentation": {
"clear": false,
"echo": true,
"focus": false,
"panel": "shared",
"reveal": "always",
"revealProblems": "onProblem",
"showReuseMessage": true
},
"problemMatcher": [
"$gcc"
],
"type": "cppbuild"
},
{
"args": [
"scripts/compile_cpp.py",
"${file}",
"-c=clang++",
"-s=c++20",
"-t=release",
"-v"
],
"command": "python",
"detail": "Compile active file using clang++ with warning and optimization flags.",
"group": "build",
"label": "Build optimized (Clang C++20)",
"presentation": {
"clear": false,
"echo": true,
"focus": false,
"panel": "shared",
"reveal": "always",
"revealProblems": "onProblem",
"showReuseMessage": true
},
"problemMatcher": [
"$gcc"
],
"type": "cppbuild"
},
{
"args": [
"scripts/compile_cpp.py",
"${file}",
"-c=clang++",
"-s=c++23",
"-t=release",
"-v"
],
"command": "python",
"detail": "Compile active file using clang++ with warning and optimization flags.",
"group": "build",
"label": "Build optimized (Clang C++23)",
"presentation": {
"clear": false,
"echo": true,
"focus": false,
"panel": "shared",
"reveal": "always",
"revealProblems": "onProblem",
"showReuseMessage": true
},
"problemMatcher": [
"$gcc"
],
"type": "cppbuild"
},
{
"args": [
"scripts/compile_cpp.py",
"${file}",
"-c=g++",
"-s=c++17",
"-t=release",
"-v"
],
"command": "python",
"detail": "Compile active file using g++ with warning and optimization flags.",
"group": "build",
"label": "Build optimized (GCC C++17)",
"presentation": {
"clear": false,
"echo": true,
"focus": false,
"panel": "shared",
"reveal": "always",
"revealProblems": "onProblem",
"showReuseMessage": true
},
"problemMatcher": [
"$gcc"
],
"type": "cppbuild"
},
{
"args": [
"scripts/compile_cpp.py",
"${file}",
"-c=g++",
"-s=c++20",
"-t=release",
"-v"
],
"command": "python",
"detail": "Compile active file using g++ with warning and optimization flags.",
"group": "build",
"label": "Build optimized (GCC C++20)",
"presentation": {
"clear": false,
"echo": true,
"focus": false,
"panel": "shared",
"reveal": "always",
"revealProblems": "onProblem",
"showReuseMessage": true
},
"problemMatcher": [
"$gcc"
],
"type": "cppbuild"
},
{
"args": [
"scripts/compile_cpp.py",
"${file}",
"-c=g++",
"-s=c++23",
"-t=release",
"-v"
],
"command": "python",
"detail": "Compile active file using g++ with warning and optimization flags.",
"group": "build",
"label": "Build optimized (GCC C++23)",
"presentation": {
"clear": false,
"echo": true,
"focus": false,
"panel": "shared",
"reveal": "always",
"revealProblems": "onProblem",
"showReuseMessage": true
},
"problemMatcher": [
"$gcc"
],
"type": "cppbuild"
},
{
"args": [
"scripts/compile_cpp.py",
"${file}",
"-c=cl",
"-s=c++17",
"-t=release",
"-v"
],
"command": "python",
"detail": "Compile active file using cl with warning and optimization flags.",
"group": "build",
"label": "Build optimized (MSVC C++17)",
"presentation": {
"clear": false,
"echo": true,
"focus": false,
"panel": "shared",
"reveal": "always",
"revealProblems": "onProblem",
"showReuseMessage": true
},
"problemMatcher": [
"$msCompile"
],
"type": "cppbuild"
},
{
"args": [
"scripts/compile_cpp.py",
"${file}",
"-c=cl",
"-s=c++20",
"-t=release",
"-v"
],
"command": "python",
"detail": "Compile active file using cl with warning and optimization flags.",
"group": "build",
"label": "Build optimized (MSVC C++20)",
"presentation": {
"clear": false,
"echo": true,
"focus": false,
"panel": "shared",
"reveal": "always",
"revealProblems": "onProblem",
"showReuseMessage": true
},
"problemMatcher": [
"$msCompile"
],
"type": "cppbuild"
},
{
"args": [
"scripts/compile_cpp.py",
"${file}",
"-c=cl",
"-s=c++23",
"-t=release",
"-v"
],
"command": "python",
"detail": "Compile active file using cl with warning and optimization flags.",
"group": "build",
"label": "Build optimized (MSVC C++23)",
"presentation": {
"clear": false,
"echo": true,
"focus": false,
"panel": "shared",
"reveal": "always",
"revealProblems": "onProblem",
"showReuseMessage": true
},
"problemMatcher": [
"$msCompile"
],
"type": "cppbuild"
},
{
"args": [
"scripts/compile_cpp.py",
"${file}",
"-c=clang++",
"-s=c++17",
"-t=release",
"-r",
"-v"
],
"command": "python",
"detail": "Compile active file using clang++ with warning and optimization flags and run the program.",
"group": "test",
"label": "Build optimized and run (Clang C++17)",
"presentation": {
"clear": false,
"echo": true,
"focus": false,
"panel": "shared",
"reveal": "always",
"revealProblems": "onProblem",
"showReuseMessage": true
}
},
{
"args": [
"scripts/compile_cpp.py",
"${file}",
"-c=clang++",
"-s=c++20",
"-t=release",
"-r",
"-v"
],
"command": "python",
"detail": "Compile active file using clang++ with warning and optimization flags and run the program.",
"group": "test",
"label": "Build optimized and run (Clang C++20)",
"presentation": {
"clear": false,
"echo": true,
"focus": false,
"panel": "shared",
"reveal": "always",
"revealProblems": "onProblem",
"showReuseMessage": true
}
},
{
"args": [
"scripts/compile_cpp.py",
"${file}",
"-c=clang++",
"-s=c++23",
"-t=release",
"-r",
"-v"
],
"command": "python",
"detail": "Compile active file using clang++ with warning and optimization flags and run the program.",
"group": "test",
"label": "Build optimized and run (Clang C++23)",
"presentation": {
"clear": false,
"echo": true,
"focus": false,
"panel": "shared",
"reveal": "always",
"revealProblems": "onProblem",
"showReuseMessage": true
}
},
{
"args": [
"scripts/compile_cpp.py",
"${file}",
"-c=g++",
"-s=c++17",
"-t=release",
"-r",
"-v"
],
"command": "python",
"detail": "Compile active file using g++ with warning and optimization flags and run the program.",
"group": "test",
"label": "Build optimized and run (GCC C++17)",
"presentation": {
"clear": false,
"echo": true,
"focus": false,
"panel": "shared",
"reveal": "always",
"revealProblems": "onProblem",
"showReuseMessage": true
}
},
{
"args": [
"scripts/compile_cpp.py",
"${file}",
"-c=g++",
"-s=c++20",
"-t=release",
"-r",
"-v"
],
"command": "python",
"detail": "Compile active file using g++ with warning and optimization flags and run the program.",
"group": "test",
"label": "Build optimized and run (GCC C++20)",
"presentation": {
"clear": false,
"echo": true,
"focus": false,
"panel": "shared",
"reveal": "always",
"revealProblems": "onProblem",
"showReuseMessage": true
}
},
{
"args": [
"scripts/compile_cpp.py",
"${file}",
"-c=g++",
"-s=c++23",
"-t=release",
"-r",
"-v"
],
"command": "python",
"detail": "Compile active file using g++ with warning and optimization flags and run the program.",
"group": "test",
"label": "Build optimized and run (GCC C++23)",
"presentation": {
"clear": false,
"echo": true,
"focus": false,
"panel": "shared",
"reveal": "always",
"revealProblems": "onProblem",
"showReuseMessage": true
}
},
{
"args": [
"scripts/compile_cpp.py",
"${file}",
"-c=cl",
"-s=c++17",
"-t=release",
"-r",
"-v"
],
"command": "python",
"detail": "Compile active file using cl with warning and optimization flags and run the program.",
"group": "test",
"label": "Build optimized and run (MSVC C++17)",
"presentation": {
"clear": false,
"echo": true,
"focus": false,
"panel": "shared",
"reveal": "always",
"revealProblems": "onProblem",
"showReuseMessage": true
}
},
{
"args": [
"scripts/compile_cpp.py",
"${file}",
"-c=cl",
"-s=c++20",
"-t=release",
"-r",
"-v"
],
"command": "python",
"detail": "Compile active file using cl with warning and optimization flags and run the program.",
"group": "test",
"label": "Build optimized and run (MSVC C++20)",
"presentation": {
"clear": false,
"echo": true,
"focus": false,
"panel": "shared",
"reveal": "always",
"revealProblems": "onProblem",
"showReuseMessage": true
}
},
{
"args": [
"scripts/compile_cpp.py",
"${file}",
"-c=cl",
"-s=c++23",
"-t=release",
"-r",
"-v"
],
"command": "python",
"detail": "Compile active file using cl with warning and optimization flags and run the program.",
"group": "test",
"label": "Build optimized and run (MSVC C++23)",
"presentation": {
"clear": false,
"echo": true,
"focus": false,
"panel": "shared",
"reveal": "always",
"revealProblems": "onProblem",
"showReuseMessage": true
}
},
{
"args": [
"scripts/compile_cpp.py",
"-b",
"-v"
],
"command": "python",
"detail": "Delete all files in the build folder.",
"group": "test",
"label": "Clear build folder",
"presentation": {
"clear": false,
"echo": true,
"focus": false,
"panel": "shared",
"reveal": "always",
"revealProblems": "onProblem",
"showReuseMessage": true
},
"type": "shell"
},
{
"args": [
"scripts/compile_cpp.py",
"${file}",
"-t=release",
"-y",
"-v"
],
"command": "python",
"detail": "Compile active file using all available compilers and all relevant C++ standards with warning and optimization flags.",
"group": "test",
"label": "Build all optimized (all compilers and standards)",
"presentation": {
"clear": false,
"echo": true,
"focus": false,
"panel": "shared",
"reveal": "always",
"revealProblems": "onProblem",
"showReuseMessage": true
},
"type": "shell"
},
{
"args": [
"scripts/compile_cpp.py",
"${file}",
"-t=release",
"-y",
"-r",
"-v"
],
"command": "python",
"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": "Build all optimized and run (all compilers and standards)",
"presentation": {
"clear": false,
"echo": true,
"focus": false,
"panel": "shared",
"reveal": "always",
"revealProblems": "onProblem",
"showReuseMessage": true
},
"type": "shell"
}
],
"version": "2.0.0"
}
+194 -2
View File
@@ -1,11 +1,13 @@
# `BS::thread_pool`: a fast, lightweight, and easy-to-use C++17 thread pool library
# `BS::thread_pool`: a fast, lightweight, modern, and easy-to-use C++17 / C++20 / C++23 thread pool library
By Barak Shoshany\
By **Barak Shoshany**\
Email: <baraksh@gmail.com>\
Website: <https://baraksh.com/>\
GitHub: <https://github.com/bshoshany>
* [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)
* [v4.0.0 (2023-12-27)](#v400-2023-12-27)
@@ -29,6 +31,196 @@ GitHub: <https://github.com/bshoshany>
## 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 `<windows.h>` to reduce compilation time.
* Bug fixes:
* The system macros `major` and `minor` (from `<sys/sysmacros.h>` on Linux) or `min` and `max` (from `<windows.h>` 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 `<windows.h>`, 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<T>::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.
* **Highlights:**
* Added support for C++20 and C++23, while maintaining full C++17 compatibility. In C++20, the library can now optionally be imported as a module using `import BS.thread_pool` on Clang, GCC, and MSVC. In C++23, both the library itself and the test program can now optionally import the C++ Standard Library as a module using `import std` on supported compilers and platforms. Extensive documentation has been added to `README.md` on how to use these features, to ease the transition.
* Optional features are now enabled via a bitmask template parameter instead of macros, using the flags `BS::tp::priority`, `BS::tp::pause`, and `BS::tp::wait_deadlock_checks`. This makes the optional features easier to use, allows multiple thread pools with different features to coexist, and makes the library compatible with C++20 modules. Exception handling is now disabled automatically if exceptions are disabled, instead of using a macro.
* Added optional native extensions for non-portable features using the operating system's native API: setting the priority and affinity for processes and threads, and setting thread names. These have been tested on the latest versions of Windows, Ubuntu, and macOS.
* This library is now back to being a true single-header library, with a single header file `BS_thread_pool.hpp`. The utility classes have been combined into the main header file. `BS::timer` has been removed, `BS::signaller` has been replaced with `BS::binary_semaphore` and `BS::counting_semaphore` (in C++17 mode only), and `BS::synced_stream` now supports multiple output streams.
* Cleanup functions can now be defined to complement the initialization functions. Both initialization and cleanup functions can now optionally take the index of the thread as an argument.
* Parallelization member functions no longer need type casting or template parameters if the start and end indices are of different types.
* The worker function no longer incorrectly reads shared variables while the mutex is unlocked.
* The type aliases `BS::this_thread::optional_index` and `BS::this_thread::optional_pool` have been removed. Instead, `BS::this_thread::get_index()` returns `std::optional<std::size_t>`, and `BS::this_thread::get_pool()` returns `std::optional<void*>`. The latter must be cast to the correct instantiation of the `BS::thread_pool` class template before using any member functions.
* The thread pool version is now accessible using the object `BS::thread_pool_version`, a `constexpr struct` of type `BS::version` with the members `major`, `minor`, and `patch`. This works even if importing the library as a C++20 module, unlike the version macros.
* The type `priority_t`, used to set priorities, is now defined as `std::int8_t`, which means it takes values from -128 to +127. The pre-defined priorities in `BS::pr`, such as `BS::pr::highest` or `BS::pr::lowest`, have been updated accordingly.
* Exceptions thrown by detached tasks are now caught and prevented from propagating, so that they do not terminate the program. Exceptions thrown by submitted tasks are still rethrown when calling `get()` on the future, as before.
* Parallelization member functions no longer destruct objects prematurely under certain circumstances.
* The test program has been expanded with many new tests for both old and new features. It can also import both the thread pool module using `import BS.thread_pool` (in C++20 and later) and the C++ Standard Library module using `import std` (in C++23) if the appropriate macros are defined, and read default command line arguments from a `default_args.txt` file for debugging purposes.
* Added new and improved benchmarks using a highly-optimized multithreaded algorithm which generates a plot of the Mandelbrot set, utilizing a normalized iteration count algorithm and linear interpolation to create smooth coloring.
* The type `BS::concurrency_t` has been removed; use `std::size_t` instead.
* **C++20 and C++23 support:**
* This library now officially supports C++20 and C++23 in addition to C++17. If compiled with C++20 and/or C++23 support (e.g. using the compiler flag `-std=c++23` in Clang/GCC or `/std:c++latest` on MSVC), the library will make use of newly available features for maximum performance, reliability, and usability.
* To be clear, the library is still fully compatible with any C++17 standard-compliant compiler. I have no plans to remove C++17 support at the moment, as it is still [the most widely used C++ standard](https://www.jetbrains.com/lp/devecosystem-2023/cpp/) among developers, but that might change in the future.
* If C++20 features are available, the library can be imported as a module using `import BS.thread_pool`. This is now the officially recommended way to use the library, as it has many benefits, such as faster compilation times, better encapsulation, no namespace pollution, no include order issues, easier maintainability, simpler dependency management, and more.
* The module file itself is `BS.thread_pool.cppm`, located in the `modules` folder, and it is just a thin wrapper around the header file `BS_thread_pool.hpp`.
* The `constexpr` flag `BS::thread_pool_module` indicates whether the thread pool library was compiled as a module.
* To my knowledge, `BS::thread_pool` is one of the only popular C++ libraries that are [currently available as a C++20 module](https://arewemodulesyet.org/) (and certainly the only thread pool library). This feature has been tested with the latest versions of Clang, GCC, and MSVC. Unfortunately, C++20 modules are still (4 years later!) not fully implemented in all compilers, and each compiler implements them differently; for instructions on how to compile and import the `BS.thread_pool` module in each compiler, please see `README.md`.
* Known issues:
* 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.
* On macOS, Apple Clang v16.0.0 (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.
* Visual Studio Code's C/C++ extension v1.23.2 (latest version at the time of writing) does not yet support modules. My temporary solution for that, as demonstrated in the test program, is to define the macro `BS_THREAD_POOL_TEST_IMPORT_MODULE` (see below) when compiling the test program, but not when editing in the IDE. If the macro is enabled, the module is imported via `import BS.thread_pool`, otherwise the header file is included using `#include "BS_thread_pool.hpp"` as usual.
* If C++23 features are available, both the library and the test program can now import the C++ Standard Library as a module using `import std`. To enable this, define the macro `BS_THREAD_POOL_IMPORT_STD` at compilation time. This is currently only officially supported by recent versions of MSVC with Microsoft STL or 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.
* If `BS_THREAD_POOL_IMPORT_STD` is defined, then you must also import the 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.
* Defining the macro before importing the module will not work, as modules cannot access macros defined in the program that imported them. Instead, define the macro as a compiler flag, e.g. `-D BS_THREAD_POOL_IMPORT_STD` (or `/D` for MSVC).
* 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.
* If C++20 features are available, the pool will use `std::jthread` instead of `std::thread`. This allows considerable simplification and added safety, since the threads no longer need to be manually joined, and `std::stop_token` is used to stop the workers automatically when destructing the threads. This eliminates the need for the `destroy_threads()` member function, as well as the `workers_running` flag, which are now only used in C++17 mode.
* If C++20 features are available, the library will use concepts to enforce the signature of the initialization function and to selectively enable member functions related to pausing only if pausing is enabled. In C++17 mode, the library will use SFINAE to achieve essentially the same effect.
* If C++23 features are available, the task queue will use `std::move_only_function<void()>` instead of `std::function<void()>`. This allows `submit_task()` to work without using a shared pointer, which should increase performance.
* **API migration:** All of the C++20/C++23 features listed above are either automatically applied based on compiler settings or optional. If you are still using C++17, or if you are using C++20 or C++23 but do not wish to import the thread pool library and/or the C++ Standard Library as a module, no changes are needed.
* **Optional features overhaul:**
* All optional features are now enabled via a bitmask template parameter instead of macros. This works using `if constexpr`, `std::conditional_t`, and concepts (in C++20 and later) or SFINAE (in C++17).
* This change makes the optional features much easier and more intuitive to use, as you no longer need to define any macros before including the header file.
* Additionally, it allows you to have multiple thread pools in the same program with different optional features enabled or disabled. For example, you can have one pool with task priority enabled and another without.
* Most importantly, this makes it possible to import the library as a C++20 module, as macros cannot be read by imported modules.
* The bitmask flags are members of the `BS::tp` enumeration:
* `BS::tp::priority` enables task priority (previously enabled via the macro `BS_THREAD_POOL_ENABLE_PRIORITY`, which has been removed).
* `BS::tp::pause` enables pausing the pool (previously enabled via the macro `BS_THREAD_POOL_ENABLE_PAUSE`, which has been removed).
* `BS::tp::wait_deadlock_checks` enables deadlock checks in `wait()`/`wait_for()`/`wait_until()` (previously enabled via the macro `BS_THREAD_POOL_ENABLE_WAIT_DEADLOCK_CHECK`, which has been removed).
* The default is `BS::tp::none`, which disables all optional features.
* Convenience aliases are defined as follows:
* `BS::light_thread_pool` disables all optional features (equivalent to `BS::thread_pool` with the default template parameter, that is, `BS::thread_pool<BS::tp::none>`).
* `BS::priority_thread_pool` enables task priority (equivalent to `BS::thread_pool<BS::tp::priority>`).
* `BS::pause_thread_pool` enables pausing the pool (equivalent to `BS::thread_pool<BS::tp::pause>`).
* `BS::wdc_thread_pool` enables wait deadlock checks (equivalent to `BS::thread_pool<BS::tp::wait_deadlock_checks>`).
* There are no aliases with multiple features enabled; if this is desired, you must either pass the template parameter explicitly or define your own alias. Note that the parameter is a bitmask, so to enable multiple features, you need to use the bitwise OR operator `|`, e.g. `BS::thread_pool<BS::tp::priority | BS::tp::pause>` to enable both task priority and pausing.
* The macro `BS_THREAD_POOL_DISABLE_EXCEPTION_HANDLING` has been removed. Exception handling is disabled automatically if exceptions are disabled, based on whether the feature-test macro `__cpp_exceptions` is defined.
* The exception thrown by wait deadlock checks is now `BS::wait_deadlock` instead of `BS::thread_pool::wait_deadlock`, to avoid having to deal with different template parameters.
* The macro `BS_THREAD_POOL_LIGHT_TEST` has been removed from the test program, as all optional features are now tested by enabling them selectively via the template parameter, so there is no need to compile with different macros.
* If for some reason you forgot which options you enabled when creating the pool, the `static constexpr` members `priority_enabled`, `pause_enabled`, and `wait_deadlock_checks_enabled` can be used to check if the corresponding features are enabled.
* **API migration:**
* `BS::thread_pool` can still be used without the template parameter, for backwards compatibility; this will create a thread pool with all optional features disabled. Therefore, if you did not use any of the optional features in existing code, no changes are needed.
* If your code uses any of the optional features by defining macros before including the header file, please remove these macros, and instead either use one of the convenience aliases above or define the template parameter explicitly using the `BS::tp` enumeration when creating the pool.
* If you use wait deadlock checks, you must now catch the exception `BS::wait_deadlock` instead of `BS::thread_pool::wait_deadlock`.
* **Native extensions:**
* While portability is one of my guiding principle when developing this library, non-portable features such as setting the thread priority using the operating system's native API are frequently requested by users. Starting with this release, the library includes native extensions, which are disabled by default.
* Currently, the extensions provide the following functions (please see `README.md` for details on how to use them):
* `BS::get_os_process_affinity()` and `BS::set_os_process_affinity()` to get and set the CPU affinity of the current process in a portable way. Should work on Windows and Linux, but not on macOS, as the native API does not allow it.
* `BS::get_os_process_priority()` and `BS::set_os_process_priority()` to get and set the priority of the current process in a portable way. Should work on Windows, Linux, and macOS.
* `BS::this_thread::get_os_thread_affinity()` and `BS::this_thread::set_os_thread_affinity()` to get and set the CPU affinity of the current thread in a portable way. Should work on Windows and Linux, but not on macOS, as the native API does not allow it.
* `BS::this_thread::get_os_thread_priority()` and `BS::this_thread::set_os_thread_priority()` to get and set the priority of the current thread in a portable way. Should work on Windows, Linux, and macOS.
* `BS::this_thread::get_os_thread_name()` and `BS::this_thread::set_os_thread_name()` to get and set the name of the current thread in a portable way, for debugging purposes. Should work on Windows, Linux, and macOS.
* The native extensions may be enabled by defining the macro `BS_THREAD_POOL_NATIVE_EXTENSIONS` at compilation time.
* Even if the macro is defined, the extensions are disabled automatically if a supported operating system (Windows, Linux, or macOS) is not detected.
* Note that if you are using the library as a C++20 module, defining the macro before importing the module will not work, as modules cannot access macros defined in the program that imported them. Instead, define the macro as a compiler flag, e.g. `-D BS_THREAD_POOL_NATIVE_EXTENSIONS` (or `/D` for MSVC).
* The macro `BS_THREAD_POOL_ENABLE_NATIVE_HANDLES` has been removed. The thread pool member function `get_native_handles()` is now part of the native extensions, so it is enabled using the macro `BS_THREAD_POOL_NATIVE_EXTENSIONS`.
* Please note that 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.
* The test program only tests the native extensions if the macro `BS_THREAD_POOL_NATIVE_EXTENSIONS` is defined at compilation time. If importing the library as a module, please ensure that the macro is also enabled when compiling the module.
* 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.
* **API migration:** The native extensions are a brand new optional feature and do not require any changes to existing code.
* **Utility classes:**
* This library is now back to being a true single-header library, with a single header file `BS_thread_pool.hpp`. The utility classes (previously in a separate header `BS_thread_pool_utils.hpp`, which has been removed) have been combined into the main header file.
* The `BS::timer` class has been removed from the library, since it doesn't really have anything to do with multithreading directly. However, it is still available in the test program if you want to use it.
* The `BS::signaller` class has been removed from the library, and replaced with `BS::binary_semaphore` and `BS::counting_semaphore`, which are C++17 polyfills for the C++20 classes `std::binary_semaphore` and `std::counting_semaphore`. If C++20 features are available, the polyfills are not used, and instead are just aliases for the standard library classes. The reason is that semaphores can do the same thing that the signaller class was previously used for, but are much more versatile.
* The `BS::synced_stream` class now supports printing to more than one output stream.
* **API migration:**
* If you previously included the `BS_thread_pool_utils.hpp` header file, this is no longer needed. Only include the header `BS_thread_pool.hpp`, or better yet, in C++20 or later, import the library as a module using `import BS.thread_pool`.
* If you previously used the `BS::timer` class, it is no longer available in the header file, but if you still need it you can copy it into your program directly from the test program `BS_thread_pool_test.cpp`.
* If you previously used the `BS::signaller` class, you can replace it with `BS::binary_semaphore` or `BS::counting_semaphore`. Previously, you defined an object `BS::signaller signal`, and then used `signal.wait()` to wait for the signal, and `signal.ready()` to unblock all waiting threads. Now, you can define an object `BS::counting_semaphore signal(0)`, and use `signal.acquire()` to wait for the signal, and `signal.release(num_threads)` to unblock waiting threads; note that the number of threads to release must be passed explicitly, as the semaphore also allows you to unblock only some of them. Use `BS::binary_semaphore` if only one thread will be waiting at any given time.
* If you previously used the `BS::synced_stream` class, no changes are needed.
* **Cleanup and initialization functions:**
* Using the new `set_cleanup_func()` member function, it is now possible to provide the pool with a cleanup function to run in each thread right before it is destroyed, which will happen when the pool is destructed or reset. See [#152](https://github.com/bshoshany/thread-pool/issues/152).
* Both initialization and cleanup functions can now optionally take the index of the thread as an argument.
* Added a warning in the documentation that both initialization and cleanup functions must not throw any exceptions, as that will result in program termination. Any exceptions must be handled explicitly within the function.
* **API migration:** No changes to existing code are needed.
* **Parallelization index types:**
* All member functions which parallelize collections of tasks, namely `detach_blocks()`, `detach_loop()`, `detach_sequence()`, `submit_blocks()`, `submit_loop()`, and `submit_sequence()`, can now be called with start and end indices of different types.
* Previously, the indices had to be of the same type, or the template parameter had to be explicitly specified; this is no longer needed, as the library will automatically cast the indices to a suitable common type.
* This was already possible in v2.X.X and v3.X.X, where it was done using [`std::common_type`](https://en.cppreference.com/w/cpp/types/common_type), but I removed it in v4.X.X because `std::common_type` sometimes completely messed up the range of the loop. For example, the `std::common_type` of `int` and `unsigned int` is `unsigned int`, which means the loop will only use non-negative indices even if the `int` start index was negative, resulting in an integer overflow.
* Starting with v5.0.0, the library uses a custom type trait `BS::common_index_type` to determine the common type of the indices. The common type of two signed integers or two unsigned integers is the larger of the integers, while the common type of a signed and an unsigned integer is a signed integer that can hold the full ranges of both integers. This avoids messing up the indices, except in the case of `std::uint64_t`, where there is no fundamental signed type that can hold its entire range. In this case, we choose `std::uint64_t` as the common type, since the most common use case is where the indices go from 0 to `x` where `x` has been previously defined as `std::size_t`. This will fail if the first index is negative; in that case, the user must cast the indices explicitly.
* **API migration:** Existing code which uses type casting or explicit template parameters in parallelization functions does not need to be changed, but it can be simplified by removing the casting or template parameters. However, if one index is negative and the other is an unsigned 64-bit integer, casting is still needed (although you should probably not be doing this in the first place, as casting to either of the two types will result in potential narrowing or overflow).
* **`BS::this_thread`:**
* `BS::this_thread` is now a class instead of a namespace, since defining it as a namespace proved to be incompatible with C++20 modules (at least in some compilers). Defining it as a class also results in a simpler implementation. However, the functionality remains the same, and since it only has static methods, the call syntax for `BS::this_thread::get_index()` and `BS::this_thread::get_pool()` is unchanged.
* The type aliases `BS::this_thread::optional_index` and `BS::this_thread::optional_pool` have been removed. Instead, `BS::this_thread::get_index()` now returns the explicit type `std::optional<std::size_t>`, and `BS::this_thread::get_pool()` returns `std::optional<void*>`.
* The rationale for this removal is that using `std::optional` explicitly provides more information about the type that is being returned, and most users are probably not using the explicit types anyway (either by using `auto` or by invoking the `std::optional` member functions directly on the returned object).
* Note that `BS::this_thread::get_pool()` now returns an optional `void*` instead of `BS::thread_pool*`. The reason for that is that `BS::thread_pool` is now a template. Once you obtain the pool pointer, you must cast it to the desired instantiation of the template if you want to use any member functions. Note that you have to cast it to the correct type; if you cast a pointer to a `BS::light_thread_pool` into a pointer to a `BS::priority_thread_pool`, for example, your program will have undefined behavior.
* **API migration:**
* If your code uses the type aliases, please replace `BS::this_thread::optional_index` with `std::optional<std::size_t>` and `BS::this_thread::optional_pool` with `std::optional<void*>`.
* If your code uses `BS::this_thread::get_pool()`, you must now cast the returned pointer to the correct instantiation of the `BS::thread_pool` class template before using any member functions.
* **Determining the library version:**
* The library now 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. For example, you can do `static_assert(BS::thread_pool_version == BS::version(5, 0, 0))`, or you can use it in `if constexpr` for conditional compilation.
* The version macros `BS_THREAD_POOL_VERSION_MAJOR`, `BS_THREAD_POOL_VERSION_MINOR`, and `BS_THREAD_POOL_VERSION_PATCH` are still defined, since they can be used in conditional code inclusion, and for backwards compatibility. However, since C++20 modules cannot export macros, `BS::thread_pool_version` is the only way to check the version of the thread pool library if you are importing it as a module.
* **API migration:** No changes needed in existing code; if you previously used the macros `BS_THREAD_POOL_VERSION_MAJOR`, `BS_THREAD_POOL_VERSION_MINOR`, and `BS_THREAD_POOL_VERSION_PATCH` to determine the version of the library when including it as a header file, you can still do so. However, if you wish to import the library as a C++20 module, you must use the object `BS::thread_pool_version` instead.
* **Task priority:**
* The type `priority_t`, used to set priorities, is now defined as `std::int8_t`, which means it takes values from -128 to +127. The pre-defined priorities in `BS::pr`, such as `BS::pr::highest` or `BS::pr::lowest`, have been updated accordingly (also, it is now an `enum` instead of a namespace). The old priority type `std::int16_t` was unnecessarily large; having fewer priority values means less bookkeeping in the priority queue, which should also improve performance.
* **API migration:** If you used the pre-defined priorities in `BS::pr`, no changes are needed. If you specified numerical priorities directly, you may need to adjust them to the new range of -128 to +127.
* **Miscellaneous:**
* Exceptions thrown by detached tasks are now caught and prevented from propagating, so that they do not terminate the program. Exceptions thrown by submitted tasks are still rethrown when calling `get()` on the future, as before.
* All member functions which parallelize collections of tasks, namely `detach_blocks()`, `detach_loop()`, `detach_sequence()`, `submit_blocks()`, `submit_loop()`, and `submit_sequence()`, now store the callable object inside an `std::shared_ptr`, and then pass that shared pointer to each subtask. Previously, the callable was passed using perfect forwarding, which under some circumstances resulted in mistakenly moving the callable during the first iteration of the loop, thus potentially destructing captured objects prematurely. The new shared pointer method resolves this issue, while also avoiding making copies of the callable. See [#149](https://github.com/bshoshany/thread-pool/issues/149).
* Fixed incorrect reading of shared variables while the mutex is unlocked in the worker function. See [#159](https://github.com/bshoshany/thread-pool/issues/159).
* Added documentation to `README.md` for all the new features. In addition, fixed some typos and other minor issues in the existing documentation.
* Added instructions in `README.md` for installing the library using CMake with `FetchContent` instead of CPM. See [#155](https://github.com/bshoshany/thread-pool/pull/155).
* The type `BS::concurrency_t` has been removed. In previous versions this type was defined to be the type of the value returned by `std::thread::hardware_concurrency()` (which is supposed to be `unsigned int`), for maximum portability. However, in practice this value is only used to indicate the size of arrays, so `std::size_t` is more appropriate, and this simplifies the code.
* **API migration:** If you used `BS::concurrency_t` in your code, please replace it with `std::size_t`. If you previously cast to/from these two types, you can now remove the cast.
* **Tests:**
* The test program `BS_thread_pool_test.cpp` will import the library as a C++20 module via `import BS.thread_pool` if the macro `BS_THREAD_POOL_TEST_IMPORT_MODULE` is defined, C++20 or later is detected, and a supported compiler is used.
* The test program will also import the C++ Standard Library as a module using `import std` if the macro `BS_THREAD_POOL_IMPORT_STD` is defined during compilation, on supported compilers and platforms.
* The new test `check_copy()` checks that the callable object does not get copied when parallelized into multiple tasks. It will succeed on previous versions of the library, but not if perfect forwarding is removed.
* The new test `check_shared_ptr()` checks that captured shared pointers do not prematurely destruct. It will fail on previous versions.
* The new test `check_task_destruct()` checks that a task is destructed immediately after it executes, and therefore does not artificially extend the lifetime of any captured objects.
* The new test `check_common_index_type()` checks that the type trait `BS::common_index_type` (see above) works as expected.
* The new tests `check_os_process_priorities()`, `check_os_thread_priorities()`, `check_os_process_affinity()`, `check_os_thread_affinity()`, and `check_os_thread_names()` check the corresponding features of the native extensions.
* The new test `check_callables()` checks that different callable types are accepted by the thread pool.
* New command line argument: `stdout`, to print to the standard output, enabled by default.
* 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.
* The test program will now detect and log the OS, compiler, standard library, C++ standard, available C++ features, whether the thread pool was imported as a C++20 module, and whether the standard library was imported as a module.
* **Benchmarks:**
* Added new and improved benchmarks using a highly-optimized multithreaded algorithm which generates a plot of the Mandelbrot set, utilizing a normalized iteration count algorithm and linear interpolation to create smooth coloring.
* These benchmarks are heavily CPU-intensive, and much less limited by memory and cache compared to the benchmarks in previous versions (which used vector or matrix operations). This results in a much higher speedup factor due to multithreading, utilizing every core and thread to their fullest extent. This makes these benchmarks more useful for optimizing the library, since they are more sensitive to the thread pool's own performance.
* 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, since I didn't want to depend on any 3rd-party libraries. This is off by default, since that file can get quite large.
* **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.
* 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.
### v4.1.0 (2024-03-22)
* This library is now published in [SoftwareX](https://www.sciencedirect.com/journal/softwarex)! If you use it 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](https://doi.org/10.1016/j.softx.2024.101687), [SoftwareX 26 (2024) 101687](https://www.sciencedirect.com/science/article/pii/S235271102400058X), [arXiv:2105.00613](https://arxiv.org/abs/2105.00613)
+1 -1
View File
@@ -9,4 +9,4 @@
url = {https://www.sciencedirect.com/science/article/pii/S235271102400058X},
volume = {26},
year = {2024}
}
}
+16 -13
View File
@@ -1,22 +1,25 @@
cff-version: 1.2.0
message: If you use this library in published research, please cite it as follows.
authors:
- given-names: Barak
- email: baraksh@gmail.com
family-names: Shoshany
given-names: Barak
orcid: https://orcid.org/0000-0003-2222-127X
email: bshoshany@brocku.ca
title: A C++17 Thread Pool for High-Performance Scientific Computing
cff-version: 1.2.0
doi: 10.1016/j.softx.2024.101687
url: https://github.com/bshoshany/thread-pool
license: MIT
message: If you use this library in published research, please cite it as follows.
preferred-citation:
type: article
authors:
- given-names: Barak
family-names: Shoshany
title: A C++17 Thread Pool for High-Performance Scientific Computing
- family-names: Shoshany
given-names: Barak
doi: 10.1016/j.softx.2024.101687
journal: SoftwareX
start: 101687
title: A C++17 Thread Pool for High-Performance Scientific Computing
type: article
url: https://www.sciencedirect.com/science/article/pii/S235271102400058X
volume: 26
year: 2024
start: 101687
doi: 10.1016/j.softx.2024.101687
url: https://www.sciencedirect.com/science/article/pii/S235271102400058X
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
+1 -1
View File
@@ -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
+2076 -624
View File
File diff suppressed because it is too large Load Diff
+31
View File
@@ -0,0 +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, /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, 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]. 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
+2021 -667
View File
File diff suppressed because it is too large Load Diff
-203
View File
@@ -1,203 +0,0 @@
#ifndef BS_THREAD_POOL_UTILS_HPP
#define BS_THREAD_POOL_UTILS_HPP
/**
* @file BS_thread_pool_utils.hpp
* @author Barak Shoshany (baraksh@gmail.com) (https://baraksh.com)
* @version 4.1.0
* @date 2024-03-22
* @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
*
* @brief BS::thread_pool: a fast, lightweight, and easy-to-use C++17 thread pool library. This header file contains independent utility classes that are part of the library, but are not needed to use the thread pool itself.
*/
#include <chrono> // std::chrono
#include <future> // std::promise, std::shared_future
#include <initializer_list> // std::initializer_list
#include <iostream> // std::cout
#include <memory> // std::make_unique, std::unique_ptr
#include <mutex> // std::mutex, std::scoped_lock
#include <ostream> // std::endl, std::flush, std::ostream
#include <utility> // std::forward
/**
* @brief A namespace used by Barak Shoshany's projects.
*/
namespace BS {
// Macros indicating the version of the thread pool utilities library.
#define BS_THREAD_POOL_UTILS_VERSION_MAJOR 4
#define BS_THREAD_POOL_UTILS_VERSION_MINOR 1
#define BS_THREAD_POOL_UTILS_VERSION_PATCH 0
/**
* @brief A utility class to allow simple signalling between threads.
*/
class [[nodiscard]] signaller
{
public:
/**
* @brief Construct a new signaller.
*/
signaller() : promise(), future(promise.get_future()) {}
// The copy constructor and copy assignment operator are deleted. The signaller works using a promise, which cannot be copied.
signaller(const signaller&) = delete;
signaller& operator=(const signaller&) = delete;
// The move constructor and move assignment operator are defaulted.
signaller(signaller&&) = default;
signaller& operator=(signaller&&) = default;
/**
* @brief Inform any waiting threads that the signaller is ready.
*/
void ready()
{
promise.set_value();
}
/**
* @brief Wait until the signaller is ready.
*/
void wait()
{
future.wait();
}
private:
/**
* @brief A promise used to set the state of the signaller.
*/
std::promise<void> promise;
/**
* @brief A future used to wait for the signaller.
*/
std::shared_future<void> future;
}; // class signaller
/**
* @brief A utility class to synchronize printing to an output stream by different threads.
*/
class [[nodiscard]] synced_stream
{
public:
/**
* @brief Construct a new synced stream.
*
* @param stream The output stream to print to. The default value is `std::cout`.
*/
explicit synced_stream(std::ostream& stream = std::cout) : out_stream(stream) {}
// The copy and move constructors and assignment operators are deleted. The synced stream uses a mutex, which cannot be copied or moved.
synced_stream(const synced_stream&) = delete;
synced_stream(synced_stream&&) = delete;
synced_stream& operator=(const synced_stream&) = delete;
synced_stream& operator=(synced_stream&&) = delete;
/**
* @brief Print any number of items into the output stream. Ensures that no other threads print to this stream simultaneously, as long as they all exclusively use the same `synced_stream` object to print.
*
* @tparam T The types of the items.
* @param items The items to print.
*/
template <typename... T>
void print(T&&... items)
{
const std::scoped_lock stream_lock(stream_mutex);
(out_stream << ... << std::forward<T>(items));
}
/**
* @brief Print any number of items into the output stream, followed by a newline character. Ensures that no other threads print to this stream simultaneously, as long as they all exclusively use the same `synced_stream` object to print.
*
* @tparam T The types of the items.
* @param items The items to print.
*/
template <typename... T>
void println(T&&... items)
{
print(std::forward<T>(items)..., '\n');
}
/**
* @brief A stream manipulator to pass to a `synced_stream` (an explicit cast of `std::endl`). Prints a newline character to the stream, and then flushes it. Should only be used if flushing is desired, otherwise a newline character should be used instead.
*/
inline static std::ostream& (&endl)(std::ostream&) = static_cast<std::ostream& (&)(std::ostream&)>(std::endl);
/**
* @brief A stream manipulator to pass to a `synced_stream` (an explicit cast of `std::flush`). Used to flush the stream.
*/
inline static std::ostream& (&flush)(std::ostream&) = static_cast<std::ostream& (&)(std::ostream&)>(std::flush);
private:
/**
* @brief The output stream to print to.
*/
std::ostream& out_stream;
/**
* @brief A mutex to synchronize printing.
*/
mutable std::mutex stream_mutex = {};
}; // class synced_stream
/**
* @brief A utility class to measure execution time for benchmarking purposes.
*/
class [[nodiscard]] timer
{
public:
/**
* @brief Construct a new timer and immediately start measuring time.
*/
timer() = default;
/**
* @brief Get the number of milliseconds that have elapsed since the object was constructed or since `start()` was last called, but keep the timer ticking.
*
* @return The number of milliseconds.
*/
[[nodiscard]] std::chrono::milliseconds::rep current_ms() const
{
return (std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::steady_clock::now() - start_time)).count();
}
/**
* @brief Start (or restart) measuring time. Note that the timer starts ticking as soon as the object is created, so this is only necessary if we want to restart the clock later.
*/
void start()
{
start_time = std::chrono::steady_clock::now();
}
/**
* @brief Stop measuring time and store the elapsed time since the object was constructed or since `start()` was last called.
*/
void stop()
{
elapsed_time = std::chrono::steady_clock::now() - start_time;
}
/**
* @brief Get the number of milliseconds stored when `stop()` was last called.
*
* @return The number of milliseconds.
*/
[[nodiscard]] std::chrono::milliseconds::rep ms() const
{
return (std::chrono::duration_cast<std::chrono::milliseconds>(elapsed_time)).count();
}
private:
/**
* @brief The time point when measuring started.
*/
std::chrono::time_point<std::chrono::steady_clock> start_time = std::chrono::steady_clock::now();
/**
* @brief The duration that has elapsed between `start()` and `stop()`.
*/
std::chrono::duration<double> elapsed_time = std::chrono::duration<double>::zero();
}; // class timer
} // namespace BS
#endif
+61
View File
@@ -0,0 +1,61 @@
/**
* ██████ ███████ ████████ ██ ██ ██████ ███████ █████ ██████ ██████ ██████ ██████ ██
* ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██
* ██████ ███████ ██ ███████ ██████ █████ ███████ ██ ██ ██████ ██ ██ ██ ██ ██
* ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██
* ██████ ███████ ██ ██ ██ ██ ██ ███████ ██ ██ ██████ ███████ ██ ██████ ██████ ███████
*
* @file BS.thread_pool.cppm
* @author Barak Shoshany (baraksh@gmail.com) (https://baraksh.com/)
* @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 module file wraps the header file BS_thread_pool.hpp inside a C++20 module so it can be imported using `import BS.thread_pool`.
*/
module;
// A macro indicating to the library that it is being imported as a module, as well as the version of the module file, which must match the version of the header file.
#define BS_THREAD_POOL_MODULE 5, 1, 0
#include "BS_thread_pool.hpp"
export module BS.thread_pool;
export namespace BS {
using BS::common_index_type_t;
using BS::light_thread_pool;
using BS::multi_future;
using BS::operator&;
using BS::operator^;
using BS::operator|;
using BS::operator~;
using BS::pause_thread_pool;
using BS::pr;
using BS::priority_t;
using BS::priority_thread_pool;
using BS::synced_stream;
using BS::this_thread;
using BS::thread_pool;
using BS::thread_pool_import_std;
using BS::thread_pool_module;
using BS::thread_pool_native_extensions;
using BS::thread_pool_version;
using BS::tp;
using BS::version;
using BS::wdc_thread_pool;
#ifdef __cpp_exceptions
using BS::wait_deadlock;
#endif
#ifdef BS_THREAD_POOL_NATIVE_EXTENSIONS
using BS::get_os_process_affinity;
using BS::get_os_process_priority;
using BS::os_process_priority;
using BS::os_thread_priority;
using BS::set_os_process_affinity;
using BS::set_os_process_priority;
#endif
} // namespace BS
+382
View File
@@ -0,0 +1,382 @@
[tool.pyright]
analyzeUnannotatedFunctions = true
deprecateTypingAliases = true
disableBytesTypePromotions = true
enableExperimentalFeatures = false
enableReachabilityAnalysis = true
enableTypeIgnoreComments = true
extraPaths = ["."]
pythonPlatform = "All"
pythonVersion = "3.13"
reportAbstractUsage = "error"
reportArgumentType = "error"
reportAssertAlwaysTrue = "error"
reportAssertTypeFailure = "error"
reportAssignmentType = "error"
reportAttributeAccessIssue = "error"
reportCallInDefaultInitializer = "error"
reportCallIssue = "error"
reportConstantRedefinition = "error"
reportDeprecated = "error"
reportDuplicateImport = "error"
reportFunctionMemberAccess = "error"
reportGeneralTypeIssues = "error"
reportImplicitOverride = "error"
reportImplicitStringConcatenation = "error"
reportImportCycles = "error"
reportIncompatibleMethodOverride = "error"
reportIncompatibleVariableOverride = "error"
reportIncompleteStub = "error"
reportInconsistentConstructor = "error"
reportInconsistentOverload = "error"
reportIndexIssue = "error"
reportInvalidStringEscapeSequence = "error"
reportInvalidStubStatement = "error"
reportInvalidTypeArguments = "error"
reportInvalidTypeForm = "error"
reportInvalidTypeVarUse = "error"
reportMatchNotExhaustive = "error"
reportMissingImports = "error"
reportMissingModuleSource = "error"
reportMissingParameterType = "error"
reportMissingTypeArgument = "error"
reportMissingTypeStubs = "error"
reportNoOverloadImplementation = "error"
reportOperatorIssue = "none"
reportOptionalCall = "error"
reportOptionalContextManager = "error"
reportOptionalIterable = "error"
reportOptionalMemberAccess = "error"
reportOptionalOperand = "error"
reportOptionalSubscript = "error"
reportOverlappingOverload = "error"
reportPossiblyUnboundVariable = "error"
reportPrivateImportUsage = "error"
reportPrivateUsage = "error"
reportPropertyTypeMismatch = "none"
reportRedeclaration = "error"
reportReturnType = "error"
reportSelfClsParameterName = "error"
reportShadowedImports = "error"
reportTypeCommentUsage = "error"
reportTypedDictNotRequiredAccess = "error"
reportUnboundVariable = "error"
reportUndefinedVariable = "error"
reportUnhashable = "error"
reportUninitializedInstanceVariable = "error"
reportUnknownArgumentType = "error"
reportUnknownLambdaType = "error"
reportUnknownMemberType = "none"
reportUnknownParameterType = "error"
reportUnknownVariableType = "error"
reportUnnecessaryCast = "error"
reportUnnecessaryComparison = "error"
reportUnnecessaryContains = "error"
reportUnnecessaryIsInstance = "error"
reportUnnecessaryTypeIgnoreComment = "error"
reportUnsupportedDunderAll = "error"
reportUntypedBaseClass = "error"
reportUntypedClassDecorator = "error"
reportUntypedFunctionDecorator = "error"
reportUntypedNamedTuple = "error"
reportUnusedCallResult = "error"
reportUnusedClass = "warning"
reportUnusedCoroutine = "error"
reportUnusedExcept = "error"
reportUnusedExpression = "error"
reportUnusedFunction = "warning"
reportUnusedImport = "warning"
reportUnusedVariable = "warning"
reportWildcardImportFromLibrary = "error"
strictDictionaryInference = true
strictListInference = true
strictParameterNoneValue = true
strictSetInference = true
typeCheckingMode = "strict"
useLibraryCodeForTypes = true
[tool.ruff]
indent-width = 4
line-length = 320
target-version = "py313"
[tool.ruff.format]
docstring-code-format = false
docstring-code-line-length = "dynamic"
indent-style = "space"
line-ending = "lf"
quote-style = "double"
skip-magic-trailing-comma = false
[tool.ruff.lint]
dummy-variable-rgx = "^(_+|(_+[a-zA-Z0-9_]*[a-zA-Z0-9]+?))$"
fixable = ["ALL"]
ignore = [
"BLE001",
"C901",
"D200",
"D203",
"D205",
"D212",
"D400",
"D402",
"D415",
"E501",
"INP001",
"N814",
"N999",
"PLR0912",
"PLR0913",
"PLR2004",
"RUF009",
"S310",
"S602",
"S603",
"S607",
"SIM108",
"SIM112",
"SLF001",
"T201",
"TCH003",
"TD002",
"TD003",
"UP015",
]
select = ["ALL"]
unfixable = []
[tool.ruff.lint.per-file-ignores]
"Interactive*" = ["ALL"]
[tool.pylint.main]
analyse-fallback-blocks = false
clear-cache-post-run = false
exit-zero = false
extension-pkg-allow-list = []
extension-pkg-whitelist = []
fail-on = ""
fail-under = 10
from-stdin = false
ignore-paths = []
ignore-patterns = []
ignored-modules = []
init-hook = ""
jobs = 0
limit-inference-results = 100
load-plugins = []
persistent = true
prefer-stubs = true
py-version = "3.13"
recursive = false
source-roots = []
unsafe-load-any-extension = false
[tool.pylint.basic]
argument-naming-style = "snake_case"
argument-rgx = ""
attr-naming-style = "snake_case"
attr-rgx = ""
bad-names = []
bad-names-rgxs = ""
class-attribute-naming-style = "any"
class-attribute-rgx = ""
class-const-naming-style = "UPPER_CASE"
class-const-rgx = ""
class-naming-style = "PascalCase"
class-rgx = ""
const-naming-style = "UPPER_CASE"
const-rgx = ""
docstring-min-length = -1
function-naming-style = "snake_case"
function-rgx = ""
good-names = ["_"]
good-names-rgxs = ""
include-naming-hint = true
inlinevar-naming-style = "any"
inlinevar-rgx = ""
method-naming-style = "snake_case"
method-rgx = ""
module-naming-style = "snake_case"
module-rgx = ""
name-group = []
no-docstring-rgx = ""
property-classes = ["abc.abstractproperty"]
typealias-rgx = ""
typevar-rgx = ""
variable-naming-style = "snake_case"
variable-rgx = ""
[tool.pylint.classes]
check-protected-access-in-special-methods = true
defining-attr-methods = [
"__init__",
"__new__",
"__post_init__",
"asyncSetUp",
"setUp",
]
exclude-protected = [
"_asdict",
"_fields",
"_make",
"_replace",
"_source",
"os._exit",
]
valid-classmethod-first-arg = ["cls"]
valid-metaclass-classmethod-first-arg = ["mcs"]
[tool.pylint.design]
exclude-too-few-public-methods = []
ignored-parents = []
max-args = 5
max-attributes = 7
max-bool-expr = 5
max-branches = 12
max-locals = 15
max-parents = 7
max-public-methods = 20
max-returns = 6
max-statements = 50
min-public-methods = 2
[tool.pylint.exceptions]
overgeneral-exceptions = ["builtins.BaseException", "builtins.Exception"]
[tool.pylint.format]
expected-line-ending-format = "LF"
ignore-long-lines = "^\\s*(# )?<?https?://\\S+>?$"
indent-after-paren = 4
indent-string = " "
max-line-length = 1024
max-module-lines = 8192
single-line-class-stmt = false
single-line-if-stmt = false
[tool.pylint.imports]
allow-any-import-level = []
allow-reexport-from-package = false
allow-wildcard-with-all = false
deprecated-modules = []
ext-import-graph = ""
import-graph = ""
int-import-graph = ""
known-standard-library = []
known-third-party = []
preferred-modules = []
[tool.pylint.logging]
logging-format-style = "new"
logging-modules = ["logging"]
[tool.pylint."messages control"]
confidence = []
disable = [
"broad-exception-caught",
"consider-using-enumerate",
"expression-not-assigned",
"import-error",
"invalid-unary-operand-type",
"missing-module-docstring",
"named-expr-without-context",
"not-callable",
"pointless-statement",
"protected-access",
"too-few-public-methods",
"too-many-arguments",
"too-many-boolean-expressions",
"too-many-branches",
"too-many-instance-attributes",
"too-many-locals",
"too-many-nested-blocks",
"too-many-public-methods",
"ungrouped-imports",
"use-implicit-booleaness-not-comparison-to-string",
"use-implicit-booleaness-not-comparison-to-zero",
"wrong-import-order",
"wrong-import-position",
]
enable = ["all"]
[tool.pylint.method_args]
timeout-methods = [
"requests.api.delete",
"requests.api.get",
"requests.api.head",
"requests.api.options",
"requests.api.patch",
"requests.api.post",
"requests.api.put",
"requests.api.request",
]
[tool.pylint.miscellaneous]
notes = ["TODO"]
notes-rgx = ""
[tool.pylint.refactoring]
max-nested-blocks = 5
never-returning-functions = ["argparse.parse_error", "sys.exit"]
suggest-join-with-non-empty-separator = true
[tool.pylint.reports]
evaluation = "max(0, 0 if fatal else 10.0 - ((float(5 * error + warning + refactor + convention) / statement) * 10))"
msg-template = ""
output-format = "text"
reports = true
score = true
[tool.pylint.similarities]
ignore-comments = true
ignore-docstrings = true
ignore-imports = true
ignore-signatures = true
min-similarity-lines = 4
[tool.pylint.spelling]
max-spelling-suggestions = 4
spelling-dict = ""
spelling-ignore-comment-directives = "fmt: on,fmt: off,noqa:,noqa,nosec,isort:skip,mypy:"
spelling-ignore-words = ""
spelling-private-dict-file = ""
spelling-store-unknown-words = false
[tool.pylint.typecheck]
contextmanager-decorators = ["contextlib.contextmanager"]
generated-members = []
ignore-mixin-members = true
ignore-none = true
ignore-on-opaque-inference = false
ignored-checks-for-mixins = [
"attribute-defined-outside-init",
"no-member",
"not-async-context-manager",
"not-context-manager",
]
ignored-classes = [
"_thread._local",
"argparse.Namespace",
"optparse.Values",
"thread._local",
]
missing-member-hint = true
missing-member-hint-distance = 1
missing-member-max-choices = 1
mixin-class-rgx = ".*[Mm]ixin"
signature-mutators = []
[tool.pylint.variables]
additional-builtins = []
allow-global-unused-variables = true
allowed-redefined-builtins = []
callbacks = ["_cb", "cb_"]
dummy-variables-rgx = "^_.*"
ignored-argument-names = "^_.*"
init-import = true
redefining-builtins-modules = [
"builtins",
"future.builtins",
"io",
"past.builtins",
"six.moves",
]
+680
View File
@@ -0,0 +1,680 @@
"""
`BS::thread_pool`: a fast, lightweight, modern, and easy-to-use C++17/C++20/C++23 thread pool library
v5.1.0 (2026-01-03)
By Barak Shoshany <baraksh@gmail.com> <https://baraksh.com/>
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
This Python script can be used to compile simple C++ programs (with only a few source and/or header files) using a variety of compilers, C++ standards, and other options. It also includes support for C++20 modules and C++23 Standard Library modules. It is used in the thread pool library's development environment to compile and run the test program using different compilers and C++ standards. It is not part of the library itself, but users of the library may find it useful, especially if they wish to use the library as a C++20 module.
"""
import argparse
import os
import pathlib
import platform
import re
import shutil
import subprocess
import sys
import time
from enum import Enum
from typing import Any, Never, cast
import yaml # Install with `pip install pyyaml`.
class Args:
"""A class to collect the command line arguments with proper type checking."""
def __init__(self, parsed_ns: argparse.Namespace) -> None:
"""Store the parsed arguments."""
self.files: list[str] = parsed_ns.files
self.arch: str = parsed_ns.arch
self.as_module: bool = parsed_ns.as_module
self.clear_output: bool = parsed_ns.clear_output
self.compiler: str | None = parsed_ns.compiler
self.define: list[str] = parsed_ns.define if parsed_ns.define is not None else []
self.deps: list[str] = parsed_ns.deps if parsed_ns.deps is not None else []
self.disable_exceptions: str | None = parsed_ns.disable_exceptions
self.flag: list[str] = parsed_ns.flag if parsed_ns.flag is not None else []
self.force: bool = parsed_ns.force
self.ignore_config: bool = parsed_ns.ignore_config
self.include: list[str] = parsed_ns.include if parsed_ns.include is not None else []
self.module: list[str] = parsed_ns.module if parsed_ns.module is not None else []
self.output: str | None = parsed_ns.output
self.pass_args: list[str] = parsed_ns.pass_args if parsed_ns.pass_args is not None else []
self.run: bool = parsed_ns.run
self.std_module: str | None = parsed_ns.std_module
self.std: str = parsed_ns.std
self.try_all: bool = parsed_ns.try_all
self.type: str = parsed_ns.type
self.verbose: bool = parsed_ns.verbose
# Parse the command-line arguments.
parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter)
_ = parser.add_argument("files", action="store", nargs="*", help="the source file(s) to compile")
_ = parser.add_argument("-a", "--arch", action="store", choices=["amd64", "arm64"], default="amd64", help="the target architecture (MSVC only)")
_ = parser.add_argument("-b", "--clear-output", action="store_true", help="clear the output folder before compiling (if no source files are specified, just clear and exit)")
_ = parser.add_argument("-c", "--compiler", action="store", choices=["cl", "clang++", "g++"], help="which compiler to use (auto determined if not specified)")
_ = parser.add_argument("-d", "--define", action="append", help="macros to define (use multiple times if more than one) [in addition to those in compile_cpp.yaml]")
_ = parser.add_argument("-e", "--force", action="store_true", help="force recompilation even if the compiled file is up to date")
_ = parser.add_argument("-f", "--flag", action="append", help="extra compiler flags to add (use multiple times if more than one) [in addition to those in compile_cpp.yaml]")
_ = parser.add_argument("-g", "--ignore-config", action="store_true", help="ignore the compile_cpp.yaml configuration file")
_ = parser.add_argument("-i", "--include", action="append", help="the include folder to use (use multiple times if more than one) [in addition to those in compile_cpp.yaml]")
_ = parser.add_argument("-l", "--as-module", action="store_true", help="compile file as module")
_ = parser.add_argument("-m", "--module", action="append", help='C++20 module files to use if desired, in the format "module_name=module_file,dependencies,..." (use multiple times if more than one) [in addition to those in compile_cpp.yaml]')
_ = parser.add_argument("-n", "--deps", action="append", help="dependencies used to detect if recompilation is needed (use multiple times if more than one) [in addition to modules and those in compile_cpp.yaml]")
_ = parser.add_argument("-o", "--output", action="store", help="the output folder (end with / to create, taken from compile_cpp.yaml if not specified) and/or binary name (auto determined if not specified)")
_ = parser.add_argument("-p", "--pass", action="append", dest="pass_args", help="pass command line arguments to the compiled program when running it, if -r/--run is specified (use multiple times if more than one) [in addition to those in compile_cpp.yaml]")
_ = parser.add_argument("-r", "--run", action="store_true", help="run the program after compiling it")
_ = parser.add_argument("-s", "--std", action="store", choices=["c++17", "c++20", "c++23"], default="c++23", help="which C++ standard to use")
_ = parser.add_argument("-t", "--type", action="store", choices=["debug", "release"], default="debug", help="whether to compile in debug or release mode")
_ = parser.add_argument("-u", "--std-module", action="store", help="path to the standard library module (C++23 only, taken from compile_cpp.yaml if not specified, use 'auto' to auto-detect, 'disable' to explicitly disable)")
_ = parser.add_argument("-v", "--verbose", action="store_true", help="whether to print this script's diagnostic messages")
_ = parser.add_argument("-x", "--disable-exceptions", action="store", choices=["true", "false"], help="whether to disable exceptions [overrides compile_cpp.yaml]")
_ = parser.add_argument("-y", "--try-all", action="store_true", help="test compilation using all possible combinations of available compilers and C++ standards (also runs each compiled program if -r/--run is specified)")
args = Args(parser.parse_args(args=None if len(sys.argv) > 1 else ["--help"]))
class ANSI(Enum):
"""Enumeration of ANSI color codes for terminal output."""
reset = 0
bold = 1
dim = 2
italic = 3
underline = 4
invert = 7
strike = 9
double_underline = 21
fg_black = 30
fg_red = 31
fg_green = 32
fg_yellow = 33
fg_blue = 34
fg_magenta = 35
fg_cyan = 36
fg_white = 37
bg_black = 40
bg_red = 41
bg_green = 42
bg_yellow = 43
bg_blue = 44
bg_magenta = 45
bg_cyan = 46
bg_white = 47
fg_bright_black = 90
fg_bright_red = 91
fg_bright_green = 92
fg_bright_yellow = 93
fg_bright_blue = 94
fg_bright_magenta = 95
fg_bright_cyan = 96
fg_bright_white = 97
bg_bright_black = 100
bg_bright_red = 101
bg_bright_green = 102
bg_bright_yellow = 103
bg_bright_blue = 104
bg_bright_magenta = 105
bg_bright_cyan = 106
bg_bright_white = 107
ANSI_INFO = ANSI.fg_bright_blue
ANSI_ERROR = ANSI.fg_bright_red
ANSI_SUCCESS = ANSI.fg_bright_green
ANSI_SEPARATOR = ANSI.fg_bright_yellow
ANSI_TRY_ALL = ANSI.fg_bright_magenta
no_color: bool = os.environ.get("NO_COLOR", "") != ""
def print_ansi(message: str, *codes: ANSI) -> None:
"""Print a message. Uses the given ANSI codes if specified. Does not add newline. Does not print color if the `NO_COLOR` environment variable is set."""
if len(codes) > 0 and not no_color:
seq = ";".join(str(c.value) for c in codes)
print(f"\033[{seq}m{message}\033[{ANSI.reset.value}m", end="")
else:
print(message, end="")
def print_if_verbose(message: str, *codes: ANSI) -> None:
"""Print a message followed by a newline, but only if the verbose flag is set. Uses the given ANSI codes if specified."""
if args.verbose:
print_ansi(message + "\n", *codes)
def print_separator() -> None:
"""Print a separator line, but only if the verbose flag is set."""
print_if_verbose("=" * 60, ANSI_SEPARATOR)
def print_key_values(key: str, values: list[str], length: int) -> None:
"""Print a key-value pair with the key left-aligned to the given length, but only if the verbose flag is set."""
if args.verbose:
print_ansi((key + ":").ljust(length), ANSI.fg_bright_white, ANSI.bold)
if len(values) == 0:
print("<None>")
else:
print(values[0])
for value in values[1:]:
print(" " * length + f"{value}")
def print_error_and_exit(message: str) -> Never:
"""Print an error message followed by a newline in red and exit."""
print_ansi(message + "\n", ANSI_ERROR)
sys.exit(1)
def relative_or_full_path(path: pathlib.Path) -> pathlib.Path:
"""If the path is relative to the current working directory, return it as a relative path; otherwise, return it as a full path."""
return path.relative_to(pathlib.Path.cwd()) if path.is_relative_to(pathlib.Path.cwd()) else path
def parse_llvm_version(path_str: str) -> tuple[int, ...] | None:
"""Extract the LLVM version from a path and returns it as a tuple of integers."""
match: re.Match[str] | None = re.search(r"/llvm[-/](\d+(?:\.\d+)*)", path_str)
if match is None:
return None
return tuple(int(part) for part in match.group(1).split("."))
def get_llvm_std_module(search: str) -> str | None:
"""Get the path to the LLVM standard library module on Linux or macOS. If multiple paths are found, return the one with the latest LLVM version."""
try:
llvm_path: str = subprocess.check_output([f"find {search} -name std.cppm"], text=True, shell=True).strip()
except subprocess.CalledProcessError:
llvm_path: str = ""
all_paths: list[str] = [line for line in llvm_path.splitlines() if line.strip()]
if len(all_paths) == 0:
return None
return max(all_paths, key=lambda p: parse_llvm_version(p) or (0,))
def find_vs_path() -> pathlib.Path | None:
"""Find the Visual Studio installation path, if it exists."""
if platform.system() != "Windows":
return None
pf86: str = os.environ.get("ProgramFiles(x86)", r"C:\Program Files (x86)")
pf: str = os.environ.get("ProgramFiles", r"C:\Program Files")
try_paths: list[pathlib.Path] = [pathlib.Path(p) / "Microsoft Visual Studio" / "Installer" / "vswhere.exe" for p in [pf86, pf]]
vswhere: pathlib.Path | None = next((p for p in try_paths if p.exists()), None)
if vswhere is None:
return None
try:
install_root: str = subprocess.check_output(
[
str(vswhere),
"-latest",
"-property",
"installationPath",
],
text=True,
).strip()
except subprocess.CalledProcessError:
return None
if install_root == "":
return None
return pathlib.Path(install_root)
def get_module_flags(name: str, module_output_path: pathlib.Path) -> list[str]:
"""Get the appropriate flags to import a module with the given name from the given output path."""
if compiler == "cl":
return ["/reference", f"{name}={module_output_path.resolve()}", *([str(build_folder / f"{module_output_path.stem}.obj")] if (name != "std" or not args.as_module) else [])]
if compiler == "clang++":
return [f"-fmodule-file={name}={module_output_path.resolve()}"]
# Otherwise, compiler == "g++".
return ["-fmodules", f"-fmodule-mapper=|@g++-mapper-server -r{build_folder}"]
def compile_module(name: str, paths: list[pathlib.Path], module_output_path: pathlib.Path) -> bool:
"""Compile a module with the given name. The first path in `paths` is the module file, and the rest are its dependencies. Returns True if the module was recompiled, False if it was up to date."""
module_file: pathlib.Path = paths[0]
if module_output_path.exists():
module_output_mod: float = module_output_path.stat().st_mtime
if not any((path.exists() and path.stat().st_mtime > module_output_mod) for path in paths):
print_if_verbose(f'Module "{name}" is up to date, skipping compilation.', ANSI_INFO)
return False
try:
module_command: list[str] = [
sys.executable,
str(pathlib.Path(__file__).resolve()),
# In the special case of GCC and the `std` module, `bits/std.cc` must be entered without the full path.
str(module_file) if not (compiler == "g++" and name == "std") else gcc_std_path,
f"--output={module_output_path.resolve()}",
f"--arch={args.arch}",
f"--compiler={compiler}",
f"--std={args.std}",
f"--type={args.type}",
# Note: Not adding the extra options from the configuration file, since they will be added by the script anyway.
*[f"--define={define}" for define in args.define],
*[f"--include={include}" for include in args.include],
*[f"--flag={flag}" for flag in args.flag],
# For the `std` module in GCC, we also need to add `-fsearch-include-path`.
*(["--flag=-fsearch-include-path"] if (compiler == "g++" and name == "std") else []),
# If compiling the `std` module itself, we need to pass `-u=disable` to avoid infinite recursion. Otherwise, we pass along the specified module path if it exists.
*(["--std-module=disable"] if name == "std" else [f"--std-module={std_module}"] if std_module is not None else []),
"--as-module",
*(["--verbose"] if args.verbose else []),
*(["--disable-exceptions=true"] if disable_exceptions else ["--disable-exceptions=false"]),
]
print_separator()
print_if_verbose(f'Compiling module "{name}" with command: {subprocess.list2cmdline(module_command)}', ANSI_INFO)
_ = sys.stdout.flush()
module_result = subprocess.run(
args=module_command,
check=False,
text=True,
)
if module_result.returncode != 0:
print_error_and_exit(f"Module compilation failed with return code: {module_result.returncode}.")
except Exception as exc:
print_error_and_exit(f"Could not compile module due to exception: {exc}.")
else:
return True
# Collect the full path(s) to the source file(s).
source_paths: list[pathlib.Path] = [pathlib.Path(file) for file in args.files]
# If the `try_all` flag is set, run this script recursively using all possible combinations of compilers and C++ standards available in the system.
if args.try_all:
if "-c" in sys.argv or "--compiler" in sys.argv:
print_error_and_exit("Error: The -y/--try-all flag cannot be used together with the -c/--compiler flag.")
if "-s" in sys.argv or "--std" in sys.argv:
print_error_and_exit("Error: The -y/--try-all flag cannot be used together with the -s/--std flag.")
# We pass all the arguments to the child processes except for the one that enables this mode, to avoid infinite recursion.
child_args: list[str] = [arg for arg in sys.argv[1:] if arg not in ("-y", "--try-all")]
# Determine which compilers are available.
compilers: list[str] = []
if find_vs_path() is not None:
compilers.append("cl")
if shutil.which("clang++") is not None:
compilers.append("clang++")
# On macOS, g++ is by default just an alias for clang++, so we skip it.
if shutil.which("g++") is not None and platform.system() != "Darwin":
compilers.append("g++")
# Compile using all available compilers using all relevant C++ standards.
standards: list[str] = ["c++17", "c++20", "c++23"]
workspace_path: pathlib.Path = pathlib.Path(__file__).parent.parent.resolve()
try:
compile_start: float = time.perf_counter()
for compiler in compilers:
for std in standards:
warnings_as_errors: list[str] = ["-f/WX"] if compiler == "cl" else ["-f-Werror"]
command: list[str] = [
sys.executable,
str(pathlib.Path(__file__).resolve()),
"-c",
compiler,
"-s",
std,
*warnings_as_errors,
*child_args,
]
print_if_verbose(f"Compiling with {compiler} using {std.upper()} standard with command: {subprocess.list2cmdline(command)}", ANSI_TRY_ALL)
compile_result = subprocess.run(
args=command,
check=False,
text=True,
)
if compile_result.returncode != 0:
print_if_verbose("Compilation failed, aborting!", ANSI_TRY_ALL)
sys.exit(1)
except Exception as exc:
print_if_verbose(f"Could not compile due to exception: {exc}, aborting!", ANSI_TRY_ALL)
sys.exit(1)
print_if_verbose(f"All compilations completed successfully in {time.perf_counter() - compile_start:.2f} seconds.", ANSI_TRY_ALL)
sys.exit(0)
# Determine the compiler if it is not given.
compiler: str = ""
vs_path: pathlib.Path | None = find_vs_path()
if args.compiler is not None:
compiler = args.compiler
elif platform.system() == "Windows":
# On Windows, we default to MSVC if the Visual Studio installation path exists, otherwise we fall back to Clang, and then GCC.
if vs_path is not None and vs_path.exists():
compiler = "cl"
elif shutil.which("clang++") is not None:
compiler = "clang++"
elif shutil.which("g++") is not None:
compiler = "g++"
elif platform.system() == "Linux":
# On Linux, we default to GCC if it is available, otherwise we fall back to Clang.
if shutil.which("g++") is not None:
compiler = "g++"
elif shutil.which("clang++") is not None:
compiler = "clang++"
elif platform.system() == "Darwin" and shutil.which("clang++") is not None:
# On macOS, we just check if Clang is available.
compiler = "clang++"
if compiler == "":
print_error_and_exit("Error: No compiler found!")
# If a file named `compile_cpp.yaml` exists in the current working directory, read the configuration from it. All options are added to those from the command line, except the output file/folder and path to the standard library module, which are only used if not provided in the command line. Note that all folders should be specified relative to the current working directory.
defines: list[str] = args.define[:]
deps: list[str] = args.deps[:]
disable_exceptions: bool = args.disable_exceptions == "true"
flags: list[str] = args.flag[:]
includes: list[str] = args.include[:]
try:
modules: dict[str, list[str]] = {name: files.split(",") for module in args.module for name, files in (module.split("="),)}
except ValueError:
print_error_and_exit('Error: Module specification must be in the format "module_name=module_file,dependencies,...".')
output: str | None = args.output
pass_args: list[str] = args.pass_args[:]
std_module: str | None = args.std_module
compile_yaml: pathlib.Path = pathlib.Path.cwd() / "compile_cpp.yaml"
if not args.ignore_config and compile_yaml.exists():
with compile_yaml.open("r") as file:
raw_config: dict[str, Any] | Any = yaml.safe_load(file) or {}
if not isinstance(raw_config, dict):
print_error_and_exit("Error: compile_cpp.yaml must be a dictionary of options.")
compile_config = cast("dict[str, Any]", raw_config)
if "defines" in compile_config:
defines.extend(compile_config["defines"])
if "deps" in compile_config:
deps.extend(compile_config["deps"])
if args.disable_exceptions is None and "disable_exceptions" in compile_config:
disable_exceptions = compile_config["disable_exceptions"] is True
if "flags" in compile_config and compiler in compile_config["flags"]:
flags.extend(compile_config["flags"][compiler])
if "includes" in compile_config:
includes.extend(compile_config["includes"])
if "modules" in compile_config:
modules.update(compile_config["modules"])
if output is None and "output" in compile_config:
output = compile_config["output"]
if "pass_args" in compile_config:
pass_args.extend(compile_config["pass_args"])
if std_module is None and "std_module" in compile_config and platform.system() in compile_config["std_module"] and compiler in compile_config["std_module"][platform.system()] and len(compile_config["std_module"][platform.system()][compiler]) > 0:
std_module = compile_config["std_module"][platform.system()][compiler]
# Determine the name of the binary file and the build folder.
binary_path: pathlib.Path | None = None
build_folder: pathlib.Path
auto_binary: bool = False
if output is not None:
# Calculate the output path relative to the current working directory. Note that if the path is absolute, `pathlib` will automatically use the absolute path instead of a relative path.
output_path: pathlib.Path = (pathlib.Path.cwd() / output).resolve()
if output.endswith(("/", "\\")) or output_path.is_dir():
# If the output path is a directory, we use it as the build folder, and automatically determine the name of the binary file.
build_folder = output_path.resolve()
auto_binary = True
elif output_path.is_absolute():
# If the output path is an absolute path to a file, the build folder is the file's folder.
build_folder = output_path.parent.resolve()
binary_path = output_path
else:
# If the output path is just a file name, the build folder is the current working directory by default.
build_folder = pathlib.Path.cwd()
binary_path = build_folder / output_path
else:
# If there is no output path at all, the build folder is the current working directory by default, and we automatically determine the name of the binary file.
build_folder = pathlib.Path.cwd()
auto_binary = True
# Clear and recreate the build folder if requested.
if args.clear_output:
if build_folder == pathlib.Path.cwd():
print_error_and_exit("Error: Cannot clear the output path if it is the current working directory.")
if build_folder.exists():
print_if_verbose(f"Clearing output folder: {relative_or_full_path(build_folder)}", ANSI_INFO)
shutil.rmtree(build_folder)
pathlib.Path(build_folder).mkdir(exist_ok=True, parents=True)
print_if_verbose("Cleared successfully!", ANSI_SUCCESS)
else:
print_if_verbose(f"Creating empty output folder: {relative_or_full_path(build_folder)}", ANSI_INFO)
pathlib.Path(build_folder).mkdir(exist_ok=True, parents=True)
print_if_verbose("Created successfully!", ANSI_SUCCESS)
if len(source_paths) == 0:
# If no source files are specified, just clear and exit.
sys.exit(0)
else:
# Otherwise, just create the build folder if it does not exist.
pathlib.Path(build_folder).mkdir(exist_ok=True, parents=True)
# Add the appropriate flags to disable exceptions if requested.
if disable_exceptions:
if compiler == "cl":
flags.extend(["/EHs-c-", "/D_HAS_EXCEPTIONS=0"])
else:
flags.append("-fno-exceptions")
elif compiler == "cl":
flags.append("/EHsc")
# Importing the C++ Standard Library is only available in C++23 mode. If "disable" is specified for the standard library module, we skip it; this is used to avoid infinite recursion.
use_std_module: bool = not (std_module is None or std_module == "disable" or args.std != "c++23")
if use_std_module and std_module is not None:
modules = {"std": [std_module], **modules}
# Figure out the path to the std module, if relevant.
gcc_std_path: str = "bits/std.cc"
if use_std_module and "std" in modules and modules["std"][0].strip() == "auto":
success: bool = False
if platform.system() == "Windows" and compiler == "cl" and vs_path is not None:
vc_version_path: pathlib.Path = vs_path / "VC" / "Auxiliary" / "Build" / "Microsoft.VCToolsVersion.default.txt"
if vc_version_path.exists():
with vc_version_path.open("r", encoding="utf-8") as vc_version_file:
vc_version: str = vc_version_file.read().strip()
vc_tools_path: pathlib.Path = vs_path / "VC" / "Tools" / "MSVC" / vc_version
modules["std"][0] = rf"{vc_tools_path}\modules\std.ixx"
success = True
elif compiler == "clang++":
# Note: The Clang `std` module is only available with libc++.
if platform.system() == "Windows":
# On Windows, libc++ is most likely installed via MSYS2, so the `std` module should be at `C:\msys64\clang64\share\libc++\v1\std.cppm`. We calculate it relative to the path where `clang++.exe` is located, in case the MSYS2 installation folder is different.
clang_path: str | None = shutil.which("clang++")
if clang_path:
std_path: pathlib.Path = pathlib.Path(clang_path).parent.parent / "share" / "libc++" / "v1" / "std.cppm"
if std_path.exists():
modules["std"][0] = str(std_path.absolute())
success = True
elif platform.system() == "Darwin":
# On macOS, the `std` module should be at `/usr/local/Cellar/llvm/<LLVM full version>/share/libc++/v1/std.cppm`.
llvm_std_path: str | None = get_llvm_std_module("/usr/local/Cellar/llvm")
if llvm_std_path:
modules["std"][0] = llvm_std_path
success = True
elif platform.system() == "Linux":
# On Linux, the `std` module should be at `/usr/lib/llvm-<LLVM major version>/share/libc++/v1/std.cppm`.
llvm_std_path: str | None = get_llvm_std_module("/usr/lib/llvm-*")
if llvm_std_path:
modules["std"][0] = llvm_std_path
success = True
else: # compiler == "g++"
# In GCC the module file is always at `bits/std.cc`.
modules["std"][0] = gcc_std_path
success = True
if not success:
print_error_and_exit('Error: "auto" specified for the standard library module path, but the script could not locate it. Please specify the path manually.')
# Determine the appropriate extension for modules.
module_extension: str = ""
if compiler == "cl":
module_extension = ".ifc"
elif compiler == "clang++":
module_extension = ".pcm"
else: # compiler == "g++"
# For GCC, the extension is `.gcm`, but we do not have control over that; however, we also create an object file with the `.o` extension so we can check if the module is up to date (see below).
module_extension = ".o"
# If we are compiling as a module, add the appropriate flags.
if args.as_module:
if compiler == "cl":
flags.extend(["/interface", "/TP", "/c"])
elif compiler == "clang++":
flags.extend(["--precompile", "-Wno-include-angled-in-module-purview", "-Wno-reserved-module-identifier", "-xc++-module"])
else: # compiler == "g++"
# Note: Creating an object file can be disabled with `-fmodule-only`, and it doesn't seem like the object file is actually needed, only the `.gcm` file. However, we create the object file anyway so we can check if the module is up to date, since there appears to be no way to control the name of the `.gcm` file.
flags.extend(["-fmodules", "-c", f"-fmodule-mapper=|@g++-mapper-server -r{build_folder}", "-xc++"])
# If the user did not provide an output file name, we use the name of the first source file, appending the compiler, mode, and C++ standard, as well as the appropriate extension.
short_compiler: str = "clang" if compiler == "clang++" else "gcc" if compiler == "g++" else "msvc"
suffix: str = f"{args.type}-{short_compiler}-cpp{args.std[-2:]}"
if auto_binary:
extension: str = module_extension if args.as_module else ".exe" if platform.system() == "Windows" else ""
module_indicator: str = "module_" if args.as_module else ""
binary_name: str = f"{source_paths[0].stem}_{module_indicator}{suffix}{extension}"
binary_path = build_folder / binary_name
if binary_path is None:
print_error_and_exit("Error: Could not determine binary file name!")
# If modules are specified, pre-compile them by calling this script recursively. If using the `std` module, pre-compile it first. If this is a module itself, don't compile any other modules to avoid infinite recursion. (Note: This assumes that modules do not depend on each other.)
recompiled_modules: bool = False
module_paths: dict[str, list[pathlib.Path]] = {name: [(pathlib.Path.cwd() / file).resolve() for file in files] for name, files in modules.items()}
module_output_paths: dict[str, pathlib.Path] = {name: build_folder / f"{path[0].stem}_module_{suffix}{module_extension}" for name, path in module_paths.items()}
if use_std_module and "std" in modules:
flags.extend(get_module_flags("std", module_output_paths["std"]))
if not args.as_module:
if use_std_module and "std" in modules:
recompiled_modules |= compile_module("std", [(pathlib.Path.cwd() / modules["std"][0]).resolve()], module_output_paths["std"])
if len(modules) > 0 and (args.std in ["c++20", "c++23"]):
for n, p in module_paths.items():
if n == "std":
continue
flags.extend(get_module_flags(n, module_output_paths[n]))
recompiled_modules |= compile_module(n, p, module_output_paths[n])
print_if_verbose("Compiling program...", ANSI_INFO)
# If the output binary already exists, check if we need to recompile based on whether any of the source files or their dependencies have changed. If we recompiled any modules, we need to recompile anyway, so we don't need to check the dependencies. The `force` flag overrides this check.
need_recompile: bool = True
deps_paths: list[pathlib.Path] = [(pathlib.Path.cwd() / file).resolve() for file in deps]
if not args.force and not recompiled_modules and binary_path.exists():
binary_mod: float = binary_path.stat().st_mtime
if not any((path.exists() and path.stat().st_mtime > binary_mod) for path in (source_paths + deps_paths)):
print_if_verbose("Binary is up to date, skipping compilation.", ANSI_INFO)
need_recompile = False
if need_recompile:
include_paths: list[pathlib.Path] = [(pathlib.Path.cwd() / folder).resolve() for folder in includes]
# On macOS, make sure we are using Homebrew Clang, if available, instead of Apple Clang, which does not support C++20 modules.
compiler_path: str | None
if compiler == "clang++" and platform.system() == "Darwin":
compiler_path = "/usr/local/opt/llvm/bin/clang++"
if not pathlib.Path(compiler_path).exists():
compiler_path = shutil.which(compiler)
else:
compiler_path = shutil.which(compiler)
# Determine the command to execute based on the chosen compiler and parameters.
command: list[str]
if compiler == "clang++":
command = [
compiler_path if compiler_path is not None else compiler,
*flags,
*[str(path.resolve()) for path in source_paths],
f"-std={args.std}",
"-g3" if args.type == "debug" else "-O3",
"-o",
str(binary_path),
*[item for include in [["-I", str(path.resolve())] for path in include_paths] for item in include],
*([f"-D{define}" for define in defines]),
]
elif compiler == "g++":
command = [
compiler_path if compiler_path is not None else compiler,
*flags,
# In the special case of GCC and the `std` module, `bits/std.cc` must be entered without the full path.
*[(str(path.resolve()) if path != pathlib.Path(gcc_std_path) else gcc_std_path) for path in source_paths],
f"-std={args.std}",
"-ggdb3" if args.type == "debug" else "-O3",
"-o",
str(binary_path),
*[item for include in [["-I", str(path.resolve())] for path in include_paths] for item in include],
*([f"-D{define}" for define in defines]),
]
else: # compiler == "cl"
command = [
compiler_path if compiler_path is not None else compiler,
*flags,
*[str(path.resolve()) for path in source_paths],
f"/std:{'c++latest' if args.std == 'c++23' else args.std}",
*(["/Zi", f"/Fd:{binary_path.with_suffix('.pdb')}"] if args.type == "debug" else ["/O2"]),
*([f"/Fe:{binary_path}"] if not args.as_module else ["/ifcOutput", str(binary_path)]),
# If compiling multiple source files, we cannot specify the names of each object file, only the output folder.
f"/Fo:{binary_path.with_suffix('.obj')}" if len(source_paths) == 1 else f"/Fo:{build_folder}\\",
*[item for include in [["/I", str(path.resolve())] for path in include_paths] for item in include],
"/permissive-",
"/nologo",
"/Zc:__cplusplus",
*([f"/D{define}" for define in defines]),
]
# For MSVC we also need to invoke the Visual Studio Developer PowerShell script.
if compiler == "cl" and vs_path is not None:
vs_pwsh_path: pathlib.Path = vs_path / "Common7" / "Tools" / "Launch-VsDevShell.ps1"
command = ["pwsh.exe", "-NoProfile", "-ExecutionPolicy", "Bypass", "-Command", f"& '{vs_pwsh_path}' -Arch {args.arch} -HostArch {args.arch} | Out-Null; {subprocess.list2cmdline(command)}"]
print_separator()
max_length = 16
print_key_values("Compiler", [compiler], max_length)
print_key_values("C++ Standard", [args.std.upper()], max_length)
print_key_values("Type", [args.type.title()], max_length)
print_key_values("Source file(s)", [str(relative_or_full_path(path)) for path in source_paths], max_length)
print_key_values("Defines", defines, max_length)
print_key_values("Dependencies", [str(relative_or_full_path(path)) for path in deps_paths], max_length)
print_key_values("Flags", flags, max_length)
print_key_values("Includes", ([str(relative_or_full_path(path)) for path in include_paths]), max_length)
if args.std in ["c++20", "c++23"]:
print_key_values("Modules", [f"{name}={relative_or_full_path(path[0])}" for name, path in module_paths.items()] if not args.as_module else ["<None>"], max_length)
else:
print_key_values("Modules", ["<Unused in C++17 mode>"], max_length)
print_key_values("Build folder", [str(relative_or_full_path(build_folder))], max_length)
print_key_values("Binary file", [str(relative_or_full_path(binary_path))], max_length)
print_key_values("Command", [subprocess.list2cmdline(command)], max_length)
print_separator()
# Perform the actual compilation.
print_if_verbose("Compiling...", ANSI_INFO)
try:
_ = sys.stdout.flush()
compile_start: float = time.perf_counter()
compile_result = subprocess.run(
args=command,
check=False,
text=True,
)
if compile_result.returncode == 0:
print_if_verbose(f"Compilation completed successfully in {time.perf_counter() - compile_start:.2f} seconds.", ANSI_SUCCESS)
else:
print_error_and_exit(f"Compilation failed with return code: {compile_result.returncode}.")
except Exception as exc:
print_error_and_exit(f"Could not compile due to exception: {exc}.")
if args.run:
# We run the program in the build folder.
os.chdir(build_folder)
print_if_verbose(f"Running program{f' with arguments {" ".join(pass_args)}' if len(pass_args) > 0 else ''}...", ANSI_INFO)
print_separator()
try:
_ = sys.stdout.flush()
run_start: float = time.perf_counter()
run_result: subprocess.CompletedProcess[str] = subprocess.run(
args=[binary_path, *pass_args],
check=False,
text=True,
)
print_separator()
if run_result.returncode == 0:
print_if_verbose(f"Program executed successfully in {time.perf_counter() - run_start:.2f} seconds.", ANSI_SUCCESS)
else:
print_error_and_exit(f"Program failed with return code: {run_result.returncode}.")
except Exception as exc:
print_separator()
print_error_and_exit(f"Could not run program due to exception: {exc}.")
File diff suppressed because it is too large Load Diff
-232
View File
@@ -1,232 +0,0 @@
#!/usr/bin/env pwsh
<#
.SYNOPSIS
BS::thread_pool: a fast, lightweight, and easy-to-use C++17 thread pool library by Barak Shoshany (baraksh@gmail.com) (https://baraksh.com) v4.1.0 (2024-03-22)
.DESCRIPTION
This script compiles and runs the bundled test program with different compilers.
.NOTES
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
.LINK
https://github.com/bshoshany/thread-pool
#>
Set-StrictMode -Version Latest
$Host.UI.RawUI.WindowTitle = 'BS::thread_pool Test Script'
$TitleColor = 'Green'
$TextColor = 'Yellow'
$ErrorColor = 'Red'
$CommandColor = 'Blue'
Function Write-Title([String] $Title)
{
If ($Title.Length -gt 0)
{
$Separator = '=' * $Title.Length
Write-Host
Write-Host $Separator -ForegroundColor $TitleColor
Write-Host $Title -ForegroundColor $TitleColor
Write-Host $Separator -ForegroundColor $TitleColor
Write-Host
}
}
Function Write-Text([String] $Text)
{
Write-Host $Text -ForegroundColor $TextColor
}
Function Write-Error([String] $Text)
{
Write-Host $Text -ForegroundColor $ErrorColor
}
Function Write-Command([String] $Text)
{
Write-Host $Text -ForegroundColor $CommandColor
}
Function Exit-Script([Int] $Code)
{
Set-Location $StartingLocation
Exit $Code
}
Write-Title '=== BS::thread_pool test script ==='
$StartingLocation = Get-Location
Set-Location $PSScriptRoot
$SourceFile = Join-Path $PSScriptRoot 'BS_thread_pool_test.cpp'
If (Test-Path -Path $SourceFile)
{
Write-Text "Found source file $SourceFile."
}
Else
{
Write-Error "Source file $SourceFile not found, aborting script!"
Exit-Script 1
}
$IncludeFile = Join-Path (Split-Path -Parent $PSScriptRoot) 'include' 'BS_thread_pool.hpp'
If (Test-Path -Path $IncludeFile)
{
Write-Text "Found main include file $IncludeFile."
}
Else
{
Write-Error "Main include file $IncludeFile not found, aborting script!"
Exit-Script 1
}
$IncludeFile = Join-Path (Split-Path -Parent $PSScriptRoot) 'include' 'BS_thread_pool_utils.hpp'
If (Test-Path -Path $IncludeFile)
{
Write-Text "Found utilities include file $IncludeFile."
}
Else
{
Write-Error "Utilities include file $IncludeFile not found, aborting script!"
Exit-Script 1
}
$BuildFolder = Join-Path (Split-Path -Parent $PSScriptRoot) 'build'
If (Test-Path -Path $BuildFolder)
{
Write-Text "Cleaning up build folder $BuildFolder..."
Remove-Item (Join-Path $BuildFolder '*')
}
Else
{
Write-Text "Creating build folder $BuildFolder..."
$Null = New-Item $BuildFolder -ItemType 'Directory'
}
Write-Text 'Done.'
Write-Title 'Compiling...'
If ($IsWindows)
{
$Extension = '.exe'
$PThread = ''
}
Else
{
$Extension = ''
$PThread = ' -pthread'
}
$ExePrefix = 'BS_thread_pool_test_'
$Executables = @()
Function Build-ClangGCC([String] $Compiler, [String] $ExeSuffix, [String] $ExtraFlags = '')
{
$FullExe = Join-Path $BuildFolder "$ExePrefix$ExeSuffix$Extension"
$Command = "$Compiler $SourceFile$PThread -I../include -std=c++17 -O3 -march=native -Wall -Wextra -Wconversion -Wsign-conversion -Wpedantic -Weffc++ -Wshadow -o $FullExe $ExtraFlags"
Write-Command $Command
Invoke-Expression $Command
If ($LASTEXITCODE)
{
Write-Error "Failed to compile, aborting script! (Exit code: $LASTEXITCODE)"
Exit-Script $LASTEXITCODE
}
Else
{
Write-Text "Successfully compiled to $FullExe."
$Script:Executables += $FullExe
}
}
If (Get-Command 'clang++' -ErrorAction SilentlyContinue)
{
Write-Text 'Compiling with Clang...'
Build-ClangGCC 'clang++' 'clang'
Build-ClangGCC 'clang++' 'clang_light' '-DBS_THREAD_POOL_LIGHT_TEST'
}
Else
{
Write-Error 'Clang not found, skipping it!'
}
Write-Host
If (Get-Command 'g++' -ErrorAction SilentlyContinue)
{
Write-Text 'Compiling with GCC...'
Build-ClangGCC 'g++' 'gcc' '-Wuseless-cast'
Build-ClangGCC 'g++' 'gcc_light' '-Wuseless-cast -DBS_THREAD_POOL_LIGHT_TEST'
}
Else
{
Write-Error 'GCC not found, skipping it!'
}
Write-Host
Function Build-MSVC([String] $ExeSuffix, [String] $ExtraFlags = '')
{
$MSVCName = "$ExePrefix$ExeSuffix"
$FullExe = Join-Path $BuildFolder "$MSVCName$Extension"
$FullObj = Join-Path $BuildFolder "$MSVCName.obj"
$Env:BS_THREAD_POOL_MSVC_COMMAND = "cl $SourceFile /I../include /std:c++17 /permissive- /O2 /W4 /EHsc /Fe:$FullExe /Fo:$FullObj $ExtraFlags"
Write-Command $Env:BS_THREAD_POOL_MSVC_COMMAND
pwsh -Command {
$CurrentDir = Get-Location
& 'C:\Program Files\Microsoft Visual Studio\2022\Community\Common7\Tools\Launch-VsDevShell.ps1'
Set-Location $CurrentDir
Invoke-Expression $Env:BS_THREAD_POOL_MSVC_COMMAND
Exit $LASTEXITCODE
}
$Env:BS_THREAD_POOL_MSVC_COMMAND = $Null
If ($LASTEXITCODE)
{
Write-Error "Failed to compile, aborting script! (Exit code: $LASTEXITCODE)"
Exit-Script $LASTEXITCODE
}
Else
{
Remove-Item $FullObj
Write-Text "Successfully compiled to $FullExe."
$Script:Executables += $FullExe
}
}
If ($IsWindows)
{
$MSVCEnv = 'C:\Program Files\Microsoft Visual Studio\2022\Community\Common7\Tools\Launch-VsDevShell.ps1'
If (Test-Path $MSVCEnv)
{
Write-Text 'Compiling with MSVC...'
Build-MSVC 'msvc'
Build-MSVC 'msvc_light' '/DBS_THREAD_POOL_LIGHT_TEST'
}
Else
{
Write-Error 'MSVC not found, skipping it!'
}
}
Set-Location $BuildFolder
Write-Title 'Starting tests. Outputs can be found in the generated log files.'
ForEach ($Executable in $Executables)
{
Write-Text "Executing: $Executable"
Invoke-Expression $Executable | Out-Null
If ($LASTEXITCODE)
{
Write-Error "Test Failed, aborting script! (Exit code: $LASTEXITCODE)"
Exit-Script $LASTEXITCODE
}
Write-Text '-> Test finished successfully!'
Write-Host
}
Write-Title '=== All tests completed successfully! ==='
Exit-Script 0