RE : Apparent thread-safety bug in Glib 2.0 docs

Christopher wrote:
> On Sat, 2003-10-25 at 14:32, Joaquin Cuenca Abela wrote:
> > Can you please elaborate a bit more how is a compiler suppossed to 
> > generate incorrect code in examples 3 & 4? They look 
> perfectly fine to 
> > me.
> Sure, no problem, this is a classic mistake C/C++ programmers 
> make in threaded environments (the problem doesn't exist in 
> languages like Java who's memory model is explicitly aware of 
> threads). Let's look at a simple getter/setter combination:


This sounds a lot like an extended misconception about volatile
and its relationship with threads.
One example is one article of A. Alexandrescu article on CUJ

The article was completely wrong about volatile semantics.
Please, see the reply from (among others) David Butenhof

> The problem comes when you are using threads. What if that 
> while loop is waiting for another thread to call setFoo(0)? 
> That other thread is working in it's own world of registers 
> and main memory. Certainly there is no way for the compiler 
> to know that when that other thread invokes
> setFoo(0) it needs to update the value in the register of the 
> thread doing the while loop.

(Let's say thread A is in the while loop, and thread B calls

In fact, the g_static_mutex_lock/unlock (if it has the same
meaning than the POSIX Threads' lock/unlock) ensure that 
the thread A will see the same memory value for foo than what
thread setted.  When thread A locks the mutex, it will see the
memory that thread B setted before it unlocked the same mutex
(or, eventually, a value written after the mutex is unlocked
by B, but that's not guaranteed).

Like Mr. Butenhof says, volatile is not necessary, nor sufficient
to guarantee proper synchronization between two threads.


[Date Prev][Date Next]   [Thread Prev][Thread Next]   [Thread Index] [Date Index] [Author Index]