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:

Hi,

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
(http://www.cuj.com/documents/s=7998/cujcexp1902alexandr/)

The article was completely wrong about volatile semantics.
Please, see the reply from (among others) David Butenhof
http://groups.google.com/groups?hl=en&lr=&ie=UTF-8&oe=UTF-8&selm=3A66E4A
1.54EE37AD%40compaq.com&prev=/groups%3Fq%3Dvolatile%2BButenhof%26hl%3Den
%26lr%3D%26ie%3DUTF-8%26oe%3DUTF-8%26selm%3D3A66E4A1.54EE37AD%2540compaq
.com%26rnum%3D1

> 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
setFoo(0).)

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.

Cheers,





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