1 /* GLIB - Library of useful routines for C programming
2 * Copyright (C) 1995-1997 Peter Mattis, Spencer Kimball and Josh MacDonald
4 * gthread.c: MT safety related functions
5 * Copyright 1998 Sebastian Wilhelmi; University of Karlsruhe
8 * This library is free software; you can redistribute it and/or
9 * modify it under the terms of the GNU Lesser General Public
10 * License as published by the Free Software Foundation; either
11 * version 2 of the License, or (at your option) any later version.
13 * This library is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16 * Lesser General Public License for more details.
18 * You should have received a copy of the GNU Lesser General Public
19 * License along with this library; if not, write to the
20 * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
21 * Boston, MA 02111-1307, USA.
24 /* Prelude {{{1 ----------------------------------------------------------- */
27 * Modified by the GLib Team and others 1997-2000. See the AUTHORS
28 * file for a list of people on the GLib Team. See the ChangeLog
29 * files for a list of changes. These files are distributed with
30 * GLib at ftp://ftp.gtk.org/pub/gtk/.
37 /* implement gthread.h's inline functions */
38 #define G_IMPLEMENT_INLINES 1
39 #define __G_THREAD_C__
44 #include "gthreadprivate.h"
57 #endif /* G_OS_WIN32 */
64 #include "gtestutils.h"
70 * @short_description: thread abstraction; including threads, different
71 * mutexes, conditions and thread private data
72 * @see_also: #GThreadPool, #GAsyncQueue
74 * Threads act almost like processes, but unlike processes all threads
75 * of one process share the same memory. This is good, as it provides
76 * easy communication between the involved threads via this shared
77 * memory, and it is bad, because strange things (so called
78 * "Heisenbugs") might happen if the program is not carefully designed.
79 * In particular, due to the concurrent nature of threads, no
80 * assumptions on the order of execution of code running in different
81 * threads can be made, unless order is explicitly forced by the
82 * programmer through synchronization primitives.
84 * The aim of the thread related functions in GLib is to provide a
85 * portable means for writing multi-threaded software. There are
86 * primitives for mutexes to protect the access to portions of memory
87 * (#GMutex, #GStaticMutex, #G_LOCK_DEFINE, #GStaticRecMutex and
88 * #GStaticRWLock). There is a facility to use individual bits for
89 * locks (g_bit_lock()). There are primitives for condition variables to
90 * allow synchronization of threads (#GCond). There are primitives for
91 * thread-private data - data that every thread has a private instance
92 * of (#GPrivate, #GStaticPrivate). There are facilities for one-time
93 * initialization (#GOnce, g_once_init_enter()). Last but definitely
94 * not least there are primitives to portably create and manage
97 * The threading system is initialized with g_thread_init(), which
98 * takes an optional custom thread implementation or %NULL for the
99 * default implementation. If you want to call g_thread_init() with a
100 * non-%NULL argument this must be done before executing any other GLib
101 * functions (except g_mem_set_vtable()). This is a requirement even if
102 * no threads are in fact ever created by the process.
104 * Calling g_thread_init() with a %NULL argument is somewhat more
105 * relaxed. You may call any other glib functions in the main thread
106 * before g_thread_init() as long as g_thread_init() is not called from
107 * a glib callback, or with any locks held. However, many libraries
108 * above glib does not support late initialization of threads, so doing
109 * this should be avoided if possible.
111 * Please note that since version 2.24 the GObject initialization
112 * function g_type_init() initializes threads (with a %NULL argument),
113 * so most applications, including those using Gtk+ will run with
114 * threads enabled. If you want a special thread implementation, make
115 * sure you call g_thread_init() before g_type_init() is called.
117 * After calling g_thread_init(), GLib is completely thread safe (all
118 * global data is automatically locked), but individual data structure
119 * instances are not automatically locked for performance reasons. So,
120 * for example you must coordinate accesses to the same #GHashTable
121 * from multiple threads. The two notable exceptions from this rule
122 * are #GMainLoop and #GAsyncQueue, which <emphasis>are</emphasis>
123 * threadsafe and need no further application-level locking to be
124 * accessed from multiple threads.
126 * To help debugging problems in multithreaded applications, GLib
127 * supports error-checking mutexes that will give you helpful error
128 * messages on common problems. To use error-checking mutexes, define
129 * the symbol #G_ERRORCHECK_MUTEXES when compiling the application.
133 * G_THREADS_IMPL_POSIX:
135 * This macro is defined if POSIX style threads are used.
141 * This macro is defined, for backward compatibility, to indicate that
142 * GLib has been compiled with thread support. As of glib 2.28, it is
147 * G_THREADS_IMPL_NONE:
149 * This macro is defined if no thread implementation is used. You can,
150 * however, provide one to g_thread_init() to make GLib multi-thread
154 /* G_LOCK Documentation {{{1 ---------------------------------------------- */
156 /* IMPLEMENTATION NOTE:
158 * G_LOCK_DEFINE and friends are convenience macros defined in
159 * gthread.h. Their documentation lives here.
164 * @name: the name of the lock.
166 * The %G_LOCK_* macros provide a convenient interface to #GStaticMutex
167 * with the advantage that they will expand to nothing in programs
168 * compiled against a thread-disabled GLib, saving code and memory
169 * there. #G_LOCK_DEFINE defines a lock. It can appear anywhere
170 * variable definitions may appear in programs, i.e. in the first block
171 * of a function or outside of functions. The @name parameter will be
172 * mangled to get the name of the #GStaticMutex. This means that you
173 * can use names of existing variables as the parameter - e.g. the name
174 * of the variable you intent to protect with the lock. Look at our
175 * <function>give_me_next_number()</function> example using the
179 * <title>Using the %G_LOCK_* convenience macros</title>
181 * G_LOCK_DEFINE (current_number);
184 * give_me_next_number (void)
186 * static int current_number = 0;
189 * G_LOCK (current_number);
190 * ret_val = current_number = calc_next_number (current_number);
191 * G_UNLOCK (current_number);
200 * G_LOCK_DEFINE_STATIC:
201 * @name: the name of the lock.
203 * This works like #G_LOCK_DEFINE, but it creates a static object.
208 * @name: the name of the lock.
210 * This declares a lock, that is defined with #G_LOCK_DEFINE in another
216 * @name: the name of the lock.
218 * Works like g_mutex_lock(), but for a lock defined with
224 * @name: the name of the lock.
225 * @Returns: %TRUE, if the lock could be locked.
227 * Works like g_mutex_trylock(), but for a lock defined with
233 * @name: the name of the lock.
235 * Works like g_mutex_unlock(), but for a lock defined with
239 /* GThreadError {{{1 ------------------------------------------------------- */
242 * @G_THREAD_ERROR_AGAIN: a thread couldn't be created due to resource
243 * shortage. Try again later.
245 * Possible errors of thread related functions.
251 * The error domain of the GLib thread subsystem.
254 g_thread_error_quark (void)
256 return g_quark_from_static_string ("g_thread_error");
259 /* Miscellaneous Structures {{{1 ------------------------------------------ */
260 typedef struct _GRealThread GRealThread;
264 /* Bit 0 protects private_data. To avoid deadlocks, do not block while
265 * holding this (particularly on the g_thread lock). */
266 volatile gint private_data_lock;
267 GArray *private_data;
270 GSystemThread system_thread;
273 #define LOCK_PRIVATE_DATA(self) g_bit_lock (&(self)->private_data_lock, 0)
274 #define UNLOCK_PRIVATE_DATA(self) g_bit_unlock (&(self)->private_data_lock, 0)
276 typedef struct _GStaticPrivateNode GStaticPrivateNode;
277 struct _GStaticPrivateNode
280 GDestroyNotify destroy;
283 static void g_thread_cleanup (gpointer data);
284 static void g_thread_fail (void);
285 static guint64 gettime (void);
287 guint64 (*g_thread_gettime) (void) = gettime;
289 /* Global Variables {{{1 -------------------------------------------------- */
291 static GSystemThread zero_thread; /* This is initialized to all zero */
292 gboolean g_thread_use_default_impl = TRUE;
295 * g_thread_supported:
296 * @Returns: %TRUE, if the thread system is initialized.
298 * This function returns %TRUE if the thread system is initialized, and
299 * %FALSE if it is not.
301 * <note><para>This function is actually a macro. Apart from taking the
302 * address of it you can however use it as if it was a
303 * function.</para></note>
306 /* IMPLEMENTATION NOTE:
308 * g_thread_supported() is just returns g_threads_got_initialized
310 gboolean g_threads_got_initialized = FALSE;
313 /* Thread Implementation Virtual Function Table {{{1 ---------------------- */
314 /* Virtual Function Table Documentation {{{2 ------------------------------ */
317 * @mutex_new: virtual function pointer for g_mutex_new()
318 * @mutex_lock: virtual function pointer for g_mutex_lock()
319 * @mutex_trylock: virtual function pointer for g_mutex_trylock()
320 * @mutex_unlock: virtual function pointer for g_mutex_unlock()
321 * @mutex_free: virtual function pointer for g_mutex_free()
322 * @cond_new: virtual function pointer for g_cond_new()
323 * @cond_signal: virtual function pointer for g_cond_signal()
324 * @cond_broadcast: virtual function pointer for g_cond_broadcast()
325 * @cond_wait: virtual function pointer for g_cond_wait()
326 * @cond_timed_wait: virtual function pointer for g_cond_timed_wait()
327 * @cond_free: virtual function pointer for g_cond_free()
328 * @private_new: virtual function pointer for g_private_new()
329 * @private_get: virtual function pointer for g_private_get()
330 * @private_set: virtual function pointer for g_private_set()
331 * @thread_create: virtual function pointer for g_thread_create()
332 * @thread_yield: virtual function pointer for g_thread_yield()
333 * @thread_join: virtual function pointer for g_thread_join()
334 * @thread_exit: virtual function pointer for g_thread_exit()
335 * @thread_set_priority: virtual function pointer for
336 * g_thread_set_priority()
337 * @thread_self: virtual function pointer for g_thread_self()
338 * @thread_equal: used internally by recursive mutex locks and by some
341 * This function table is used by g_thread_init() to initialize the
342 * thread system. The functions in the table are directly used by their
343 * g_* prepended counterparts (described in this document). For
344 * example, if you call g_mutex_new() then mutex_new() from the table
345 * provided to g_thread_init() will be called.
347 * <note><para>Do not use this struct unless you know what you are
348 * doing.</para></note>
351 /* IMPLEMENTATION NOTE:
353 * g_thread_functions_for_glib_use is a global symbol that gets used by
354 * most of the "primitive" threading calls. g_mutex_lock(), for
355 * example, is just a macro that calls the appropriate virtual function
358 * For that reason, all of those macros are documented here.
360 static GThreadFunctions g_thread_functions_for_glib_use_old = {
361 /* GMutex Virtual Functions {{{2 ------------------------------------------ */
366 * The #GMutex struct is an opaque data structure to represent a mutex
367 * (mutual exclusion). It can be used to protect data against shared
368 * access. Take for example the following function:
371 * <title>A function which will not work in a threaded environment</title>
374 * give_me_next_number (void)
376 * static int current_number = 0;
378 * /<!-- -->* now do a very complicated calculation to calculate the new
379 * * number, this might for example be a random number generator
381 * current_number = calc_next_number (current_number);
383 * return current_number;
388 * It is easy to see that this won't work in a multi-threaded
389 * application. There current_number must be protected against shared
390 * access. A first naive implementation would be:
393 * <title>The wrong way to write a thread-safe function</title>
396 * give_me_next_number (void)
398 * static int current_number = 0;
400 * static GMutex * mutex = NULL;
402 * if (!mutex) mutex = g_mutex_new (<!-- -->);
404 * g_mutex_lock (mutex);
405 * ret_val = current_number = calc_next_number (current_number);
406 * g_mutex_unlock (mutex);
413 * This looks like it would work, but there is a race condition while
414 * constructing the mutex and this code cannot work reliable. Please do
415 * not use such constructs in your own programs! One working solution
419 * <title>A correct thread-safe function</title>
421 * static GMutex *give_me_next_number_mutex = NULL;
423 * /<!-- -->* this function must be called before any call to
424 * * give_me_next_number(<!-- -->)
426 * * it must be called exactly once.
429 * init_give_me_next_number (void)
431 * g_assert (give_me_next_number_mutex == NULL);
432 * give_me_next_number_mutex = g_mutex_new (<!-- -->);
436 * give_me_next_number (void)
438 * static int current_number = 0;
441 * g_mutex_lock (give_me_next_number_mutex);
442 * ret_val = current_number = calc_next_number (current_number);
443 * g_mutex_unlock (give_me_next_number_mutex);
450 * #GStaticMutex provides a simpler and safer way of doing this.
452 * If you want to use a mutex, and your code should also work without
453 * calling g_thread_init() first, then you cannot use a #GMutex, as
454 * g_mutex_new() requires that the thread system be initialized. Use a
455 * #GStaticMutex instead.
457 * A #GMutex should only be accessed via the following functions.
460 (GMutex*(*)())g_thread_fail,
466 /* GCond Virtual Functions {{{2 ------------------------------------------ */
471 * The #GCond struct is an opaque data structure that represents a
472 * condition. Threads can block on a #GCond if they find a certain
473 * condition to be false. If other threads change the state of this
474 * condition they signal the #GCond, and that causes the waiting
475 * threads to be woken up.
479 * Using GCond to block a thread until a condition is satisfied
482 * GCond* data_cond = NULL; /<!-- -->* Must be initialized somewhere *<!-- -->/
483 * GMutex* data_mutex = NULL; /<!-- -->* Must be initialized somewhere *<!-- -->/
484 * gpointer current_data = NULL;
487 * push_data (gpointer data)
489 * g_mutex_lock (data_mutex);
490 * current_data = data;
491 * g_cond_signal (data_cond);
492 * g_mutex_unlock (data_mutex);
500 * g_mutex_lock (data_mutex);
501 * while (!current_data)
502 * g_cond_wait (data_cond, data_mutex);
503 * data = current_data;
504 * current_data = NULL;
505 * g_mutex_unlock (data_mutex);
512 * Whenever a thread calls <function>pop_data()</function> now, it will
513 * wait until current_data is non-%NULL, i.e. until some other thread
514 * has called <function>push_data()</function>.
516 * <note><para>It is important to use the g_cond_wait() and
517 * g_cond_timed_wait() functions only inside a loop which checks for the
518 * condition to be true. It is not guaranteed that the waiting thread
519 * will find the condition fulfilled after it wakes up, even if the
520 * signaling thread left the condition in that state: another thread may
521 * have altered the condition before the waiting thread got the chance
522 * to be woken up, even if the condition itself is protected by a
523 * #GMutex, like above.</para></note>
525 * A #GCond should only be accessed via the following functions.
528 (GCond*(*)())g_thread_fail,
535 /* GPrivate Virtual Functions {{{2 --------------------------------------- */
541 * #GStaticPrivate is a better choice for most uses.
544 * The #GPrivate struct is an opaque data structure to represent a
545 * thread private data key. Threads can thereby obtain and set a
546 * pointer which is private to the current thread. Take our
547 * <function>give_me_next_number(<!-- -->)</function> example from
548 * above. Suppose we don't want <literal>current_number</literal> to be
549 * shared between the threads, but instead to be private to each thread.
550 * This can be done as follows:
553 * <title>Using GPrivate for per-thread data</title>
555 * GPrivate* current_number_key = NULL; /<!-- -->* Must be initialized somewhere
556 * with g_private_new (g_free); *<!-- -->/
559 * give_me_next_number (void)
561 * int *current_number = g_private_get (current_number_key);
563 * if (!current_number)
565 * current_number = g_new (int, 1);
566 * *current_number = 0;
567 * g_private_set (current_number_key, current_number);
570 * *current_number = calc_next_number (*current_number);
572 * return *current_number;
577 * Here the pointer belonging to the key
578 * <literal>current_number_key</literal> is read. If it is %NULL, it has
579 * not been set yet. Then get memory for an integer value, assign this
580 * memory to the pointer and write the pointer back. Now we have an
581 * integer value that is private to the current thread.
583 * The #GPrivate struct should only be accessed via the following
586 * <note><para>All of the <function>g_private_*</function> functions are
587 * actually macros. Apart from taking their addresses, you can however
588 * use them as if they were functions.</para></note>
591 (GPrivate*(*)(GDestroyNotify))g_thread_fail,
595 /* GThread Virtual Functions {{{2 ---------------------------------------- */
599 * The #GThread struct represents a running thread. It has three public
600 * read-only members, but the underlying struct is bigger, so you must
601 * not copy this struct.
603 * <note><para>Resources for a joinable thread are not fully released
604 * until g_thread_join() is called for that thread.</para></note>
609 * @data: data passed to the thread.
610 * @Returns: the return value of the thread, which will be returned by
613 * Specifies the type of the @func functions passed to
614 * g_thread_create() or g_thread_create_full().
619 * @G_THREAD_PRIORITY_LOW: a priority lower than normal
620 * @G_THREAD_PRIORITY_NORMAL: the default priority
621 * @G_THREAD_PRIORITY_HIGH: a priority higher than normal
622 * @G_THREAD_PRIORITY_URGENT: the highest priority
624 * Deprecated:2.32: thread priorities no longer have any effect.
627 (void(*)(GThreadFunc, gpointer, gulong,
628 gboolean, gboolean, GThreadPriority,
629 gpointer, GError**))g_thread_fail,
631 NULL, /* thread_yield */
632 NULL, /* thread_join */
633 NULL, /* thread_exit */
634 NULL, /* thread_set_priority */
635 NULL, /* thread_self */
636 NULL /* thread_equal */
639 /* Local Data {{{1 -------------------------------------------------------- */
641 static GMutex g_once_mutex = G_MUTEX_INIT;
642 static GCond g_once_cond = G_COND_INIT;
643 static GPrivate g_thread_specific_private;
644 static GRealThread *g_thread_all_threads = NULL;
645 static GSList *g_thread_free_indices = NULL;
646 static GSList* g_once_init_list = NULL;
648 G_LOCK_DEFINE_STATIC (g_thread);
650 /* Initialisation {{{1 ---------------------------------------------------- */
654 * @vtable: a function table of type #GThreadFunctions, that provides
655 * the entry points to the thread system to be used.
657 * If you use GLib from more than one thread, you must initialize the
658 * thread system by calling g_thread_init(). Most of the time you will
659 * only have to call <literal>g_thread_init (NULL)</literal>.
661 * <note><para>Do not call g_thread_init() with a non-%NULL parameter unless
662 * you really know what you are doing.</para></note>
664 * <note><para>g_thread_init() must not be called directly or indirectly as a
665 * callback from GLib. Also no mutexes may be currently locked while
666 * calling g_thread_init().</para></note>
668 * <note><para>g_thread_init() changes the way in which #GTimer measures
669 * elapsed time. As a consequence, timers that are running while
670 * g_thread_init() is called may report unreliable times.</para></note>
672 * Calling g_thread_init() multiple times is allowed (since version
673 * 2.24), but nothing happens except for the first call. If the
674 * argument is non-%NULL on such a call a warning will be printed, but
675 * otherwise the argument is ignored.
677 * If no thread system is available and @vtable is %NULL or if not all
678 * elements of @vtable are non-%NULL, then g_thread_init() will abort.
680 * <note><para>To use g_thread_init() in your program, you have to link with
681 * the libraries that the command <command>pkg-config --libs
682 * gthread-2.0</command> outputs. This is not the case for all the
683 * other thread related functions of GLib. Those can be used without
684 * having to link with the thread libraries.</para></note>
687 /* This must be called only once, before any threads are created.
688 * It will only be called from g_thread_init() in -lgthread.
691 g_thread_init_glib (void)
693 static gboolean already_done;
700 _g_thread_impl_init ();
702 /* We let the main thread (the one that calls g_thread_init) inherit
703 * the static_private data set before calling g_thread_init
705 GRealThread* main_thread = (GRealThread*) g_thread_self ();
707 /* setup the basic threading system */
708 g_threads_got_initialized = TRUE;
709 g_private_init (&g_thread_specific_private, g_thread_cleanup);
710 g_private_set (&g_thread_specific_private, main_thread);
711 g_system_thread_self (&main_thread->system_thread);
713 /* accomplish log system initialization to enable messaging */
714 _g_messages_thread_init_nomessage ();
717 /* The following sections implement: GOnce, GStaticMutex, GStaticRecMutex,
721 /* GOnce {{{1 ------------------------------------------------------------- */
725 * @status: the status of the #GOnce
726 * @retval: the value returned by the call to the function, if @status
727 * is %G_ONCE_STATUS_READY
729 * A #GOnce struct controls a one-time initialization function. Any
730 * one-time initialization function must have its own unique #GOnce
739 * A #GOnce must be initialized with this macro before it can be used.
743 * GOnce my_once = G_ONCE_INIT;
752 * @G_ONCE_STATUS_NOTCALLED: the function has not been called yet.
753 * @G_ONCE_STATUS_PROGRESS: the function call is currently in progress.
754 * @G_ONCE_STATUS_READY: the function has been called.
756 * The possible statuses of a one-time initialization function
757 * controlled by a #GOnce struct.
764 * @once: a #GOnce structure
765 * @func: the #GThreadFunc function associated to @once. This function
766 * is called only once, regardless of the number of times it and
767 * its associated #GOnce struct are passed to g_once().
768 * @arg: data to be passed to @func
770 * The first call to this routine by a process with a given #GOnce
771 * struct calls @func with the given argument. Thereafter, subsequent
772 * calls to g_once() with the same #GOnce struct do not call @func
773 * again, but return the stored result of the first call. On return
774 * from g_once(), the status of @once will be %G_ONCE_STATUS_READY.
776 * For example, a mutex or a thread-specific data key must be created
777 * exactly once. In a threaded environment, calling g_once() ensures
778 * that the initialization is serialized across multiple threads.
780 * <note><para>Calling g_once() recursively on the same #GOnce struct in
781 * @func will lead to a deadlock.</para></note>
786 * get_debug_flags (void)
788 * static GOnce my_once = G_ONCE_INIT;
790 * g_once (&my_once, parse_debug_flags, NULL);
792 * return my_once.retval;
800 g_once_impl (GOnce *once,
804 g_mutex_lock (&g_once_mutex);
806 while (once->status == G_ONCE_STATUS_PROGRESS)
807 g_cond_wait (&g_once_cond, &g_once_mutex);
809 if (once->status != G_ONCE_STATUS_READY)
811 once->status = G_ONCE_STATUS_PROGRESS;
812 g_mutex_unlock (&g_once_mutex);
814 once->retval = func (arg);
816 g_mutex_lock (&g_once_mutex);
817 once->status = G_ONCE_STATUS_READY;
818 g_cond_broadcast (&g_once_cond);
821 g_mutex_unlock (&g_once_mutex);
828 * @value_location: location of a static initializable variable
830 * @Returns: %TRUE if the initialization section should be entered,
831 * %FALSE and blocks otherwise
833 * Function to be called when starting a critical initialization
834 * section. The argument @value_location must point to a static
835 * 0-initialized variable that will be set to a value other than 0 at
836 * the end of the initialization section. In combination with
837 * g_once_init_leave() and the unique address @value_location, it can
838 * be ensured that an initialization section will be executed only once
839 * during a program's life time, and that concurrent threads are
840 * blocked until initialization completed. To be used in constructs
845 * static gsize initialization_value = 0;
847 * if (g_once_init_enter (&initialization_value))
849 * gsize setup_value = 42; /<!-- -->* initialization code here *<!-- -->/
851 * g_once_init_leave (&initialization_value, setup_value);
854 * /<!-- -->* use initialization_value here *<!-- -->/
861 g_once_init_enter_impl (volatile gsize *value_location)
863 gboolean need_init = FALSE;
864 g_mutex_lock (&g_once_mutex);
865 if (g_atomic_pointer_get (value_location) == NULL)
867 if (!g_slist_find (g_once_init_list, (void*) value_location))
870 g_once_init_list = g_slist_prepend (g_once_init_list, (void*) value_location);
874 g_cond_wait (&g_once_cond, &g_once_mutex);
875 while (g_slist_find (g_once_init_list, (void*) value_location));
877 g_mutex_unlock (&g_once_mutex);
883 * @value_location: location of a static initializable variable
885 * @initialization_value: new non-0 value for *@value_location.
887 * Counterpart to g_once_init_enter(). Expects a location of a static
888 * 0-initialized initialization variable, and an initialization value
889 * other than 0. Sets the variable to the initialization value, and
890 * releases concurrent threads blocking in g_once_init_enter() on this
891 * initialization variable.
896 g_once_init_leave (volatile gsize *value_location,
897 gsize initialization_value)
899 g_return_if_fail (g_atomic_pointer_get (value_location) == NULL);
900 g_return_if_fail (initialization_value != 0);
901 g_return_if_fail (g_once_init_list != NULL);
903 g_atomic_pointer_set (value_location, initialization_value);
904 g_mutex_lock (&g_once_mutex);
905 g_once_init_list = g_slist_remove (g_once_init_list, (void*) value_location);
906 g_cond_broadcast (&g_once_cond);
907 g_mutex_unlock (&g_once_mutex);
910 /* GStaticMutex {{{1 ------------------------------------------------------ */
915 * A #GStaticMutex works like a #GMutex, but it has one significant
916 * advantage. It doesn't need to be created at run-time like a #GMutex,
917 * but can be defined at compile-time. Here is a shorter, easier and
918 * safer version of our <function>give_me_next_number()</function>
923 * Using <structname>GStaticMutex</structname>
924 * to simplify thread-safe programming
928 * give_me_next_number (void)
930 * static int current_number = 0;
932 * static GStaticMutex mutex = G_STATIC_MUTEX_INIT;
934 * g_static_mutex_lock (&mutex);
935 * ret_val = current_number = calc_next_number (current_number);
936 * g_static_mutex_unlock (&mutex);
943 * Sometimes you would like to dynamically create a mutex. If you don't
944 * want to require prior calling to g_thread_init(), because your code
945 * should also be usable in non-threaded programs, you are not able to
946 * use g_mutex_new() and thus #GMutex, as that requires a prior call to
947 * g_thread_init(). In theses cases you can also use a #GStaticMutex.
948 * It must be initialized with g_static_mutex_init() before using it
949 * and freed with with g_static_mutex_free() when not needed anymore to
950 * free up any allocated resources.
952 * Even though #GStaticMutex is not opaque, it should only be used with
953 * the following functions, as it is defined differently on different
956 * All of the <function>g_static_mutex_*</function> functions apart
957 * from <function>g_static_mutex_get_mutex</function> can also be used
958 * even if g_thread_init() has not yet been called. Then they do
959 * nothing, apart from <function>g_static_mutex_trylock</function>,
960 * which does nothing but returning %TRUE.
962 * <note><para>All of the <function>g_static_mutex_*</function>
963 * functions are actually macros. Apart from taking their addresses, you
964 * can however use them as if they were functions.</para></note>
968 * G_STATIC_MUTEX_INIT:
970 * A #GStaticMutex must be initialized with this macro, before it can
971 * be used. This macro can used be to initialize a variable, but it
972 * cannot be assigned to a variable. In that case you have to use
973 * g_static_mutex_init().
977 * GStaticMutex my_mutex = G_STATIC_MUTEX_INIT;
983 * g_static_mutex_init:
984 * @mutex: a #GStaticMutex to be initialized.
986 * Initializes @mutex. Alternatively you can initialize it with
987 * #G_STATIC_MUTEX_INIT.
990 g_static_mutex_init (GStaticMutex *mutex)
992 static const GStaticMutex init_mutex = G_STATIC_MUTEX_INIT;
994 g_return_if_fail (mutex);
999 /* IMPLEMENTATION NOTE:
1001 * On some platforms a GStaticMutex is actually a normal GMutex stored
1002 * inside of a structure instead of being allocated dynamically. We can
1003 * only do this for platforms on which we know, in advance, how to
1004 * allocate (size) and initialise (value) that memory.
1006 * On other platforms, a GStaticMutex is nothing more than a pointer to
1007 * a GMutex. In that case, the first access we make to the static mutex
1008 * must first allocate the normal GMutex and store it into the pointer.
1010 * configure.ac writes macros into glibconfig.h to determine if
1011 * g_static_mutex_get_mutex() accesses the structure in memory directly
1012 * (on platforms where we are able to do that) or if it ends up here,
1013 * where we may have to allocate the GMutex before returning it.
1017 * g_static_mutex_get_mutex:
1018 * @mutex: a #GStaticMutex.
1019 * @Returns: the #GMutex corresponding to @mutex.
1021 * For some operations (like g_cond_wait()) you must have a #GMutex
1022 * instead of a #GStaticMutex. This function will return the
1023 * corresponding #GMutex for @mutex.
1026 g_static_mutex_get_mutex_impl (GMutex** mutex)
1030 if (!g_thread_supported ())
1033 result = g_atomic_pointer_get (mutex);
1037 g_mutex_lock (&g_once_mutex);
1042 result = g_mutex_new ();
1043 g_atomic_pointer_set (mutex, result);
1046 g_mutex_unlock (&g_once_mutex);
1052 /* IMPLEMENTATION NOTE:
1054 * g_static_mutex_lock(), g_static_mutex_trylock() and
1055 * g_static_mutex_unlock() are all preprocessor macros that wrap the
1056 * corresponding g_mutex_*() function around a call to
1057 * g_static_mutex_get_mutex().
1061 * g_static_mutex_lock:
1062 * @mutex: a #GStaticMutex.
1064 * Works like g_mutex_lock(), but for a #GStaticMutex.
1068 * g_static_mutex_trylock:
1069 * @mutex: a #GStaticMutex.
1070 * @Returns: %TRUE, if the #GStaticMutex could be locked.
1072 * Works like g_mutex_trylock(), but for a #GStaticMutex.
1076 * g_static_mutex_unlock:
1077 * @mutex: a #GStaticMutex.
1079 * Works like g_mutex_unlock(), but for a #GStaticMutex.
1083 * g_static_mutex_free:
1084 * @mutex: a #GStaticMutex to be freed.
1086 * Releases all resources allocated to @mutex.
1088 * You don't have to call this functions for a #GStaticMutex with an
1089 * unbounded lifetime, i.e. objects declared 'static', but if you have
1090 * a #GStaticMutex as a member of a structure and the structure is
1091 * freed, you should also free the #GStaticMutex.
1093 * <note><para>Calling g_static_mutex_free() on a locked mutex may
1094 * result in undefined behaviour.</para></note>
1097 g_static_mutex_free (GStaticMutex* mutex)
1099 GMutex **runtime_mutex;
1101 g_return_if_fail (mutex);
1103 /* The runtime_mutex is the first (or only) member of GStaticMutex,
1104 * see both versions (of glibconfig.h) in configure.ac. Note, that
1105 * this variable is NULL, if g_thread_init() hasn't been called or
1106 * if we're using the default thread implementation and it provides
1107 * static mutexes. */
1108 runtime_mutex = ((GMutex**)mutex);
1111 g_mutex_free (*runtime_mutex);
1113 *runtime_mutex = NULL;
1116 /* ------------------------------------------------------------------------ */
1121 * A #GStaticRecMutex works like a #GStaticMutex, but it can be locked
1122 * multiple times by one thread. If you enter it n times, you have to
1123 * unlock it n times again to let other threads lock it. An exception
1124 * is the function g_static_rec_mutex_unlock_full(): that allows you to
1125 * unlock a #GStaticRecMutex completely returning the depth, (i.e. the
1126 * number of times this mutex was locked). The depth can later be used
1127 * to restore the state of the #GStaticRecMutex by calling
1128 * g_static_rec_mutex_lock_full().
1130 * Even though #GStaticRecMutex is not opaque, it should only be used
1131 * with the following functions.
1133 * All of the <function>g_static_rec_mutex_*</function> functions can
1134 * be used even if g_thread_init() has not been called. Then they do
1135 * nothing, apart from <function>g_static_rec_mutex_trylock</function>,
1136 * which does nothing but returning %TRUE.
1140 * G_STATIC_REC_MUTEX_INIT:
1142 * A #GStaticRecMutex must be initialized with this macro before it can
1143 * be used. This macro can used be to initialize a variable, but it
1144 * cannot be assigned to a variable. In that case you have to use
1145 * g_static_rec_mutex_init().
1149 * GStaticRecMutex my_mutex = G_STATIC_REC_MUTEX_INIT;
1155 * g_static_rec_mutex_init:
1156 * @mutex: a #GStaticRecMutex to be initialized.
1158 * A #GStaticRecMutex must be initialized with this function before it
1159 * can be used. Alternatively you can initialize it with
1160 * #G_STATIC_REC_MUTEX_INIT.
1163 g_static_rec_mutex_init (GStaticRecMutex *mutex)
1165 static const GStaticRecMutex init_mutex = G_STATIC_REC_MUTEX_INIT;
1167 g_return_if_fail (mutex);
1169 *mutex = init_mutex;
1173 * g_static_rec_mutex_lock:
1174 * @mutex: a #GStaticRecMutex to lock.
1176 * Locks @mutex. If @mutex is already locked by another thread, the
1177 * current thread will block until @mutex is unlocked by the other
1178 * thread. If @mutex is already locked by the calling thread, this
1179 * functions increases the depth of @mutex and returns immediately.
1182 g_static_rec_mutex_lock (GStaticRecMutex* mutex)
1186 g_return_if_fail (mutex);
1188 if (!g_thread_supported ())
1191 g_system_thread_self (&self);
1193 if (g_system_thread_equal (&self, &mutex->owner))
1198 g_static_mutex_lock (&mutex->mutex);
1199 g_system_thread_assign (mutex->owner, self);
1204 * g_static_rec_mutex_trylock:
1205 * @mutex: a #GStaticRecMutex to lock.
1206 * @Returns: %TRUE, if @mutex could be locked.
1208 * Tries to lock @mutex. If @mutex is already locked by another thread,
1209 * it immediately returns %FALSE. Otherwise it locks @mutex and returns
1210 * %TRUE. If @mutex is already locked by the calling thread, this
1211 * functions increases the depth of @mutex and immediately returns
1215 g_static_rec_mutex_trylock (GStaticRecMutex* mutex)
1219 g_return_val_if_fail (mutex, FALSE);
1221 if (!g_thread_supported ())
1224 g_system_thread_self (&self);
1226 if (g_system_thread_equal (&self, &mutex->owner))
1232 if (!g_static_mutex_trylock (&mutex->mutex))
1235 g_system_thread_assign (mutex->owner, self);
1241 * g_static_rec_mutex_unlock:
1242 * @mutex: a #GStaticRecMutex to unlock.
1244 * Unlocks @mutex. Another thread will be allowed to lock @mutex only
1245 * when it has been unlocked as many times as it had been locked
1246 * before. If @mutex is completely unlocked and another thread is
1247 * blocked in a g_static_rec_mutex_lock() call for @mutex, it will be
1248 * woken and can lock @mutex itself.
1251 g_static_rec_mutex_unlock (GStaticRecMutex* mutex)
1253 g_return_if_fail (mutex);
1255 if (!g_thread_supported ())
1258 if (mutex->depth > 1)
1263 g_system_thread_assign (mutex->owner, zero_thread);
1264 g_static_mutex_unlock (&mutex->mutex);
1268 * g_static_rec_mutex_lock_full:
1269 * @mutex: a #GStaticRecMutex to lock.
1270 * @depth: number of times this mutex has to be unlocked to be
1271 * completely unlocked.
1273 * Works like calling g_static_rec_mutex_lock() for @mutex @depth times.
1276 g_static_rec_mutex_lock_full (GStaticRecMutex *mutex,
1280 g_return_if_fail (mutex);
1282 if (!g_thread_supported ())
1288 g_system_thread_self (&self);
1290 if (g_system_thread_equal (&self, &mutex->owner))
1292 mutex->depth += depth;
1295 g_static_mutex_lock (&mutex->mutex);
1296 g_system_thread_assign (mutex->owner, self);
1297 mutex->depth = depth;
1301 * g_static_rec_mutex_unlock_full:
1302 * @mutex: a #GStaticRecMutex to completely unlock.
1303 * @Returns: number of times @mutex has been locked by the current
1306 * Completely unlocks @mutex. If another thread is blocked in a
1307 * g_static_rec_mutex_lock() call for @mutex, it will be woken and can
1308 * lock @mutex itself. This function returns the number of times that
1309 * @mutex has been locked by the current thread. To restore the state
1310 * before the call to g_static_rec_mutex_unlock_full() you can call
1311 * g_static_rec_mutex_lock_full() with the depth returned by this
1315 g_static_rec_mutex_unlock_full (GStaticRecMutex *mutex)
1319 g_return_val_if_fail (mutex, 0);
1321 if (!g_thread_supported ())
1324 depth = mutex->depth;
1326 g_system_thread_assign (mutex->owner, zero_thread);
1328 g_static_mutex_unlock (&mutex->mutex);
1334 * g_static_rec_mutex_free:
1335 * @mutex: a #GStaticRecMutex to be freed.
1337 * Releases all resources allocated to a #GStaticRecMutex.
1339 * You don't have to call this functions for a #GStaticRecMutex with an
1340 * unbounded lifetime, i.e. objects declared 'static', but if you have
1341 * a #GStaticRecMutex as a member of a structure and the structure is
1342 * freed, you should also free the #GStaticRecMutex.
1345 g_static_rec_mutex_free (GStaticRecMutex *mutex)
1347 g_return_if_fail (mutex);
1349 g_static_mutex_free (&mutex->mutex);
1352 /* GStaticPrivate {{{1 ---------------------------------------------------- */
1357 * A #GStaticPrivate works almost like a #GPrivate, but it has one
1358 * significant advantage. It doesn't need to be created at run-time
1359 * like a #GPrivate, but can be defined at compile-time. This is
1360 * similar to the difference between #GMutex and #GStaticMutex. Now
1361 * look at our <function>give_me_next_number()</function> example with
1365 * <title>Using GStaticPrivate for per-thread data</title>
1368 * give_me_next_number (<!-- -->)
1370 * static GStaticPrivate current_number_key = G_STATIC_PRIVATE_INIT;
1371 * int *current_number = g_static_private_get (&current_number_key);
1373 * if (!current_number)
1375 * current_number = g_new (int,1);
1376 * *current_number = 0;
1377 * g_static_private_set (&current_number_key, current_number, g_free);
1380 * *current_number = calc_next_number (*current_number);
1382 * return *current_number;
1389 * G_STATIC_PRIVATE_INIT:
1391 * Every #GStaticPrivate must be initialized with this macro, before it
1396 * GStaticPrivate my_private = G_STATIC_PRIVATE_INIT;
1398 * </informalexample>
1402 * g_static_private_init:
1403 * @private_key: a #GStaticPrivate to be initialized.
1405 * Initializes @private_key. Alternatively you can initialize it with
1406 * #G_STATIC_PRIVATE_INIT.
1409 g_static_private_init (GStaticPrivate *private_key)
1411 private_key->index = 0;
1415 * g_static_private_get:
1416 * @private_key: a #GStaticPrivate.
1417 * @Returns: the corresponding pointer.
1419 * Works like g_private_get() only for a #GStaticPrivate.
1421 * This function works even if g_thread_init() has not yet been called.
1424 g_static_private_get (GStaticPrivate *private_key)
1426 GRealThread *self = (GRealThread*) g_thread_self ();
1428 gpointer ret = NULL;
1430 LOCK_PRIVATE_DATA (self);
1432 array = self->private_data;
1434 if (array && private_key->index != 0 && private_key->index <= array->len)
1435 ret = g_array_index (array, GStaticPrivateNode,
1436 private_key->index - 1).data;
1438 UNLOCK_PRIVATE_DATA (self);
1443 * g_static_private_set:
1444 * @private_key: a #GStaticPrivate.
1445 * @data: the new pointer.
1446 * @notify: a function to be called with the pointer whenever the
1447 * current thread ends or sets this pointer again.
1449 * Sets the pointer keyed to @private_key for the current thread and
1450 * the function @notify to be called with that pointer (%NULL or
1451 * non-%NULL), whenever the pointer is set again or whenever the
1452 * current thread ends.
1454 * This function works even if g_thread_init() has not yet been called.
1455 * If g_thread_init() is called later, the @data keyed to @private_key
1456 * will be inherited only by the main thread, i.e. the one that called
1459 * <note><para>@notify is used quite differently from @destructor in
1460 * g_private_new().</para></note>
1463 g_static_private_set (GStaticPrivate *private_key,
1465 GDestroyNotify notify)
1467 GRealThread *self = (GRealThread*) g_thread_self ();
1469 static guint next_index = 0;
1470 GStaticPrivateNode *node;
1471 gpointer ddata = NULL;
1472 GDestroyNotify ddestroy = NULL;
1474 if (!private_key->index)
1478 if (!private_key->index)
1480 if (g_thread_free_indices)
1482 private_key->index =
1483 GPOINTER_TO_UINT (g_thread_free_indices->data);
1484 g_thread_free_indices =
1485 g_slist_delete_link (g_thread_free_indices,
1486 g_thread_free_indices);
1489 private_key->index = ++next_index;
1492 G_UNLOCK (g_thread);
1495 LOCK_PRIVATE_DATA (self);
1497 array = self->private_data;
1500 array = g_array_new (FALSE, TRUE, sizeof (GStaticPrivateNode));
1501 self->private_data = array;
1504 if (private_key->index > array->len)
1505 g_array_set_size (array, private_key->index);
1507 node = &g_array_index (array, GStaticPrivateNode, private_key->index - 1);
1510 ddestroy = node->destroy;
1513 node->destroy = notify;
1515 UNLOCK_PRIVATE_DATA (self);
1522 * g_static_private_free:
1523 * @private_key: a #GStaticPrivate to be freed.
1525 * Releases all resources allocated to @private_key.
1527 * You don't have to call this functions for a #GStaticPrivate with an
1528 * unbounded lifetime, i.e. objects declared 'static', but if you have
1529 * a #GStaticPrivate as a member of a structure and the structure is
1530 * freed, you should also free the #GStaticPrivate.
1533 g_static_private_free (GStaticPrivate *private_key)
1535 guint idx = private_key->index;
1536 GRealThread *thread, *next;
1537 GArray *garbage = NULL;
1542 private_key->index = 0;
1546 thread = g_thread_all_threads;
1548 for (thread = g_thread_all_threads; thread; thread = next)
1552 next = thread->next;
1554 LOCK_PRIVATE_DATA (thread);
1556 array = thread->private_data;
1558 if (array && idx <= array->len)
1560 GStaticPrivateNode *node = &g_array_index (array,
1563 gpointer ddata = node->data;
1564 GDestroyNotify ddestroy = node->destroy;
1567 node->destroy = NULL;
1571 /* defer non-trivial destruction til after we've finished
1572 * iterating, since we must continue to hold the lock */
1573 if (garbage == NULL)
1574 garbage = g_array_new (FALSE, TRUE,
1575 sizeof (GStaticPrivateNode));
1577 g_array_set_size (garbage, garbage->len + 1);
1579 node = &g_array_index (garbage, GStaticPrivateNode,
1582 node->destroy = ddestroy;
1586 UNLOCK_PRIVATE_DATA (thread);
1588 g_thread_free_indices = g_slist_prepend (g_thread_free_indices,
1589 GUINT_TO_POINTER (idx));
1590 G_UNLOCK (g_thread);
1596 for (i = 0; i < garbage->len; i++)
1598 GStaticPrivateNode *node;
1600 node = &g_array_index (garbage, GStaticPrivateNode, i);
1601 node->destroy (node->data);
1604 g_array_free (garbage, TRUE);
1608 /* GThread Extra Functions {{{1 ------------------------------------------- */
1610 g_thread_cleanup (gpointer data)
1614 GRealThread* thread = data;
1617 LOCK_PRIVATE_DATA (thread);
1618 array = thread->private_data;
1619 thread->private_data = NULL;
1620 UNLOCK_PRIVATE_DATA (thread);
1626 for (i = 0; i < array->len; i++ )
1628 GStaticPrivateNode *node =
1629 &g_array_index (array, GStaticPrivateNode, i);
1631 node->destroy (node->data);
1633 g_array_free (array, TRUE);
1636 /* We only free the thread structure, if it isn't joinable. If
1637 it is, the structure is freed in g_thread_join */
1638 if (!thread->thread.joinable)
1643 for (t = g_thread_all_threads, p = NULL; t; p = t, t = t->next)
1650 g_thread_all_threads = t->next;
1654 G_UNLOCK (g_thread);
1656 /* Just to make sure, this isn't used any more */
1657 g_system_thread_assign (thread->system_thread, zero_thread);
1664 g_thread_fail (void)
1666 g_error ("The thread system is not yet initialized.");
1669 #define G_NSEC_PER_SEC 1000000000
1674 return g_get_monotonic_time () * 1000;
1678 g_thread_create_proxy (gpointer data)
1680 GRealThread* thread = data;
1684 /* This has to happen before G_LOCK, as that might call g_thread_self */
1685 g_private_set (&g_thread_specific_private, data);
1687 /* the lock makes sure, that thread->system_thread is written,
1688 before thread->thread.func is called. See g_thread_create. */
1690 G_UNLOCK (g_thread);
1692 thread->retval = thread->thread.func (thread->thread.data);
1699 * @func: a function to execute in the new thread
1700 * @data: an argument to supply to the new thread
1701 * @joinable: should this thread be joinable?
1702 * @error: return location for error, or %NULL
1704 * This function creates a new thread.
1706 * If @joinable is %TRUE, you can wait for this threads termination
1707 * calling g_thread_join(). Otherwise the thread will just disappear
1708 * when it terminates.
1710 * The new thread executes the function @func with the argument @data.
1711 * If the thread was created successfully, it is returned.
1713 * @error can be %NULL to ignore errors, or non-%NULL to report errors.
1714 * The error is set, if and only if the function returns %NULL.
1716 * Returns: the new #GThread on success
1720 * g_thread_create_full:
1721 * @func: a function to execute in the new thread.
1722 * @data: an argument to supply to the new thread.
1723 * @stack_size: a stack size for the new thread.
1724 * @joinable: should this thread be joinable?
1725 * @bound: should this thread be bound to a system thread?
1726 * @priority: ignored
1727 * @error: return location for error.
1728 * @Returns: the new #GThread on success.
1730 * This function creates a new thread. If the underlying thread
1731 * implementation supports it, the thread gets a stack size of
1732 * @stack_size or the default value for the current platform, if
1735 * If @joinable is %TRUE, you can wait for this threads termination
1736 * calling g_thread_join(). Otherwise the thread will just disappear
1737 * when it terminates. If @bound is %TRUE, this thread will be
1738 * scheduled in the system scope, otherwise the implementation is free
1739 * to do scheduling in the process scope. The first variant is more
1740 * expensive resource-wise, but generally faster. On some systems (e.g.
1741 * Linux) all threads are bound.
1743 * The new thread executes the function @func with the argument @data.
1744 * If the thread was created successfully, it is returned.
1746 * @error can be %NULL to ignore errors, or non-%NULL to report errors.
1747 * The error is set, if and only if the function returns %NULL.
1749 * <note><para>Only use g_thread_create_full() if you really can't use
1750 * g_thread_create() instead. g_thread_create() does not take
1751 * @stack_size, @bound, and @priority as arguments, as they should only
1752 * be used in cases in which it is unavoidable.</para></note>
1755 g_thread_create_full (GThreadFunc func,
1760 GThreadPriority priority,
1763 GRealThread* result;
1764 GError *local_error = NULL;
1765 g_return_val_if_fail (func, NULL);
1767 result = g_new0 (GRealThread, 1);
1769 result->thread.joinable = joinable;
1770 result->thread.func = func;
1771 result->thread.data = data;
1772 result->private_data = NULL;
1774 g_system_thread_create (g_thread_create_proxy, result,
1775 stack_size, joinable, bound, 0,
1776 &result->system_thread, &local_error);
1779 result->next = g_thread_all_threads;
1780 g_thread_all_threads = result;
1782 G_UNLOCK (g_thread);
1786 g_propagate_error (error, local_error);
1791 return (GThread*) result;
1796 * @retval: the return value of this thread.
1798 * Exits the current thread. If another thread is waiting for that
1799 * thread using g_thread_join() and the current thread is joinable, the
1800 * waiting thread will be woken up and get @retval as the return value
1801 * of g_thread_join(). If the current thread is not joinable, @retval
1802 * is ignored. Calling
1805 * g_thread_exit (retval);
1808 * is equivalent to returning @retval from the function @func, as given
1809 * to g_thread_create().
1811 * <note><para>Never call g_thread_exit() from within a thread of a
1812 * #GThreadPool, as that will mess up the bookkeeping and lead to funny
1813 * and unwanted results.</para></note>
1816 g_thread_exit (gpointer retval)
1818 GRealThread* real = (GRealThread*) g_thread_self ();
1819 real->retval = retval;
1821 g_system_thread_exit ();
1826 * @thread: a #GThread to be waited for.
1827 * @Returns: the return value of the thread.
1829 * Waits until @thread finishes, i.e. the function @func, as given to
1830 * g_thread_create(), returns or g_thread_exit() is called by @thread.
1831 * All resources of @thread including the #GThread struct are released.
1832 * @thread must have been created with @joinable=%TRUE in
1833 * g_thread_create(). The value returned by @func or given to
1834 * g_thread_exit() by @thread is returned by this function.
1837 g_thread_join (GThread* thread)
1839 GRealThread* real = (GRealThread*) thread;
1843 g_return_val_if_fail (thread, NULL);
1844 g_return_val_if_fail (thread->joinable, NULL);
1845 g_return_val_if_fail (!g_system_thread_equal (&real->system_thread, &zero_thread), NULL);
1847 g_system_thread_join (&real->system_thread);
1849 retval = real->retval;
1852 for (t = g_thread_all_threads, p = NULL; t; p = t, t = t->next)
1854 if (t == (GRealThread*) thread)
1859 g_thread_all_threads = t->next;
1863 G_UNLOCK (g_thread);
1865 /* Just to make sure, this isn't used any more */
1866 thread->joinable = 0;
1867 g_system_thread_assign (real->system_thread, zero_thread);
1869 /* the thread structure for non-joinable threads is freed upon
1870 thread end. We free the memory here. This will leave a loose end,
1871 if a joinable thread is not joined. */
1879 * g_thread_set_priority:
1880 * @thread: a #GThread.
1881 * @priority: ignored
1883 * This function does nothing.
1885 * Deprecated:2.32: Thread priorities no longer have any effect.
1888 g_thread_set_priority (GThread *thread,
1889 GThreadPriority priority)
1895 * @Returns: the current thread.
1897 * This functions returns the #GThread corresponding to the calling
1901 g_thread_self (void)
1903 GRealThread* thread = g_private_get (&g_thread_specific_private);
1907 /* If no thread data is available, provide and set one. This
1908 can happen for the main thread and for threads, that are not
1910 thread = g_new0 (GRealThread, 1);
1911 thread->thread.joinable = FALSE; /* This is a save guess */
1912 thread->thread.func = NULL;
1913 thread->thread.data = NULL;
1914 thread->private_data = NULL;
1916 g_system_thread_self (&thread->system_thread);
1918 g_private_set (&g_thread_specific_private, thread);
1921 thread->next = g_thread_all_threads;
1922 g_thread_all_threads = thread;
1923 G_UNLOCK (g_thread);
1926 return (GThread*)thread;
1929 /* GStaticRWLock {{{1 ----------------------------------------------------- */
1934 * The #GStaticRWLock struct represents a read-write lock. A read-write
1935 * lock can be used for protecting data that some portions of code only
1936 * read from, while others also write. In such situations it is
1937 * desirable that several readers can read at once, whereas of course
1938 * only one writer may write at a time. Take a look at the following
1942 * <title>An array with access functions</title>
1944 * GStaticRWLock rwlock = G_STATIC_RW_LOCK_INIT;
1948 * my_array_get (guint index)
1950 * gpointer retval = NULL;
1955 * g_static_rw_lock_reader_lock (&rwlock);
1956 * if (index < array->len)
1957 * retval = g_ptr_array_index (array, index);
1958 * g_static_rw_lock_reader_unlock (&rwlock);
1964 * my_array_set (guint index, gpointer data)
1966 * g_static_rw_lock_writer_lock (&rwlock);
1969 * array = g_ptr_array_new (<!-- -->);
1971 * if (index >= array->len)
1972 * g_ptr_array_set_size (array, index+1);
1973 * g_ptr_array_index (array, index) = data;
1975 * g_static_rw_lock_writer_unlock (&rwlock);
1980 * This example shows an array which can be accessed by many readers
1981 * (the <function>my_array_get()</function> function) simultaneously,
1982 * whereas the writers (the <function>my_array_set()</function>
1983 * function) will only be allowed once at a time and only if no readers
1984 * currently access the array. This is because of the potentially
1985 * dangerous resizing of the array. Using these functions is fully
1986 * multi-thread safe now.
1988 * Most of the time, writers should have precedence over readers. That
1989 * means, for this implementation, that as soon as a writer wants to
1990 * lock the data, no other reader is allowed to lock the data, whereas,
1991 * of course, the readers that already have locked the data are allowed
1992 * to finish their operation. As soon as the last reader unlocks the
1993 * data, the writer will lock it.
1995 * Even though #GStaticRWLock is not opaque, it should only be used
1996 * with the following functions.
1998 * All of the <function>g_static_rw_lock_*</function> functions can be
1999 * used even if g_thread_init() has not been called. Then they do
2000 * nothing, apart from <function>g_static_rw_lock_*_trylock</function>,
2001 * which does nothing but returning %TRUE.
2003 * <note><para>A read-write lock has a higher overhead than a mutex. For
2004 * example, both g_static_rw_lock_reader_lock() and
2005 * g_static_rw_lock_reader_unlock() have to lock and unlock a
2006 * #GStaticMutex, so it takes at least twice the time to lock and unlock
2007 * a #GStaticRWLock that it does to lock and unlock a #GStaticMutex. So
2008 * only data structures that are accessed by multiple readers, and which
2009 * keep the lock for a considerable time justify a #GStaticRWLock. The
2010 * above example most probably would fare better with a
2011 * #GStaticMutex.</para></note>
2015 * G_STATIC_RW_LOCK_INIT:
2017 * A #GStaticRWLock must be initialized with this macro before it can
2018 * be used. This macro can used be to initialize a variable, but it
2019 * cannot be assigned to a variable. In that case you have to use
2020 * g_static_rw_lock_init().
2024 * GStaticRWLock my_lock = G_STATIC_RW_LOCK_INIT;
2026 * </informalexample>
2030 * g_static_rw_lock_init:
2031 * @lock: a #GStaticRWLock to be initialized.
2033 * A #GStaticRWLock must be initialized with this function before it
2034 * can be used. Alternatively you can initialize it with
2035 * #G_STATIC_RW_LOCK_INIT.
2038 g_static_rw_lock_init (GStaticRWLock* lock)
2040 static const GStaticRWLock init_lock = G_STATIC_RW_LOCK_INIT;
2042 g_return_if_fail (lock);
2048 g_static_rw_lock_wait (GCond** cond, GStaticMutex* mutex)
2051 *cond = g_cond_new ();
2052 g_cond_wait (*cond, g_static_mutex_get_mutex (mutex));
2056 g_static_rw_lock_signal (GStaticRWLock* lock)
2058 if (lock->want_to_write && lock->write_cond)
2059 g_cond_signal (lock->write_cond);
2060 else if (lock->want_to_read && lock->read_cond)
2061 g_cond_broadcast (lock->read_cond);
2065 * g_static_rw_lock_reader_lock:
2066 * @lock: a #GStaticRWLock to lock for reading.
2068 * Locks @lock for reading. There may be unlimited concurrent locks for
2069 * reading of a #GStaticRWLock at the same time. If @lock is already
2070 * locked for writing by another thread or if another thread is already
2071 * waiting to lock @lock for writing, this function will block until
2072 * @lock is unlocked by the other writing thread and no other writing
2073 * threads want to lock @lock. This lock has to be unlocked by
2074 * g_static_rw_lock_reader_unlock().
2076 * #GStaticRWLock is not recursive. It might seem to be possible to
2077 * recursively lock for reading, but that can result in a deadlock, due
2078 * to writer preference.
2081 g_static_rw_lock_reader_lock (GStaticRWLock* lock)
2083 g_return_if_fail (lock);
2085 if (!g_threads_got_initialized)
2088 g_static_mutex_lock (&lock->mutex);
2089 lock->want_to_read++;
2090 while (lock->have_writer || lock->want_to_write)
2091 g_static_rw_lock_wait (&lock->read_cond, &lock->mutex);
2092 lock->want_to_read--;
2093 lock->read_counter++;
2094 g_static_mutex_unlock (&lock->mutex);
2098 * g_static_rw_lock_reader_trylock:
2099 * @lock: a #GStaticRWLock to lock for reading.
2100 * @Returns: %TRUE, if @lock could be locked for reading.
2102 * Tries to lock @lock for reading. If @lock is already locked for
2103 * writing by another thread or if another thread is already waiting to
2104 * lock @lock for writing, immediately returns %FALSE. Otherwise locks
2105 * @lock for reading and returns %TRUE. This lock has to be unlocked by
2106 * g_static_rw_lock_reader_unlock().
2109 g_static_rw_lock_reader_trylock (GStaticRWLock* lock)
2111 gboolean ret_val = FALSE;
2113 g_return_val_if_fail (lock, FALSE);
2115 if (!g_threads_got_initialized)
2118 g_static_mutex_lock (&lock->mutex);
2119 if (!lock->have_writer && !lock->want_to_write)
2121 lock->read_counter++;
2124 g_static_mutex_unlock (&lock->mutex);
2129 * g_static_rw_lock_reader_unlock:
2130 * @lock: a #GStaticRWLock to unlock after reading.
2132 * Unlocks @lock. If a thread waits to lock @lock for writing and all
2133 * locks for reading have been unlocked, the waiting thread is woken up
2134 * and can lock @lock for writing.
2137 g_static_rw_lock_reader_unlock (GStaticRWLock* lock)
2139 g_return_if_fail (lock);
2141 if (!g_threads_got_initialized)
2144 g_static_mutex_lock (&lock->mutex);
2145 lock->read_counter--;
2146 if (lock->read_counter == 0)
2147 g_static_rw_lock_signal (lock);
2148 g_static_mutex_unlock (&lock->mutex);
2152 * g_static_rw_lock_writer_lock:
2153 * @lock: a #GStaticRWLock to lock for writing.
2155 * Locks @lock for writing. If @lock is already locked for writing or
2156 * reading by other threads, this function will block until @lock is
2157 * completely unlocked and then lock @lock for writing. While this
2158 * functions waits to lock @lock, no other thread can lock @lock for
2159 * reading. When @lock is locked for writing, no other thread can lock
2160 * @lock (neither for reading nor writing). This lock has to be
2161 * unlocked by g_static_rw_lock_writer_unlock().
2164 g_static_rw_lock_writer_lock (GStaticRWLock* lock)
2166 g_return_if_fail (lock);
2168 if (!g_threads_got_initialized)
2171 g_static_mutex_lock (&lock->mutex);
2172 lock->want_to_write++;
2173 while (lock->have_writer || lock->read_counter)
2174 g_static_rw_lock_wait (&lock->write_cond, &lock->mutex);
2175 lock->want_to_write--;
2176 lock->have_writer = TRUE;
2177 g_static_mutex_unlock (&lock->mutex);
2181 * g_static_rw_lock_writer_trylock:
2182 * @lock: a #GStaticRWLock to lock for writing.
2183 * @Returns: %TRUE, if @lock could be locked for writing.
2185 * Tries to lock @lock for writing. If @lock is already locked (for
2186 * either reading or writing) by another thread, it immediately returns
2187 * %FALSE. Otherwise it locks @lock for writing and returns %TRUE. This
2188 * lock has to be unlocked by g_static_rw_lock_writer_unlock().
2191 g_static_rw_lock_writer_trylock (GStaticRWLock* lock)
2193 gboolean ret_val = FALSE;
2195 g_return_val_if_fail (lock, FALSE);
2197 if (!g_threads_got_initialized)
2200 g_static_mutex_lock (&lock->mutex);
2201 if (!lock->have_writer && !lock->read_counter)
2203 lock->have_writer = TRUE;
2206 g_static_mutex_unlock (&lock->mutex);
2211 * g_static_rw_lock_writer_unlock:
2212 * @lock: a #GStaticRWLock to unlock after writing.
2214 * Unlocks @lock. If a thread is waiting to lock @lock for writing and
2215 * all locks for reading have been unlocked, the waiting thread is
2216 * woken up and can lock @lock for writing. If no thread is waiting to
2217 * lock @lock for writing, and some thread or threads are waiting to
2218 * lock @lock for reading, the waiting threads are woken up and can
2219 * lock @lock for reading.
2222 g_static_rw_lock_writer_unlock (GStaticRWLock* lock)
2224 g_return_if_fail (lock);
2226 if (!g_threads_got_initialized)
2229 g_static_mutex_lock (&lock->mutex);
2230 lock->have_writer = FALSE;
2231 g_static_rw_lock_signal (lock);
2232 g_static_mutex_unlock (&lock->mutex);
2236 * g_static_rw_lock_free:
2237 * @lock: a #GStaticRWLock to be freed.
2239 * Releases all resources allocated to @lock.
2241 * You don't have to call this functions for a #GStaticRWLock with an
2242 * unbounded lifetime, i.e. objects declared 'static', but if you have
2243 * a #GStaticRWLock as a member of a structure, and the structure is
2244 * freed, you should also free the #GStaticRWLock.
2247 g_static_rw_lock_free (GStaticRWLock* lock)
2249 g_return_if_fail (lock);
2251 if (lock->read_cond)
2253 g_cond_free (lock->read_cond);
2254 lock->read_cond = NULL;
2256 if (lock->write_cond)
2258 g_cond_free (lock->write_cond);
2259 lock->write_cond = NULL;
2261 g_static_mutex_free (&lock->mutex);
2264 /* Unsorted {{{1 ---------------------------------------------------------- */
2268 * @thread_func: function to call for all GThread structures
2269 * @user_data: second argument to @thread_func
2271 * Call @thread_func on all existing #GThread structures. Note that
2272 * threads may decide to exit while @thread_func is running, so
2273 * without intimate knowledge about the lifetime of foreign threads,
2274 * @thread_func shouldn't access the GThread* pointer passed in as
2275 * first argument. However, @thread_func will not be called for threads
2276 * which are known to have exited already.
2278 * Due to thread lifetime checks, this function has an execution complexity
2279 * which is quadratic in the number of existing threads.
2284 g_thread_foreach (GFunc thread_func,
2287 GSList *slist = NULL;
2288 GRealThread *thread;
2289 g_return_if_fail (thread_func != NULL);
2290 /* snapshot the list of threads for iteration */
2292 for (thread = g_thread_all_threads; thread; thread = thread->next)
2293 slist = g_slist_prepend (slist, thread);
2294 G_UNLOCK (g_thread);
2295 /* walk the list, skipping non-existent threads */
2298 GSList *node = slist;
2300 /* check whether the current thread still exists */
2302 for (thread = g_thread_all_threads; thread; thread = thread->next)
2303 if (thread == node->data)
2305 G_UNLOCK (g_thread);
2307 thread_func (thread, user_data);
2308 g_slist_free_1 (node);
2313 * g_thread_get_initialized:
2315 * Indicates if g_thread_init() has been called.
2317 * Returns: %TRUE if threads have been initialized.
2322 g_thread_get_initialized ()
2324 return g_thread_supported ();
2330 * Creates a new #GMutex.
2332 * Returns: a newly allocated #GMutex. Use g_mutex_free() to free
2339 mutex = g_slice_new (GMutex);
2340 g_mutex_init (mutex);
2349 * Destroys a @mutex that has been created with g_mutex_new().
2351 * <note>Calling g_mutex_free() on a locked mutex may result
2352 * in undefined behaviour.</note>
2355 g_mutex_free (GMutex *mutex)
2357 g_mutex_clear (mutex);
2358 g_slice_free (GMutex, mutex);
2364 * Creates a new #GCond.
2366 * Returns: a newly allocated #GCond. Free with g_cond_free()
2373 cond = g_slice_new (GCond);
2383 * Destroys a #GCond that has been created with g_cond_new().
2386 g_cond_free (GCond *cond)
2388 g_cond_clear (cond);
2389 g_slice_free (GCond, cond);
2394 * @destructor: a function to destroy the data keyed to
2395 * the #GPrivate when a thread ends
2397 * Creates a new #GPrivate. If @destructor is non-%NULL, it is a
2398 * pointer to a destructor function. Whenever a thread ends and the
2399 * corresponding pointer keyed to this instance of #GPrivate is
2400 * non-%NULL, the destructor is called with this pointer as the
2404 * #GStaticPrivate is a better choice for most uses.
2407 * <note><para>@destructor is used quite differently from @notify in
2408 * g_static_private_set().</para></note>
2410 * <note><para>A #GPrivate cannot be freed. Reuse it instead, if you
2411 * can, to avoid shortage, or use #GStaticPrivate.</para></note>
2413 * <note><para>This function will abort if g_thread_init() has not been
2414 * called yet.</para></note>
2416 * Returns: a newly allocated #GPrivate
2419 g_private_new (GDestroyNotify notify)
2423 key = g_slice_new (GPrivate);
2424 g_private_init (key, notify);
2429 GThreadFunctions g_thread_functions_for_glib_use =