1 <!-- ##### SECTION Title ##### -->
4 <!-- ##### SECTION Short_Description ##### -->
6 thread abstraction; including threads, different mutexes, conditions
7 and thread private data.
9 <!-- ##### SECTION Long_Description ##### -->
12 Threads act almost like processes, but unlike processes all threads of
13 one process share the same memory. This is good, as it provides easy
14 communication between the involved threads via this shared memory, and
15 it is bad, because strange things (so called "Heisenbugs") might
16 happen if the program is not carefully designed. In particular, due to
17 the concurrent nature of threads, no assumptions on the order of
18 execution of code running in different threads can be made, unless
19 order is explicitly forced by the programmer through synchronization
24 The aim of the thread related functions in GLib is to provide a
25 portable means for writing multi-threaded software. There are
26 primitives for mutexes to protect the access to portions of memory
27 (#GMutex, #GStaticMutex, #G_LOCK_DEFINE, #GStaticRecMutex and
28 #GStaticRWLock). There are primitives for condition variables to allow
29 synchronization of threads (#GCond). There are primitives
30 for thread-private data - data that every thread has a private instance of
31 (#GPrivate, #GStaticPrivate). Last but definitely not least there are
32 primitives to portably create and manage threads (#GThread).
36 You must call g_thread_init() before executing any other GLib
37 functions in a threaded GLib program. After that, GLib is completely
38 thread safe (all global data is automatically locked), but individual
39 data structure instances are not automatically locked for performance
40 reasons. So, for example you must coordinate accesses to the same
41 #GHashTable from multiple threads. The two notable exceptions from
42 this rule are #GMainLoop and #GAsyncQueue,
43 which <emphasis>are</emphasis> threadsafe and needs no further
44 application-level locking to be accessed from multiple threads.
48 To help debugging problems in multithreaded applications, GLib supports
49 error-checking mutexes that will give you helpful error messages on
50 common problems. To use error-checking mutexes, define the symbol
51 #G_ERRORCHECK_MUTEXES when compiling the application.
54 <!-- ##### SECTION See_Also ##### -->
59 <term>#GThreadPool</term>
60 <listitem><para>Thread pools.</para></listitem>
64 <term>#GAsyncQueue</term>
65 <listitem><para>Send asynchronous messages between threads.</para></listitem>
71 <!-- ##### SECTION Stability_Level ##### -->
74 <!-- ##### MACRO G_THREADS_ENABLED ##### -->
77 This macro is defined if GLib was compiled with thread support. This
78 does not necessarily mean that there is a thread implementation
79 available, but it does mean that the infrastructure is in place and
80 that once you provide a thread implementation to g_thread_init(), GLib
81 will be multi-thread safe. If #G_THREADS_ENABLED is not defined, then
82 Glib is not, and cannot be, multi-thread safe.
87 <!-- ##### MACRO G_THREADS_IMPL_POSIX ##### -->
90 This macro is defined if POSIX style threads are used.
95 <!-- ##### MACRO G_THREADS_IMPL_NONE ##### -->
98 This macro is defined if no thread implementation is used. You can,
99 however, provide one to g_thread_init() to make GLib multi-thread safe.
104 <!-- ##### MACRO G_THREAD_ERROR ##### -->
106 The error domain of the GLib thread subsystem.
111 <!-- ##### ENUM GThreadError ##### -->
113 Possible errors of thread related functions.
116 @G_THREAD_ERROR_AGAIN: a thread couldn't be created due to resource
117 shortage. Try again later.
119 <!-- ##### STRUCT GThreadFunctions ##### -->
122 This function table is used by g_thread_init() to initialize the
123 thread system. The functions in the table are directly used by their
124 g_* prepended counterparts (described in this document). For example,
125 if you call g_mutex_new() then mutex_new() from the table provided to
126 g_thread_init() will be called.
131 Do not use this struct unless you know what you are doing.
153 @thread_set_priority:
157 <!-- ##### FUNCTION g_thread_init ##### -->
160 If you use GLib from more than one thread, you must initialize
161 the thread system by calling g_thread_init(). Most of the time you
162 will only have to call <literal>g_thread_init (NULL)</literal>.
167 Do not call g_thread_init() with a non-%NULL parameter unless you
168 really know what you are doing.
174 g_thread_init() must not be called directly or indirectly as a
175 callback from GLib. Also no mutexes may be currently locked while
176 calling g_thread_init().
181 g_thread_init() might only be called once. On the second call
182 it will abort with an error. If you want to make sure that the thread
183 system is initialized, you can do this:
189 if (!g_thread_supported (<!-- -->)) g_thread_init (NULL);
195 After that line, either the thread system is initialized or, if no
196 thread system is available in GLib (i.e. either #G_THREADS_ENABLED is
197 not defined or #G_THREADS_IMPL_NONE is defined), the program will
202 If no thread system is available and @vtable is %NULL or if not all
203 elements of @vtable are non-%NULL, then g_thread_init() will abort.
208 To use g_thread_init() in your program, you have to link with the
209 libraries that the command <command>pkg-config --libs gthread-2.0</command>
210 outputs. This is not the case for all the other thread related functions of
211 GLib. Those can be used without having to link with the thread libraries.
215 @vtable: a function table of type #GThreadFunctions, that provides the
216 entry points to the thread system to be used.
219 <!-- ##### FUNCTION g_thread_supported ##### -->
221 This function returns %TRUE if the thread system is initialized, and
227 This function is actually a macro. Apart from taking the address of it
228 you can however use it as if it was a function.
232 @Returns: %TRUE, if the thread system is initialized.
235 <!-- ##### USER_FUNCTION GThreadFunc ##### -->
237 Specifies the type of the @func functions passed to
238 g_thread_create() or g_thread_create_full().
241 @data: data passed to the thread.
242 @Returns: the return value of the thread, which will be returned by
246 <!-- ##### ENUM GThreadPriority ##### -->
248 Specifies the priority of a thread.
253 It is not guaranteed that threads with different priorities really
254 behave accordingly. On some systems (e.g. Linux) there are no thread
255 priorities. On other systems (e.g. Solaris) there doesn't seem to be
256 different scheduling for different priorities. All in all try to avoid
257 being dependent on priorities.
261 @G_THREAD_PRIORITY_LOW: a priority lower than normal
262 @G_THREAD_PRIORITY_NORMAL: the default priority
263 @G_THREAD_PRIORITY_HIGH: a priority higher than normal
264 @G_THREAD_PRIORITY_URGENT: the highest priority
266 <!-- ##### STRUCT GThread ##### -->
268 The #GThread struct represents a running thread. It has three public
269 read-only members, but the underlying struct is bigger, so you must
270 not copy this struct.
275 Resources for a joinable thread are not fully released until
276 g_thread_join() is called for that thread.
281 <!-- ##### FUNCTION g_thread_create ##### -->
283 This function creates a new thread with the default priority.
287 If @joinable is %TRUE, you can wait for this threads termination
288 calling g_thread_join(). Otherwise the thread will just disappear when
293 The new thread executes the function @func with the argument
294 @data. If the thread was created successfully, it is returned.
298 @error can be %NULL to ignore errors, or non-%NULL to report errors. The
299 error is set, if and only if the function returns %NULL.
302 @func: a function to execute in the new thread.
303 @data: an argument to supply to the new thread.
304 @joinable: should this thread be joinable?
305 @error: return location for error.
306 @Returns: the new #GThread on success.
309 <!-- ##### FUNCTION g_thread_create_full ##### -->
311 This function creates a new thread with the priority @priority. If the
312 underlying thread implementation supports it, the thread gets a stack
313 size of @stack_size or the default value for the current platform, if
318 If @joinable is %TRUE, you can wait for this threads termination
319 calling g_thread_join(). Otherwise the thread will just disappear when
320 it terminates. If @bound is %TRUE, this thread will be scheduled in
321 the system scope, otherwise the implementation is free to do
322 scheduling in the process scope. The first variant is more expensive
323 resource-wise, but generally faster. On some systems (e.g. Linux) all
328 The new thread executes the function @func with the argument
329 @data. If the thread was created successfully, it is returned.
333 @error can be %NULL to ignore errors, or non-%NULL to report errors. The
334 error is set, if and only if the function returns %NULL.
339 It is not guaranteed that threads with different priorities really
340 behave accordingly. On some systems (e.g. Linux) there are no thread
341 priorities. On other systems (e.g. Solaris) there doesn't seem to be
342 different scheduling for different priorities. All in all try to avoid
343 being dependent on priorities. Use %G_THREAD_PRIORITY_NORMAL here as a
350 Only use g_thread_create_full() if you really can't use
351 g_thread_create() instead. g_thread_create() does not take
352 @stack_size, @bound, and @priority as arguments, as they should only
353 be used in cases in which it is unavoidable.
357 @func: a function to execute in the new thread.
358 @data: an argument to supply to the new thread.
359 @stack_size: a stack size for the new thread.
360 @joinable: should this thread be joinable?
361 @bound: should this thread be bound to a system thread?
362 @priority: a priority for the thread.
363 @error: return location for error.
364 @Returns: the new #GThread on success.
367 <!-- ##### FUNCTION g_thread_self ##### -->
369 This functions returns the #GThread corresponding to the calling thread.
372 @Returns: the current thread.
375 <!-- ##### FUNCTION g_thread_join ##### -->
377 Waits until @thread finishes, i.e. the function @func, as given
378 to g_thread_create(), returns or g_thread_exit() is called by
379 @thread. All resources of @thread including the #GThread struct are
380 released. @thread must have been created with @joinable=%TRUE in
381 g_thread_create(). The value returned by @func or given to
382 g_thread_exit() by @thread is returned by this function.
385 @thread: a #GThread to be waited for.
386 @Returns: the return value of the thread.
389 <!-- ##### FUNCTION g_thread_set_priority ##### -->
391 Changes the priority of @thread to @priority.
396 It is not guaranteed that threads with different priorities really
397 behave accordingly. On some systems (e.g. Linux) there are no thread
398 priorities. On other systems (e.g. Solaris) there doesn't seem to be
399 different scheduling for different priorities. All in all try to avoid
400 being dependent on priorities.
405 @priority: a new priority for @thread.
408 <!-- ##### FUNCTION g_thread_yield ##### -->
410 Gives way to other threads waiting to be scheduled.
414 This function is often used as a method to make busy wait less
415 evil. But in most cases you will encounter, there are better methods
416 to do that. So in general you shouldn't use this function.
421 <!-- ##### FUNCTION g_thread_exit ##### -->
423 Exits the current thread. If another thread is waiting for that thread
424 using g_thread_join() and the current thread is joinable, the waiting
425 thread will be woken up and get @retval as the return value of
426 g_thread_join(). If the current thread is not joinable, @retval is
433 g_thread_exit (retval);
439 is equivalent to calling
451 in the function @func, as given to g_thread_create().
456 Never call g_thread_exit() from within a thread of a #GThreadPool, as
457 that will mess up the bookkeeping and lead to funny and unwanted results.
461 @retval: the return value of this thread.
464 <!-- ##### FUNCTION g_thread_foreach ##### -->
473 <!-- ##### STRUCT GMutex ##### -->
476 The #GMutex struct is an opaque data structure to represent a mutex
477 (mutual exclusion). It can be used to protect data against shared
478 access. Take for example the following function:
481 <title>A function which will not work in a threaded environment</title>
483 int give_me_next_number (<!-- -->)
485 static int current_number = 0;
487 /* now do a very complicated calculation to calculate the new number,
488 this might for example be a random number generator */
489 current_number = calc_next_number (current_number);
490 return current_number;
497 It is easy to see that this won't work in a multi-threaded
498 application. There current_number must be protected against shared
499 access. A first naive implementation would be:
504 <title>The wrong way to write a thread-safe function</title>
506 int give_me_next_number (<!-- -->)
508 static int current_number = 0;
510 static GMutex * mutex = NULL;
513 mutex = g_mutex_new (<!-- -->);
514 g_mutex_lock (mutex);
515 ret_val = current_number = calc_next_number (current_number);
516 g_mutex_unlock (mutex);
524 This looks like it would work, but there is a race condition while
525 constructing the mutex and this code cannot work reliable. Please do
526 not use such constructs in your own programs! One working solution is:
531 <title>A correct thread-safe function</title>
533 static GMutex *give_me_next_number_mutex = NULL;
535 /* this function must be called before any call to give_me_next_number (<!-- -->)
536 it must be called exactly once. */
537 void init_give_me_next_number (<!-- -->)
539 g_assert (give_me_next_number_mutex == NULL);
540 give_me_next_number_mutex = g_mutex_new (<!-- -->);
543 int give_me_next_number (<!-- -->)
545 static int current_number = 0;
548 g_mutex_lock (give_me_next_number_mutex);
549 ret_val = current_number = calc_next_number (current_number);
550 g_mutex_unlock (give_me_next_number_mutex);
558 #GStaticMutex provides a simpler and safer way of doing this.
562 If you want to use a mutex, and your code should also work without
563 calling g_thread_init() first, then you can not use a #GMutex, as
564 g_mutex_new() requires that the thread system be initialized. Use a
565 #GStaticMutex instead.
569 A #GMutex should only be accessed via the following functions.
574 All of the <function>g_mutex_*</function> functions are actually macros.
575 Apart from taking their addresses, you can however use them as if they
581 <!-- ##### FUNCTION g_mutex_new ##### -->
584 Creates a new #GMutex.
589 This function will abort if g_thread_init() has not been called yet.
593 @Returns: a new #GMutex.
596 <!-- ##### FUNCTION g_mutex_lock ##### -->
599 Locks @mutex. If @mutex is already locked by another thread, the
600 current thread will block until @mutex is unlocked by the other
605 This function can be used even if g_thread_init() has not yet been
606 called, and, in that case, will do nothing.
611 #GMutex is neither guaranteed to be recursive nor to be non-recursive,
612 i.e. a thread could deadlock while calling g_mutex_lock(), if it
613 already has locked @mutex. Use #GStaticRecMutex, if you need recursive
621 <!-- ##### FUNCTION g_mutex_trylock ##### -->
624 Tries to lock @mutex. If @mutex is already locked by another
625 thread, it immediately returns %FALSE. Otherwise it locks @mutex
630 This function can be used even if g_thread_init() has not yet been
631 called, and, in that case, will immediately return %TRUE.
636 #GMutex is neither guaranteed to be recursive nor to be non-recursive,
637 i.e. the return value of g_mutex_trylock() could be both %FALSE or
638 %TRUE, if the current thread already has locked @mutex. Use
639 #GStaticRecMutex, if you need recursive mutexes.
644 @Returns: %TRUE, if @mutex could be locked.
647 <!-- ##### FUNCTION g_mutex_unlock ##### -->
650 Unlocks @mutex. If another thread is blocked in a g_mutex_lock() call
651 for @mutex, it will be woken and can lock @mutex itself.
655 This function can be used even if g_thread_init() has not yet been
656 called, and, in that case, will do nothing.
662 <!-- ##### FUNCTION g_mutex_free ##### -->
671 <!-- ##### STRUCT GStaticMutex ##### -->
674 A #GStaticMutex works like a #GMutex, but it has one significant
675 advantage. It doesn't need to be created at run-time like a #GMutex,
676 but can be defined at compile-time. Here is a shorter, easier and
677 safer version of our <function>give_me_next_number()</function> example:
682 <title>Using <structname>GStaticMutex</structname> to simplify thread-safe programming</title>
684 int give_me_next_number (<!-- -->)
686 static int current_number = 0;
688 static GStaticMutex mutex = G_STATIC_MUTEX_INIT;
690 g_static_mutex_lock (&mutex);
691 ret_val = current_number = calc_next_number (current_number);
692 g_static_mutex_unlock (&mutex);
700 Sometimes you would like to dynamically create a mutex. If you don't
701 want to require prior calling to g_thread_init(), because your code
702 should also be usable in non-threaded programs, you are not able to
703 use g_mutex_new() and thus #GMutex, as that requires a prior call to
704 g_thread_init(). In theses cases you can also use a #GStaticMutex. It
705 must be initialized with g_static_mutex_init() before using it and
706 freed with with g_static_mutex_free() when not needed anymore to free
707 up any allocated resources.
711 Even though #GStaticMutex is not opaque, it should only be used with
712 the following functions, as it is defined differently on different
717 All of the <function>g_static_mutex_*</function> functions apart from
718 <function>g_static_mutex_get_mutex</function> can also be used even if
719 g_thread_init() has not yet been called. Then they do nothing, apart
720 from <function>g_static_mutex_trylock</function>, which does nothing
726 All of the <function>g_static_mutex_*</function> functions are actually
727 macros. Apart from taking their addresses, you can however use them
728 as if they were functions.
733 <!-- ##### MACRO G_STATIC_MUTEX_INIT ##### -->
736 A #GStaticMutex must be initialized with this macro, before it can be
737 used. This macro can used be to initialize a variable, but it cannot
738 be assigned to a variable. In that case you have to use
739 g_static_mutex_init().
745 GStaticMutex my_mutex = G_STATIC_MUTEX_INIT;
752 <!-- ##### FUNCTION g_static_mutex_init ##### -->
754 Initializes @mutex. Alternatively you can initialize it with
755 #G_STATIC_MUTEX_INIT.
758 @mutex: a #GStaticMutex to be initialized.
761 <!-- ##### FUNCTION g_static_mutex_lock ##### -->
763 Works like g_mutex_lock(), but for a #GStaticMutex.
766 @mutex: a #GStaticMutex.
769 <!-- ##### FUNCTION g_static_mutex_trylock ##### -->
772 Works like g_mutex_trylock(), but for a #GStaticMutex.
775 @mutex: a #GStaticMutex.
776 @Returns: %TRUE, if the #GStaticMutex could be locked.
779 <!-- ##### FUNCTION g_static_mutex_unlock ##### -->
782 Works like g_mutex_unlock(), but for a #GStaticMutex.
785 @mutex: a #GStaticMutex.
788 <!-- ##### FUNCTION g_static_mutex_get_mutex ##### -->
791 For some operations (like g_cond_wait()) you must have a #GMutex
792 instead of a #GStaticMutex. This function will return the
793 corresponding #GMutex for @mutex.
796 @mutex: a #GStaticMutex.
797 @Returns: the #GMutex corresponding to @mutex.
800 <!-- ##### FUNCTION g_static_mutex_free ##### -->
802 Releases all resources allocated to @mutex.
806 You don't have to call this functions for a #GStaticMutex with an
807 unbounded lifetime, i.e. objects declared 'static', but if you have a
808 #GStaticMutex as a member of a structure and the structure is freed,
809 you should also free the #GStaticMutex.
812 @mutex: a #GStaticMutex to be freed.
815 <!-- ##### MACRO G_LOCK_DEFINE ##### -->
818 The %G_LOCK_* macros provide a convenient interface to #GStaticMutex
819 with the advantage that they will expand to nothing in programs
820 compiled against a thread-disabled GLib, saving code and memory
821 there. #G_LOCK_DEFINE defines a lock. It can appear anywhere variable
822 definitions may appear in programs, i.e. in the first block of a
823 function or outside of functions. The @name parameter will be mangled
824 to get the name of the #GStaticMutex. This means that you can use
825 names of existing variables as the parameter - e.g. the name of the
826 variable you intent to protect with the lock. Look at our
827 <function>give_me_next_number()</function> example using the %G_LOCK_* macros:
832 <title>Using the %G_LOCK_* convenience macros</title>
834 G_LOCK_DEFINE (current_number);
836 int give_me_next_number (<!-- -->)
838 static int current_number = 0;
841 G_LOCK (current_number);
842 ret_val = current_number = calc_next_number (current_number);
843 G_UNLOCK (current_number);
850 @name: the name of the lock.
853 <!-- ##### MACRO G_LOCK_DEFINE_STATIC ##### -->
856 This works like #G_LOCK_DEFINE, but it creates a static object.
859 @name: the name of the lock.
862 <!-- ##### MACRO G_LOCK_EXTERN ##### -->
865 This declares a lock, that is defined with #G_LOCK_DEFINE in another module.
868 @name: the name of the lock.
871 <!-- ##### MACRO G_LOCK ##### -->
874 Works like g_mutex_lock(), but for a lock defined with #G_LOCK_DEFINE.
877 @name: the name of the lock.
880 <!-- ##### MACRO G_TRYLOCK ##### -->
883 Works like g_mutex_trylock(), but for a lock defined with #G_LOCK_DEFINE.
886 @name: the name of the lock.
887 @Returns: %TRUE, if the lock could be locked.
890 <!-- ##### MACRO G_UNLOCK ##### -->
893 Works like g_mutex_unlock(), but for a lock defined with #G_LOCK_DEFINE.
896 @name: the name of the lock.
899 <!-- ##### STRUCT GStaticRecMutex ##### -->
901 A #GStaticRecMutex works like a #GStaticMutex, but it can be locked
902 multiple times by one thread. If you enter it n times, you have to
903 unlock it n times again to let other threads lock it. An exception is
904 the function g_static_rec_mutex_unlock_full(): that allows you to
905 unlock a #GStaticRecMutex completely returning the depth, (i.e. the
906 number of times this mutex was locked). The depth can later be used to
907 restore the state of the #GStaticRecMutex by calling
908 g_static_rec_mutex_lock_full().
912 Even though #GStaticRecMutex is not opaque, it should only be used with
913 the following functions.
917 All of the <function>g_static_rec_mutex_*</function> functions can be
918 used even if g_thread_init() has not been called. Then they do
919 nothing, apart from <function>g_static_rec_mutex_trylock</function>,
920 which does nothing but returning %TRUE.
924 <!-- ##### MACRO G_STATIC_REC_MUTEX_INIT ##### -->
926 A #GStaticRecMutex must be initialized with this macro before it can
927 be used. This macro can used be to initialize a variable, but it
928 cannot be assigned to a variable. In that case you have to use
929 g_static_rec_mutex_init().
935 GStaticRecMutex my_mutex = G_STATIC_REC_MUTEX_INIT;
942 <!-- ##### FUNCTION g_static_rec_mutex_init ##### -->
944 A #GStaticRecMutex must be initialized with this function before it
945 can be used. Alternatively you can initialize it with
946 #G_STATIC_REC_MUTEX_INIT.
949 @mutex: a #GStaticRecMutex to be initialized.
952 <!-- ##### FUNCTION g_static_rec_mutex_lock ##### -->
954 Locks @mutex. If @mutex is already locked by another thread, the
955 current thread will block until @mutex is unlocked by the other
956 thread. If @mutex is already locked by the calling thread, this
957 functions increases the depth of @mutex and returns immediately.
960 @mutex: a #GStaticRecMutex to lock.
963 <!-- ##### FUNCTION g_static_rec_mutex_trylock ##### -->
965 Tries to lock @mutex. If @mutex is already locked by another thread,
966 it immediately returns %FALSE. Otherwise it locks @mutex and returns
967 %TRUE. If @mutex is already locked by the calling thread, this
968 functions increases the depth of @mutex and immediately returns %TRUE.
971 @mutex: a #GStaticRecMutex to lock.
972 @Returns: %TRUE, if @mutex could be locked.
975 <!-- ##### FUNCTION g_static_rec_mutex_unlock ##### -->
977 Unlocks @mutex. Another thread will be allowed to lock @mutex only
978 when it has been unlocked as many times as it had been locked
979 before. If @mutex is completely unlocked and another thread is blocked
980 in a g_static_rec_mutex_lock() call for @mutex, it will be woken and
981 can lock @mutex itself.
984 @mutex: a #GStaticRecMutex to unlock.
987 <!-- ##### FUNCTION g_static_rec_mutex_lock_full ##### -->
989 Works like calling g_static_rec_mutex_lock() for @mutex @depth times.
992 @mutex: a #GStaticRecMutex to lock.
993 @depth: number of times this mutex has to be unlocked to be completely unlocked.
996 <!-- ##### FUNCTION g_static_rec_mutex_unlock_full ##### -->
998 Completely unlocks @mutex. If another thread is blocked in a
999 g_static_rec_mutex_lock() call for @mutex, it will be woken and can
1000 lock @mutex itself. This function returns the number of times that
1001 @mutex has been locked by the current thread. To restore the state
1002 before the call to g_static_rec_mutex_unlock_full() you can call
1003 g_static_rec_mutex_lock_full() with the depth returned by this
1007 @mutex: a #GStaticRecMutex to completely unlock.
1008 @Returns: number of times @mutex has been locked by the current thread.
1011 <!-- ##### FUNCTION g_static_rec_mutex_free ##### -->
1013 Releases all resources allocated to a #GStaticRecMutex.
1017 You don't have to call this functions for a #GStaticRecMutex with an
1018 unbounded lifetime, i.e. objects declared 'static', but if you have a
1019 #GStaticRecMutex as a member of a structure and the structure is
1020 freed, you should also free the #GStaticRecMutex.
1023 @mutex: a #GStaticRecMutex to be freed.
1026 <!-- ##### STRUCT GStaticRWLock ##### -->
1028 The #GStaticRWLock struct represents a read-write lock. A read-write
1029 lock can be used for protecting data that some portions of code only
1030 read from, while others also write. In such situations it is
1031 desirable that several readers can read at once, whereas of course
1032 only one writer may write at a time. Take a look at the following
1036 <title>An array with access functions</title>
1038 GStaticRWLock rwlock = G_STATIC_RW_LOCK_INIT;
1042 gpointer my_array_get (guint index)
1044 gpointer retval = NULL;
1049 g_static_rw_lock_reader_lock (&rwlock);
1051 if (index < array->len)
1052 retval = g_ptr_array_index (array, index);
1054 g_static_rw_lock_reader_unlock (&rwlock);
1059 void my_array_set (guint index, gpointer data)
1061 g_static_rw_lock_writer_lock (&rwlock);
1064 array = g_ptr_array_new (<!-- -->);
1066 if (index >= array->len)
1067 g_ptr_array_set_size (array, index+1);
1069 g_ptr_array_index (array, index) = data;
1071 g_static_rw_lock_writer_unlock (&rwlock);
1078 This example shows an array which can be accessed by many readers
1079 (the <function>my_array_get()</function> function) simultaneously,
1080 whereas the writers (the <function>my_array_set()</function> function)
1081 will only be allowed once at a time and only if no readers currently access
1082 the array. This is because of the potentially dangerous resizing of the
1083 array. Using these functions is fully multi-thread safe now.
1087 Most of the time, writers should have precedence over readers. That
1088 means, for this implementation, that as soon as a writer wants to lock
1089 the data, no other reader is allowed to lock the data, whereas, of
1090 course, the readers that already have locked the data are allowed to
1091 finish their operation. As soon as the last reader unlocks the data,
1092 the writer will lock it.
1096 Even though #GStaticRWLock is not opaque, it should only be used with
1097 the following functions.
1101 All of the <function>g_static_rw_lock_*</function> functions can be
1102 used even if g_thread_init() has not been called. Then they do
1103 nothing, apart from <function>g_static_rw_lock_*_trylock</function>,
1104 which does nothing but returning %TRUE.
1109 A read-write lock has a higher overhead than a mutex. For example, both
1110 g_static_rw_lock_reader_lock() and g_static_rw_lock_reader_unlock()
1111 have to lock and unlock a #GStaticMutex, so it takes at least twice the
1112 time to lock and unlock a #GStaticRWLock that it does to lock and unlock a
1113 #GStaticMutex. So only data structures that are accessed by multiple
1114 readers, and which keep the lock for a considerable time justify a
1115 #GStaticRWLock. The above example most probably would fare better with
1121 <!-- ##### MACRO G_STATIC_RW_LOCK_INIT ##### -->
1123 A #GStaticRWLock must be initialized with this macro before it can
1124 be used. This macro can used be to initialize a variable, but it
1125 cannot be assigned to a variable. In that case you have to use
1126 g_static_rw_lock_init().
1132 GStaticRWLock my_lock = G_STATIC_RW_LOCK_INIT;
1139 <!-- ##### FUNCTION g_static_rw_lock_init ##### -->
1141 A #GStaticRWLock must be initialized with this function before it can
1142 be used. Alternatively you can initialize it with
1143 #G_STATIC_RW_LOCK_INIT.
1146 @lock: a #GStaticRWLock to be initialized.
1149 <!-- ##### FUNCTION g_static_rw_lock_reader_lock ##### -->
1151 Locks @lock for reading. There may be unlimited concurrent locks for
1152 reading of a #GStaticRWLock at the same time. If @lock is already
1153 locked for writing by another thread or if another thread is already
1154 waiting to lock @lock for writing, this function will block until
1155 @lock is unlocked by the other writing thread and no other writing
1156 threads want to lock @lock. This lock has to be unlocked by
1157 g_static_rw_lock_reader_unlock().
1161 #GStaticRWLock is not recursive. It might seem to be possible to
1162 recursively lock for reading, but that can result in a deadlock, due
1163 to writer preference.
1166 @lock: a #GStaticRWLock to lock for reading.
1169 <!-- ##### FUNCTION g_static_rw_lock_reader_trylock ##### -->
1171 Tries to lock @lock for reading. If @lock is already locked for
1172 writing by another thread or if another thread is already waiting to
1173 lock @lock for writing, immediately returns %FALSE. Otherwise locks
1174 @lock for reading and returns %TRUE. This lock has to be unlocked by
1175 g_static_rw_lock_reader_unlock().
1178 @lock: a #GStaticRWLock to lock for reading.
1179 @Returns: %TRUE, if @lock could be locked for reading.
1182 <!-- ##### FUNCTION g_static_rw_lock_reader_unlock ##### -->
1184 Unlocks @lock. If a thread waits to lock @lock for writing and all
1185 locks for reading have been unlocked, the waiting thread is woken up
1186 and can lock @lock for writing.
1189 @lock: a #GStaticRWLock to unlock after reading.
1192 <!-- ##### FUNCTION g_static_rw_lock_writer_lock ##### -->
1194 Locks @lock for writing. If @lock is already locked for writing or
1195 reading by other threads, this function will block until @lock is
1196 completely unlocked and then lock @lock for writing. While this
1197 functions waits to lock @lock, no other thread can lock @lock for
1198 reading. When @lock is locked for writing, no other thread can lock
1199 @lock (neither for reading nor writing). This lock has to be unlocked
1200 by g_static_rw_lock_writer_unlock().
1203 @lock: a #GStaticRWLock to lock for writing.
1206 <!-- ##### FUNCTION g_static_rw_lock_writer_trylock ##### -->
1208 Tries to lock @lock for writing. If @lock is already locked (for
1209 either reading or writing) by another thread, it immediately returns
1210 %FALSE. Otherwise it locks @lock for writing and returns %TRUE. This
1211 lock has to be unlocked by g_static_rw_lock_writer_unlock().
1214 @lock: a #GStaticRWLock to lock for writing.
1215 @Returns: %TRUE, if @lock could be locked for writing.
1218 <!-- ##### FUNCTION g_static_rw_lock_writer_unlock ##### -->
1220 Unlocks @lock. If a thread is waiting to lock @lock for writing and
1221 all locks for reading have been unlocked, the waiting thread is woken
1222 up and can lock @lock for writing. If no thread is waiting to lock
1223 @lock for writing, and some thread or threads are waiting to lock @lock
1224 for reading, the waiting threads are woken up and can lock @lock for
1228 @lock: a #GStaticRWLock to unlock after writing.
1231 <!-- ##### FUNCTION g_static_rw_lock_free ##### -->
1233 Releases all resources allocated to @lock.
1237 You don't have to call this functions for a #GStaticRWLock with an
1238 unbounded lifetime, i.e. objects declared 'static', but if you have a
1239 #GStaticRWLock as a member of a structure, and the structure is freed,
1240 you should also free the #GStaticRWLock.
1243 @lock: a #GStaticRWLock to be freed.
1246 <!-- ##### STRUCT GCond ##### -->
1249 The #GCond struct is an opaque data structure that represents a
1250 condition. Threads can block on a #GCond if they find a certain
1251 condition to be false. If other threads change the state of this
1252 condition they signal the #GCond, and that causes the waiting threads
1258 <title>Using GCond to block a thread until a condition is satisfied</title>
1260 GCond* data_cond = NULL; /* Must be initialized somewhere */
1261 GMutex* data_mutex = NULL; /* Must be initialized somewhere */
1262 gpointer current_data = NULL;
1264 void push_data (gpointer data)
1266 g_mutex_lock (data_mutex);
1267 current_data = data;
1268 g_cond_signal (data_cond);
1269 g_mutex_unlock (data_mutex);
1272 gpointer pop_data (<!-- -->)
1276 g_mutex_lock (data_mutex);
1277 while (!current_data)
1278 g_cond_wait (data_cond, data_mutex);
1279 data = current_data;
1280 current_data = NULL;
1281 g_mutex_unlock (data_mutex);
1289 Whenever a thread calls <function>pop_data()</function> now, it will
1290 wait until current_data is non-%NULL, i.e. until some other thread
1291 has called <function>push_data()</function>.
1296 It is important to use the g_cond_wait() and g_cond_timed_wait()
1297 functions only inside a loop which checks for the condition to be
1298 true. It is not guaranteed that the waiting thread will find the
1299 condition fulfilled after it wakes up, even if the signaling thread
1300 left the condition in that state: another thread may have altered the
1301 condition before the waiting thread got the chance to be woken up,
1302 even if the condition itself is protected by a #GMutex, like above.
1307 A #GCond should only be accessed via the following functions.
1312 All of the <function>g_cond_*</function> functions are actually macros.
1313 Apart from taking their addresses, you can however use them as if they
1319 <!-- ##### FUNCTION g_cond_new ##### -->
1322 Creates a new #GCond. This function will abort, if g_thread_init()
1323 has not been called yet.
1326 @Returns: a new #GCond.
1329 <!-- ##### FUNCTION g_cond_signal ##### -->
1331 If threads are waiting for @cond, exactly one of them is woken up. It
1332 is good practice to hold the same lock as the waiting thread while
1333 calling this function, though not required.
1337 This function can be used even if g_thread_init() has not yet been called,
1338 and, in that case, will do nothing.
1344 <!-- ##### FUNCTION g_cond_broadcast ##### -->
1347 If threads are waiting for @cond, all of them are woken up. It is good
1348 practice to lock the same mutex as the waiting threads, while calling
1349 this function, though not required.
1353 This function can be used even if g_thread_init() has not yet been called,
1354 and, in that case, will do nothing.
1360 <!-- ##### FUNCTION g_cond_wait ##### -->
1363 Waits until this thread is woken up on @cond. The @mutex is unlocked
1364 before falling asleep and locked again before resuming.
1368 This function can be used even if g_thread_init() has not yet been
1369 called, and, in that case, will immediately return.
1373 @mutex: a #GMutex, that is currently locked.
1376 <!-- ##### FUNCTION g_cond_timed_wait ##### -->
1379 Waits until this thread is woken up on @cond, but not longer than
1380 until the time specified by @abs_time. The @mutex is
1381 unlocked before falling asleep and locked again before resuming.
1385 If @abs_time is %NULL, g_cond_timed_wait() acts like g_cond_wait().
1389 This function can be used even if g_thread_init() has not yet been
1390 called, and, in that case, will immediately return %TRUE.
1394 To easily calculate @abs_time a combination of g_get_current_time()
1395 and g_time_val_add() can be used.
1399 @mutex: a #GMutex that is currently locked.
1400 @abs_time: a #GTimeVal, determining the final time.
1401 @Returns: %TRUE if @cond was signalled, or %FALSE on timeout.
1404 <!-- ##### FUNCTION g_cond_free ##### -->
1407 Destroys the #GCond.
1413 <!-- ##### STRUCT GPrivate ##### -->
1415 The #GPrivate struct is an opaque data structure to represent a thread
1416 private data key. Threads can thereby obtain and set a pointer which
1417 is private to the current thread.
1418 Take our <function>give_me_next_number()</function> example from above.
1419 Suppose we don't want <literal>current_number</literal> to be shared
1420 between the threads, but instead to be private to each thread. This can be
1424 <title>Using GPrivate for per-thread data</title>
1426 GPrivate* current_number_key = NULL; /* Must be initialized somewhere */
1427 /* with g_private_new (g_free); */
1429 int give_me_next_number (<!-- -->)
1431 int *current_number = g_private_get (current_number_key);
1433 if (!current_number)
1435 current_number = g_new (int, 1);
1436 *current_number = 0;
1437 g_private_set (current_number_key, current_number);
1439 *current_number = calc_next_number (*current_number);
1440 return *current_number;
1447 Here the pointer belonging to the key <literal>current_number_key</literal>
1448 is read. If it is %NULL, it has not been set yet. Then get memory for an
1449 integer value, assign this memory to the pointer and write the pointer
1450 back. Now we have an integer value that is private to the current thread.
1454 The #GPrivate struct should only be accessed via the following functions.
1459 All of the <function>g_private_*</function> functions are actually macros.
1460 Apart from taking their addresses, you can however use them as if they were
1466 <!-- ##### FUNCTION g_private_new ##### -->
1469 Creates a new #GPrivate. If @destructor is non-%NULL, it is a pointer
1470 to a destructor function. Whenever a thread ends and the corresponding
1471 pointer keyed to this instance of #GPrivate is non-%NULL, the
1472 destructor is called with this pointer as the argument.
1477 @destructor is used quite differently from @notify in
1478 g_static_private_set().
1484 A #GPrivate can not be freed. Reuse it instead, if you can, to avoid
1485 shortage, or use #GStaticPrivate.
1491 This function will abort if g_thread_init() has not been called yet.
1495 @destructor: a function to destroy the data keyed to #GPrivate when a
1497 @Returns: a new #GPrivate.
1500 <!-- ##### FUNCTION g_private_get ##### -->
1503 Returns the pointer keyed to @private_key for the current thread.
1504 If g_private_set() hasn't been called for the
1505 current @private_key and thread yet, this pointer will be %NULL.
1509 This function can be used even if g_thread_init() has not yet been
1510 called, and, in that case, will return the value of @private_key casted to #gpointer.
1513 @private_key: a #GPrivate.
1514 @Returns: the corresponding pointer.
1517 <!-- ##### FUNCTION g_private_set ##### -->
1520 Sets the pointer keyed to @private_key for the current thread.
1524 This function can be used even if g_thread_init() has not yet been
1525 called, and, in that case, will set @private_key to @data casted to #GPrivate*.
1528 @private_key: a #GPrivate.
1529 @data: the new pointer.
1532 <!-- ##### STRUCT GStaticPrivate ##### -->
1535 A #GStaticPrivate works almost like a #GPrivate, but it has one
1536 significant advantage. It doesn't need to be created at run-time like
1537 a #GPrivate, but can be defined at compile-time. This is similar to
1538 the difference between #GMutex and #GStaticMutex. Now look at our
1539 <function>give_me_next_number()</function> example with #GStaticPrivate:
1544 <title>Using GStaticPrivate for per-thread data</title>
1546 int give_me_next_number (<!-- -->)
1548 static GStaticPrivate current_number_key = G_STATIC_PRIVATE_INIT;
1549 int *current_number = g_static_private_get (&current_number_key);
1551 if (!current_number)
1553 current_number = g_new (int,1);
1554 *current_number = 0;
1555 g_static_private_set (&current_number_key, current_number, g_free);
1557 *current_number = calc_next_number (*current_number);
1558 return *current_number;
1565 <!-- ##### MACRO G_STATIC_PRIVATE_INIT ##### -->
1567 Every #GStaticPrivate must be initialized with this macro, before it can
1574 GStaticPrivate my_private = G_STATIC_PRIVATE_INIT;
1581 <!-- ##### FUNCTION g_static_private_init ##### -->
1583 Initializes @private_key. Alternatively you can initialize it with
1584 #G_STATIC_PRIVATE_INIT.
1587 @private_key: a #GStaticPrivate to be initialized.
1590 <!-- ##### FUNCTION g_static_private_get ##### -->
1592 Works like g_private_get() only for a #GStaticPrivate.
1596 This function works even if g_thread_init() has not yet been called.
1599 @private_key: a #GStaticPrivate.
1600 @Returns: the corresponding pointer.
1603 <!-- ##### FUNCTION g_static_private_set ##### -->
1605 Sets the pointer keyed to @private_key for the current thread and the
1606 function @notify to be called with that pointer (%NULL or non-%NULL),
1607 whenever the pointer is set again or whenever the current thread ends.
1611 This function works even if g_thread_init() has not yet been
1612 called. If g_thread_init() is called later, the @data keyed to
1613 @private_key will be inherited only by the main thread, i.e. the one that
1614 called g_thread_init().
1619 @notify is used quite differently from @destructor in
1624 @private_key: a #GStaticPrivate.
1625 @data: the new pointer.
1626 @notify: a function to be called with the pointer whenever the
1627 current thread ends or sets this pointer again.
1630 <!-- ##### FUNCTION g_static_private_free ##### -->
1632 Releases all resources allocated to @private_key.
1636 You don't have to call this functions for a #GStaticPrivate with an
1637 unbounded lifetime, i.e. objects declared 'static', but if you have a
1638 #GStaticPrivate as a member of a structure and the structure is freed,
1639 you should also free the #GStaticPrivate.
1642 @private_key: a #GStaticPrivate to be freed.
1645 <!-- ##### STRUCT GOnce ##### -->
1647 A <structname>GOnce</structname> struct controls a one-time initialization
1648 function. Any one-time initialization function must have its own unique
1649 <structname>GOnce</structname> struct.
1652 @status: the status of the #GOnce
1653 @retval: the value returned by the call to the function, if @status
1654 is %G_ONCE_STATUS_READY
1657 <!-- ##### ENUM GOnceStatus ##### -->
1659 The possible statuses of a one-time initialization function controlled by a #GOnce struct.
1662 @G_ONCE_STATUS_NOTCALLED: the function has not been called yet.
1663 @G_ONCE_STATUS_PROGRESS: the function call is currently in progress.
1664 @G_ONCE_STATUS_READY: the function has been called.
1667 <!-- ##### MACRO G_ONCE_INIT ##### -->
1669 A #GOnce must be initialized with this macro before it can be used.
1674 GOnce my_once = G_ONCE_INIT;
1682 <!-- ##### MACRO g_once ##### -->
1684 The first call to this routine by a process with a given #GOnce struct calls
1685 @func with the given argument. Thereafter, subsequent calls to g_once() with
1686 the same #GOnce struct do not call @func again, but return the stored result
1687 of the first call. On return from g_once(), the status of @once will be
1688 %G_ONCE_STATUS_READY.
1691 For example, a mutex or a thread-specific data key must be created exactly
1692 once. In a threaded environment, calling g_once() ensures that the
1693 initialization is serialized across multiple threads.
1696 Calling g_once() recursively on the same #GOnce struct in @func will lead
1705 static GOnce my_once = G_ONCE_INIT;
1707 g_once (&my_once, parse_debug_flags, NULL);
1709 return my_once.retval;
1715 @once: a #GOnce structure
1716 @func: the #GThreadFunc function associated to @once. This function is
1717 called only once, regardless of the number of times it and its
1718 associated #GOnce struct are passed to g_once() .
1719 @arg: data to be passed to @func
1723 <!-- ##### FUNCTION g_once_init_enter ##### -->
1725 Function to be called when starting a critical initialization section.
1726 The argument value_location must point to a static 0-initialized variable
1727 that will be set to a value other than 0 at the end of the initialization section.
1728 In combination with g_once_init_leave() and the unique address value_location,
1729 it can be ensured that an initialization section will be executed only once
1730 during a programs life time, and that concurrent threads are blocked until
1731 initialization completed. To be used in constructs like this:
1737 static gsize initialization_value = 0;
1738 if (g_once_init_enter (&initialization_value)) // section start
1740 gsize setup_value = 42; // initialization code here
1741 g_once_init_leave (&initialization_value, setup_value); // section end
1747 @value_location: location of a static initializable variable containing 0.
1748 @Returns: %TRUE if the initialization section should be netered, %FALSE and blocks otheriwse
1751 <!-- ##### FUNCTION g_once_init_leave ##### -->
1753 Counterpart to g_once_init_enter(). Expects a location of a static 0-initialized
1754 initialization variable, and an initialization value other than 0. Sets the variable
1755 to the initialization value, and releases concurrent threads blocking in
1756 g_once_init_enter() on this initialization variable.
1759 @value_location: location of a static initializable variable containing 0.
1760 @initialization_value: new non-0 value for *@value_location: