Mmap returns a void*, but not a volatile void*. If I’m using mmap to map shared memory, then another process could be writing to that memory, which means two subsequent reads from the same memory location can yield different values — the exact situation volatile is meant for. So why doesn’t it return a volatile void*?
My best guess is that if you have a process that’s exclusively writing to the shared memory segment, it doesn’t need to look at the shared memory through volatile pointers because it will always have the right understanding of what’s present; any optimizations the compiler does to prevent redundant reads won’t matter since there is nothing else writing and changing the values under its feet. Or is there some other historical reason? I’m inclined to say returning volatile void* would be a safer default, and those wanting this optimization could then manually cast to void*.
POSIX mmap description: http://opengroup.org/onlinepubs/007908775/xsh/mmap.html
The deeply-held assumption running through many software systems is that most programmers are sequential programmers. This has only recently started to change.
mmaphas dozens of uses not related to shared memory. In the event that a programmer is writing a multithreaded program, they must take their own steps to ensure safety. Protecting each variable with a mutex is not the default. Likewise,mmapdoes not assume that another thread will make contentious accesses to the same shared-memory segment, or even that a segment so mapped will be accessible by another thread.I’m also unconvinced that marking the return of
mmapasvolatilewill have an effect on this. A programmer would still have to ensure safety in access to the mapped region, no?