Last active
May 17, 2017 15:05
-
-
Save Centril/0621e8274e083501e920 to your computer and use it in GitHub Desktop.
Rust: Sending callbacks in struct to a scoped thread with Box
This file contains 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
#![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); | |
} | |
} |
This file contains 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
#![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