|
|
Log in / Subscribe / Register

Beingessner: Rust's Unsafe Pointer Types Need An Overhaul

Beingessner: Rust's Unsafe Pointer Types Need An Overhaul

Posted Mar 22, 2022 9:05 UTC (Tue) by tialaramex (subscriber, #21167)
In reply to: Beingessner: Rust's Unsafe Pointer Types Need An Overhaul by jlombera
Parent article: Beingessner: Rust's Unsafe Pointer Types Need An Overhaul

> the processor takes care of maintaining cache coherence

The CPU doesn't promise sequential consistency, because doing so would make it (much) slower. So now your program doesn't have sequential consistency. This is inherently a very difficult environment in which to write programs at all, but C and C++ don't bother you with that trouble because both languages have the same rule about sequential consistency: If your program doesn't exhibit sequential consistency it instead has Undefined Behaviour and they wash their hands of you entirely.

Again, you can write "volatile" on some more variables and maybe you get lucky and on the CPU you're working with the extra spills cause a cache flush, or forces an extra wait cycle somewhere and it happens to mask the bug. And then maybe somebody buys a CPU with more L1 cache, or a different cache policy and now the mysterious bug is back. You are using the wrong tool for the job.


to post comments

Beingessner: Rust's Unsafe Pointer Types Need An Overhaul

Posted Mar 22, 2022 15:45 UTC (Tue) by jlombera (guest, #155698) [Link] (1 responses)

Sure, you might need to resort to explicit memory fencing when you want to ensure sequential consistency, but this is not what volatile is about.

Beingessner: Rust's Unsafe Pointer Types Need An Overhaul

Posted Apr 4, 2022 2:54 UTC (Mon) by ncm (guest, #165) [Link]

Being absolutely clear: "volatile" is completely useless for synchronizing between threads. If you have been relying on volatile for synchronization, you are shipping bugs.

Unless you are pinging hardware registers, "volatile" is doing absolutely nothing for you, no matter how it looks to you in Godbolt. To synchronize between threads, you need memory fences, which are expressed as "atomic" types in C and C++. If you are using atomics, there is exactly zero value in adding "volatile". If you are not using atomics and not pinging hardware registers, there is exactly zero value in adding "volatile". "Volatile" appearing in code not part of an OS driver reliably indicates bugs.


Copyright © 2026, Eklektix, Inc.
Comments and public postings are copyrighted by their creators.
Linux is a registered trademark of Linus Torvalds