Skip to content

Instantly share code, notes, and snippets.

@flaper87
Created September 11, 2013 22:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save flaper87/6530648 to your computer and use it in GitHub Desktop.
Save flaper87/6530648 to your computer and use it in GitHub Desktop.
try_for
/**
* Executes a function in another task and waits
* N msecs for it to complete.
*
* # Return Value
*
* if the function succeeds, the returned value will
* be sent back wrapped in result::Ok, otherwise,
* result::Err will be returned.
*
* # Failure
* Fails if a future_result was already set for this task.
*/
pub fn try_for<T: Send>(&mut self, msecs: u64, f: ~fn() -> T) -> Result<T, ()> {
let f = Cell::new(f);
do self.try {
let (po, ch) = stream::<T>();
let f = Cell::new(f.take());
// Run the function in a separate
// task. This task will fail if
// when its parent ends.
do spawn { ch.send(f.take()()); }
let timer = Timer::new();
// TODO: Handle unwrap error
let mut t = timer.unwrap();
// TODO: Fragment waiting time.
t.sleep(msecs);
match po.peek() {
true => po.recv(),
false => fail!("Timeout")
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment