Skip to content

Instantly share code, notes, and snippets.

@Centril
Created February 20, 2015 06:43
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 Centril/d224c40ae7fd56d96dc8 to your computer and use it in GitHub Desktop.
Save Centril/d224c40ae7fd56d96dc8 to your computer and use it in GitHub Desktop.
Rust: scoped, accessing parent thread
use std::thread::{self, JoinGuard};
use std::option::Option;
use std::marker::Send;
fn callback(v: usize) -> usize { v * 2 }
type CB = Fn(usize) -> usize + Sync + Send;
type Callback = Box<CB>;
struct S<'a> {
cb: Callback,
pub join_guard: Option<JoinGuard<'a, usize>>,
}
unsafe impl<'a> Send for S<'a> {}
impl<'a> S<'a> {
fn new( cb: Callback ) -> Self {
let mut s = S { cb: cb, join_guard: None };
s.join_guard = Some( thread::scoped( || {
(s.cb)(1337)
}) );
return s;
}
}
fn main() {
let mut s = S::new( Box::new( callback ) );
if let Some(jg) = s.join_guard {
let r = jg.join();
println!("{}", r);
}
}
@Centril
Copy link
Author

Centril commented Feb 20, 2015

Results in:

λ cargo build
   Compiling fsnotify v0.0.1 (file:///D:/Programming/Lumenix/rust-fsnotify)
src\main.rs:20:41: 22:4 error: cannot infer an appropriate lifetime due to conflicting requirements
src\main.rs:20                  s.join_guard = Some( thread::scoped( || {
src\main.rs:21                          (s.cb)(1337)
src\main.rs:22          }) );
src\main.rs:19:45: 24:3 note: first, the lifetime cannot outlive the block suffix following statement 0 at 19:44...
src\main.rs:19          let mut s = S { cb: cb, join_guard: None };
src\main.rs:20                  s.join_guard = Some( thread::scoped( || {
src\main.rs:21                          (s.cb)(1337)
src\main.rs:22          }) );
src\main.rs:23          return s;
src\main.rs:24  }
src\main.rs:21:6: 21:7 note: ...so that captured variable `s` does not outlive the enclosing closure
src\main.rs:21                          (s.cb)(1337)
                                         ^
src\main.rs:18:33: 24:3 note: but, the lifetime must be valid for the lifetime 'a as defined on the block at 18:32...
src\main.rs:18  fn new( cb: Callback ) -> Self {
src\main.rs:19          let mut s = S { cb: cb, join_guard: None };
src\main.rs:20                  s.join_guard = Some( thread::scoped( || {
src\main.rs:21                          (s.cb)(1337)
src\main.rs:22          }) );
src\main.rs:23          return s;
               ...
src\main.rs:23:10: 23:11 note: ...so that expression is assignable (expected `S<'a>`, found `S<'_>`)
src\main.rs:23          return s;
                               ^
error: aborting due to previous error
Could not compile `fsnotify`.

To learn more, run the command again with --verbose.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment