Re: [gtk-list] Recursive mutexes in glib



Hi, Bertrand 

> I use glib-thread in a library I am writing. Unfortunately, glib
> does not allow recursive mutexes. As I do not have Solaris, or other
> non-linux system,
> I was wondering if this was because it was hard to implement
> (as it is very easy with posix threads)

It is not hard to implement, and something like that MIGHT (don't nail me
on that) come into glib for >=1.3, but:

1. glib does not need recursive mutexes and the thread support so far is 
   only to make glib itself reentrant.

2. most of the time you really do not need recursive mutexes.

> Is there any obvious (portable) replacement to the recursive mechanism?

Try to do without them. or

do some tricks with g_static_private. You can make a GStaticPrivate for
every GMutex and store the number of times, you have enterd the lock.

Something like (untested, written as thought)

struct 
{
  GMutex mutex;
  GStaticPrivate counter;
}
 
g_rec_mutex_new ()
{
  /* g_new etc. */
  retval->counter = G_STATIC_PRIVATE_INIT;
  return retval;
}

g_rec_mutex_lock (GRecursiveMutex* mutex)
{
  guint counter = g_static_mutex_get (mutex->counter);
  if (counter == 0)
    {
      g_mutex_lock (mutex->mutex)
    }
  counter++;
  g_static_mutex_set (mutex->counter, counter, NULL);
}

g_rec_mutex_unlock (GRecursiveMutex* mutex)
{
  guint counter = g_static_mutex_get (mutex->counter);
  if (counter == 1)
    {
      g_mutex_unlock (mutex->mutex)
    }
  counter--;
  g_static_mutex_set (mutex->counter, counter, NULL);
}

Bye,
Sebastian

PS: I know, that this solutuion is slower than the one with
pthread_self(), but it works with glib out of the box.
-- 
Sebastian Wilhelmi                   |            här ovanför alla molnen
mailto:wilhelmi@ira.uka.de           |      är himmlen så förunerligt blå
http://goethe.ira.uka.de/~wilhelmi   |



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