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
use std::io;
use std::time;
use std::thread;
use std::sync::mpsc as std_mpsc;
use num_cpus;
use futures::{Async, Future, BoxFuture};
use fiber::{self, Spawn};
use io::poll;
use sync::oneshot::{self, Link};
use internal::fiber::Task;
use super::Executor;
#[derive(Debug)]
pub struct ThreadPoolExecutor {
pool: SchedulerPool,
pollers: PollerPool,
spawn_rx: std_mpsc::Receiver<Task>,
spawn_tx: std_mpsc::Sender<Task>,
round: usize,
steps: usize,
}
impl ThreadPoolExecutor {
pub fn new() -> io::Result<Self> {
Self::with_thread_count(num_cpus::get() * 2)
}
pub fn with_thread_count(count: usize) -> io::Result<Self> {
assert!(count > 0);
let pollers = PollerPool::new(count)?;
let schedulers = SchedulerPool::new(&pollers);
let (tx, rx) = std_mpsc::channel();
Ok(ThreadPoolExecutor {
pool: schedulers,
pollers: pollers,
spawn_tx: tx,
spawn_rx: rx,
round: 0,
steps: 0,
})
}
}
impl Executor for ThreadPoolExecutor {
type Handle = ThreadPoolExecutorHandle;
fn handle(&self) -> Self::Handle {
ThreadPoolExecutorHandle { spawn_tx: self.spawn_tx.clone() }
}
fn run_once(&mut self) -> io::Result<()> {
match self.spawn_rx.try_recv() {
Err(std_mpsc::TryRecvError::Empty) => {
thread::sleep(time::Duration::from_millis(1));
}
Err(std_mpsc::TryRecvError::Disconnected) => unreachable!(),
Ok(task) => {
let i = self.round % self.pool.schedulers.len();
self.pool.schedulers[i].spawn_boxed(task.0);
self.round = self.round.wrapping_add(1);
}
}
self.steps = self.steps.wrapping_add(1);
let i = self.steps % self.pool.schedulers.len();
if let Err(_) = self.pool.links[i].poll() {
Err(io::Error::new(io::ErrorKind::Other,
format!("The {}-th scheduler thread is aborted", i)))
} else {
Ok(())
}
}
}
impl Spawn for ThreadPoolExecutor {
fn spawn_boxed(&self, fiber: BoxFuture<(), ()>) {
self.handle().spawn_boxed(fiber)
}
}
#[derive(Debug, Clone)]
pub struct ThreadPoolExecutorHandle {
spawn_tx: std_mpsc::Sender<Task>,
}
impl Spawn for ThreadPoolExecutorHandle {
fn spawn_boxed(&self, fiber: BoxFuture<(), ()>) {
let _ = self.spawn_tx.send(Task(fiber));
}
}
#[derive(Debug)]
struct PollerPool {
pollers: Vec<poll::PollerHandle>,
links: Vec<Link<(), io::Error>>,
}
impl PollerPool {
pub fn new(pool_size: usize) -> io::Result<Self> {
let mut pollers = Vec::new();
let mut links = Vec::new();
for _ in 0..pool_size {
let (link0, mut link1) = oneshot::link();
let mut poller = poll::Poller::new()?;
links.push(link0);
pollers.push(poller.handle());
thread::spawn(move || while let Ok(Async::NotReady) = link1.poll() {
let timeout = time::Duration::from_millis(1);
if let Err(e) = poller.poll(Some(timeout)) {
link1.exit(Err(e));
return;
}
});
}
Ok(PollerPool {
pollers: pollers,
links: links,
})
}
}
#[derive(Debug)]
struct SchedulerPool {
schedulers: Vec<fiber::SchedulerHandle>,
links: Vec<Link<(), ()>>,
}
impl SchedulerPool {
pub fn new(poller_pool: &PollerPool) -> Self {
let mut schedulers = Vec::new();
let mut links = Vec::new();
for poller in &poller_pool.pollers {
let (link0, mut link1) = oneshot::link();
let mut scheduler = fiber::Scheduler::new(poller.clone());
links.push(link0);
schedulers.push(scheduler.handle());
thread::spawn(move || while let Ok(Async::NotReady) = link1.poll() {
scheduler.run_once(true);
});
}
SchedulerPool {
schedulers: schedulers,
links: links,
}
}
}