-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy paththreadpool.h
More file actions
53 lines (51 loc) · 1.34 KB
/
threadpool.h
File metadata and controls
53 lines (51 loc) · 1.34 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
#pragma once
#include <thread>
#include <mutex>
#include <vector>
#include <queue>
#include <atomic>
#include <functional>
#include <condition_variable>
#include <map>
#include <future>
using namespace std;
// Ï̳߳ØÀà
class ThreadPool
{
public:
ThreadPool(int min = 4, int max = thread::hardware_concurrency());
~ThreadPool();
void addTask(function<void()> f);
template<typename F, typename... Args>
auto addTask(F&& f, Args&&... args) -> future<typename result_of<F(Args...)>::type>
{
using returnType = typename result_of<F(Args...)>::type;
auto task = make_shared<packaged_task<returnType()>>(
bind(forward<F>(f), forward<Args>(args)...)
);
future<returnType> res = task->get_future();
{
unique_lock<mutex> lock(m_queueMutex);
m_tasks.emplace([task]() { (*task)(); });
}
m_condition.notify_one();
return res;
}
private:
void manager();
void worker();
private:
thread* m_manager;
map<thread::id, thread> m_workers;
vector<thread::id> m_ids;
int m_minThreads;
int m_maxThreads;
atomic<bool> m_stop;
atomic<int> m_curThreads;
atomic<int> m_idleThreads;
atomic<int> m_exitNumber;
queue<function<void()>> m_tasks;
mutex m_idsMutex;
mutex m_queueMutex;
condition_variable m_condition;
};