CNum 0.2.1
CPU-optimized ML library for C++
Loading...
Searching...
No Matches
ThreadPool.h
Go to the documentation of this file.
1#ifndef THREAD_POOL_H
2#define THREAD_POOL_H
3
6
7#include <functional>
8#include <vector>
9#include <thread>
10#include <mutex>
11#include <future>
12#include <atomic>
13#include <atomic>
14
19namespace CNum::Multithreading {
20 using Func = std::function< void(arena_t *) >;
21
23 constexpr size_t default_arena_init_block_ct = 16500;
24
29
34 class ThreadPool {
35 private:
37 int _num_threads;
38 std::vector<std::thread> _threads;
39 std::mutex _mtx;
40 ::std::atomic<bool> _is_shutdown;
41 static thread_local int _worker_id;
42
46 void worker(ThreadPoolConfig config, int worker_id);
47
49 ThreadPool(ThreadPoolConfig config);
50
51
52 public:
57
60 static int get_worker_id();
61
64
65 ThreadPool(const ThreadPool &other) = delete;
66 ThreadPool &operator=(const ThreadPool &other) = delete;
67 ThreadPool(ThreadPool &&other) = delete;
68 ThreadPool &operator=(ThreadPool &&other) = delete;
69
71 void shutdown();
72
76 template<typename T>
77 std::future<T> submit(std::function< T(arena_t *arena) > f) {
78 if (_is_shutdown.load(::std::memory_order_acquire))
79 throw ::std::runtime_error("Thread pool submit error - Submit cannot be called after thread pool is shut down");
80
81 auto p = std::make_shared< std::promise<T> >();
82 std::future<T> fut = p->get_future();
83
84 auto func = [p, f] (arena_t *arena) mutable {
85 if constexpr (std::is_void_v<T>) {
86 f(arena);
87 p->set_value();
88 } else {
89 p->set_value(f(arena));
90 }
91 };
92
93 _q.enqueue(func);
94 return fut;
95 }
96 };
97};
98
99#endif
struct arena arena_t
ThreadPool(ThreadPool &&other)=delete
static int get_worker_id()
Get the thread-local id of a worker.
void shutdown()
Shut the ThreadPool down.
ThreadPool & operator=(const ThreadPool &other)=delete
ThreadPool(const ThreadPool &other)=delete
static ThreadPool * get_thread_pool(ThreadPoolConfig config={ default_arena_init_block_ct })
Get the instance of the ThreadPool singleton.
ThreadPool & operator=(ThreadPool &&other)=delete
std::future< T > submit(std::function< T(arena_t *arena) > f)
Submit a task to the ThreadPool.
Definition ThreadPool.h:77
Structures and algorithms used for multithreaded operations.
std::function< void(arena_t *) > Func
Definition ThreadPool.h:20
constexpr size_t default_arena_init_block_ct
The default amount of blocks allocated to a newly initialized arena.
Definition ThreadPool.h:23
The configuration of the ThreadPool.
Definition ThreadPool.h:26
size_t arena_blocks_to_allocate
Definition ThreadPool.h:27
A thread local mini "heap" used for thread local memory allocation.
Definition Arena.h:36