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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
use jobserver_crate::{Client, HelperThread, Acquired};
use lazy_static::lazy_static;
use std::sync::{Condvar, Arc, Mutex};
use std::mem;
#[derive(Default)]
struct LockedProxyData {
free: usize,
waiters: usize,
requested: usize,
tokens: Vec<Acquired>,
}
impl LockedProxyData {
fn request_token(&mut self, thread: &Mutex<HelperThread>) {
self.requested += 1;
thread.lock().unwrap().request_token();
}
fn release_token(&mut self, cond_var: &Condvar) {
if self.waiters > 0 {
self.free += 1;
cond_var.notify_one();
} else {
if self.tokens.is_empty() {
self.free += 1;
} else {
self.tokens.pop().unwrap();
}
}
}
fn take_token(&mut self, thread: &Mutex<HelperThread>) -> bool {
if self.free > 0 {
self.free -= 1;
self.waiters -= 1;
if self.requested + self.free < self.waiters {
self.request_token(thread);
}
true
} else {
false
}
}
fn new_requested_token(&mut self, token: Acquired, cond_var: &Condvar) {
self.requested -= 1;
if self.waiters > 0 {
self.free += 1;
self.tokens.push(token);
cond_var.notify_one();
} else {
mem::drop(token);
}
}
}
#[derive(Default)]
struct ProxyData {
lock: Mutex<LockedProxyData>,
cond_var: Condvar,
}
struct Proxy {
thread: Mutex<HelperThread>,
data: Arc<ProxyData>,
}
lazy_static! {
static ref GLOBAL_CLIENT: Client = unsafe {
Client::from_env().unwrap_or_else(|| {
Client::new(32).expect("failed to create jobserver")
})
};
static ref GLOBAL_PROXY: Proxy = {
let data = Arc::new(ProxyData::default());
Proxy {
data: data.clone(),
thread: Mutex::new(client().into_helper_thread(move |token| {
data.lock.lock().unwrap().new_requested_token(token.unwrap(), &data.cond_var);
}).unwrap()),
}
};
}
pub fn client() -> Client {
GLOBAL_CLIENT.clone()
}
pub fn acquire_thread() {
GLOBAL_PROXY.acquire_token();
}
pub fn release_thread() {
GLOBAL_PROXY.release_token();
}
impl Proxy {
fn release_token(&self) {
self.data.lock.lock().unwrap().release_token(&self.data.cond_var);
}
fn acquire_token(&self) {
let mut data = self.data.lock.lock().unwrap();
data.waiters += 1;
if data.take_token(&self.thread) {
return;
}
data.request_token(&self.thread);
loop {
data = self.data.cond_var.wait(data).unwrap();
if data.take_token(&self.thread) {
return;
}
}
}
}