about summary refs log tree commit diff
path: root/src/libstd/task_pool.rs
blob: 4ed3c16c994a2ff95c03cb09412857bb64b9be07 (plain)
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
/// A task pool abstraction. Useful for achieving predictable CPU
/// parallelism.

use pipes::{Chan, Port};
use task::{SchedMode, SingleThreaded};

enum Msg<T> {
    Execute(~fn(&T)),
    Quit
}

pub struct TaskPool<T> {
    channels: ~[Chan<Msg<T>>],
    mut next_index: uint,

    drop {
        for self.channels.each |channel| {
            channel.send(Quit);
        }
    }
}

pub impl<T> TaskPool<T> {
    /// Spawns a new task pool with `n_tasks` tasks. If the `sched_mode`
    /// is None, the tasks run on this scheduler; otherwise, they run on a
    /// new scheduler with the given mode. The provided `init_fn_factory`
    /// returns a function which, given the index of the task, should return
    /// local data to be kept around in that task.
    static fn new(n_tasks: uint,
                  opt_sched_mode: Option<SchedMode>,
                  init_fn_factory: ~fn() -> ~fn(uint) -> T) -> TaskPool<T> {
        assert n_tasks >= 1;

        let channels = do vec::from_fn(n_tasks) |i| {
            let (chan, port) = pipes::stream::<Msg<T>>();
            let init_fn = init_fn_factory();

            let task_body: ~fn() = |move port, move init_fn| {
                let local_data = init_fn(i);
                loop {
                    match port.recv() {
                        Execute(move f) => f(&local_data),
                        Quit => break
                    }
                }
            };

            // Start the task.
            match opt_sched_mode {
                None => {
                    // Run on this scheduler.
                    task::spawn(move task_body);
                }
                Some(sched_mode) => {
                    task::task().sched_mode(sched_mode).spawn(move task_body);
                }
            }

            move chan
        };

        return TaskPool { channels: move channels, next_index: 0 };
    }

    /// Executes the function `f` on a task in the pool. The function
    /// receives a reference to the local data returned by the `init_fn`.
    fn execute(&self, f: ~fn(&T)) {
        self.channels[self.next_index].send(Execute(move f));
        self.next_index += 1;
        if self.next_index == self.channels.len() { self.next_index = 0; }
    }
}

#[test]
fn test_task_pool() {
    let f: ~fn() -> ~fn(uint) -> uint = || {
        let g: ~fn(uint) -> uint = |i| i;
        move g
    };
    let pool = TaskPool::new(4, Some(SingleThreaded), move f);
    for 8.times {
        pool.execute(|i| io::println(fmt!("Hello from thread %u!", *i)));
    }
}