The volatile C ++ keyword with a global shared variable accessed by a function

I have a multithreaded C ++ application.

Now I know that for global shared variables you should use volatile in some cases when checking the state of a variable, otherwise the compiler could assume that the value of the variable never changes (in this thread).

What if, instead of checking the status of a variable, I call a method that returns the value of the variable? For instance:

static int num = 0;

...

void foo()
{
   while(getNum() == 0)
   {
      // do something (or nothing)
   }
}

Should I make num volatile variable? or does the compiler acknowledge that since I use a method to access this num variable, it will not cache the result?

Does anyone have any ideas?

Thanks in advance,

~ Julian

edit: while - , , - ( )

+5
4

, volatile , .

, , , "" .

sleep, , , . num, setter setter foo.

, , . , , . , IR- .o .

.

, : 1. , 2. , .

1: sleep " ". , . , .

2: , sleep - . volatile . , - , too > tops, , , .

+4

, , "volatile", - , , .

.. , , .

, .., , . , , , , "" .

num && x'00000001' 
+2

, . .

Potatoswatter , , num . , ... .

, , , , , - , . "" .

corensic jinx.h, . - :

 inline void memory_barrier() { asm volatile("nop" ::: "memory"); }

, (gcc), asm asm . / .

:

memory_barrier();  while (num == 0) {     memory_barrier();     ...  }

num . , , . , :

 while (flag == 0) { memory_barrier(); }  // spin
 process data[0..N]

:

 populate data[0..N]
 memory_barrier();
 flag = 1;

PS. ( ), , . Jinx . , - , .

. Linux , " ", .

0

. , , , ++. getNum, num ( , - , ) .

, () , . - .

-1

All Articles