[ACCEPTED]-Why mark function argument as volatile-volatile
volatile BufferDesc *buf means that the data that
buf points to is volatile, not 13 that the pointer contained by
buf is volatile. (That 12 would be
BufferDesc * volatile buf.)
From the page you linked to:
On the other hand, if you 11 have a pointer variable where the address 10 itself was volatile but the memory pointed 9 to was not then we have:
int * volatile x;
Re this part of 8 your question:
So why are certain function 7 arguments declared as volatile?
Presumably 6 because the data it points to can change 5 in a way that the compiler wouldn't necessarily 4 know about. The
volatile keyword is there to prevent 3 the compiler applying optimizations that 2 assume the data doesn't change in ways it 1 doesn't know about.
I don't expect that DMA changes the pointer 2 location.
Not the location, but maybe the 1 content. And that's exactly what it is about...
Databases implementation does not rely on 18 the OS buffers&caches when accessing 17 files. They prefer to implement they own 16 cache system and get direct access to the file on the physical disk, for reliability issues: data 15 MUST to be flushed to the physical disk. (They 14 use the O_DIRECT option to perform direct 13 access to physical disk.)
The 3 functions 12 you are showing us make me think of asynchronous 11 handling of data coming from the disk. (StartBufferIO(), TerminatedBufferIO() and 10 so on). Honestly I am not sure of what is 9 their purpose, but based on what I know 8 about databases implementation, and those 7 function names, I would say that the buffer 6 content might be modified by the "disk" itself 5 with data from the file on the disk (or 4 whatever device), and therefore needs to 3 be flaged as volatile.
This hypothesis joins your 2 usual interpretation of what the volatile keyword 1 is usually used for: device drivers.
DMA isn't the only reason to use "volatile". It's 6 also useful for multithreaded and shared 5 memory applications, where another thread 4 may change memory referenced by this code. I'm 3 sure that PostgreSql is multi-threaded, so 2 this is a likely reason why volatile is 1 being used here.
One thing a compiler usually does when optimising 13 is removing dead code, so if you do some 12 operations with a variable that its never 11 read neither and its result is useless compiler 10 will probably just remove it, as well as 9 removing the rest of operations that affects 8 it. That behaviour can be very annoying 7 when your debug a code ore your are performing 6 some kind of benchamrks. If you declare 5 as volatile a variable you alert the compiler 4 it could be used by external libraries or 3 programs, among other implications the keyword 2 may have. Then it should never treat it 1 as dead code.
More Related questions