18 ms·
What about Rust’s borrow checker (affine types) enforces the use of mutexes (or other sync prims) here?
by e-dant 3y ago
What about Rust’s borrow checker (affine types) enforces the use of mutexes (or other sync prims) here?
- chowells 3y agoWhy would it need to? Rust's borrow checker makes it a compile-time error to share a mutable array between threads. No need for run time synchronization.
- e-dant 3y agoRight, that’s my understanding. But OP and a sibling thread here seem pretty sure about the mutex thing. I think there’s some nuance, but not in the general case. Shared memory, lazy statics in async blocks, and asynchronous constructors might have different initialization order mechanics that would require synchronization — but even then, the borrow checker would at least point it out
- Sharlin 3y agoWithout a mutex, you can’t even write code equivalent to that in the article because you cant mutably share as you pointed out. With a mutex you could – and the mutex would prevent data races (but not race conditions in general) – but indeed mutexes are a red herring here (at least in the specific sense of a runtime synchronization primitive). In Java you can’t synchronize defensively because synchronization requires that everybody who has access to the shared resource cooperates with you. And even if you could, you wouldn’t want to, not in this sort of a case. In Rust mutexes own the data they protect, and make it impossible for anyone to access the data without locking the mutex first, but again, an API like this would clearly not bother with dealing with mutexes but rather take a normal compile-time-checked borrow.
- kaba0 3y agoUnfortunately I can no longer edit my comment, please have a look at my reply: https://news.ycombinator.com/item?id=36690710 https://news.ycombinator.com/item?id=36690710
- ekimekim 3y agoAs sibling comments point out, mutexes aren't needed here. But to answer your direct question, Rust's type system enforces the use of mutexes to access protected values (if you're using the stdlib Mutex implementation) by only allowing access to protected values through a MutexGuard object which is created by locking the mutex. The borrow checker enforces you can't access the MutexGuard concurrently, so therefore you can't access the protected value concurrently.