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
#![allow(missing_doc)]
use std::task;
enum Msg<T> {
Execute(proc:Send(&T)),
Quit
}
pub struct TaskPool<T> {
priv channels: Vec<Sender<Msg<T>>>,
priv next_index: uint,
}
#[unsafe_destructor]
impl<T> Drop for TaskPool<T> {
fn drop(&mut self) {
for channel in self.channels.mut_iter() {
channel.send(Quit);
}
}
}
impl<T> TaskPool<T> {
pub fn new(n_tasks: uint,
init_fn_factory: || -> proc:Send(uint) -> T)
-> TaskPool<T> {
assert!(n_tasks >= 1);
let channels = Vec::from_fn(n_tasks, |i| {
let (tx, rx) = channel::<Msg<T>>();
let init_fn = init_fn_factory();
let task_body = proc() {
let local_data = init_fn(i);
loop {
match rx.recv() {
Execute(f) => f(&local_data),
Quit => break
}
}
};task::spawn(task_body);
tx
});
return TaskPool {
channels: channels,
next_index: 0,
};
}
pub fn execute(&mut self, f: proc:Send(&T)) {
self.channels.get(self.next_index).send(Execute(f));
self.next_index += 1;
if self.next_index == self.channels.len() { self.next_index = 0; }
}
}
#[test]
fn test_task_pool() {
let f: || -> proc:Send(uint) -> uint = || {
let g: proc:Send(uint) -> uint = proc(i) i;
g
};
let mut pool = TaskPool::new(4, f);
for _ in range(0, 8) {
pool.execute(proc(i) println!("Hello from thread {}!", *i));
}
}