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
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
use latch::{LockLatch, SpinLatch};
#[allow(unused_imports)]
use log::Event::*;
use job::JobImpl;
use std::sync::Arc;
use std::error::Error;
use std::fmt;
use thread_pool::{self, Registry, WorkerThread};
use std::{thread, mem};
#[derive(Debug,PartialEq)]
pub enum InitError {
NumberOfThreadsZero,
GlobalPoolAlreadyInitialized,
}
impl fmt::Display for InitError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
InitError::NumberOfThreadsZero =>
write!(f, "The number of threads was set to zero but must be greater than zero."),
InitError::GlobalPoolAlreadyInitialized =>
write!(f, "The gobal thread pool has already been initialized with a different \
configuration. Only one valid configuration is allowed.")
}
}
}
impl Error for InitError {
fn description(&self) -> &str {
match *self {
InitError::NumberOfThreadsZero =>
"number of threads set to zero",
InitError::GlobalPoolAlreadyInitialized =>
"global thread pool has already been initialized"
}
}
}
#[derive(Clone, Debug)]
pub struct Configuration {
num_threads: Option<usize>
}
impl Configuration {
pub fn new() -> Configuration {
Configuration { num_threads: None }
}
pub fn num_threads(&self) -> Option<usize> {
self.num_threads
}
pub fn set_num_threads(mut self, num_threads: usize) -> Configuration {
self.num_threads = Some(num_threads);
self
}
fn validate(&self) -> Result<(), InitError> {
if let Some(value) = self.num_threads {
if value == 0 {
return Err(InitError::NumberOfThreadsZero);
}
}
Ok(())
}
}
pub fn initialize(config: Configuration) -> Result<(), InitError> {
try!(config.validate());
let num_threads = config.num_threads;
let registry = thread_pool::get_registry_with_config(config);
if let Some(value) = num_threads {
if value != registry.num_threads() {
return Err(InitError::GlobalPoolAlreadyInitialized);
}
}
registry.wait_until_primed();
Ok(())
}
pub fn dump_stats() {
dump_stats!();
}
pub fn join<A,B,RA,RB>(oper_a: A,
oper_b: B)
-> (RA, RB)
where A: FnOnce() -> RA + Send,
B: FnOnce() -> RB + Send,
RA: Send,
RB: Send,
{
unsafe {
let worker_thread = WorkerThread::current();
if worker_thread.is_null() {
return join_inject(oper_a, oper_b);
}
log!(Join { worker: (*worker_thread).index() });
let mut job_b = JobImpl::new(oper_b, SpinLatch::new());
(*worker_thread).push(job_b.as_job());
struct PanicGuard<'a>(&'a SpinLatch);
impl<'a> Drop for PanicGuard<'a> {
fn drop(&mut self) {
unsafe {
if !(*WorkerThread::current()).pop() {
while !self.0.probe() {
thread::yield_now();
}
}
}
}
}
let result_a;
{
let guard = PanicGuard(&job_b.latch);
result_a = oper_a();
mem::forget(guard);
}
let result_b;
if (*worker_thread).pop() {
log!(PoppedJob { worker: (*worker_thread).index() });
result_b = job_b.run_inline();
} else {
log!(LostJob { worker: (*worker_thread).index() });
(*worker_thread).steal_until(&job_b.latch);
result_b = job_b.into_result();
}
(result_a, result_b)
}
}
#[cold]
unsafe fn join_inject<A,B,RA,RB>(oper_a: A,
oper_b: B)
-> (RA, RB)
where A: FnOnce() -> RA + Send,
B: FnOnce() -> RB + Send,
RA: Send,
RB: Send,
{
let mut job_a = JobImpl::new(oper_a, LockLatch::new());
let mut job_b = JobImpl::new(oper_b, LockLatch::new());
thread_pool::get_registry().inject(&[job_a.as_job(), job_b.as_job()]);
job_a.latch.wait();
job_b.latch.wait();
(job_a.into_result(), job_b.into_result())
}
pub struct ThreadPool {
registry: Arc<Registry>
}
impl ThreadPool {
pub fn new(configuration: Configuration) -> Result<ThreadPool,InitError> {
try!(configuration.validate());
Ok(ThreadPool {
registry: Registry::new(configuration.num_threads)
})
}
pub fn install<OP,R>(&self, op: OP) -> R
where OP: FnOnce() -> R + Send
{
unsafe {
let mut job_a = JobImpl::new(op, LockLatch::new());
self.registry.inject(&[job_a.as_job()]);
job_a.latch.wait();
job_a.into_result()
}
}
}
impl Drop for ThreadPool {
fn drop(&mut self) {
self.registry.terminate();
}
}