-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy paththread_pool.hpp
More file actions
2373 lines (2210 loc) · 111 KB
/
thread_pool.hpp
File metadata and controls
2373 lines (2210 loc) · 111 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* ██████ ███████ ████████ ██ ██ ██████ ███████ █████ ██████ ██████ ██████ ██████ ██
* ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██
* ██████ ███████ ██ ███████ ██████ █████ ███████ ██ ██ ██████ ██ ██ ██ ██ ██
* ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██
* ██████ ███████ ██ ██ ██ ██ ██ ███████ ██ ██ ██████ ███████ ██ ██████ ██████ ███████
*
* @file BS_thread_pool.hpp
* @author Barak Shoshany (baraksh@gmail.com) (https://baraksh.com/)
* @version 5.0.0
* @date 2024-12-19
* @copyright Copyright (c) 2024 Barak Shoshany. Licensed under the MIT license. If you found this project useful, please consider starring it on GitHub! If you use this library in software of any kind, please provide a link to the GitHub repository https://github.com/bshoshany/thread-pool in the source code and documentation. If you use this library in published research, please cite it as follows: Barak Shoshany, "A C++17 Thread Pool for High-Performance Scientific Computing", doi:10.1016/j.softx.2024.101687, SoftwareX 26 (2024) 101687, arXiv:2105.00613
*
* @brief `BS::thread_pool`: a fast, lightweight, modern, and easy-to-use C++17/C++20/C++23 thread pool library. This header file contains the entire library, and is the only file needed to use the library.
*/
#ifndef BS_THREAD_POOL_HPP
#define BS_THREAD_POOL_HPP
// We need to include <version> since if we're using `import std` it will not define any feature-test macros, including `__cpp_lib_modules`, which we need to check if `import std` is supported in the first place.
#ifdef __has_include
#if __has_include(<version>)
#include <version> // NOLINT(misc-include-cleaner)
#endif
#endif
// If the macro `BS_THREAD_POOL_IMPORT_STD` is defined, import the C++ Standard Library as a module. Otherwise, include the relevant Standard Library header files. This is currently only officially supported by MSVC with Microsoft STL and LLVM Clang (NOT Apple Clang) with LLVM libc++. It is not supported by GCC with any standard library, or any compiler with GNU libstdc++. We also check that the feature is enabled by checking `__cpp_lib_modules`. However, MSVC defines this macro even in C++20 mode, which is not standards-compliant, so we check that we are in C++23 mode; MSVC currently reports `__cplusplus` as `202004L` for C++23 mode, so we use that value.
#if defined(BS_THREAD_POOL_IMPORT_STD) && defined(__cpp_lib_modules) && (__cplusplus >= 202004L) && (defined(_MSC_VER) || (defined(__clang__) && defined(_LIBCPP_VERSION) && !defined(__apple_build_version__)))
// Only allow importing the `std` module if the library itself is imported as a module. If the library is included as a header file, this will force the program that included the header file to also import `std`, which is not desirable and can lead to compilation errors if the program `#include`s any Standard Library header files.
#ifdef BS_THREAD_POOL_MODULE
import std;
#else
#error "The thread pool library cannot import the C++ Standard Library as a module using `import std` if the library itself is not imported as a module. Either use `import BS.thread_pool` to import the libary, or remove the `BS_THREAD_POOL_IMPORT_STD` macro. Aborting compilation."
#endif
#else
#undef BS_THREAD_POOL_IMPORT_STD
#include <algorithm>
#include <chrono>
#include <condition_variable>
#include <cstddef>
#include <cstdint>
#include <functional>
#include <future>
#include <iostream>
#include <limits>
#include <memory>
#include <mutex>
#include <optional>
#include <queue>
#include <string>
#include <thread>
#include <tuple>
#include <type_traits>
#include <utility>
#include <variant>
#include <vector>
#ifdef __cpp_concepts
#include <concepts>
#endif
#ifdef __cpp_exceptions
#include <exception>
#include <stdexcept>
#endif
#ifdef __cpp_impl_three_way_comparison
#include <compare>
#endif
#ifdef __cpp_lib_int_pow2
#include <bit>
#endif
#ifdef __cpp_lib_semaphore
#include <semaphore>
#endif
#ifdef __cpp_lib_jthread
#include <stop_token>
#endif
#endif
#ifdef BS_THREAD_POOL_NATIVE_EXTENSIONS
#if defined(_WIN32)
#include <windows.h>
#undef min
#undef max
#elif defined(__linux__) || defined(__APPLE__)
#include <pthread.h>
#include <sched.h>
#include <sys/resource.h>
#include <unistd.h>
#if defined(__linux__)
#include <sys/syscall.h>
#include <sys/sysinfo.h>
#endif
#else
#undef BS_THREAD_POOL_NATIVE_EXTENSIONS
#endif
#endif
#if defined(__linux__)
// On Linux, <sys/sysmacros.h> defines macros called `major` and `minor`. We undefine them here so the `version` struct can work.
#ifdef major
#undef major
#endif
#ifdef minor
#undef minor
#endif
#endif
/**
* @brief A namespace used by Barak Shoshany's projects.
*/
namespace BS {
// Macros indicating the version of the thread pool library.
#define BS_THREAD_POOL_VERSION_MAJOR 5
#define BS_THREAD_POOL_VERSION_MINOR 0
#define BS_THREAD_POOL_VERSION_PATCH 0
/**
* @brief A struct used to store a version number, which can be checked and compared at compilation time.
*/
struct version
{
constexpr version(const std::uint64_t major_, const std::uint64_t minor_, const std::uint64_t patch_) noexcept : major(major_), minor(minor_), patch(patch_) {}
// In C++20 and later we can use the spaceship operator `<=>` to automatically generate comparison operators. In C++17 we have to define them manually.
#ifdef __cpp_impl_three_way_comparison
std::strong_ordering operator<=>(const version&) const = default;
#else
[[nodiscard]] constexpr friend bool operator==(const version& lhs, const version& rhs) noexcept
{
return std::tuple(lhs.major, lhs.minor, lhs.patch) == std::tuple(rhs.major, rhs.minor, rhs.patch);
}
[[nodiscard]] constexpr friend bool operator!=(const version& lhs, const version& rhs) noexcept
{
return !(lhs == rhs);
}
[[nodiscard]] constexpr friend bool operator<(const version& lhs, const version& rhs) noexcept
{
return std::tuple(lhs.major, lhs.minor, lhs.patch) < std::tuple(rhs.major, rhs.minor, rhs.patch);
}
[[nodiscard]] constexpr friend bool operator>=(const version& lhs, const version& rhs) noexcept
{
return !(lhs < rhs);
}
[[nodiscard]] constexpr friend bool operator>(const version& lhs, const version& rhs) noexcept
{
return std::tuple(lhs.major, lhs.minor, lhs.patch) > std::tuple(rhs.major, rhs.minor, rhs.patch);
}
[[nodiscard]] constexpr friend bool operator<=(const version& lhs, const version& rhs) noexcept
{
return !(lhs > rhs);
}
#endif
[[nodiscard]] std::string to_string() const
{
return std::to_string(major) + '.' + std::to_string(minor) + '.' + std::to_string(patch);
}
friend std::ostream& operator<<(std::ostream& stream, const version& ver)
{
stream << ver.to_string();
return stream;
}
std::uint64_t major;
std::uint64_t minor;
std::uint64_t patch;
}; // struct version
/**
* @brief The version of the thread pool library.
*/
inline constexpr version thread_pool_version(BS_THREAD_POOL_VERSION_MAJOR, BS_THREAD_POOL_VERSION_MINOR, BS_THREAD_POOL_VERSION_PATCH);
#ifdef BS_THREAD_POOL_MODULE
// If the library is being compiled as a module, ensure that the version of the module file matches the version of the header file.
static_assert(thread_pool_version == version(BS_THREAD_POOL_MODULE), "The versions of BS.thread_pool.cppm and BS_thread_pool.hpp do not match. Aborting compilation.");
/**
* @brief A flag indicating whether the thread pool library was compiled as a C++20 module.
*/
inline constexpr bool thread_pool_module = true;
#else
/**
* @brief A flag indicating whether the thread pool library was compiled as a C++20 module.
*/
inline constexpr bool thread_pool_module = false;
#endif
#ifdef BS_THREAD_POOL_IMPORT_STD
/**
* @brief A flag indicating whether the thread pool library imported the C++23 Standard Library module using `import std`.
*/
inline constexpr bool thread_pool_import_std = true;
#else
/**
* @brief A flag indicating whether the thread pool library imported the C++23 Standard Library module using `import std`.
*/
inline constexpr bool thread_pool_import_std = false;
#endif
#ifdef BS_THREAD_POOL_NATIVE_EXTENSIONS
/**
* @brief A flag indicating whether the thread pool library's native extensions are enabled.
*/
inline constexpr bool thread_pool_native_extensions = true;
#else
/**
* @brief A flag indicating whether the thread pool library's native extensions are enabled.
*/
inline constexpr bool thread_pool_native_extensions = false;
#endif
/**
* @brief The type used for the bitmask template parameter of the thread pool.
*/
using opt_t = std::uint8_t;
template <opt_t>
class thread_pool;
#ifdef __cpp_lib_move_only_function
/**
* @brief The template to use to store functions in the task queue and other places. In C++23 and later we use `std::move_only_function`.
*/
template <typename... S>
using function_t = std::move_only_function<S...>;
#else
/**
* @brief The template to use to store functions in the task queue and other places. In C++17 we use `std::function`.
*/
template <typename... S>
using function_t = std::function<S...>;
#endif
/**
* @brief The type of tasks in the task queue.
*/
using task_t = function_t<void()>;
#ifdef __cpp_lib_jthread
/**
* @brief The type of threads to use. In C++20 and later we use `std::jthread`.
*/
using thread_t = std::jthread;
// The following macros are used to determine how to stop the workers. In C++20 and later we can use `std::stop_token`.
#define BS_THREAD_POOL_WORKER_TOKEN const std::stop_token &stop_token,
#define BS_THREAD_POOL_WAIT_TOKEN , stop_token
#define BS_THREAD_POOL_STOP_CONDITION stop_token.stop_requested()
#define BS_THREAD_POOL_OR_STOP_CONDITION
#else
/**
* @brief The type of threads to use. In C++17 we use`std::thread`.
*/
using thread_t = std::thread;
// The following macros are used to determine how to stop the workers. In C++17 we use a manual flag `workers_running`.
#define BS_THREAD_POOL_WORKER_TOKEN
#define BS_THREAD_POOL_WAIT_TOKEN
#define BS_THREAD_POOL_STOP_CONDITION !workers_running
#define BS_THREAD_POOL_OR_STOP_CONDITION || !workers_running
#endif
/**
* @brief A type used to indicate the priority of a task. Defined to be a signed integer with a width of exactly 8 bits (-128 to +127).
*/
using priority_t = std::int8_t;
/**
* @brief An enum containing some pre-defined priorities for convenience.
*/
enum pr : priority_t
{
lowest = -128,
low = -64,
normal = 0,
high = +64,
highest = +127
};
/**
* @brief A helper struct to store a task with an assigned priority.
*/
struct [[nodiscard]] pr_task
{
/**
* @brief Construct a new task with an assigned priority.
*
* @param task_ The task.
* @param priority_ The desired priority.
*/
explicit pr_task(task_t&& task_, const priority_t priority_ = 0) noexcept(std::is_nothrow_move_constructible_v<task_t>) : task(std::move(task_)), priority(priority_) {}
/**
* @brief Compare the priority of two tasks.
*
* @param lhs The first task.
* @param rhs The second task.
* @return `true` if the first task has a lower priority than the second task, `false` otherwise.
*/
[[nodiscard]] friend bool operator<(const pr_task& lhs, const pr_task& rhs) noexcept
{
return lhs.priority < rhs.priority;
}
/**
* @brief The task.
*/
task_t task;
/**
* @brief The priority of the task.
*/
priority_t priority = 0;
}; // struct pr_task
// In C++20 and later we can use concepts. In C++17 we instead use SFINAE ("Substitution Failure Is Not An Error") with `std::enable_if_t`.
#ifdef __cpp_concepts
#define BS_THREAD_POOL_IF_PAUSE_ENABLED template <bool P = pause_enabled> requires(P)
template <typename F>
concept init_func_c = std::invocable<F> || std::invocable<F, std::size_t>;
#define BS_THREAD_POOL_INIT_FUNC_CONCEPT(F) init_func_c F
#else
#define BS_THREAD_POOL_IF_PAUSE_ENABLED template <bool P = pause_enabled, typename = std::enable_if_t<P>>
#define BS_THREAD_POOL_INIT_FUNC_CONCEPT(F) typename F, typename = std::enable_if_t<std::is_invocable_v<F> || std::is_invocable_v<F, std::size_t>> // NOLINT(bugprone-macro-parentheses)
#endif
/**
* @brief A helper class to facilitate waiting for and/or getting the results of multiple futures at once.
*
* @tparam T The return type of the futures.
*/
template <typename T>
class [[nodiscard]] multi_future : public std::vector<std::future<T>>
{
public:
// Inherit all constructors from the base class `std::vector`.
using std::vector<std::future<T>>::vector;
/**
* @brief Get the results from all the futures stored in this `BS::multi_future`, rethrowing any stored exceptions.
*
* @return If the futures return `void`, this function returns `void` as well. Otherwise, it returns a vector containing the results.
*/
[[nodiscard]] std::conditional_t<std::is_void_v<T>, void, std::vector<T>> get()
{
if constexpr (std::is_void_v<T>)
{
for (std::future<T>& future : *this)
future.get();
return;
}
else
{
std::vector<T> results;
results.reserve(this->size());
for (std::future<T>& future : *this)
results.push_back(future.get());
return results;
}
}
/**
* @brief Check how many of the futures stored in this `BS::multi_future` are ready.
*
* @return The number of ready futures.
*/
[[nodiscard]] std::size_t ready_count() const
{
std::size_t count = 0;
for (const std::future<T>& future : *this)
{
if (future.wait_for(std::chrono::duration<double>::zero()) == std::future_status::ready)
++count;
}
return count;
}
/**
* @brief Check if all the futures stored in this `BS::multi_future` are valid.
*
* @return `true` if all futures are valid, `false` if at least one of the futures is not valid.
*/
[[nodiscard]] bool valid() const noexcept
{
bool is_valid = true;
for (const std::future<T>& future : *this)
is_valid = is_valid && future.valid();
return is_valid;
}
/**
* @brief Wait for all the futures stored in this `BS::multi_future`.
*/
void wait() const
{
for (const std::future<T>& future : *this)
future.wait();
}
/**
* @brief Wait for all the futures stored in this `BS::multi_future`, but stop waiting after the specified duration has passed. This function first waits for the first future for the desired duration. If that future is ready before the duration expires, this function waits for the second future for whatever remains of the duration. It continues similarly until the duration expires.
*
* @tparam R An arithmetic type representing the number of ticks to wait.
* @tparam P An `std::ratio` representing the length of each tick in seconds.
* @param duration The amount of time to wait.
* @return `true` if all futures have been waited for before the duration expired, `false` otherwise.
*/
template <typename R, typename P>
bool wait_for(const std::chrono::duration<R, P>& duration) const
{
const std::chrono::time_point<std::chrono::steady_clock> start_time = std::chrono::steady_clock::now();
for (const std::future<T>& future : *this)
{
future.wait_for(duration - (std::chrono::steady_clock::now() - start_time));
if (duration < std::chrono::steady_clock::now() - start_time)
return false;
}
return true;
}
/**
* @brief Wait for all the futures stored in this `BS::multi_future`, but stop waiting after the specified time point has been reached. This function first waits for the first future until the desired time point. If that future is ready before the time point is reached, this function waits for the second future until the desired time point. It continues similarly until the time point is reached.
*
* @tparam C The type of the clock used to measure time.
* @tparam D An `std::chrono::duration` type used to indicate the time point.
* @param timeout_time The time point at which to stop waiting.
* @return `true` if all futures have been waited for before the time point was reached, `false` otherwise.
*/
template <typename C, typename D>
bool wait_until(const std::chrono::time_point<C, D>& timeout_time) const
{
for (const std::future<T>& future : *this)
{
future.wait_until(timeout_time);
if (timeout_time < std::chrono::steady_clock::now())
return false;
}
return true;
}
}; // class multi_future
/**
* @brief A helper class to divide a range into blocks. Used by `detach_blocks()`, `submit_blocks()`, `detach_loop()`, and `submit_loop()`.
*
* @tparam T The type of the indices. Should be a signed or unsigned integer.
*/
template <typename T>
class [[nodiscard]] blocks
{
public:
/**
* @brief Construct a `blocks` object with the given specifications.
*
* @param first_index_ The first index in the range.
* @param index_after_last_ The index after the last index in the range.
* @param num_blocks_ The desired number of blocks to divide the range into.
*/
blocks(const T first_index_, const T index_after_last_, const std::size_t num_blocks_) noexcept : first_index(first_index_), index_after_last(index_after_last_), num_blocks(num_blocks_)
{
if (index_after_last > first_index)
{
const std::size_t total_size = static_cast<std::size_t>(index_after_last - first_index);
num_blocks = std::min(num_blocks, total_size);
block_size = total_size / num_blocks;
remainder = total_size % num_blocks;
if (block_size == 0)
{
block_size = 1;
num_blocks = (total_size > 1) ? total_size : 1;
}
}
else
{
num_blocks = 0;
}
}
/**
* @brief Get the index after the last index of a block.
*
* @param block The block number.
* @return The index after the last index.
*/
[[nodiscard]] T end(const std::size_t block) const noexcept
{
return (block == num_blocks - 1) ? index_after_last : start(block + 1);
}
/**
* @brief Get the number of blocks. Note that this may be different than the desired number of blocks that was passed to the constructor.
*
* @return The number of blocks.
*/
[[nodiscard]] std::size_t get_num_blocks() const noexcept
{
return num_blocks;
}
/**
* @brief Get the first index of a block.
*
* @param block The block number.
* @return The first index.
*/
[[nodiscard]] T start(const std::size_t block) const noexcept
{
return first_index + static_cast<T>(block * block_size) + static_cast<T>(block < remainder ? block : remainder);
}
private:
/**
* @brief The size of each block (except possibly the last block).
*/
std::size_t block_size = 0;
/**
* @brief The first index in the range.
*/
T first_index = 0;
/**
* @brief The index after the last index in the range.
*/
T index_after_last = 0;
/**
* @brief The number of blocks.
*/
std::size_t num_blocks = 0;
/**
* @brief The remainder obtained after dividing the total size by the number of blocks.
*/
std::size_t remainder = 0;
}; // class blocks
#ifdef __cpp_exceptions
/**
* @brief An exception that will be thrown by `wait()`, `wait_for()`, and `wait_until()` if the user tries to call them from within a thread of the same pool, which would result in a deadlock. Only used if the flag `BS:tp::wait_deadlock_checks` is enabled in the template parameter of `BS::thread_pool`.
*/
struct wait_deadlock : public std::runtime_error
{
wait_deadlock() : std::runtime_error("BS::wait_deadlock") {};
};
#endif
#ifdef BS_THREAD_POOL_NATIVE_EXTENSIONS
#if defined(_WIN32)
/**
* @brief An enum containing pre-defined OS-specific process priority values for portability.
*/
enum class os_process_priority
{
idle = IDLE_PRIORITY_CLASS,
below_normal = BELOW_NORMAL_PRIORITY_CLASS,
normal = NORMAL_PRIORITY_CLASS,
above_normal = ABOVE_NORMAL_PRIORITY_CLASS,
high = HIGH_PRIORITY_CLASS,
realtime = REALTIME_PRIORITY_CLASS
};
/**
* @brief An enum containing pre-defined OS-specific thread priority values for portability.
*/
enum class os_thread_priority
{
idle = THREAD_PRIORITY_IDLE,
lowest = THREAD_PRIORITY_LOWEST,
below_normal = THREAD_PRIORITY_BELOW_NORMAL,
normal = THREAD_PRIORITY_NORMAL,
above_normal = THREAD_PRIORITY_ABOVE_NORMAL,
highest = THREAD_PRIORITY_HIGHEST,
realtime = THREAD_PRIORITY_TIME_CRITICAL
};
#elif defined(__linux__) || defined(__APPLE__)
/**
* @brief An enum containing pre-defined OS-specific process priority values for portability.
*/
enum class os_process_priority
{
idle = PRIO_MAX - 2,
below_normal = PRIO_MAX / 2,
normal = 0,
above_normal = PRIO_MIN / 3,
high = PRIO_MIN * 2 / 3,
realtime = PRIO_MIN
};
/**
* @brief An enum containing pre-defined OS-specific thread priority values for portability.
*/
enum class os_thread_priority
{
idle,
lowest,
below_normal,
normal,
above_normal,
highest,
realtime
};
#endif
/**
* @brief Get the processor affinity of the current process using the current platform's native API. This should work on Windows and Linux, but is not possible on macOS as the native API does not allow it.
*
* @return An `std::optional` object, optionally containing the processor affinity of the current process as an `std::vector<bool>` where each element corresponds to a logical processor. If the returned object does not contain a value, then the affinity could not be determined. On macOS, this function always returns `std::nullopt`.
*/
[[nodiscard]] inline std::optional<std::vector<bool>> get_os_process_affinity()
{
#if defined(_WIN32)
DWORD_PTR process_mask = 0;
DWORD_PTR system_mask = 0;
if (GetProcessAffinityMask(GetCurrentProcess(), &process_mask, &system_mask) == 0)
return std::nullopt;
#ifdef __cpp_lib_int_pow2
const std::size_t num_cpus = static_cast<std::size_t>(std::bit_width(system_mask));
#else
std::size_t num_cpus = 0;
if (system_mask != 0)
{
num_cpus = 1;
while ((system_mask >>= 1U) != 0U)
++num_cpus;
}
#endif
std::vector<bool> affinity(num_cpus);
for (std::size_t i = 0; i < num_cpus; ++i)
affinity[i] = ((process_mask & (1ULL << i)) != 0ULL);
return affinity;
#elif defined(__linux__)
cpu_set_t cpu_set;
CPU_ZERO(&cpu_set);
if (sched_getaffinity(getpid(), sizeof(cpu_set_t), &cpu_set) != 0)
return std::nullopt;
const int num_cpus = get_nprocs();
if (num_cpus < 1)
return std::nullopt;
std::vector<bool> affinity(static_cast<std::size_t>(num_cpus));
for (std::size_t i = 0; i < affinity.size(); ++i)
affinity[i] = CPU_ISSET(i, &cpu_set);
return affinity;
#elif defined(__APPLE__)
return std::nullopt;
#endif
}
/**
* @brief Set the processor affinity of the current process using the current platform's native API. This should work on Windows and Linux, but is not possible on macOS as the native API does not allow it.
*
* @param affinity The processor affinity to set, as an `std::vector<bool>` where each element corresponds to a logical processor.
* @return `true` if the affinity was set successfully, `false` otherwise. On macOS, this function always returns `false`.
*/
inline bool set_os_process_affinity(const std::vector<bool>& affinity)
{
#if defined(_WIN32)
DWORD_PTR process_mask = 0;
for (std::size_t i = 0; i < std::min<std::size_t>(affinity.size(), sizeof(DWORD_PTR) * 8); ++i)
process_mask |= (affinity[i] ? (1ULL << i) : 0ULL);
return SetProcessAffinityMask(GetCurrentProcess(), process_mask) != 0;
#elif defined(__linux__)
cpu_set_t cpu_set;
CPU_ZERO(&cpu_set);
for (std::size_t i = 0; i < std::min<std::size_t>(affinity.size(), CPU_SETSIZE); ++i)
{
if (affinity[i])
CPU_SET(i, &cpu_set);
}
return sched_setaffinity(getpid(), sizeof(cpu_set_t), &cpu_set) == 0;
#elif defined(__APPLE__)
return affinity[0] && false; // NOLINT(readability-simplify-boolean-expr) // Using `affinity` to suppress unused parameter warning.
#endif
}
/**
* @brief Get the priority of the current process using the current platform's native API. This should work on Windows, Linux, and macOS.
*
* @return An `std::optional` object, optionally containing the priority of the current process, as a member of the enum `BS::os_process_priority`. If the returned object does not contain a value, then either the priority could not be determined, or it is not one of the pre-defined values and therefore cannot be represented in a portable way.
*/
[[nodiscard]] inline std::optional<os_process_priority> get_os_process_priority()
{
#if defined(_WIN32)
// On Windows, this is straightforward.
const DWORD priority = GetPriorityClass(GetCurrentProcess());
if (priority == 0)
return std::nullopt;
return static_cast<os_process_priority>(priority);
#elif defined(__linux__) || defined(__APPLE__)
// On Linux/macOS there is no direct analogue of `GetPriorityClass()` on Windows, so instead we get the "nice" value. The usual range is -20 to 19 or 20, with higher values corresponding to lower priorities. However, we are only using 6 pre-defined values for portability, so if the value was set via any means other than `BS::set_os_process_priority()`, it may not match one of our pre-defined values. Note that `getpriority()` returns -1 on error, but since this does not correspond to any of our pre-defined values, this function will return `std::nullopt` anyway.
const int nice_val = getpriority(PRIO_PROCESS, static_cast<id_t>(getpid()));
switch (nice_val)
{
case static_cast<int>(os_process_priority::idle):
return os_process_priority::idle;
case static_cast<int>(os_process_priority::below_normal):
return os_process_priority::below_normal;
case static_cast<int>(os_process_priority::normal):
return os_process_priority::normal;
case static_cast<int>(os_process_priority::above_normal):
return os_process_priority::above_normal;
case static_cast<int>(os_process_priority::high):
return os_process_priority::high;
case static_cast<int>(os_process_priority::realtime):
return os_process_priority::realtime;
default:
return std::nullopt;
}
#endif
}
/**
* @brief Set the priority of the current process using the current platform's native API. This should work on Windows, Linux, and macOS. However, note that higher priorities might require elevated permissions.
*
* @param priority The priority to set. Must be a value from the enum `BS::os_process_priority`.
* @return `true` if the priority was set successfully, `false` otherwise. Usually, `false` means that the user does not have the necessary permissions to set the desired priority.
*/
inline bool set_os_process_priority(const os_process_priority priority)
{
#if defined(_WIN32)
// On Windows, this is straightforward.
return SetPriorityClass(GetCurrentProcess(), static_cast<DWORD>(priority)) != 0;
#elif defined(__linux__) || defined(__APPLE__)
// On Linux/macOS there is no direct analogue of `SetPriorityClass()` on Windows, so instead we set the "nice" value. The usual range is -20 to 19 or 20, with higher values corresponding to lower priorities. However, we are only using 6 pre-defined values for portability. Note that the "nice" values are only relevant for the `SCHED_OTHER` policy, but we do not set that policy here, as it is per-thread rather than per-process.
// Also, it's important to note that a non-root user cannot decrease the nice value (i.e. increase the process priority), only increase it. This can cause confusing behavior. For example, if the current priority is `BS::os_process_priority::normal` and the user sets it to `BS::os_process_priority::idle`, they cannot change it back `BS::os_process_priority::normal`.
return setpriority(PRIO_PROCESS, static_cast<id_t>(getpid()), static_cast<int>(priority)) == 0;
#endif
}
#endif
/**
* @brief A class used to obtain information about the current thread and, if native extensions are enabled, set its priority and affinity.
*/
class [[nodiscard]] this_thread
{
template <opt_t>
friend class thread_pool;
public:
/**
* @brief Get the index of the current thread. If this thread belongs to a `BS::thread_pool` object, the return value will be an index in the range `[0, N)` where `N == BS::thread_pool::get_thread_count()`. Otherwise, for example if this thread is the main thread or an independent thread not in any pools, `std::nullopt` will be returned.
*
* @return An `std::optional` object, optionally containing a thread index.
*/
[[nodiscard]] static std::optional<std::size_t> get_index() noexcept
{
return my_index;
}
/**
* @brief Get a pointer to the thread pool that owns the current thread. If this thread belongs to a `BS::thread_pool` object, the return value will be a `void` pointer to that object. Otherwise, for example if this thread is the main thread or an independent thread not in any pools, `std::nullopt` will be returned.
*
* @return An `std::optional` object, optionally containing a pointer to a thread pool. Note that this will be a `void` pointer, so it must be cast to the desired instantiation of the `BS::thread_pool` template in order to use any member functions.
*/
[[nodiscard]] static std::optional<void*> get_pool() noexcept
{
return my_pool;
}
#ifdef BS_THREAD_POOL_NATIVE_EXTENSIONS
/**
* @brief Get the processor affinity of the current thread using the current platform's native API. This should work on Windows and Linux, but is not possible on macOS as the native API does not allow it.
*
* @return An `std::optional` object, optionally containing the processor affinity of the current thread as an `std::vector<bool>` where each element corresponds to a logical processor. If the returned object does not contain a value, then the affinity could not be determined. On macOS, this function always returns `std::nullopt`.
*/
[[nodiscard]] static std::optional<std::vector<bool>> get_os_thread_affinity()
{
#if defined(_WIN32)
// Windows does not have a `GetThreadAffinityMask()` function, but `SetThreadAffinityMask()` returns the previous affinity mask, so we can use that to get the current affinity and then restore it. It's a bit of a hack, but it works. Since the thread affinity must be a subset of the process affinity, we use the process affinity as the temporary value.
DWORD_PTR process_mask = 0;
DWORD_PTR system_mask = 0;
if (GetProcessAffinityMask(GetCurrentProcess(), &process_mask, &system_mask) == 0)
return std::nullopt;
const DWORD_PTR previous_mask = SetThreadAffinityMask(GetCurrentThread(), process_mask);
if (previous_mask == 0)
return std::nullopt;
SetThreadAffinityMask(GetCurrentThread(), previous_mask);
#ifdef __cpp_lib_int_pow2
const std::size_t num_cpus = static_cast<std::size_t>(std::bit_width(system_mask));
#else
std::size_t num_cpus = 0;
if (system_mask != 0)
{
num_cpus = 1;
while ((system_mask >>= 1U) != 0U)
++num_cpus;
}
#endif
std::vector<bool> affinity(num_cpus);
for (std::size_t i = 0; i < num_cpus; ++i)
affinity[i] = ((previous_mask & (1ULL << i)) != 0ULL);
return affinity;
#elif defined(__linux__)
cpu_set_t cpu_set;
CPU_ZERO(&cpu_set);
if (pthread_getaffinity_np(pthread_self(), sizeof(cpu_set_t), &cpu_set) != 0)
return std::nullopt;
const int num_cpus = get_nprocs();
if (num_cpus < 1)
return std::nullopt;
std::vector<bool> affinity(static_cast<std::size_t>(num_cpus));
for (std::size_t i = 0; i < affinity.size(); ++i)
affinity[i] = CPU_ISSET(i, &cpu_set);
return affinity;
#elif defined(__APPLE__)
return std::nullopt;
#endif
}
/**
* @brief Set the processor affinity of the current thread using the current platform's native API. This should work on Windows and Linux, but is not possible on macOS as the native API does not allow it. Note that the thread affinity must be a subset of the process affinity (as obtained using `BS::get_os_process_affinity()`) for the containing process of a thread.
*
* @param affinity The processor affinity to set, as an `std::vector<bool>` where each element corresponds to a logical processor.
* @return `true` if the affinity was set successfully, `false` otherwise. On macOS, this function always returns `false`.
*/
static bool set_os_thread_affinity(const std::vector<bool>& affinity)
{
#if defined(_WIN32)
DWORD_PTR thread_mask = 0;
for (std::size_t i = 0; i < std::min<std::size_t>(affinity.size(), sizeof(DWORD_PTR) * 8); ++i)
thread_mask |= (affinity[i] ? (1ULL << i) : 0ULL);
return SetThreadAffinityMask(GetCurrentThread(), thread_mask) != 0;
#elif defined(__linux__)
cpu_set_t cpu_set;
CPU_ZERO(&cpu_set);
for (std::size_t i = 0; i < std::min<std::size_t>(affinity.size(), CPU_SETSIZE); ++i)
{
if (affinity[i])
CPU_SET(i, &cpu_set);
}
return pthread_setaffinity_np(pthread_self(), sizeof(cpu_set_t), &cpu_set) == 0;
#elif defined(__APPLE__)
return affinity[0] && false; // NOLINT(readability-simplify-boolean-expr) // Using `affinity` to suppress unused parameter warning.
#endif
}
/**
* @brief Get the name of the current thread using the current platform's native API. This should work on Windows, Linux, and macOS.
*
* @return An `std::optional` object, optionally containing the name of the current thread. If the returned object does not contain a value, then the name could not be determined.
*/
[[nodiscard]] static std::optional<std::string> get_os_thread_name()
{
#if defined(_WIN32)
// On Windows thread names are wide strings, so we need to convert them to normal strings.
PWSTR data = nullptr;
const HRESULT hr = GetThreadDescription(GetCurrentThread(), &data);
if (FAILED(hr))
return std::nullopt;
if (data == nullptr)
return std::nullopt;
const int size = WideCharToMultiByte(CP_UTF8, 0, data, -1, nullptr, 0, nullptr, nullptr);
if (size == 0)
{
LocalFree(data);
return std::nullopt;
}
std::string name(static_cast<std::size_t>(size) - 1, 0);
const int result = WideCharToMultiByte(CP_UTF8, 0, data, -1, name.data(), size, nullptr, nullptr);
LocalFree(data);
if (result == 0)
return std::nullopt;
return name;
#elif defined(__linux__) || defined(__APPLE__)
#ifdef __linux__
// On Linux thread names are limited to 16 characters, including the null terminator.
constexpr std::size_t buffer_size = 16;
#else
// On macOS thread names are limited to 64 characters, including the null terminator.
constexpr std::size_t buffer_size = 64;
#endif
char name[buffer_size] = {};
if (pthread_getname_np(pthread_self(), name, buffer_size) != 0)
return std::nullopt;
return std::string(name);
#endif
}
/**
* @brief Set the name of the current thread using the current platform's native API. This should work on Windows, Linux, and macOS. Note that on Linux thread names are limited to 16 characters, including the null terminator.
*
* @param name The name to set.
* @return `true` if the name was set successfully, `false` otherwise.
*/
static bool set_os_thread_name(const std::string& name)
{
#if defined(_WIN32)
// On Windows thread names are wide strings, so we need to convert them from normal strings.
const int size = MultiByteToWideChar(CP_UTF8, 0, name.data(), -1, nullptr, 0);
if (size == 0)
return false;
std::wstring wide(static_cast<std::size_t>(size), 0);
if (MultiByteToWideChar(CP_UTF8, 0, name.data(), -1, wide.data(), size) == 0)
return false;
const HRESULT hr = SetThreadDescription(GetCurrentThread(), wide.data());
return SUCCEEDED(hr);
#elif defined(__linux__)
// On Linux this is straightforward.
return pthread_setname_np(pthread_self(), name.data()) == 0;
#elif defined(__APPLE__)
// On macOS, unlike Linux, a thread can only set a name for itself, so the signature is different.
return pthread_setname_np(name.data()) == 0;
#endif
}
/**
* @brief Get the priority of the current thread using the current platform's native API. This should work on Windows, Linux, and macOS.
*
* @return An `std::optional` object, optionally containing the priority of the current thread, as a member of the enum `BS::os_thread_priority`. If the returned object does not contain a value, then either the priority could not be determined, or it is not one of the pre-defined values.
*/
[[nodiscard]] static std::optional<os_thread_priority> get_os_thread_priority()
{
#if defined(_WIN32)
// On Windows, this is straightforward.
const int priority = GetThreadPriority(GetCurrentThread());
if (priority == THREAD_PRIORITY_ERROR_RETURN)
return std::nullopt;
return static_cast<os_thread_priority>(priority);
#elif defined(__linux__)
// On Linux, we distill the choices of scheduling policy, priority, and "nice" value into 7 pre-defined levels, for simplicity and portability. The total number of possible combinations of policies and priorities is much larger, so if the value was set via any means other than `BS::this_thread::set_os_thread_priority()`, it may not match one of our pre-defined values.
int policy = 0;
struct sched_param param = {};
if (pthread_getschedparam(pthread_self(), &policy, ¶m) != 0)
return std::nullopt;
if (policy == SCHED_FIFO && param.sched_priority == sched_get_priority_max(SCHED_FIFO))
{
// The only pre-defined priority that uses SCHED_FIFO and the maximum available priority value is the "realtime" priority.
return os_thread_priority::realtime;
}
if (policy == SCHED_RR && param.sched_priority == sched_get_priority_min(SCHED_RR) + (sched_get_priority_max(SCHED_RR) - sched_get_priority_min(SCHED_RR)) / 2)
{
// The only pre-defined priority that uses SCHED_RR and a priority in the middle of the available range is the "highest" priority.
return os_thread_priority::highest;
}
#ifdef __linux__
if (policy == SCHED_IDLE)
{
// The only pre-defined priority that uses SCHED_IDLE is the "idle" priority. Note that this scheduling policy is not available on macOS.
return os_thread_priority::idle;
}
#endif
if (policy == SCHED_OTHER)
{
// For SCHED_OTHER, the result depends on the "nice" value. The usual range is -20 to 19 or 20, with higher values corresponding to lower priorities. Note that `getpriority()` returns -1 on error, but since this does not correspond to any of our pre-defined values, this function will return `std::nullopt` anyway.
const int nice_val = getpriority(PRIO_PROCESS, static_cast<id_t>(syscall(SYS_gettid)));
switch (nice_val)
{
case PRIO_MIN + 2:
return os_thread_priority::above_normal;
case 0:
return os_thread_priority::normal;
case (PRIO_MAX / 2) + (PRIO_MAX % 2):
return os_thread_priority::below_normal;
case PRIO_MAX - 3:
return os_thread_priority::lowest;
#ifdef __APPLE__
// `SCHED_IDLE` doesn't exist on macOS, so we use the policy `SCHED_OTHER` with a "nice" value of `PRIO_MAX - 2`.
case PRIO_MAX - 2:
return os_thread_priority::idle;
#endif
default:
return std::nullopt;
}
}
return std::nullopt;
#elif defined(__APPLE__)
// On macOS, we distill the choices of scheduling policy and priority into 7 pre-defined levels, for simplicity and portability. The total number of possible combinations of policies and priorities is much larger, so if the value was set via any means other than `BS::this_thread::set_os_thread_priority()`, it may not match one of our pre-defined values.
int policy = 0;
struct sched_param param = {};
if (pthread_getschedparam(pthread_self(), &policy, ¶m) != 0)
return std::nullopt;
if (policy == SCHED_FIFO && param.sched_priority == sched_get_priority_max(SCHED_FIFO))
{
// The only pre-defined priority that uses SCHED_FIFO and the maximum available priority value is the "realtime" priority.
return os_thread_priority::realtime;
}
if (policy == SCHED_RR && param.sched_priority == sched_get_priority_min(SCHED_RR) + (sched_get_priority_max(SCHED_RR) - sched_get_priority_min(SCHED_RR)) / 2)
{
// The only pre-defined priority that uses SCHED_RR and a priority in the middle of the available range is the "highest" priority.
return os_thread_priority::highest;
}
if (policy == SCHED_OTHER)
{
// For SCHED_OTHER, the result depends on the specific value of the priority.
if (param.sched_priority == sched_get_priority_max(SCHED_OTHER))
return os_thread_priority::above_normal;
if (param.sched_priority == sched_get_priority_min(SCHED_OTHER) + (sched_get_priority_max(SCHED_OTHER) - sched_get_priority_min(SCHED_OTHER)) / 2)
return os_thread_priority::normal;
if (param.sched_priority == sched_get_priority_min(SCHED_OTHER) + (sched_get_priority_max(SCHED_OTHER) - sched_get_priority_min(SCHED_OTHER)) * 2 / 3)
return os_thread_priority::below_normal;
if (param.sched_priority == sched_get_priority_min(SCHED_OTHER) + (sched_get_priority_max(SCHED_OTHER) - sched_get_priority_min(SCHED_OTHER)) / 3)
return os_thread_priority::lowest;
if (param.sched_priority == sched_get_priority_min(SCHED_OTHER))
return os_thread_priority::idle;
return std::nullopt;
}