-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy paththread_pool.h
More file actions
59 lines (52 loc) · 1.5 KB
/
thread_pool.h
File metadata and controls
59 lines (52 loc) · 1.5 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
#pragma once
#include <thread>
#include <future>
#include <queue>
#include <mutex>
#include <vector>
#include <queue>
#include <functional>
#include <memory>
namespace pool {
class ThreadPool {
private:
class Worker {
public:
Worker(ThreadPool& pool);
void operator()();
private:
ThreadPool& Pool;
};
public:
ThreadPool(size_t poolSize);
template<class Func, class... Args>
auto AddTask(Func&& func, Args&&... args)
-> std::future<decltype(func(args...))>
{
using result_type = decltype(func(args...));
auto task = std::make_shared<std::packaged_task<result_type()>>(
std::bind(std::forward<Func>(func), std::forward<Args>(args)...)
);
auto result = task->get_future();
{
std::unique_lock<std::mutex> lock(Mutex);
if (!Working) {
throw std::runtime_error("Cannot AddTask after stopping ThreadPool");
}
Tasks.emplace([task]() { (*task)(); });
}
return result;
}
~ThreadPool();
private:
void ManageTasks();
private:
std::vector<std::thread> Workers;
std::queue<std::function<void()>> Tasks;
std::condition_variable WaitsTask;
std::condition_variable HasTask;
std::mutex Mutex;
std::thread ManageThread;
bool Working;
};
}