-
Notifications
You must be signed in to change notification settings - Fork 0
/
ThreadPool.hpp
49 lines (37 loc) · 981 Bytes
/
ThreadPool.hpp
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
#pragma once
#ifndef THREADPOOL_HPP
#define THREADPOOL_HPP
#include "Shared.hpp"
namespace ThreadPool {
class ThreadPool {
std::atomic_bool halt_ = false;
std::vector<std::jthread> threads_;
std::queue<std::function<void()>> jobs_;
mutex job_mutex_;
std::condition_variable condition_;
void setupThreadPool(u64 thread_count);
void workerLoop();
public:
ThreadPool(u64 thread_count = std::thread::hardware_concurrency());
~ThreadPool();
template<typename F>
void addJob(F job)
{
if (halt_) return;
std::unique_lock lock(job_mutex_);
jobs_.push(std::function<void()>(job));
condition_.notify_one();
}
template<typename F, typename... Arg>
void addJob(const F& job, const Arg&... args)
{
addJob([job, args...] {job(args...); });
}
void join();
u64 getThreadCount() const;
void dropUnstartedJobs();
void halt();
void start(u64 thread_count = std::thread::hardware_concurrency());
};
}
#endif // !THREADPOOL_HPP