In this case, does it mean vague selection?

I saw a code sample demonstrating the use of a qualifier volatilein answering a question about the function of C ++ volatile elements given below:

volatile int x;

int DoSomething() {
    x = 1;
    DoSomeOtherStuff();
    return x+1; // Don't just return 2 because we stored a 1 in x.  
                // Check to get its current value
}

I do not know if the qualifier has a volatiledifference in the above code. xis a global variable, and there is a function call between writing and reading on x, and we only read xat a time. Should the compiler do a real read on x(even this is not volatile)?

I think this is different from the following case:

volatile int x;

int DoSomething() {
    x = 1;
    while (x != 1)
        break;
}

In this case, we re-read ximmediately after writing to x, so volatileit is necessary to get the updated value xwritten by other threads.

, , , .

( ): , . , , volatile ( volatile). , volatile, , x DoSomeOtherStuff() return x+1, , IO , , , volatile, , volatile, . , , , .
(, , .)

+3
5

volatile . , DoSomeOtherStuff() x, x , volatile . volatile, , x - IOP , . , , , :

int
MeasureExecutionTime()
{
    x = 0;
    DoSomeOtherStuff();
    return x;
}

, DoSomeOtherStuff; , DoSomeOtherStuff , x.

, , , IO, , , . , , . volatile.

EDIT:

: , volatile , x. , volatile, g++, Sun CC , , V++. x , , . , membar.

, ( - , ), , , . , volatile .

volatile, . , .. , (C) ( ). volatile , IO, , . , . , . - :

globalPointer = new Xxx;

globalPointer, Xxx globalPointer . globalPointer volatile, Xxx, - Xxx Xxx. ; , volatile. , volatile, membar . (FWIW: membar , 10 .)

, ( ) , atomic_load atomic_store, ++ 11. ; . atomic_load to , ( , atomic_read, , atomic_write , "" atomic_read , "" , ).

+3

DoSomeOtherStuff(). :

static int DoSomeOtherStuff()
{
    return 42;
}

volatile int x;

int DoSomething() {
  x = 1;
  DoSomeOtherStuff();
  return x+1; // Don't just return 2 because we stored a 1 in x.
  // Check to get its current value
}

GCC -O3 DoSomeOtherStuff() ( ), x, x+1 .

0

SO : volatile?

, , x volatile. , , , , x , - , . , . , x. .

volatile. Volatile , , . . ++, .

Herb Sutter, .

0

, , . volatile , , x .

0

volatile - , , , - , . , .

volatile , GPIO, . , .

volatile

​​, . , :

  Accessing the memory-mapped peripherals register.

  Sharing the global variables or buffers between the multiple threads.

  Accessing the global variables in an interrupt routine or signal handler.

This link is also useful: http://aticleworld.com/understanding-volatile-qualifier-in-c/

0
source

All Articles