LabWindows/CVI

cancel
Showing results for 
Search instead for 
Did you mean: 

what's the difference between volatile variable and thread safe variable?

It seems to me those flags changed only in main thread and read in secondary thread should be defined as volatile type variable. Those variables which are changed both in main and secondary thread should be defined as thread safe variable. Am I right? If I am correct, why I also see some volatile variables be changed in both threads, such as in main set it to be 1 and in second set it to be 0.
thanks.
 
0 Kudos
Message 1 of 4
(4,168 Views)
The volatile keyword indicates to the compiler that it should not optimize the code accessing the variable as the programmer knows that the data may change in unpredicatable ways not apparent to the compiler - like from multiple threads. On x86 systems, 32-bit integer reads and writes are atomic - meaning that 32-bit integer types are automatically thread-safe at the CPU level. But one should still notify the compiler that the variable can be changed from multiple threads to prevent optimization which would change program semantics, and hence the volatile keyword is required.
0 Kudos
Message 2 of 4
(4,151 Views)

So that means we can use volatile int data to replace thread safe int data, right?

 

0 Kudos
Message 3 of 4
(4,136 Views)
Just to clarify, delclaring a variable volatile is not a way to ensure thread safety.  In essence, it just makes your program work "as expected" -- it prevents compiler optimization from hiding value changes from your program.  While these unexpected changes can be the result of having multiple threads in your program, variable volatility is a separate issue from thread safety.

As Mohan pointed out, reading/writing a 32-bit int is inherently thread-safe, because the processor cannot be interrupted in the middle of a read/write.  You only need to use thread-safe storage when reading/writing the data can take more than one CPU operation.

Mert A.
National Instruments
0 Kudos
Message 4 of 4
(4,132 Views)