-
Notifications
You must be signed in to change notification settings - Fork 4
/
concurrent.rs
41 lines (36 loc) · 1.07 KB
/
concurrent.rs
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
extern mod extra;
use std::*;
use extra::future::{Future,from_port};
struct ConcurrentCalc<T,U> {
priv chan: Chan<(T,~fn(T)->U,comm::ChanOne<U>)>
}
impl<T:Send, U: Send> ConcurrentCalc<T,U> {
pub fn new() -> ConcurrentCalc<T,U> {
let (p, c) = comm::stream();
do spawn {
loop {
match p.try_recv() {
Some(message) => {
let (data,f,chan): (T,~fn(T)->U,comm::ChanOne<U>) = message;
chan.send(f(data))
}
None => break
};
}
}
ConcurrentCalc{ chan: c }
}
pub fn calculate(&mut self, data: T, f: ~fn(T)->U) -> Future<U> {
let (p, c) = comm::oneshot();
self.chan.send( (data,f,c) );
from_port(p)
}
}
#[test]
fn testConcurrent() {
let mut cc: ConcurrentCalc<uint,uint> = ConcurrentCalc::new();
let mut future = cc.calculate(3, |x| {x+1});
assert!(future.get() == 4);
let mut future = cc.calculate(10, |x| {x-4});
assert!(future.get() == 6);
}