1 <!-- ##### SECTION Title ##### -->
5 <!-- ##### SECTION Short_Description ##### -->
7 thread abstraction; including threads, different mutexes, conditions
8 and thread private data.
10 <!-- ##### SECTION Long_Description ##### -->
13 Threads act almost like processes, but unlike processes all threads of
14 one process share the same memory. This is good, as it provides easy
15 communication between the involved threads via this shared memory, and
16 it is bad, because strange things (so called Heisenbugs) might happen,
17 when the program is not carefully designed. Especially bad is, that due
18 to the concurrent nature of threads no assumptions on the order of
19 execution of different threads can be done unless explicitly forced by
20 the programmer through synchronization primitives.
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) and finally there are primitives
30 for thread-private 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).
35 <!-- ##### SECTION See_Also ##### -->
40 <term>#GThreadPool</term>
41 <listitem><para>Thread pools.</para></listitem>
45 <term>#GAsyncQueue</term>
46 <listitem><para>Send asynchronous messages between threads.</para></listitem>
52 <!-- ##### MACRO G_THREADS_ENABLED ##### -->
55 This macro is defined, if GLib was compiled with thread support. This
56 does not necessarily mean, that there is a thread implementation
57 available, but the infrastructure is in place and once you provide a
58 thread implementation to g_thread_init(), GLib will be multi-thread
59 safe. It isn't and cannot be, if #G_THREADS_ENABLED is not defined.
64 <!-- ##### MACRO G_THREADS_IMPL_POSIX ##### -->
67 This macro is defined, if POSIX style threads are used.
72 <!-- ##### MACRO G_THREADS_IMPL_SOLARIS ##### -->
75 This macro is defined, if the Solaris thread system is used.
80 <!-- ##### MACRO G_THREADS_IMPL_NONE ##### -->
83 This macro is defined, if no thread implementation is used. You can
84 however provide one to g_thread_init() to make GLib multi-thread safe.
89 <!-- ##### MACRO G_THREAD_ERROR ##### -->
91 The error domain of the GLib thread subsystem.
96 <!-- ##### ENUM GThreadError ##### -->
98 Possible errors of thread related functions.
101 @G_THREAD_ERROR_AGAIN: a thread couldn't be created due to resource
102 shortage. Try again later.
104 <!-- ##### STRUCT GThreadFunctions ##### -->
107 This function table is used by g_thread_init() to initialize the
108 thread system. The functions in that table are directly used by their
109 g_* prepended counterparts, that are described here, e.g. if you call
110 g_mutex_new() then mutex_new() from the table provided to
111 g_thread_init() will be called.
116 This struct should only be used, if you know, what you are doing.
138 @thread_set_priority:
142 <!-- ##### FUNCTION g_thread_init ##### -->
145 Before you use a thread related function in GLib, you should
146 initialize the thread system. This is done by calling
147 g_thread_init(). Most of the time you will only have to call
148 <literal>g_thread_init(NULL)</literal>.
153 You should only call g_thread_init() with a non-%NULL parameter if you
154 really know what you are doing.
160 g_thread_init() must not be called directly or indirectly as a
161 callback from GLib. Also no mutexes may be currently locked, while
162 calling g_thread_init().
167 g_thread_init() might only be called once. On the second call
168 it will abort with an error. If you want to make sure, that the thread
169 system is initialized, you can do that too:
175 if (!g_thread_supported (<!-- -->)) g_thread_init (NULL);
181 After that line either the thread system is initialized or the program
182 will abort, if no thread system is available in GLib, i.e. either
183 #G_THREADS_ENABLED is not defined or #G_THREADS_IMPL_NONE is defined.
187 If no thread system is available and @vtable is %NULL or if not all
188 elements of @vtable are non-%NULL, then g_thread_init() will abort.
193 To use g_thread_init() in your program, you have to link with the
194 libraries that the command <command>pkg-config --libs gthread-2.0</command>
195 outputs. This is not the case for all the other thread related functions of
196 GLib. Those can be used without having to link with the thread libraries.
200 @vtable: a function table of type #GThreadFunctions, that provides the
201 entry points to the thread system to be used.
204 <!-- ##### FUNCTION g_thread_supported ##### -->
206 This function returns, whether the thread system is initialized or
212 This function is actually a macro. Apart from taking the address of it
213 you can however use it as if it was a function.
217 @Returns: %TRUE, if the thread system is initialized.
220 <!-- ##### USER_FUNCTION GThreadFunc ##### -->
222 Specifies the type of the @func functions passed to
223 g_thread_create() or g_thread_create_full().
226 @data: data passed to the thread.
227 @Returns: the return value of the thread, which will be returned by
231 <!-- ##### ENUM GThreadPriority ##### -->
233 Specifies the priority of a thread.
238 It is not guaranteed, that threads with different priorities really
239 behave accordingly. On some systems (e.g. Linux) only root can increase
240 priorities. On other systems (e.g. Solaris) there doesn't seem to be
241 different scheduling for different priorities. All in all try to avoid
242 being dependent on priorities.
246 @G_THREAD_PRIORITY_LOW: a priority lower than normal
247 @G_THREAD_PRIORITY_NORMAL: the default priority
248 @G_THREAD_PRIORITY_HIGH: a priority higher than normal
249 @G_THREAD_PRIORITY_URGENT: the highest priority
251 <!-- ##### STRUCT GThread ##### -->
253 The #GThread struct represents a running thread. It has three public
254 read-only members, but the underlying struct is bigger, so you must
255 not copy this struct.
260 Resources for a joinable thread are not fully released until
261 g_thread_join() is called for that thread.
265 @func: the function executing in that thread
266 @data: the argument to the function
267 @joinable: is this thread joinable?
268 @priority: the priority of the thread
270 <!-- ##### FUNCTION g_thread_create ##### -->
272 This function creates a new thread with the priority @priority.
276 If @joinable is %TRUE, you can wait for this threads termination
277 calling g_thread_join(). Otherwise the thread will just disappear, when
282 The new thread executes the function @func with the argument
283 @data. If the thread was created successfully, it is returned.
287 @error can be %NULL to ignore errors, or non-%NULL to report errors. The
288 error is set, if and only if the function returns %NULL.
291 @func: a function to execute in the new thread.
292 @data: an argument to supply to the new thread.
293 @joinable: should this thread be joinable?
294 @error: return location for error.
295 @Returns: the new #GThread on success.
298 <!-- ##### FUNCTION g_thread_create_full ##### -->
300 This function creates a new thread with the priority @priority. The
301 stack gets the size @stack_size or the default value for the current
302 platform, if @stack_size is 0.
306 If @joinable is %TRUE, you can wait for this threads termination
307 calling g_thread_join(). Otherwise the thread will just disappear, when
308 ready. If @bound is %TRUE, this thread will be scheduled in the system
309 scope, otherwise the implementation is free to do scheduling in the
310 process scope. The first variant is more expensive resource-wise, but
311 generally faster. On some systems (e.g. Linux) all threads are bound.
315 The new thread executes the function @func with the argument
316 @data. If the thread was created successfully, it is returned.
320 @error can be %NULL to ignore errors, or non-%NULL to report errors. The
321 error is set, if and only if the function returns %NULL.
326 It is not guaranteed, that threads with different priorities really
327 behave accordingly. On some systems (e.g. Linux) only root can increase
328 priorities. On other systems (e.g. Solaris) there doesn't seem to be
329 different scheduling for different priorities. All in all try to avoid
330 being dependent on priorities. Use %G_THREAD_PRIORITY_NORMAL here as a
337 Only use g_thread_create_full(), when you really can't use
338 g_thread_create() instead. g_thread_create() does not take
339 @stack_size, @bound and @priority as arguments, as they should only be
340 used for cases, where it is inevitable.
344 @func: a function to execute in the new thread.
345 @data: an argument to supply to the new thread.
346 @stack_size: a stack size for the new thread.
347 @joinable: should this thread be joinable?
348 @bound: should this thread be bound to a system thread?
349 @priority: a priority for the thread.
350 @error: return location for error.
351 @Returns: the new #GThread on success.
354 <!-- ##### FUNCTION g_thread_self ##### -->
356 This functions returns the #GThread corresponding to the calling thread.
359 @Returns: the current thread.
362 <!-- ##### FUNCTION g_thread_join ##### -->
364 Waits until @thread finishes, i.e. the function @func, as given
365 to g_thread_create(), returns or g_thread_exit() is called by
366 @thread. All resources of @thread including the #GThread struct are
367 released. @thread must have been created with @joinable=%TRUE in
368 g_thread_create(). The value returned by @func or given to
369 g_thread_exit() by @thread is returned by this function.
372 @thread: a #GThread to be waited for.
373 @Returns: the return value of the thread.
376 <!-- ##### FUNCTION g_thread_set_priority ##### -->
378 Changes the priority of @thread to @priority.
383 It is not guaranteed, that threads with different priorities really
384 behave accordingly. On some systems (e.g. Linux) only root can increase
385 priorities. On other systems (e.g. Solaris) there doesn't seem to be
386 different scheduling for different priorities. All in all try to avoid
387 being dependent on priorities.
392 @priority: a new priority for @thread.
395 <!-- ##### FUNCTION g_thread_yield ##### -->
397 Gives way to other threads waiting to be scheduled.
401 This function is often used as a method to make busy wait less
402 evil. But in most cases, you will encounter, there are better methods
403 to do that. So in general you shouldn't use that function.
408 <!-- ##### FUNCTION g_thread_exit ##### -->
410 Exits the current thread. If another thread is waiting for that thread
411 using g_thread_join() and the current thread is joinable, the waiting
412 thread will be woken up and getting @retval as the return value of
413 g_thread_join(). If the current thread is not joinable, @retval is
420 g_thread_exit (retval);
426 is equivalent to calling
438 in the function @func, as given to g_thread_create().
443 Never call g_thread_exit() from within a thread of a #GThreadPool, as
444 that will mess up the bookkeeping and lead to funny and unwanted results.
448 @retval: the return value of this thread.
451 <!-- ##### STRUCT GMutex ##### -->
454 The #GMutex struct is an opaque data structure to represent a mutex
455 (mutual exclusion). It can be used to protect data against shared
456 access. Take for example the following function:
459 <title>A function which will not work in a threaded environment</title>
461 int give_me_next_number (<!-- -->)
463 static int current_number = 0;
465 /* now do a very complicated calculation to calculate the new number,
466 this might for example be a random number generator */
467 current_number = calc_next_number (current_number);
468 return current_number;
475 It is easy to see, that this won't work in a multi-threaded
476 application. There current_number must be protected against shared
477 access. A first naive implementation would be:
482 <title>The wrong way to write a thread-safe function</title>
484 int give_me_next_number (<!-- -->)
486 static int current_number = 0;
488 static GMutex * mutex = NULL;
491 mutex = g_mutex_new ();
492 g_mutex_lock (mutex);
493 ret_val = current_number = calc_next_number (current_number);
494 g_mutex_unlock (mutex);
502 This looks like it would work, but there is a race condition while
503 constructing the mutex and this code cannot work reliable. So please do
504 not use such constructs in your own programs. One working solution is:
509 <title>A correct thread-safe function</title>
511 static GMutex *give_me_next_number_mutex = NULL;
513 /* this function must be called before any call to give_me_next_number (<!-- -->)
514 it must be called exactly once. */
515 void init_give_me_next_number (<!-- -->)
517 g_assert (give_me_next_number_mutex == NULL);
518 give_me_next_number_mutex = g_mutex_new (<!-- -->);
521 int give_me_next_number (<!-- -->)
523 static int current_number = 0;
526 g_mutex_lock (give_me_next_number_mutex);
527 ret_val = current_number = calc_next_number (current_number);
528 g_mutex_unlock (give_me_next_number_mutex);
536 #GStaticMutex provides a simpler and safer way of doing this.
540 If you want to use a mutex, but your code should also work without
541 calling g_thread_init() first, you can not use a #GMutex, as
542 g_mutex_new() requires that. Use a #GStaticMutex instead.
546 A #GMutex should only be accessed via the following functions.
551 All of the <function>g_mutex_*</function> functions are actually macros.
552 Apart from taking their addresses, you can however use them as if they
558 <!-- ##### FUNCTION g_mutex_new ##### -->
561 Creates a new #GMutex.
566 This function will abort, if g_thread_init() has not been called yet.
570 @Returns: a new #GMutex.
573 <!-- ##### FUNCTION g_mutex_lock ##### -->
576 Locks @mutex. If @mutex is already locked by another thread, the
577 current thread will block until @mutex is unlocked by the other
582 This function can also be used, if g_thread_init() has not yet been
583 called and will do nothing then.
588 #GMutex is neither guaranteed to be recursive nor to be non-recursive,
589 i.e. a thread could deadlock while calling g_mutex_lock(), if it
590 already has locked @mutex. Use #GStaticRecMutex, if you need recursive
598 <!-- ##### FUNCTION g_mutex_trylock ##### -->
601 Tries to lock @mutex. If @mutex is already locked by another
602 thread, it immediately returns %FALSE. Otherwise it locks @mutex
607 This function can also be used, if g_thread_init() has not yet been
608 called and will immediately return %TRUE then.
613 #GMutex is neither guaranteed to be recursive nor to be non-recursive,
614 i.e. the return value of g_mutex_trylock() could be both %FALSE or
615 %TRUE, if the current thread already has locked @mutex. Use
616 #GStaticRecMutex, if you need recursive mutexes.
621 @Returns: %TRUE, if @mutex could be locked.
624 <!-- ##### FUNCTION g_mutex_unlock ##### -->
627 Unlocks @mutex. If another thread is blocked in a g_mutex_lock() call
628 for @mutex, it will be woken and can lock @mutex itself.
632 This function can also be used, if g_thread_init() has not yet been
633 called and will do nothing then.
639 <!-- ##### FUNCTION g_mutex_free ##### -->
648 <!-- ##### STRUCT GStaticMutex ##### -->
651 A #GStaticMutex works like a #GMutex, but it has one significant
652 advantage. It doesn't need to be created at run-time like a #GMutex,
653 but can be defined at compile-time. Here is a shorter, easier and
654 safer version of our <function>give_me_next_number()</function> example:
659 <title>Using <structname>GStaticMutex</structname> to simplify thread-safe programming</title>
661 int give_me_next_number (<!-- -->)
663 static int current_number = 0;
665 static GStaticMutex mutex = G_STATIC_MUTEX_INIT;
667 g_static_mutex_lock (&mutex);
668 ret_val = current_number = calc_next_number (current_number);
669 g_static_mutex_unlock (&mutex);
677 Sometimes you would like to dynamically create a mutex. If you don't
678 want to require prior calling to g_thread_init(), because your code
679 should also be usable in non-threaded programs, you are not able to
680 use g_mutex_new() and thus #GMutex, as that requires a prior call to
681 g_thread_init(). In theses cases you can also use a #GStaticMutex. It
682 must be initialized with g_static_mutex_init() before using it and
683 freed with with g_static_mutex_free() when not needed anymore to free
684 up any allocated resources.
688 Even though #GStaticMutex is not opaque, it should only be used with
689 the following functions, as it is defined differently on different
694 All of the <function>g_static_mutex_*</function> functions can also be
695 used, if g_thread_init() has not yet been called.
700 All of the <function>g_static_mutex_*</function> functions are actually
701 macros. Apart from taking their addresses, you can however use them
702 as if they were functions.
707 <!-- ##### MACRO G_STATIC_MUTEX_INIT ##### -->
710 A #GStaticMutex must be initialized with this macro, before it can be
711 used. This macro can used be to initialize a variable, but it cannot
712 be assigned to a variable. In that case you have to use
713 g_static_mutex_init().
719 GStaticMutex my_mutex = G_STATIC_MUTEX_INIT;
726 <!-- ##### FUNCTION g_static_mutex_init ##### -->
728 Initializes @mutex. Alternatively you can initialize it with
729 #G_STATIC_MUTEX_INIT.
732 @mutex: a #GStaticMutex to be initialized.
735 <!-- ##### FUNCTION g_static_mutex_lock ##### -->
737 Works like g_mutex_lock(), but for a #GStaticMutex.
740 @mutex: a #GStaticMutex.
743 <!-- ##### FUNCTION g_static_mutex_trylock ##### -->
746 Works like g_mutex_trylock(), but for a #GStaticMutex.
749 @mutex: a #GStaticMutex.
750 @Returns: %TRUE, if the #GStaticMutex could be locked.
753 <!-- ##### FUNCTION g_static_mutex_unlock ##### -->
756 Works like g_mutex_unlock(), but for a #GStaticMutex.
759 @mutex: a #GStaticMutex.
762 <!-- ##### FUNCTION g_static_mutex_get_mutex ##### -->
765 For some operations (like g_cond_wait()) you must have a #GMutex
766 instead of a #GStaticMutex. This function will return the
767 corresponding #GMutex for @mutex.
770 @mutex: a #GStaticMutex.
771 @Returns: the #GMutex corresponding to @mutex.
774 <!-- ##### FUNCTION g_static_mutex_free ##### -->
776 Releases all resources allocated to @mutex.
780 You don't have to call this functions for a #GStaticMutex with an
781 unbounded lifetime, i.e. objects declared 'static', but if you have a
782 #GStaticMutex as a member of a structure and the structure is freed,
783 you should also free the #GStaticMutex.
786 @mutex: a #GStaticMutex to be freed.
789 <!-- ##### MACRO G_LOCK_DEFINE ##### -->
792 The %G_LOCK_* macros provide a convenient interface to #GStaticMutex
793 with the advantage that they will expand to nothing in programs
794 compiled against a thread-disabled GLib, saving code and memory
795 there. #G_LOCK_DEFINE defines a lock. It can appear, where variable
796 definitions may appear in programs, i.e. in the first block of a
797 function or outside of functions. The @name parameter will be mangled
798 to get the name of the #GStaticMutex. This means, that you can use
799 names of existing variables as the parameter, e.g. the name of the
800 variable you intent to protect with the lock. Look at our
801 <function>give_me_next_number()</function> example using the %G_LOCK_* macros:
806 <title>Using the %G_LOCK_* convenience macros</title>
808 G_LOCK_DEFINE (current_number);
810 int give_me_next_number (<!-- -->)
812 static int current_number = 0;
815 G_LOCK (current_number);
816 ret_val = current_number = calc_next_number (current_number);
817 G_UNLOCK (current_number);
824 @name: the name of the lock.
827 <!-- ##### MACRO G_LOCK_DEFINE_STATIC ##### -->
830 This works like #G_LOCK_DEFINE, but it creates a static object.
833 @name: the name of the lock.
836 <!-- ##### MACRO G_LOCK_EXTERN ##### -->
839 This declares a lock, that is defined with #G_LOCK_DEFINE in another module.
842 @name: the name of the lock.
845 <!-- ##### MACRO G_LOCK ##### -->
848 Works like g_mutex_lock(), but for a lock defined with #G_LOCK_DEFINE.
851 @name: the name of the lock.
854 <!-- ##### MACRO G_TRYLOCK ##### -->
857 Works like g_mutex_trylock(), but for a lock defined with #G_LOCK_DEFINE.
860 @name: the name of the lock.
861 @Returns: %TRUE, if the lock could be locked.
864 <!-- ##### MACRO G_UNLOCK ##### -->
867 Works like g_mutex_unlock(), but for a lock defined with #G_LOCK_DEFINE.
870 @name: the name of the lock.
873 <!-- ##### STRUCT GStaticRecMutex ##### -->
875 A #GStaticRecMutex works like a #GStaticMutex, but it can be locked
876 multiple times by one thread. If you enter it n times, however, you
877 have to unlock it n times again to let other threads lock it. An
878 exception is the function g_static_rec_mutex_unlock_full(), that
879 allows you to unlock a #GStaticRecMutex completely returning the depth,
880 i.e. the number of times this mutex was locked. The depth can later be
881 used to restore the state by calling g_static_rec_mutex_lock_full().
885 Even though #GStaticRecMutex is not opaque, it should only be used with
886 the following functions.
890 All of the <function>g_static_rec_mutex_*</function> functions can also
891 be used, if g_thread_init() has not been called.
898 <!-- ##### MACRO G_STATIC_REC_MUTEX_INIT ##### -->
900 A #GStaticRecMutex must be initialized with this macro, before it can
901 be used. This macro can used be to initialize a variable, but it
902 cannot be assigned to a variable. In that case you have to use
903 g_static_rec_mutex_init().
909 GStaticRecMutex my_mutex = G_STATIC_REC_MUTEX_INIT;
916 <!-- ##### FUNCTION g_static_rec_mutex_init ##### -->
918 A #GStaticRecMutex must be initialized with this function, before it
919 can be used. Alternatively you can initialize it with
920 #G_STATIC_REC_MUTEX_INIT.
923 @mutex: a #GStaticRecMutex to be initialized.
926 <!-- ##### FUNCTION g_static_rec_mutex_lock ##### -->
928 Locks @mutex. If @mutex is already locked by another thread, the
929 current thread will block until @mutex is unlocked by the other
930 thread. If @mutex is already locked by the calling thread, this
931 functions increases the depth of @mutex and returns immediately.
934 @mutex: a #GStaticRecMutex to lock.
937 <!-- ##### FUNCTION g_static_rec_mutex_trylock ##### -->
939 Tries to lock @mutex. If @mutex is already locked by another thread,
940 it immediately returns %FALSE. Otherwise it locks @mutex and returns
941 %TRUE. If @mutex is already locked by the calling thread, this
942 functions increases the depth of @mutex and immediately returns %TRUE.
945 @mutex: a #GStaticRecMutex to lock.
946 @Returns: %TRUE, if @mutex could be locked.
949 <!-- ##### FUNCTION g_static_rec_mutex_unlock ##### -->
951 Unlocks @mutex. Another threads can, however, only lock @mutex when it
952 has been unlocked as many times, as it had been locked before. If
953 @mutex is completely unlocked and another thread is blocked in a
954 g_static_rec_mutex_lock() call for @mutex, it will be woken and can
958 @mutex: a #GStaticRecMutex to unlock.
961 <!-- ##### FUNCTION g_static_rec_mutex_lock_full ##### -->
963 Works like calling g_static_rec_mutex_lock() for @mutex @depth times.
966 @mutex: a #GStaticRecMutex to lock.
967 @depth: number of times this mutex has to be unlocked to be completely unlocked.
970 <!-- ##### FUNCTION g_static_rec_mutex_unlock_full ##### -->
972 Completely unlocks @mutex. If another thread is blocked in a
973 g_static_rec_mutex_lock() call for @mutex, it will be woken and can
974 lock @mutex itself. This function returns the number of times, that
975 @mutex has been locked by the current thread. To restore the state
976 before the call to g_static_rec_mutex_unlock_full() you can call
977 g_static_rec_mutex_lock_full() with the depth returned by this
981 @mutex: a #GStaticRecMutex to completely unlock.
982 @Returns: number of times @mutex has been locked by the current thread.
985 <!-- ##### FUNCTION g_static_rec_mutex_free ##### -->
987 Releases all resources allocated to a #GStaticRecMutex.
991 You don't have to call this functions for a #GStaticRecMutex with an
992 unbounded lifetime, i.e. objects declared 'static', but if you have a
993 #GStaticRecMutex as a member of a structure and the structure is
994 freed, you should also free the #GStaticRecMutex.
997 @mutex: a #GStaticRecMutex to be freed.
1000 <!-- ##### STRUCT GStaticRWLock ##### -->
1002 The #GStaticRWLock struct represents a read-write lock. A read-write
1003 lock can be used for protecting data, that some portions of code only
1004 read from, while others also write. In such situations it is
1005 desirable, that several readers can read at once, whereas of course
1006 only one writer may write at a time. Take a look at the following
1010 <title>An array with access functions</title>
1012 GStaticRWLock rwlock = G_STATIC_RW_LOCK_INIT;
1016 gpointer my_array_get (guint index)
1018 gpointer retval = NULL;
1023 g_static_rw_lock_reader_lock (&rwlock);
1025 if (index < array->len)
1026 retval = g_ptr_array_index (array, index);
1028 g_static_rw_lock_reader_unlock (&rwlock);
1033 void my_array_set (guint index, gpointer data)
1035 g_static_rw_lock_writer_lock (&rwlock);
1038 array = g_ptr_array_new (<!-- -->);
1040 if (index >= array->len)
1041 g_ptr_array_set_size (array, index+1);
1043 g_ptr_array_index (array, index) = data;
1045 g_static_rw_lock_writer_unlock (&rwlock);
1052 This example shows an array, which can be accessed by many readers
1053 (the <function>my_array_get()</function> function) simultaneously,
1054 whereas the writers (the <function>my_array_set()</function> function)
1055 will only be allowed once a time and only if no readers currently access
1056 the array. This is because of the potentially dangerous resizing of the
1057 array. Using these functions is fully multi-thread safe now.
1061 Most of the time the writers should have precedence of readers. That
1062 means for this implementation, that as soon as a writer wants to lock
1063 the data, no other reader is allowed to lock the data, whereas of
1064 course the readers, that already have locked the data are allowed to
1065 finish their operation. As soon as the last reader unlocks the data,
1066 the writer will lock it.
1070 Even though #GStaticRWLock is not opaque, it should only be used with
1071 the following functions.
1075 All of the <function>g_static_rw_lock_*</function> functions can also be
1076 used, if g_thread_init() has not been called.
1081 A read-write lock has a higher overhead as a mutex. For example both
1082 g_static_rw_lock_reader_lock() and g_static_rw_lock_reader_unlock()
1083 have to lock and unlock a #GStaticMutex, so it takes at least twice the
1084 time to lock and unlock a #GStaticRWLock than to lock and unlock a
1085 #GStaticMutex. So only data structures, that are accessed by multiple
1086 readers, which keep the lock for a considerable time justify a
1087 #GStaticRWLock. The above example most probably would fare better with
1100 <!-- ##### MACRO G_STATIC_RW_LOCK_INIT ##### -->
1102 A #GStaticRWLock must be initialized with this macro, before it can
1103 be used. This macro can used be to initialize a variable, but it
1104 cannot be assigned to a variable. In that case you have to use
1105 g_static_rw_lock_init().
1111 GStaticRWLock my_lock = G_STATIC_RW_LOCK_INIT;
1118 <!-- ##### FUNCTION g_static_rw_lock_init ##### -->
1120 A #GStaticRWLock must be initialized with this function, before it can
1121 be used. Alternatively you can initialize it with
1122 #G_STATIC_RW_LOCK_INIT.
1125 @lock: a #GStaticRWLock to be initialized.
1128 <!-- ##### FUNCTION g_static_rw_lock_reader_lock ##### -->
1130 Locks @lock for reading. There may be unlimited concurrent locks for
1131 reading of a #GStaticRWLock at the same time. If @lock is already
1132 locked for writing by another thread or if another thread is already
1133 waiting to lock @lock for writing, this function will block until
1134 @lock is unlocked by the other writing thread and no other writing
1135 threads want to lock @lock. This lock has to be unlocked by
1136 g_static_rw_lock_reader_unlock().
1140 #GStaticRWLock is not recursive. It might seem to be possible to
1141 recursively lock for reading, but that can result in a deadlock as
1142 well, due to writer preference.
1145 @lock: a #GStaticRWLock to lock for reading.
1148 <!-- ##### FUNCTION g_static_rw_lock_reader_trylock ##### -->
1150 Tries to lock @lock for reading. If @lock is already locked for
1151 writing by another thread or if another thread is already waiting to
1152 lock @lock for writing, it immediately returns %FALSE. Otherwise it
1153 locks @lock for reading and returns %TRUE. This lock has to be unlocked
1154 by g_static_rw_lock_reader_unlock().
1157 @lock: a #GStaticRWLock to lock for reading.
1158 @Returns: %TRUE, if @lock could be locked for reading.
1161 <!-- ##### FUNCTION g_static_rw_lock_reader_unlock ##### -->
1163 Unlocks @lock. If a thread waits to lock @lock for writing and all
1164 locks for reading have been unlocked, the waiting thread is woken up
1165 and can lock @lock for writing.
1168 @lock: a #GStaticRWLock to unlock after reading.
1171 <!-- ##### FUNCTION g_static_rw_lock_writer_lock ##### -->
1173 Locks @lock for writing. If @lock is already locked for writing or
1174 reading by other threads, this function will block until @lock is
1175 completely unlocked and then lock @lock for writing. While this
1176 functions waits to lock @lock, no other thread can lock @lock for
1177 reading. When @lock is locked for writing, no other thread can lock
1178 @lock (neither for reading nor writing). This lock has to be unlocked
1179 by g_static_rw_lock_writer_unlock().
1182 @lock: a #GStaticRWLock to lock for writing.
1185 <!-- ##### FUNCTION g_static_rw_lock_writer_trylock ##### -->
1187 Tries to lock @lock for writing. If @lock is already locked (for
1188 either reading or writing) by another thread, it immediately returns
1189 %FALSE. Otherwise it locks @lock for writing and returns %TRUE. This
1190 lock has to be unlocked by g_static_rw_lock_writer_unlock().
1193 @lock: a #GStaticRWLock to lock for writing.
1194 @Returns: %TRUE, if @lock could be locked for writing.
1197 <!-- ##### FUNCTION g_static_rw_lock_writer_unlock ##### -->
1199 Unlocks @lock. If a thread waits to lock @lock for writing and all
1200 locks for reading have been unlocked, the waiting thread is woken up
1201 and can lock @lock for writing. If no thread waits to lock @lock for
1202 writing and threads wait to lock @lock for reading, the waiting
1203 threads are woken up and can lock @lock for reading.
1206 @lock: a #GStaticRWLock to unlock after writing.
1209 <!-- ##### FUNCTION g_static_rw_lock_free ##### -->
1211 Releases all resources allocated to @lock.
1215 You don't have to call this functions for a #GStaticRWLock with an
1216 unbounded lifetime, i.e. objects declared 'static', but if you have a
1217 #GStaticRWLock as a member of a structure and the structure is freed,
1218 you should also free the #GStaticRWLock.
1221 @lock: a #GStaticRWLock to be freed.
1224 <!-- ##### STRUCT GCond ##### -->
1227 The #GCond struct is an opaque data structure to represent a
1228 condition. A #GCond is an object, that threads can block on, if they
1229 find a certain condition to be false. If other threads change the
1230 state of this condition they can signal the #GCond, such that the
1231 waiting thread is woken up.
1236 <title>Using GCond to block a thread until a condition is satisfied</title>
1238 GCond* data_cond = NULL; /* Must be initialized somewhere */
1239 GMutex* data_mutex = NULL; /* Must be initialized somewhere */
1240 gpointer current_data = NULL;
1242 void push_data (gpointer data)
1244 g_mutex_lock (data_mutex);
1245 current_data = data;
1246 g_cond_signal (data_cond);
1247 g_mutex_unlock (data_mutex);
1250 gpointer pop_data (<!-- -->)
1254 g_mutex_lock (data_mutex);
1255 while (!current_data)
1256 g_cond_wait (data_cond, data_mutex);
1257 data = current_data;
1258 current_data = NULL;
1259 g_mutex_unlock (data_mutex);
1267 Whenever a thread calls <function>pop_data()</function> now, it will
1268 wait until current_data is non-%NULL, i.e. until some other thread
1269 has called <function>push_data()</function>.
1274 It is important to use the g_cond_wait() and g_cond_timed_wait()
1275 functions only inside a loop, which checks for the condition to be
1276 true as it is not guaranteed that the waiting thread will find it
1277 fulfilled, even if the signaling thread left the condition
1278 in that state. This is because another thread can have altered the
1279 condition, before the waiting thread got the chance to be woken up,
1280 even if the condition itself is protected by a #GMutex, like above.
1285 A #GCond should only be accessed via the following functions.
1290 All of the <function>g_cond_*</function> functions are actually macros.
1291 Apart from taking their addresses, you can however use them as if they
1297 <!-- ##### FUNCTION g_cond_new ##### -->
1300 Creates a new #GCond. This function will abort, if g_thread_init()
1301 has not been called yet.
1304 @Returns: a new #GCond.
1307 <!-- ##### FUNCTION g_cond_signal ##### -->
1309 If threads are waiting for @cond, exactly one of them is woken up. It
1310 is good practice to hold the same lock as the waiting thread, while
1311 calling this function, though not required.
1315 This function can also be used, if g_thread_init() has
1316 not yet been called and will do nothing then.
1322 <!-- ##### FUNCTION g_cond_broadcast ##### -->
1325 If threads are waiting for @cond, all of them are woken up. It is good
1326 practice to lock the same mutex as the waiting threads, while calling
1327 this function, though not required.
1331 This function can also be used, if g_thread_init() has
1332 not yet been called and will do nothing then.
1338 <!-- ##### FUNCTION g_cond_wait ##### -->
1341 Waits until this thread is woken up on @cond. The @mutex is unlocked
1342 before falling asleep and locked again before resuming.
1346 This function can also be used, if g_thread_init() has not yet been
1347 called and will immediately return then.
1351 @mutex: a #GMutex, that is currently locked.
1354 <!-- ##### FUNCTION g_cond_timed_wait ##### -->
1357 Waits until this thread is woken up on @cond, but not longer than
1358 until the time, that is specified by @abs_time. The @mutex is
1359 unlocked before falling asleep and locked again before resuming.
1363 If @abs_time is %NULL, g_cond_timed_wait() acts like g_cond_wait().
1367 This function can also be used, if g_thread_init() has not yet been
1368 called and will immediately return %TRUE then.
1372 To easily calculate @abs_time a combination of g_get_current_time()
1373 and g_time_val_add() can be used.
1377 @mutex: a #GMutex, that is currently locked.
1378 @abs_time: a #GTimeVal, determining the final time.
1379 @Returns: %TRUE, if the thread is woken up in time.
1382 <!-- ##### FUNCTION g_cond_free ##### -->
1385 Destroys the #GCond.
1391 <!-- ##### STRUCT GPrivate ##### -->
1393 The #GPrivate struct is an opaque data structure to represent a thread
1394 private data key. Threads can thereby obtain and set a pointer, which
1395 is private to the current thread.
1396 Take our <function>give_me_next_number()</function> example from above.
1397 Now we don't want <literal>current_number</literal> to be shared
1398 between the threads, but to be private to each thread. This can be
1402 <title>Using GPrivate for per-thread data</title>
1404 GPrivate* current_number_key = NULL; /* Must be initialized somewhere */
1405 /* with g_private_new (g_free); */
1407 int give_me_next_number (<!-- -->)
1409 int *current_number = g_private_get (current_number_key);
1411 if (!current_number)
1413 current_number = g_new (int,1);
1414 *current_number = 0;
1415 g_private_set (current_number_key, current_number);
1417 *current_number = calc_next_number (*current_number);
1418 return *current_number;
1425 Here the pointer belonging to the key <literal>current_number_key</literal>
1426 is read. If it is %NULL, it has not been set yet. Then get memory for an
1427 integer value, assign this memory to the pointer and write the pointer
1428 back. Now we have an integer value, that is private to the current thread.
1432 The #GPrivate struct should only be accessed via the following functions.
1437 All of the <function>g_private_*</function> functions are actually macros.
1438 Apart from taking their addresses, you can however use them as if they were
1444 <!-- ##### FUNCTION g_private_new ##### -->
1447 Creates a new #GPrivate. If @destructor is non-%NULL, it is a pointer
1448 to a destructor function. Whenever a thread ends and the corresponding
1449 pointer keyed to this instance of #GPrivate is non-%NULL, the
1450 destructor is called with this pointer as the argument.
1455 @destructor is working quite differently from @notify in
1456 g_static_private_set().
1462 A #GPrivate can not be freed. Reuse it instead, if you can to avoid
1463 shortage or use #GStaticPrivate.
1469 This function will abort, if g_thread_init() has not been called yet.
1473 @destructor: a function to handle the data keyed to #GPrivate, when a
1475 @Returns: a new #GPrivate.
1478 <!-- ##### FUNCTION g_private_get ##### -->
1481 Returns the pointer keyed to @private_key for the current thread. This
1482 pointer is %NULL, when g_private_set() hasn't been called for the
1483 current @private_key and thread yet.
1487 This function can also be used, if g_thread_init() has not yet been
1488 called and will return the value of @private_key casted to #gpointer then.
1491 @private_key: a #GPrivate.
1492 @Returns: the corresponding pointer.
1495 <!-- ##### FUNCTION g_private_set ##### -->
1498 Sets the pointer keyed to @private_key for the current thread.
1502 This function can also be used, if g_thread_init() has not yet been
1503 called and will set @private_key to @data casted to #GPrivate* then.
1506 @private_key: a #GPrivate.
1507 @data: the new pointer.
1510 <!-- ##### STRUCT GStaticPrivate ##### -->
1513 A #GStaticPrivate works almost like a #GPrivate, but it has one
1514 significant advantage. It doesn't need to be created at run-time like
1515 a #GPrivate, but can be defined at compile-time. This is similar to
1516 the difference between #GMutex and #GStaticMutex. Now look at our
1517 <function>give_me_next_number()</function> example with #GStaticPrivate:
1522 <title>Using GStaticPrivate for per-thread data</title>
1524 int give_me_next_number (<!-- -->)
1526 static GStaticPrivate current_number_key = G_STATIC_PRIVATE_INIT;
1527 int *current_number = g_static_private_get (&current_number_key);
1529 if (!current_number)
1531 current_number = g_new (int,1);
1532 *current_number = 0;
1533 g_static_private_set (&current_number_key, current_number, g_free);
1535 *current_number = calc_next_number (*current_number);
1536 return *current_number;
1544 <!-- ##### MACRO G_STATIC_PRIVATE_INIT ##### -->
1546 Every #GStaticPrivate must be initialized with this macro, before it can
1553 GStaticPrivate my_private = G_STATIC_PRIVATE_INIT;
1560 <!-- ##### FUNCTION g_static_private_init ##### -->
1562 Initializes @private_key. Alternatively you can initialize it with
1563 #G_STATIC_PRIVATE_INIT.
1566 @private_key: a #GStaticPrivate to be initialized.
1569 <!-- ##### FUNCTION g_static_private_get ##### -->
1571 Works like g_private_get() only for a #GStaticPrivate.
1575 This function also works, if g_thread_init() has not yet been called.
1578 @private_key: a #GStaticPrivate.
1579 @Returns: the corresponding pointer.
1582 <!-- ##### FUNCTION g_static_private_set ##### -->
1584 Sets the pointer keyed to @private_key for the current thread and the
1585 function @notify to be called with that pointer (%NULL or non-%NULL),
1586 whenever the pointer is set again or whenever the current thread ends.
1590 This function also works, if g_thread_init() has not yet been
1591 called. If g_thread_init() is called later, the @data keyed to
1592 @private_key will be inherited only by the main thread, i.e. the one that
1593 called g_thread_init().
1598 @notify is working quite differently from @destructor in
1603 @private_key: a #GStaticPrivate.
1604 @data: the new pointer.
1605 @notify: a function to be called with the pointer, whenever the
1606 current thread ends or sets this pointer again.
1609 <!-- ##### FUNCTION g_static_private_free ##### -->
1611 Releases all resources allocated to @private_key.
1615 You don't have to call this functions for a #GStaticPrivate with an
1616 unbounded lifetime, i.e. objects declared 'static', but if you have a
1617 #GStaticPrivate as a member of a structure and the structure is freed,
1618 you should also free the #GStaticPrivate.
1621 @private_key: a #GStaticPrivate to be freed.