Skip to content

Instantly share code, notes, and snippets.

@Centril
Last active May 17, 2017 15:05
Show Gist options
  • Save Centril/0621e8274e083501e920 to your computer and use it in GitHub Desktop.
Save Centril/0621e8274e083501e920 to your computer and use it in GitHub Desktop.
Rust: Sending callbacks in struct to a scoped thread with Box
#![feature(core)]
#![feature(std_misc)]
use std::thread::{Thread, JoinGuard};
fn callback(v: usize) -> usize { v * 2 }
struct S {
cb: Box<Fn(usize) -> usize + Send>,
}
fn threaded<'a>(s: S ) -> JoinGuard<'a, usize> {
Thread::scoped( move || {
(s.cb)(1337)
})
}
fn main() {
if let Ok(r) = threaded( S { cb: Box::new( callback ) } ).join() {
println!("{}", r);
}
}
#![feature(core)]
#![feature(std_misc)]
use std::thread::{Thread, JoinGuard};
fn callback(v: usize) -> usize { v * 2 }
// For ease of use:
trait CB: Fn(usize) -> usize + Send {}
impl<F> CB for F where F: Fn(usize) -> usize + Send {}
struct S<T>
where T: CB {
cb: T,
}
fn threaded<'a, T>(s: S<T>) -> JoinGuard<'a, usize>
where T: CB {
Thread::scoped( move || {
(s.cb)(1337)
})
}
fn main() {
if let Ok(r) = threaded( S { cb: callback } ).join() {
println!("{}", r);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment