Created
August 4, 2013 15:22
-
-
Save bct/6150669 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use std::comm::*; | |
use std::libc::funcs::posix88::unistd; | |
// this simulates a processing-intesive task. | |
fn test(x: bool) -> bool { | |
unsafe { | |
unistd::sleep(1); | |
} | |
x | |
} | |
// search through the given vec sequentially | |
fn search_seq(haystack: &[bool]) { | |
for haystack.iter().advance |&x| { | |
if test(x) { | |
println("Found it!"); | |
return; | |
} else { | |
println("Not it."); | |
} | |
} | |
} | |
// search through the given vec in parallel | |
fn search_par(haystack: &[bool]) { | |
// we'll use 4 tasks. | |
// break our vector into 4 chunks | |
// each tasks will operate on one of these chunks. | |
let chunks = [ | |
haystack.slice(0, 12), | |
haystack.slice(12, 24), | |
haystack.slice(24, 36), | |
haystack.slice(36, 48), | |
]; | |
// set up intertask communication | |
let (port, chan) = stream(); | |
let chan = SharedChan::new(chan); | |
// spawn the search subtasks | |
for chunks.iter().advance |&chunk| { | |
// this needs to be owned so that it can be passed into our closure. | |
let chunk: ~[bool] = chunk.to_owned(); | |
let child_chan = chan.clone(); | |
do spawn { | |
// do a sequential search through this subtask's chunk | |
for chunk.iter().advance |&x| { | |
child_chan.send(test(x)); | |
// this seems to be necessary to wake up the main task | |
std::task::yield(); | |
} | |
} | |
} | |
// look at the results coming coming from each subtask | |
loop { | |
let result = port.recv(); | |
if result { | |
// we're done. my hope is that exiting this function will kill the | |
// subtasks. | |
println("Found it!"); | |
return; | |
} else { | |
println("Not it."); | |
} | |
} | |
} | |
fn main() { | |
let haystack = [ | |
false, false, false, false, false, false, false, false, false, false, false, false, | |
false, false, false, false, false, false, false, false, false, false, false, false, | |
false, false, false, false, false, false, false, false, false, false, false, false, | |
false, false, false, false, true, false, false, false, false, false, false, false | |
]; | |
//search_seq(haystack); | |
search_par(haystack); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment