-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathThreadPool.h
More file actions
89 lines (70 loc) · 1.86 KB
/
ThreadPool.h
File metadata and controls
89 lines (70 loc) · 1.86 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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
#pragma once
#include <iostream>
#include <thread>
#include <mutex>
#include <condition_variable>
#include <queue>
#include <functional>
#include <chrono>
namespace ndtech {
class ThreadPool
{
public:
ThreadPool(int threads) : shutdown_(false)
{
// Create the specified number of threads
threads_.reserve(threads);
for (int i = 0; i < threads; ++i)
threads_.emplace_back(std::bind(&ThreadPool::threadEntry, this, i));
}
~ThreadPool()
{
{
// Unblock any threads and tell them to stop
std::unique_lock <std::mutex> l(lock_);
shutdown_ = true;
condVar_.notify_all();
}
// Wait for all threads to stop
std::cerr << "Joining threads" << std::endl;
for (auto& thread : threads_)
thread.join();
}
void doJob(std::function <void(void)> func)
{
// Place a job on the queu and unblock a thread
std::unique_lock <std::mutex> l(lock_);
jobs_.emplace(std::move(func));
condVar_.notify_one();
}
protected:
void threadEntry(int i)
{
std::function <void(void)> job;
while (1)
{
{
std::unique_lock <std::mutex> l(lock_);
while (!shutdown_ && jobs_.empty())
condVar_.wait(l);
if (jobs_.empty())
{
// No jobs to do and we are shutting down
std::cerr << "Thread " << i << " terminates" << std::endl;
return;
}
std::cerr << "Thread " << i << " does a job" << std::endl;
job = std::move(jobs_.front());
jobs_.pop();
}
// Do the job without holding any locks
job();
}
}
std::mutex lock_;
std::condition_variable condVar_;
bool shutdown_;
std::queue <std::function <void(void)>> jobs_;
std::vector <std::thread> threads_;
};
}