3

Possible Duplicate:
Using C/Pthreads: do shared variables need to be volatile?

In Linux/C: Do the global variables shared between threads need to be declared volatile (assume the variable get modified in one of the threads)?

What all situations do I need to declare a variable as volatile in threads?

Community
  • 1
  • 1
Lunar Mushrooms
  • 8,358
  • 18
  • 66
  • 88

4 Answers4

4

If you are using pthreads, then no - volatile is neither necessary nor sufficient for correct synchronisation. If your accesses to the global variable are properly protected by a mutex (or another synchronisation primitive), then you can simply declare them as ordinary variables.

caf
  • 233,326
  • 40
  • 323
  • 462
0

It is sometimes preferable to declare the data as volatile (mostly in the case where it is atomic and is operated by atomic operations). But it is very important to use synchronisation mechanisms (like mutexes, rwlocks, ...) to serialize access to the global data.

The real reason to use volatile are rare: when the variable is e.g. an integer, and when you use special atomic operations on it.

You need to use synchronisation primitives because e.g. of the cache

Basile Starynkevitch
  • 223,805
  • 18
  • 296
  • 547
0

I see someone said it is not necessary when you are using pthreads. I'm not sure how pthread works to protect such case , but as I know it is important to define a global variable as "volatile" if you are in multi-thread environment, the reason is like myrkos said above , multi thread env is the case that the variable could be modified "externally" . Modern compile does more optimizing than you thought , it will make the code not read the value from memory if it THINKs the variable is not modified , however in such an env the variable could change .

But it is not enough to make global variable work well , you need use automic operations or mutex to protect it .

-1

Volatile just tells the compiler than the variable could be modified from an external thing, so it shouldn't do any optimizations on it (skipping read/write,putting into register). So you should always declare a global variable volatile if multiple threads are to use it.

slartibartfast
  • 4,348
  • 5
  • 31
  • 46