Re: RE : Apparent thread-safety bug in Glib 2.0 docs



Hi,

> > 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:
> 
> 
> static int foo;
> 
> int getFoo() { return foo; }
> 
> void setFoo(int aFoo) { foo = aFoo; }
> 
> Now, let's say we have a thread that's in a loop waiting for foo to
> reach zero:
> 
> while (getFoo() != 0) {
>     /* do stuff */
> }
> 
> All looks good so far right? Now let's make the getter's and setter's
> thread safe:
> 
> static int foo;
> static GStaticMutex mutex = G_STATIC_MUTEX_INIT;
> 
> int getFoo() {
>     int ret_val;
>     g_static_mutex_lock(&mutex);
>     ret_val = foo;
>     g_static_mutex_unlock(&mutex);
>     return ret_val;
> }
> 
> void setFoo(int aFoo) {
>     g_static_mutex_lock(&mutex);
>     foo = aFoo;
>     g_static_mutex_lock(&mutex);
> }

Actually in that case everything should work OK, because the compiler
does not know, whether g_static_mutex_lock (which is just another
function for gcc) could indirectly access foo (e.g. by calling setFoo),
so foo has to written to real memory before calling g_static_mutex_lock.
Thats why I wrote: 

        For global static or non-static variables this is in general not
        necessary, if they are protected by mutexes.
        
BUT: Looking at the mentioned example in the docs now I notice, that
it's the same there. As far as the compiler is concerned,
g_static_mutex_lock could directly or indirectly call
give_me_next_number, so it has to write back current_number to memory.

So actually, once a variable is protected by a mutex, it is safe to use,
even static function variables. So we simply forget about the whole
thing for the time being. 

Bye,
Sebastian
-- 
Sebastian Wilhelmi                 |            här ovanför alla molnen
mailto:seppi seppi de              |     är himmlen så förunderligt blå
http://seppi.de                    |




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