Is volatility needed here?

EDITED and clarified my question after Johannes' valuable answer

bool b = true;
volatile bool vb = true;    
void f1() { }
void f2() { b = false; }

void(* volatile pf)() = &f1; //a volatile pointer to function

int main()
{
   //different threads start here, some of which may change pf 
   while(b && vb)
   {
      pf();
   }
}

So, let him forget the synchronization for a while. The question is whether b should be declared volatile. I read a standard and peculiar description of the formal definition of volatile semantics (I even almost understand them, the word is almost the key). But let it be a little informal here. If the compiler sees that there is no possibility in the loop to change b, then if b is unstable, it can optimize it and assume that it is equivalent while(vb). The question is, in this case, pf itself is volatile, and the compiler allowed us to assume that b will not change in the loop, even if b is not volatile?

, , , , . , , , , , , , .

, .

:
?

bool b = true;
volatile bool vb = true;
void f1() {}
void f2() {b = false;}
void (*pf) () = &f1;

#include <iosrteam>
int main()
{
   //threads here

   while(b && vb)
   {
      int x;
      std::cin >> x;
      if(x == 0)
         pf = &f1;
      else
         pf = &f2;    
      pf();
   } 
}

. , ?

+5
3

, pf volatile, , b , b ?

, , pf , b, pf while. , b , , , ( b false vb ).


pf , , f1 f2 b false. main

int main()
{
   // threads here (which you say can only change "vb")

   while(vb)
   {
      int x;
      std::cin >> x;
      if(x != 0)
         break;    
   } 
}

, , , - (. [stmt.iter] p5 n3126). , . ++ 03 ( ).

, , . . , volatile, , , .

+3

volatile ++ , , , . . , .

, , . , , . , , , b . , volatile .

, pf volatile, , ( f1 f2!), , , , -, volatile b - .

- vb . , , - b. undefined, volatile - , , volatile - -op. , vb volatile, , vb .

, : volatile . , , fp , b, , , .

+2

volatile , , , , -, .

, . , , volatile, , - ( ).

, , , , , volatile.

Do not use volatile when you should lead to incorrect behavior, as optimization changes the meaning of the code.

I'm worried about coding the little things about the standard and the behavior of your compilers, because such things can change, and even if they don't, your code will change (which may affect the compiler) - so if you are not looking for micro-optimization improvements in this particular code, I would just leave it unstable.

0
source

All Articles