6 ms·
How come the first example isn’t a race on a since it’s accessed from two threads?
by rvcdbn 4y ago
How come the first example isn’t a race on a since it’s accessed from two threads?
- jcranmer 4y agoBoth threads are only reading the array. For it to be a race, at least one of the accesses must be a write.
- rvcdbn 4y agoah, that makes sense thanks
- theptip 4y agoThe second usage is a mut borrow and I think would be incompatible with a read only borrow if they were run in parallel. As the comment eludes to, each spawned thread is implicitly joined if you drop the join handle returned by s::spawn(). So in this case the spawned threads run serially.
- DenseComet 4y agoNope, the threads run in parallel. The variable x is mutably borrowed only once by the second thread. The variable a is immutably borrowed twice, so there is no issue.
- theptip 4y agoAre you certain? From the docs on https://doc.rust-lang.org/stable/std/thread/struct.Scope.html#method.spawn https://doc.rust-lang.org/stable/std/thread/struct.Scope.htm..., > If the join handle is dropped, the spawned thread will implicitly joined at the end of the scope. Plus the comment says > // We can even mutably borrow `x` here, // because no other threads are using it. Which doesn’t line up with another thread having a read-only borrow on it. Anyway not at my machine to test right now, I could be wrong.
- theptip 4y agoOh never mind, I’m completely misreading. Thanks for the pointer.
- deleted 4y ago[deleted]
- Tuna-Fish 4y agox is not used by the other thread, a is. > If the join handle is dropped, the spawned thread will implicitly joined at the end of the scope. "end of scope" here refers to the end of the closure, after the second thread is spawned. You can trivially show that the threads exist in parallel by adding waits.
- tomjakubowski 4y agoThe second use is a mutable borrow of x, not the array. x is borrowed read-only later, after the scoped threads are joined.
- nextaccountic 4y agoIf one thread tries to mutate the variable a instead of just reading from it, the compiler will output a compile-time error saying you can't do that. (But, if you wrap a into a mutex and add the required methods to lock the mutex, you suddenly can)