Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is volatile useful at all in a singlethreaded application in C++?

Like the title says - is there any case in which volatile is useful in the context of singlethreaded programming? I know it's used to make sure the value of the variable is always actually checked in memory so is there any case in which that value may change (in a ST app) in a way that the app/compiler won't notice?

I'm leaving this question language-agnostic as I'm not aware of any differences between them that would affect the answer to this question. But if there are any please let me know.

Edit: As it's been pointed out to me, the question isn't language-agnostic. I'm making it C++ specific then (I've read that there are differences in C++ versions as well but I hope they aren't big enough to make this question too broad).

like image 660
NPS Avatar asked Feb 07 '23 20:02

NPS


1 Answers

This is an answer for C and C++

Yes! When the variable is mapped to a hardware register (an I/O device for instance). The hardware modifies the register, independently of the application.

Example:

extern volatile uint32_t MY_DEVICE_START; // write-only register
extern volatile const uint32_t MY_DEVICE_STATUS; // read-only register
extern volatile uint32_t MY_DEVICE_DATA; // read-write register

...
MY_DEVICE_DATA = 42; // send input to the device
MY_DEVICE_START = 1; // start the device
while (MY_DEVICE_STATUS == 0) {} // busy-wait for the device to finish
int result = MY_DEVICE_DATA; // read output from the device
...

At least in C/C++ that's the main reason for it. Volatile is even not recommended for multi-threaded use.

like image 84
bolov Avatar answered May 08 '23 02:05

bolov