Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

In the C programming language and Pthreads as the threading library; do variables/structures that are shared between threads need to be declared as volatile? Assuming that they might be protected by a lock or not (barriers perhaps).

Does the pthread POSIX standard have any say about this, is this compiler-dependent or neither?

Edit to add: Thanks for the great answers. But what if you're not using locks; what if you're using barriers for example? Or code that uses primitives such as compare-and-swap to directly and atomically modify a shared variable...

like image 267
fuad Avatar asked Sep 16 '08 22:09

fuad


People also ask

Do pthreads share variables?

Threads can "share" variables in the initialized data, uninitialized data, and heap segments.

When should volatile be used in C?

Volatile is used in C programming when we need to go and read the value stored by the pointer at the address pointed by the pointer. If you need to change anything in your code that is out of compiler reach you can use this volatile keyword before the variable for which you want to change the value.

Should semaphores be volatile?

No need to declare them as volatile . Save this answer. Show activity on this post. Semaphores should not be used in the place of synchronized because semaphores does not hold exclusive mutual lock even if it is initialized to one, like synchronized on some object.

Are pthreads shared memory?

Threads are concurrently running functions that operate within a single process. Each thread in a process belongs to the same address (memory) space and thus shares memory with the other threads in the process. Threads can communicate with one another by writing to and reading from addresses in the shared memory.


1 Answers

As long as you are using locks to control access to the variable, you do not need volatile on it. In fact, if you're putting volatile on any variable you're probably already wrong.

https://software.intel.com/en-us/blogs/2007/11/30/volatile-almost-useless-for-multi-threaded-programming/

like image 119
Don Neufeld Avatar answered Sep 19 '22 19:09

Don Neufeld