3 ms·
Interior mutability via atomic values (https://doc.rust-lang.org/std/sync/atomic/index.html https://doc.rust-lang.org/std/sync/atomic/index.html) works great fo
by dbaupp 7y ago
Interior mutability via atomic values (https://doc.rust-lang.org/std/sync/atomic/index.html https://doc.rust-lang.org/std/sync/atomic/index.html) works great for the first one, and, indeed, some sort of atomicity/synchronisation is required even in languages without the XOR rule (such as C++) to prevent undefined behaviour.
There's a variety of safe arena types that give allocation inside pools too: https://crates.io/search?q=Arena&sort=downloads https://crates.io/search?q=Arena&sort=downloads
- tomp 7y agoAtomics are very useful indeed, but an overkill for some situations. In particular, if there's just one writer and multiple readers, the write doesn't need to be synchronised (as there's no possibility of someone else mutating the value in the middle of you incrementing it). An example would be the GC thread incrementing the epoch id/count that all mutator (user) threads read. Presumably you'd still need some sort of synchronisation otherwise the memory will stay mutated just in one CPU's cache, you need to "flush" the updated memory so that other CPUs can then see it, but that's likely cheaper than executing the whole operation atomically... Basically, increments are fundamentally not atomic (i.e. composed of multiple separate operations) whereas reads (of a single word) are, so if all mutations happen from a single thread (assuming a sensible CPU architecture and cooperative compiler) there's nothing else that needs to be done to ensure atomicity, you only need to care about the "happens before" relationship. But then I'm not a low-level programmer so the above is probably all wrong :)
- dbaupp 7y agoThey have to go via the atomic types or it is undefined behaviour. One can use a very weak ordering (such as Relaxed) to require little or no "physical" synchronisation by the CPU. Like C++, Rust atomics offer a range of levels of synchronisation, weaker than sequential consistency. A platform like the JVM disguises this because every read and write (even without 'volatile') use minimal synchronisation to avoid the worst aspects of the danger here. This ensures that programs that do it wrong (e.g. forget a 'volatile') are "only" incorrect, but not unsafe.
- tomp 7y agoAh, you're right, weaker ordering takes care of a lot of these issues! Good point, thanks!