[vlc-devel] Reminder: volatile considered harmful

Rémi Denis-Courmont rdenis at simphalempin.com
Mon May 19 22:14:53 CEST 2008


	Hello,

I thought it was a well documented fact, but it does seem that several VLC 
developpers still believe that "volatile" is a solution to thread-safety.

Sorry. It just is NOT. volatile forbids the compiler from optimizing accesses 
to a variable. Essentially, this is such that the value may change 
asynchronously. volatile does NOT mean atomic read/write, which is pretty 
much always needed for thread-safety. And it does NOT imply a full memory 
barrier, which is also required for thread-safety (as threads cannot be 
assumed to all share the same memory cache).

Note that the gcc 4.3 documentation has no mention of volatile implying a 
memory barrier, let alone the C99 standard. gcc provides its own intrinsics 
for atomic memory accesses; much like the Win32 API Interlocked*() functions.

See also:
http://softwareblogs.intel.com/2007/11/30/volatile-almost-useless-for-multi-threaded-programming/
http://kernel.org/doc/Documentation/volatile-considered-harmful.txt

As far as I can tell, when it comes to VLC, the only valid use cases for 
volatile are:
- variables modified by signal handlers (src/vlc.c and src/misc/cpu.c),
- in front of "asm" stanzas.

Other potential valid use of volatile, which VLC currently does not have:
- interacting with setjmp()/longjmp(),
- preventing clobbered variables with thread cancellation.


And of course, there very suspicious-looking use of volatile:
- the thread subsystem initialization counter,
- i_waiting_threads from Win32 vlc_cond_t,
- the MSW video ouput, the XVMC "codec",
- the Atmo filter,
and most seriously:
- b_error, b_die and b_dead from VLC_COMMON_MEMBERS.

-- 
Rémi Denis-Courmont
http://www.remlab.net/



More information about the vlc-devel mailing list