-
Notifications
You must be signed in to change notification settings - Fork 0
/
job.h
90 lines (81 loc) · 1.54 KB
/
job.h
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
90
#pragma once
#include <atomic>
#include <cassert>
#include <condition_variable>
#include <memory>
#include <mutex>
#include <utility>
class WorkQueue;
class Job {
public:
virtual ~Job() = default;
virtual void operator()() = 0;
private:
std::unique_ptr<Job> next;
friend class WorkQueue;
};
template <typename F>
struct Defer {
F f;
~Defer() {
std::move(f)();
}
};
class WorkQueue {
public:
void push(std::unique_ptr<Job> job) {
std::unique_lock lk(m);
(void)++pending;
if (back) {
back->next = std::move(job);
back = back->next.get();
}
else {
front = std::move(job);
back = front.get();
lk.unlock();
cv.notify_one();
}
}
bool runOne() {
auto job = take();
if (job) {
Defer d([this]{
std::unique_lock lk(m);
assert(pending > 0);
if (--pending == 0) {
assert(!front);
lk.unlock();
cv.notify_all();
}
});
(*std::move(job))();
return true;
}
return false;
}
void runUntilEmpty() {
while (runOne()) { }
}
private:
std::unique_ptr<Job> take() {
std::unique_lock lk(m);
cv.wait(lk, [this]{ return front || !pending; });
auto ret = std::move(front);
if (ret) {
front = std::move(ret->next);
if (front) {
lk.unlock();
cv.notify_one();
} else {
back = nullptr;
}
}
return ret;
}
std::mutex m;
std::condition_variable cv;
int pending = 0;
std::unique_ptr<Job> front;
Job* back = nullptr;
};