3 ms·
I thought Rust was thread-safe and I don't see any "unsafe" blocks. What am I missing?
by clearprop 2y ago
I thought Rust was thread-safe and I don't see any "unsafe" blocks. What am I missing?
- chc4 2y agoLosing updates to the atomic counter is thread safe behavior, it's just a logic bug.
- kibwen 2y agoSpecifically, one thread reads the counter with proper synchronization, then another thread writes an incremented value to the counter with proper synchronization, then the first thread writes its own incremented value to the counter with proper synchronization. At every step the use of an AtomicU32 guarantees proper synchronization to the underlying memory, which is what Rust is concerned with. The fix for the logic bug in this case would be to indicate that you want the increment itself to be an atomic operation, using the fetch_add method: https://doc.rust-lang.org/std/sync/atomic/struct.AtomicU32.html#method.fetch_add https://doc.rust-lang.org/std/sync/atomic/struct.AtomicU32.h...
- deleted 2y ago[deleted]
- kibwen 2y agoFrom https://doc.rust-lang.org/nomicon/races.html https://doc.rust-lang.org/nomicon/races.html : "Safe Rust guarantees an absence of data races, which are defined as: two or more threads concurrently accessing a location of memory, where one or more of them is a write, and one or more of them is unsynchronized. A data race has Undefined Behavior, and is therefore impossible to perform in Safe Rust. [...] However Rust does not prevent general race conditions. This is mathematically impossible in situations where you do not control the scheduler, which is true for the normal OS environment. [...] For this reason, it is considered "safe" for Rust to get deadlocked or do something nonsensical with incorrect synchronization: this is known as a general race condition or resource race. Obviously such a program isn't very good, but Rust of course cannot prevent all logic errors. In any case, a race condition cannot violate memory safety in a Rust program on its own. Only in conjunction with some other unsafe code can a race condition actually violate memory safety."