1

I'm currently moving a project from Python to Rust, and I ran into a small problem with the concept of ownership in Rust.

My main thread create a empty vector, then, I start another thread and that thread will run forever (loop) and add data to the vector every second. Until here, no problem.

The problem comes when from my main thread, I want to read the vector (print it or use the data inside it). Since the ownership has been moved, I can't use the vector in my main thread.

let mut prices: Vec<f64> = Vec::new();
thread::spawn(move || {
    start_filling_prices(&mut prices);
});
println!("{:?}", prices);
                 ^^^^^^^ value borrowed here after move

I've tried using a Mutex, Arc, Box, but the same problem occurs every time (or maybe I used the wrong one).

So, does someone know how to use the same variable in different threads at the same time?

Boiethios
  • 38,438
  • 19
  • 134
  • 183
Finrod
  • 103
  • 8
  • 1
    Use `Arc>` or `Arc>`. I'm sure there's a duplicate somewhere. – edwardw Feb 18 '20 at 10:25
  • Or this answer answers your literal question, even if that's not the idiomatic thing to do in your very case, as far as I can tell: https://stackoverflow.com/questions/31373255/how-do-i-share-a-mutable-object-between-threads-using-arc – Boiethios Feb 18 '20 at 10:29
  • 1
    @Finrod I've a hard time finding it, so don't worry, that's why there are duplicates. – Boiethios Feb 18 '20 at 10:29
  • 1
    See also [this answer](https://stackoverflow.com/a/45674912/4498831) to understand what is the purpose of those wrapper (`Arc`, `Mutex`, `Box`, etc.) – Boiethios Feb 18 '20 at 10:32

0 Answers0