[fpc-devel] volatile variables
Michael Schnell
mschnell at lumino.de
Tue Jun 28 13:14:54 CEST 2011
A similar discussion is going on in Lazarus-develop, but this obviously
is a compiler question.
In C, there is the volatile keyword that ensures that after the code
sequence enters the next C instruction after that which modified this
variable, another thread sees the correct state of the variable.
This is ensured by not caching the value in registers and on SMP systems
additionally by low level stuff like memory barriers.
Of course this does not protect concurrent read-modify-write accesses
(same need to be protected by low level atomic instructions or MUTEX and
friend).
For variables not defined as volatile, (e.g.) pthread_mutex (and similar
stuff on Windows) can be used to protect them.
AFAIK, in Pascal all Global (Static) variables are considered to be
handled as volatile, so no problem here (other than handling all of them
them as volatiles might decrease performance slightly).
But what about variables on the heap ? If class instance variables or -
say - a liked list done with records created by "new" are accessed by
multiple threads, how can said consistency be enforced ?
Even if you use a critical section to do the protection, this does not
help if the compiler decides to cache the variable in a register while
entering or exiting the critical section.
But even without dedicated protection, a volatile variable should be
able to be be monitored from another thread. Can this be enforced in
Pascal for help variables ?
-Michael
More information about the fpc-devel
mailing list