As I described on stackoverflow: rust - create a container struct hold two field, referencing from one to another - Stack Overflow
After reconsidering the design, my code is still not meeting the requirements.
I'm trying to share reference between (green) threads, I'd like to capture all referenced object into a single struct, without a lifetime parameter, so that it can be transfered between threads.
As long as the struct exists, the inner reference is always valid. It sounds std::pin::Pin
should work, right!
Make a simple code
use std::sync::Arc;
use std::thread;
#[derive(Debug)]
struct A {
a: String,
}
#[derive(Debug)]
struct B<'a> {
b: &'a str,
}
impl A {
fn new() -> A {
A{ a:"abcdefg".to_string() }
}
fn gen_b(&self) -> B<'_> {
B{ b: &self.a }
}
}
fn main() {
let a = Arc::new(A::new());
thread::spawn( || {
println!("{:?}", a);
let b = a.gen_b();
let t1 = thread::spawn(move || {
let id = "id-1";
println!("{} {:?}", id, b);
});
let t2 = thread::spawn(move || {
let id = "id-2";
println!("{} {:?}", id, b);
});
t1.join();
t2.join();
}).join();
}
Is there any struct can be moved into t1 and t2, so that they shared the same b
which reference to a