Clustering
C++20 header-only: DBSCAN, HDBSCAN, k-means.
Loading...
Searching...
No Matches
thread.h
Go to the documentation of this file.
1#pragma once
2
3#include <BS_thread_pool.hpp>
4#include <cstddef>
5#include <optional>
6#include <thread>
7
8namespace clustering::math {
9
21inline std::size_t clampedJobCount(std::size_t nJobs) noexcept {
22 if (nJobs == 0) {
23 const std::size_t hw = std::thread::hardware_concurrency();
24 return hw == 0 ? std::size_t{1} : hw;
25 }
26 return nJobs;
27}
28
43inline bool shouldSpawnPool(std::size_t totalOps, std::size_t nJobs,
44 std::size_t minOpsPerWorker = std::size_t{1} << 15) noexcept {
45 if (nJobs <= 1) {
46 return false;
47 }
48 return (totalOps / nJobs) >= minOpsPerWorker;
49}
50
63struct Pool {
65 BS::light_thread_pool *pool = nullptr;
66
72 [[nodiscard]] std::size_t workerCount() const noexcept {
73 return (pool != nullptr) ? pool->get_thread_count() : std::size_t{1};
74 }
75
82 [[nodiscard]] static std::size_t workerIndex() noexcept {
83 return BS::this_thread::get_index().value_or(std::size_t{0});
84 }
85
98 [[nodiscard]] bool shouldParallelize(std::size_t totalWork, std::size_t minChunk,
99 std::size_t minTasksPerWorker = 2) const noexcept {
100 if (pool == nullptr || minChunk == 0) {
101 return false;
102 }
103 return (totalWork / minChunk) >= (workerCount() * minTasksPerWorker);
104 }
105
118 [[nodiscard]] bool shouldParallelizeWork(std::size_t totalOps,
119 std::size_t minOpsPerWorker = std::size_t{1}
120 << 15) const noexcept {
121 if (pool == nullptr) {
122 return false;
123 }
124 return (totalOps / workerCount()) >= minOpsPerWorker;
125 }
126};
127
128} // namespace clustering::math
std::size_t clampedJobCount(std::size_t nJobs) noexcept
Clamp a caller-supplied nJobs to a valid BS::light_thread_pool worker count.
Definition thread.h:21
bool shouldSpawnPool(std::size_t totalOps, std::size_t nJobs, std::size_t minOpsPerWorker=std::size_t{1}<< 15) noexcept
Decide whether spawning a pool with nJobs workers is worth it for totalOps of arithmetic work.
Definition thread.h:43
Thin injection wrapper around a BS::light_thread_pool.
Definition thread.h:63
static std::size_t workerIndex() noexcept
Stable index of the calling worker thread within the owning pool.
Definition thread.h:82
std::size_t workerCount() const noexcept
Number of worker threads available, or 1 in serial mode.
Definition thread.h:72
BS::light_thread_pool * pool
Underlying pool, or nullptr to force serial execution.
Definition thread.h:65
bool shouldParallelize(std::size_t totalWork, std::size_t minChunk, std::size_t minTasksPerWorker=2) const noexcept
Decide whether totalWork warrants parallel dispatch.
Definition thread.h:98
bool shouldParallelizeWork(std::size_t totalOps, std::size_t minOpsPerWorker=std::size_t{1}<< 15) const noexcept
Decide whether totalOps warrants parallel dispatch, based on work volume.
Definition thread.h:118