-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathworkers.cc
More file actions
60 lines (36 loc) · 981 Bytes
/
workers.cc
File metadata and controls
60 lines (36 loc) · 981 Bytes
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
// The worker thread that calls the gosia calculations
// Liam Gaffney (liam.gaffney@liverpool.ac.uk) - 29/04/2020
#ifndef __workers_cc__
#define __workers_cc__
#include "workers.hh"
// Constructor to create the thread
workers::workers() : stop(false) {
t = std::thread( &workers::loop, this );
}
// The destructor joins all threads
workers::~workers() {
{
std::unique_lock<std::mutex> lock(m);
stop = true;
}
cv.notify_all();
t.join();
}
void workers::loop() {
while( !stop ) {
std::unique_lock<std::mutex> lock(m);
cv.wait( lock, [this] { return !jobs.empty(); } );
(jobs.front())();
jobs.pop();
}
}
template< class Func, class ... Args >
bool workers::add_job( Func f, Args ... a ) {
std::unique_lock<std::mutex> lock(m);
std::packaged_task<void()> task( std::bind(f,a...) );
jobs.emplace( std::move(task) );
// Notify the thread that there is a new job
cv.notify_one();
return true;
}
#endif