Capture all referenced object into single struct

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

You must use a scoped thread to do this. Scoped threads are available in the rayon crate or crossbeam crate.

Pin is completely irrelevant to this.

Hi alice,
According to what I learnt, Pin is used to keep variables inside async function available when the async function is waken, since the stack is not persistent. The example of self-referential struct seems like my situation.

Back to my situation, if tokio is used for concurrency, is there any "scoped feture"?

Your struct isn't self-referential. The reference goes from B to A, and not from B to B.

Besides, Pin doesn't do what you think. Even if you use Pin, you still can't write self-referential structs in safe code.

1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.