Skip to content

Instantly share code, notes, and snippets.

@Centril Centril/box_callback.rs
Last active May 17, 2017

Embed
What would you like to do?
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
You can’t perform that action at this time.