Is volatile useful at all in a single threaded C ++ application?

As in the title - is there any case when it volatileis useful in the context of single-threaded programming? I know what he used to make sure that the value of the variable is always checked in memory, so is there a case where this value can change (in the ST application) in such a way that the application / compiler will not notice?

I leave this question an agnostic language, because I do not know any differences between them that would affect the answer to this question. But if there is any request, let me know.

Edit: As I pointed out, the question is not a language agnostic. I make this C ++ concrete then (I read that there are differences in C ++ versions too, but I hope they are not big enough to make this question too wide).

+4
source share
3 answers

This is the answer for C and C ++

Yes! When a variable is mapped to a hardware register (for example, an I / O device). Hardware is case-insensitive regardless of 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 ++, this is the main reason. Volatility is not even recommended for multi-threaded use .

+4
source

, volatile , , , volatile ( / ).

, volatile C ++, . :

void do_thing(const std::vector<int>& v) {
    if (v.empty()) {
        do_thing_1();
    } else {
        do_thing_2();
    }
}

, volatile if:

void do_thing(const std::vector<int>& v) {
    volatile bool condition = v.empty();
    if (condition) {
        do_thing_1();
    } else {
        do_thing_2();
    }
}

volatile, . if, condition ( v).

condition a static, : , , "" .

, , , .

+3

. , , , volatile.

p.s. , .

0
source

Source: https://habr.com/ru/post/1627268/


All Articles