Let's not race ahead!

As with anything to do with memory, we do have times where memory is shared between pointers. Typically, when we write an application, we don't consider that, at any given time, there may be multiple threads running at the same time, and while we can fairly accurately predict what will happen by following the flow, we can sometimes face an issue known as a race condition. Quite simply, we don't know which condition will hit first.

Let's look at the following example:

    // 05/threads-1/src/main.rs
use std::thread; use std::rc::Rc; struct MyCounter { count: i32 } fn wont_work() { let mut counter = Rc::new(MyCounter {count: 0}); thread::spawn(move || // new thread { counter.count += 1; }); println!("{}", counter.count); }

This won't compile because the compiler doesn't know which thread will be 0 or 1, as they both attempt to access counter at the same time. In Rust terms, counter gets moved to the inner thread, which means that it cannot be accessed anywhere else. Reference counting via the Rc type does not help here, because it's not thread-safe.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset