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
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
use std::io;
use std::fmt;
use std::sync::Arc;
use std::boxed::FnBox;
use std::collections::VecDeque;
use std::sync::{Mutex, Condvar};
use backbone::{Control, Reactor, TimerQueue};
use {IoObject, IoService};
type TaskHandler = Box<FnBox(*const IoService) + Send + 'static>;
struct TaskQueue {
stopped: bool,
blocked: bool,
queue: VecDeque<TaskHandler>,
}
pub struct TaskExecutor {
mutex: Mutex<TaskQueue>,
condvar: Condvar,
}
impl TaskExecutor {
fn new() -> TaskExecutor {
TaskExecutor {
mutex: Mutex::new(TaskQueue {
stopped: false,
blocked: false,
queue: VecDeque::new(),
}),
condvar: Condvar::new()
}
}
pub fn count(&self) -> usize {
let task = self.mutex.lock().unwrap();
task.queue.len()
}
pub fn stopped(&self) -> bool {
let task = self.mutex.lock().unwrap();
task.stopped
}
pub fn stop(&self) {
let mut task = self.mutex.lock().unwrap();
if !task.stopped{
task.stopped = true;
self.condvar.notify_all();
}
}
pub fn reset(&self) {
let mut task = self.mutex.lock().unwrap();
task.stopped = false;
}
pub fn is_block(&self) -> bool {
let task = self.mutex.lock().unwrap();
task.blocked
}
pub fn set_block(&self, on: bool) {
let mut task = self.mutex.lock().unwrap();
task.blocked = on;
}
fn post(&self, handler: TaskHandler) {
let mut task = self.mutex.lock().unwrap();
task.queue.push_back(handler);
self.condvar.notify_one();
}
fn pop(&self) -> Option<TaskHandler> {
let mut task = self.mutex.lock().unwrap();
loop {
if let Some(handler) = task.queue.pop_front() {
return Some(handler);
} else if task.stopped || !task.blocked {
return None
}
task = self.condvar.wait(task).unwrap();
}
}
}
pub struct IoServiceBase {
pub task: TaskExecutor,
pub ctrl: Control,
pub react: Reactor,
pub queue: TimerQueue,
}
impl IoServiceBase {
pub fn new() -> io::Result<IoServiceBase> {
Ok(IoServiceBase {
task: TaskExecutor::new(),
ctrl: try!(Control::new()),
react: try!(Reactor::new()),
queue: TimerQueue::new(),
})
}
pub fn stop(io: &IoService) {
io.0.task.stop();
io.0.ctrl.stop_interrupt();
}
pub fn post<F>(&self, handler: F)
where F: FnOnce(&IoService) + Send + 'static {
self.task.post(Box::new(move |io: *const IoService| handler(unsafe { &*io })));
}
fn dispatch(io: &IoService) {
if io.stopped() {
io.0.react.cancel_all(io);
io.0.queue.cancel_all(io);
io.0.ctrl.stop_polling(io);
} else {
io.post(move |io| {
let block = io.0.task.is_block();
let count = io.0.react.poll(block, &io)
+ io.0.queue.cancel_expired(&io);
if !block && count == 0 && io.0.task.count() == 0 {
io.0.task.stop();
}
Self::dispatch(&io);
});
}
}
pub fn run(io: &IoService) {
if io.0.ctrl.start_polling(io) {
Self::dispatch(io);
}
while let Some(handler) = io.0.task.pop() {
handler(io);
}
}
}
impl IoService {
/// Constructs a new `IoService`.
///
/// # Panics
/// Panics if too many open files.
///
/// # Examples
/// ```
/// use asio::IoService;
///
/// let io = IoService::new();
/// ```
pub fn new() -> IoService {
IoService(Arc::new(IoServiceBase::new().unwrap()))
}
/// Sets a stop request and cancel all of the waiting event in an `IoService`.
///
/// # Examples
/// ```
/// use asio::IoService;
///
/// let io = IoService::new();
/// io.stop();
/// ```
pub fn stop(&self) {
IoServiceBase::stop(self)
}
/// Returns true if this has been stopped.
///
/// # Examples
/// ```
/// use asio::IoService;
///
/// let io = IoService::new();
/// assert_eq!(io.stopped(), false);
/// io.stop();
/// assert_eq!(io.stopped(), true);
/// ```
pub fn stopped(&self) -> bool {
self.0.task.stopped()
}
/// Resets a stopped `IoService`.
///
/// # Examples
/// ```
/// use asio::IoService;
///
/// let io = IoService::new();
/// assert_eq!(io.stopped(), false);
/// io.stop();
/// assert_eq!(io.stopped(), true);
/// io.reset();
/// assert_eq!(io.stopped(), false);
/// ```
pub fn reset(&self) {
self.0.task.reset()
}
/// Requests a process to invoke the given handler and return immediately.
///
/// # Examples
/// ```
/// use asio::IoService;
/// use std::sync::atomic::*;
///
/// let io = IoService::new();
/// static PASS: AtomicBool = ATOMIC_BOOL_INIT;
///
/// io.post(|_| PASS.store(true, Ordering::Relaxed));
/// assert_eq!(PASS.load(Ordering::Relaxed), false);
///
/// io.run();
/// assert_eq!(PASS.load(Ordering::Relaxed), true);
/// ```
pub fn post<F>(&self, handler: F)
where F: FnOnce(&IoService) + Send + 'static
{
self.0.post(handler);
}
/// Runs all given handlers.
///
/// # Examples
/// ```
/// use asio::IoService;
///
/// let io = IoService::new();
/// io.run();
/// ```
pub fn run(&self) {
if !self.stopped() {
IoServiceBase::run(self)
}
}
/// Runs all given handlers until call the `stop()`.
///
/// This is ensured to not exit until explicity stopped, so it can invoking given handlers in multi-threads.
///
/// # Examples
/// Execute 5 parallel's event loop (4 thread::spawn + 1 main thread).
///
/// ```
/// use asio::IoService;
/// use std::thread;
///
/// let mut thrds = Vec::new();
/// IoService::new().work(|io| {
/// for _ in 0..4 {
/// let io = io.clone();
/// thrds.push(thread::spawn(move || io.run()));
/// }
///
/// io.post(move |io| {
/// io.stop(); // If does not explicity stop, not returns in this `work()`.
/// });
/// });
///
/// for thrd in thrds {
/// thrd.join().unwrap();
/// }
/// ```
pub fn work<F: FnOnce(&IoService)>(&self, callback: F) {
if !self.stopped() {
self.0.task.set_block(true);
callback(self);
IoServiceBase::run(self);
self.0.task.set_block(false);
}
}
}
impl IoObject for IoService {
fn io_service(&self) -> &IoService {
self
}
}
impl fmt::Debug for IoService {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "IoService")
}
}