RWLock


Object Hierarchy:

Object hierarchy for RWLock

Description:

public struct RWLock

The GRWLock struct is an opaque data structure to represent a reader-writer lock.

It is similar to a Mutex in that it allows multiple threads to coordinate access to a shared resource.

The difference to a mutex is that a reader-writer lock discriminates between read-only ('reader') and full ('writer') access. While only one thread at a time is allowed write access (by holding the 'writer' lock via writer_lock), multiple threads can gain simultaneous read-only access (by holding the 'reader' lock via reader_lock).

Here is an example for an array with access functions:

  GRWLock lock;
GPtrArray *array;

gpointer
my_array_get (guint index)
{
gpointer retval = NULL;

if (!array)
return NULL;

g_rw_lock_reader_lock (&lock);
if (index < array->len)
retval = g_ptr_array_index (array, index);
g_rw_lock_reader_unlock (&lock);

return retval;
}

void
my_array_set (guint index, gpointer data)
{
g_rw_lock_writer_lock (&lock);

if (!array)
array = g_ptr_array_new ();

if (index >= array->len)
g_ptr_array_set_size (array, index+1);
g_ptr_array_index (array, index) = data;

g_rw_lock_writer_unlock (&lock);
}
This example shows an array which can be accessed by many readers (the my_array_get function) simultaneously, whereas the writers (the my_array_set function) will only be allowed one at a time and only if no readers currently access the array. This is because of the potentially dangerous resizing of the array. Using these functions is fully multi-thread safe now.

If a RWLock is allocated in static storage then it can be used without initialisation. Otherwise, you should call RWLock on it and g_rw_lock_clear when done.

A GRWLock should only be accessed with the g_rw_lock_ functions.


Namespace: GLib
Package: glib-2.0

Content:

Creation methods:

Methods: