4 ms·
`Arc<Mutex<T>>` is not a shared mutable state. You cannot have two mutable reference at the same time. To mutate stuff inside the mutex, you got to hold the mut
by siscia 6y ago
`Arc<Mutex<T>>` is not a shared mutable state. You cannot have two mutable reference at the same time. To mutate stuff inside the mutex, you got to hold the mutex, which guarantees that there are only one mutable reference at any given moment.
`RefCell` is one "escape hatches".
- brundolf 6y agoWorth noting that RefCell still enforces single-mutable-reference, it just does so at runtime. It lets you do things that could never be verified statically, but if you ever actually violate the condition, you'll get a panic (which is still better than memory unsafety).
- pjmlp 6y agoShould be noted that this only works across threads. Nothing can be assumed regarding data races if it happens to be a shared value of some sort modified via IPC or other kind of APIs across multiple processes accessing the same resource.
- brundolf 6y agoThat would require getting into unsafe { } code and passing along a raw pointer, wouldn't it? Nothing regarding safety can be assumed about unsafe code at all
- pjmlp 6y agoNope, since when do you need to do that when using file IO or database connections? The library code down at the bottom layer might do that, depending on how the bindings to the APIs are implemented, but it won't be necessarily exposed to the code you are writing yourself. For example, doing SQL statements isn't unsafe { }.
- brundolf 6y agoWhat I'm not seeing is how the actual value contained inside a RefCell would get modified out from underneath your code without going through its checked methods, unless something has a raw pointer directly to its contents
- pjmlp 6y agoBecause you aren't looking at it from the context of data races anywhere on the application, and focusing on RefCell alone instead. Yes, Rust prevents data races when several threads try to modify a memory location inside the same process. This is just a special case of data races, which may take several forms. If several processes, or even threads are accessing an external resource, like a database, each of them can issue UPDATE statements on the same record, and it is impossible to validate which value you will get back, unless it is done inside a proper transaction block. Ensuring that a SQL data race doesn't happen, might be critical, e.g. several people to the same plane seat, yet there is nothing on the RefCell or not using unsafe {} that can enforce it. I would advise to read the "Data Races and Race Conditions" chapter of Rustonomicon regarding what guarantees Rust actually provides, anything else is up to the programmer to take care they don't happen. https://doc.rust-lang.org/nomicon/races.html https://doc.rust-lang.org/nomicon/races.html