1

How can I move reference into new thread in my case?

// How can I move reference into new thread?

pub mod tds {
        use std::thread;
        use std::thread::JoinHandle;

        pub fn f(sts: &u8) -> JoinHandle<()> {
            thread::spawn(move || {
                *sts = 88;
                println!("flow: {:?}", sts);
            })
        }
}


fn main() {
    let mut sts: u8 = 5;
    let handle = tds::f(&sts);

    println!("main_01: {:?}", sts);

    handle.join().unwrap();
    
    println!("main_02: {:?}", sts);
}

I found some link but couldn't apply, text

One solution is scoped threads — threads that are guaranteed to exit before the parent thread exits. These can ensure that stack variables in the parent thread will be available for the entire duration of the thread.

example_01

example_02

example_03

inshade
  • 13
  • 4

1 Answers1

0

You cannot return a JoinHandle from scoped threads. They are joined when the callback for thread::scope() returns automatically, and you cannot prevent that. If you want some code to execute before they're joined, you need to move it from main() to tds::f().

As @isaactfa said, you also cannot mutate a shared reference. You need to take &mut i32.

Another problem with your code is that you cannot read sts while another thread is mutating it. This could cause a data race, and is forbidden in Rust. You need to use atomics for that.

Chayim Friedman
  • 47,971
  • 5
  • 48
  • 77
  • Thank you for your feedback. "`... you cannot read sts while another thread is mutating it`" - this is an important note for me, maybe in the future, I need to learn how to do this. – inshade Jul 10 '23 at 07:44
  • In this case, the `sts` is sent and there will be a new `sts` for the new thread. `Sts` is the data for a request in a new thread to postgres, which is received in the main thread also from the postgres database. – inshade Jul 10 '23 at 07:48
  • I send data to the thread as struct, - so that each thread can work with its own postgres in parallel. If I send a value without a link, - it works (in my opinion). I expect 5-20 threads. By postgres I will have a separate question. – inshade Jul 10 '23 at 07:48
  • Please correct my code from example _3 for my complete understanding. As you see fit. Thank you very much. – inshade Jul 10 '23 at 07:50