11#include <promeki/config.h>
12#if PROMEKI_ENABLE_CORE
33PROMEKI_NAMESPACE_BEGIN
92 using WorkTag = StringRegistry<
"ThreadPoolWorkTag">::Item;
106 Duration totalQueueWait;
121 ThreadPool(
int maxThreadCount = -1,
bool lazy =
true);
128 ThreadPool(
const ThreadPool &) =
delete;
129 ThreadPool &operator=(
const ThreadPool &) =
delete;
130 ThreadPool(ThreadPool &&) =
delete;
131 ThreadPool &operator=(ThreadPool &&) =
delete;
151 template <
typename F>
auto submit(F &&callable) -> Future<std::invoke_result_t<F>> {
152 return submit(WorkTag(), std::forward<F>(callable));
174 template <
typename F>
auto submit(WorkTag tag, F &&callable) -> Future<std::invoke_result_t<F>> {
175 using R = std::invoke_result_t<F>;
176 auto task = std::make_shared<std::packaged_task<R()>>(std::forward<F>(callable));
177 Future<R> fut(task->get_future());
178 bool runInline =
false;
181 entry.enqueuedAt = TimeStamp::now();
182 entry.callable = [task]() { (*task)(); };
184 Mutex::Locker locker(_mutex);
185 if (_maxThreadCount == 0) {
188 _tasks.pushToBack(std::move(entry));
194 runTaskWithStats(entry);
209 void setNamePrefix(
const String &prefix);
215 String namePrefix()
const;
228 void setThreadCount(
int count,
bool lazy =
true);
234 int maxThreadCount()
const;
240 int threadCount()
const;
246 int activeThreadCount()
const;
258 Error waitForDone(
unsigned int timeoutMs);
276 void setName(
const String &name);
291 List<WorkStats> snapshotWorkStats()
const;
303 void resetWorkStats();
317 static List<ThreadPool *> allPools();
320 using Task = Function<void()>;
327 TimeStamp enqueuedAt;
335 Atomic<int64_t> totalWallNs{0};
336 Atomic<int64_t> totalCpuNs{0};
337 Atomic<int64_t> totalQueueWaitNs{0};
338 Atomic<int64_t> count{0};
343 void workerFunc(
int index);
344 void spawnThreads(
int count);
345 void maybeSpawnOne();
353 void runTaskWithStats(TaggedTask &t);
358 WorkRecord *recordFor(WorkTag tag);
363 static Mutex ®istryMutex();
364 static List<ThreadPool *> ®istry();
366 mutable Mutex _mutex;
368 WaitCondition _doneCv;
369 List<TaggedTask> _tasks;
370 List<BasicThread> _threads;
373 int _maxThreadCount = 0;
374 int _threadCount = 0;
375 int _activeCount = 0;
376 int _waitingCount = 0;
377 bool _shutdown =
false;
379 mutable ReadWriteLock _statsLock;
380 HashMap<uint64_t, UniquePtr<WorkRecord>> _stats;