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.
459 * <note><para>All of the <function>g_mutex_*</function> functions are
460 * actually macros. Apart from taking their addresses, you can however
461 * use them as if they were functions.</para></note>
466 * @Returns: a new #GMutex.
468 * Creates a new #GMutex.
470 * <note><para>This function will abort if g_thread_init() has not been
471 * called yet.</para></note>
473 (GMutex*(*)())g_thread_fail,
479 * Locks @mutex. If @mutex is already locked by another thread, the
480 * current thread will block until @mutex is unlocked by the other
483 * This function can be used even if g_thread_init() has not yet been
484 * called, and, in that case, will do nothing.
486 * <note><para>#GMutex is neither guaranteed to be recursive nor to be
487 * non-recursive, i.e. a thread could deadlock while calling
488 * g_mutex_lock(), if it already has locked @mutex. Use
489 * #GStaticRecMutex, if you need recursive mutexes.</para></note>
496 * @Returns: %TRUE, if @mutex could be locked.
498 * Tries to lock @mutex. If @mutex is already locked by another thread,
499 * it immediately returns %FALSE. Otherwise it locks @mutex and returns
502 * This function can be used even if g_thread_init() has not yet been
503 * called, and, in that case, will immediately return %TRUE.
505 * <note><para>#GMutex is neither guaranteed to be recursive nor to be
506 * non-recursive, i.e. the return value of g_mutex_trylock() could be
507 * both %FALSE or %TRUE, if the current thread already has locked
508 * @mutex. Use #GStaticRecMutex, if you need recursive
509 * mutexes.</para></note>
517 * Unlocks @mutex. If another thread is blocked in a g_mutex_lock()
518 * call for @mutex, it will be woken and can lock @mutex itself.
520 * This function can be used even if g_thread_init() has not yet been
521 * called, and, in that case, will do nothing.
531 * <note><para>Calling g_mutex_free() on a locked mutex may result in
532 * undefined behaviour.</para></note>
536 /* GCond Virtual Functions {{{2 ------------------------------------------ */
541 * The #GCond struct is an opaque data structure that represents a
542 * condition. Threads can block on a #GCond if they find a certain
543 * condition to be false. If other threads change the state of this
544 * condition they signal the #GCond, and that causes the waiting
545 * threads to be woken up.
549 * Using GCond to block a thread until a condition is satisfied
552 * GCond* data_cond = NULL; /<!-- -->* Must be initialized somewhere *<!-- -->/
553 * GMutex* data_mutex = NULL; /<!-- -->* Must be initialized somewhere *<!-- -->/
554 * gpointer current_data = NULL;
557 * push_data (gpointer data)
559 * g_mutex_lock (data_mutex);
560 * current_data = data;
561 * g_cond_signal (data_cond);
562 * g_mutex_unlock (data_mutex);
570 * g_mutex_lock (data_mutex);
571 * while (!current_data)
572 * g_cond_wait (data_cond, data_mutex);
573 * data = current_data;
574 * current_data = NULL;
575 * g_mutex_unlock (data_mutex);
582 * Whenever a thread calls <function>pop_data()</function> now, it will
583 * wait until current_data is non-%NULL, i.e. until some other thread
584 * has called <function>push_data()</function>.
586 * <note><para>It is important to use the g_cond_wait() and
587 * g_cond_timed_wait() functions only inside a loop which checks for the
588 * condition to be true. It is not guaranteed that the waiting thread
589 * will find the condition fulfilled after it wakes up, even if the
590 * signaling thread left the condition in that state: another thread may
591 * have altered the condition before the waiting thread got the chance
592 * to be woken up, even if the condition itself is protected by a
593 * #GMutex, like above.</para></note>
595 * A #GCond should only be accessed via the following functions.
597 * <note><para>All of the <function>g_cond_*</function> functions are
598 * actually macros. Apart from taking their addresses, you can however
599 * use them as if they were functions.</para></note>
604 * @Returns: a new #GCond.
606 * Creates a new #GCond. This function will abort, if g_thread_init()
607 * has not been called yet.
609 (GCond*(*)())g_thread_fail,
615 * If threads are waiting for @cond, exactly one of them is woken up.
616 * It is good practice to hold the same lock as the waiting thread
617 * while calling this function, though not required.
619 * This function can be used even if g_thread_init() has not yet been
620 * called, and, in that case, will do nothing.
628 * If threads are waiting for @cond, all of them are woken up. It is
629 * good practice to lock the same mutex as the waiting threads, while
630 * calling this function, though not required.
632 * This function can be used even if g_thread_init() has not yet been
633 * called, and, in that case, will do nothing.
640 * @mutex: a #GMutex, that is currently locked.
642 * Waits until this thread is woken up on @cond. The @mutex is unlocked
643 * before falling asleep and locked again before resuming.
645 * This function can be used even if g_thread_init() has not yet been
646 * called, and, in that case, will immediately return.
653 * @mutex: a #GMutex that is currently locked.
654 * @abs_time: a #GTimeVal, determining the final time.
655 * @Returns: %TRUE if @cond was signalled, or %FALSE on timeout.
657 * Waits until this thread is woken up on @cond, but not longer than
658 * until the time specified by @abs_time. The @mutex is unlocked before
659 * falling asleep and locked again before resuming.
661 * If @abs_time is %NULL, g_cond_timed_wait() acts like g_cond_wait().
663 * This function can be used even if g_thread_init() has not yet been
664 * called, and, in that case, will immediately return %TRUE.
666 * To easily calculate @abs_time a combination of g_get_current_time()
667 * and g_time_val_add() can be used.
675 * Destroys the #GCond.
679 /* GPrivate Virtual Functions {{{2 --------------------------------------- */
685 * #GStaticPrivate is a better choice for most uses.
688 * The #GPrivate struct is an opaque data structure to represent a
689 * thread private data key. Threads can thereby obtain and set a
690 * pointer which is private to the current thread. Take our
691 * <function>give_me_next_number(<!-- -->)</function> example from
692 * above. Suppose we don't want <literal>current_number</literal> to be
693 * shared between the threads, but instead to be private to each thread.
694 * This can be done as follows:
697 * <title>Using GPrivate for per-thread data</title>
699 * GPrivate* current_number_key = NULL; /<!-- -->* Must be initialized somewhere
700 * with g_private_new (g_free); *<!-- -->/
703 * give_me_next_number (void)
705 * int *current_number = g_private_get (current_number_key);
707 * if (!current_number)
709 * current_number = g_new (int, 1);
710 * *current_number = 0;
711 * g_private_set (current_number_key, current_number);
714 * *current_number = calc_next_number (*current_number);
716 * return *current_number;
721 * Here the pointer belonging to the key
722 * <literal>current_number_key</literal> is read. If it is %NULL, it has
723 * not been set yet. Then get memory for an integer value, assign this
724 * memory to the pointer and write the pointer back. Now we have an
725 * integer value that is private to the current thread.
727 * The #GPrivate struct should only be accessed via the following
730 * <note><para>All of the <function>g_private_*</function> functions are
731 * actually macros. Apart from taking their addresses, you can however
732 * use them as if they were functions.</para></note>
737 * @destructor: a function to destroy the data keyed to #GPrivate when
739 * @Returns: a new #GPrivate.
741 * Creates a new #GPrivate. If @destructor is non-%NULL, it is a
742 * pointer to a destructor function. Whenever a thread ends and the
743 * corresponding pointer keyed to this instance of #GPrivate is
744 * non-%NULL, the destructor is called with this pointer as the
748 * #GStaticPrivate is a better choice for most uses.
751 * <note><para>@destructor is used quite differently from @notify in
752 * g_static_private_set().</para></note>
754 * <note><para>A #GPrivate cannot be freed. Reuse it instead, if you
755 * can, to avoid shortage, or use #GStaticPrivate.</para></note>
757 * <note><para>This function will abort if g_thread_init() has not been
758 * called yet.</para></note>
760 (GPrivate*(*)(GDestroyNotify))g_thread_fail,
764 * @private_key: a #GPrivate.
765 * @Returns: the corresponding pointer.
767 * Returns the pointer keyed to @private_key for the current thread. If
768 * g_private_set() hasn't been called for the current @private_key and
769 * thread yet, this pointer will be %NULL.
771 * This function can be used even if g_thread_init() has not yet been
772 * called, and, in that case, will return the value of @private_key
773 * casted to #gpointer. Note however, that private data set
774 * <emphasis>before</emphasis> g_thread_init() will
775 * <emphasis>not</emphasis> be retained <emphasis>after</emphasis> the
776 * call. Instead, %NULL will be returned in all threads directly after
777 * g_thread_init(), regardless of any g_private_set() calls issued
778 * before threading system intialization.
784 * @private_key: a #GPrivate.
785 * @data: the new pointer.
787 * Sets the pointer keyed to @private_key for the current thread.
789 * This function can be used even if g_thread_init() has not yet been
790 * called, and, in that case, will set @private_key to @data casted to
791 * #GPrivate*. See g_private_get() for resulting caveats.
795 /* GThread Virtual Functions {{{2 ---------------------------------------- */
799 * The #GThread struct represents a running thread. It has three public
800 * read-only members, but the underlying struct is bigger, so you must
801 * not copy this struct.
803 * <note><para>Resources for a joinable thread are not fully released
804 * until g_thread_join() is called for that thread.</para></note>
809 * @data: data passed to the thread.
810 * @Returns: the return value of the thread, which will be returned by
813 * Specifies the type of the @func functions passed to
814 * g_thread_create() or g_thread_create_full().
819 * @G_THREAD_PRIORITY_LOW: a priority lower than normal
820 * @G_THREAD_PRIORITY_NORMAL: the default priority
821 * @G_THREAD_PRIORITY_HIGH: a priority higher than normal
822 * @G_THREAD_PRIORITY_URGENT: the highest priority
824 * Specifies the priority of a thread.
826 * <note><para>It is not guaranteed that threads with different priorities
827 * really behave accordingly. On some systems (e.g. Linux) there are no
828 * thread priorities. On other systems (e.g. Solaris) there doesn't
829 * seem to be different scheduling for different priorities. All in all
830 * try to avoid being dependent on priorities.</para></note>
835 * @func: a function to execute in the new thread.
836 * @data: an argument to supply to the new thread.
837 * @joinable: should this thread be joinable?
838 * @error: return location for error.
839 * @Returns: the new #GThread on success.
841 * This function creates a new thread with the default priority.
843 * If @joinable is %TRUE, you can wait for this threads termination
844 * calling g_thread_join(). Otherwise the thread will just disappear
845 * when it terminates.
847 * The new thread executes the function @func with the argument @data.
848 * If the thread was created successfully, it is returned.
850 * @error can be %NULL to ignore errors, or non-%NULL to report errors.
851 * The error is set, if and only if the function returns %NULL.
853 (void(*)(GThreadFunc, gpointer, gulong,
854 gboolean, gboolean, GThreadPriority,
855 gpointer, GError**))g_thread_fail,
860 * Gives way to other threads waiting to be scheduled.
862 * This function is often used as a method to make busy wait less evil.
863 * But in most cases you will encounter, there are better methods to do
864 * that. So in general you shouldn't use this function.
868 NULL, /* thread_join */
869 NULL, /* thread_exit */
870 NULL, /* thread_set_priority */
871 NULL, /* thread_self */
872 NULL /* thread_equal */
875 /* Local Data {{{1 -------------------------------------------------------- */
877 static GMutex g_once_mutex = G_MUTEX_INIT;
878 static GCond g_once_cond = G_COND_INIT;
879 static GPrivate g_thread_specific_private;
880 static GRealThread *g_thread_all_threads = NULL;
881 static GSList *g_thread_free_indices = NULL;
882 static GSList* g_once_init_list = NULL;
884 G_LOCK_DEFINE_STATIC (g_thread);
886 /* Initialisation {{{1 ---------------------------------------------------- */
890 * @vtable: a function table of type #GThreadFunctions, that provides
891 * the entry points to the thread system to be used.
893 * If you use GLib from more than one thread, you must initialize the
894 * thread system by calling g_thread_init(). Most of the time you will
895 * only have to call <literal>g_thread_init (NULL)</literal>.
897 * <note><para>Do not call g_thread_init() with a non-%NULL parameter unless
898 * you really know what you are doing.</para></note>
900 * <note><para>g_thread_init() must not be called directly or indirectly as a
901 * callback from GLib. Also no mutexes may be currently locked while
902 * calling g_thread_init().</para></note>
904 * <note><para>g_thread_init() changes the way in which #GTimer measures
905 * elapsed time. As a consequence, timers that are running while
906 * g_thread_init() is called may report unreliable times.</para></note>
908 * Calling g_thread_init() multiple times is allowed (since version
909 * 2.24), but nothing happens except for the first call. If the
910 * argument is non-%NULL on such a call a warning will be printed, but
911 * otherwise the argument is ignored.
913 * If no thread system is available and @vtable is %NULL or if not all
914 * elements of @vtable are non-%NULL, then g_thread_init() will abort.
916 * <note><para>To use g_thread_init() in your program, you have to link with
917 * the libraries that the command <command>pkg-config --libs
918 * gthread-2.0</command> outputs. This is not the case for all the
919 * other thread related functions of GLib. Those can be used without
920 * having to link with the thread libraries.</para></note>
923 /* This must be called only once, before any threads are created.
924 * It will only be called from g_thread_init() in -lgthread.
927 g_thread_init_glib (void)
929 static gboolean already_done;
936 _g_thread_impl_init ();
938 /* We let the main thread (the one that calls g_thread_init) inherit
939 * the static_private data set before calling g_thread_init
941 GRealThread* main_thread = (GRealThread*) g_thread_self ();
943 /* we may only create mutex and cond in here */
944 _g_mem_thread_init_noprivate_nomessage ();
946 /* setup the basic threading system */
947 g_threads_got_initialized = TRUE;
948 g_private_init (&g_thread_specific_private, g_thread_cleanup);
949 g_private_set (&g_thread_specific_private, main_thread);
950 G_THREAD_UF (thread_self, (&main_thread->system_thread));
952 /* complete memory system initialization, g_private_*() works now */
953 _g_slice_thread_init_nomessage ();
955 /* accomplish log system initialization to enable messaging */
956 _g_messages_thread_init_nomessage ();
959 /* The following sections implement: GOnce, GStaticMutex, GStaticRecMutex,
963 /* GOnce {{{1 ------------------------------------------------------------- */
967 * @status: the status of the #GOnce
968 * @retval: the value returned by the call to the function, if @status
969 * is %G_ONCE_STATUS_READY
971 * A #GOnce struct controls a one-time initialization function. Any
972 * one-time initialization function must have its own unique #GOnce
981 * A #GOnce must be initialized with this macro before it can be used.
985 * GOnce my_once = G_ONCE_INIT;
994 * @G_ONCE_STATUS_NOTCALLED: the function has not been called yet.
995 * @G_ONCE_STATUS_PROGRESS: the function call is currently in progress.
996 * @G_ONCE_STATUS_READY: the function has been called.
998 * The possible statuses of a one-time initialization function
999 * controlled by a #GOnce struct.
1006 * @once: a #GOnce structure
1007 * @func: the #GThreadFunc function associated to @once. This function
1008 * is called only once, regardless of the number of times it and
1009 * its associated #GOnce struct are passed to g_once().
1010 * @arg: data to be passed to @func
1012 * The first call to this routine by a process with a given #GOnce
1013 * struct calls @func with the given argument. Thereafter, subsequent
1014 * calls to g_once() with the same #GOnce struct do not call @func
1015 * again, but return the stored result of the first call. On return
1016 * from g_once(), the status of @once will be %G_ONCE_STATUS_READY.
1018 * For example, a mutex or a thread-specific data key must be created
1019 * exactly once. In a threaded environment, calling g_once() ensures
1020 * that the initialization is serialized across multiple threads.
1022 * <note><para>Calling g_once() recursively on the same #GOnce struct in
1023 * @func will lead to a deadlock.</para></note>
1028 * get_debug_flags (void)
1030 * static GOnce my_once = G_ONCE_INIT;
1032 * g_once (&my_once, parse_debug_flags, NULL);
1034 * return my_once.retval;
1037 * </informalexample>
1042 g_once_impl (GOnce *once,
1046 g_mutex_lock (&g_once_mutex);
1048 while (once->status == G_ONCE_STATUS_PROGRESS)
1049 g_cond_wait (&g_once_cond, &g_once_mutex);
1051 if (once->status != G_ONCE_STATUS_READY)
1053 once->status = G_ONCE_STATUS_PROGRESS;
1054 g_mutex_unlock (&g_once_mutex);
1056 once->retval = func (arg);
1058 g_mutex_lock (&g_once_mutex);
1059 once->status = G_ONCE_STATUS_READY;
1060 g_cond_broadcast (&g_once_cond);
1063 g_mutex_unlock (&g_once_mutex);
1065 return once->retval;
1069 * g_once_init_enter:
1070 * @value_location: location of a static initializable variable
1072 * @Returns: %TRUE if the initialization section should be entered,
1073 * %FALSE and blocks otherwise
1075 * Function to be called when starting a critical initialization
1076 * section. The argument @value_location must point to a static
1077 * 0-initialized variable that will be set to a value other than 0 at
1078 * the end of the initialization section. In combination with
1079 * g_once_init_leave() and the unique address @value_location, it can
1080 * be ensured that an initialization section will be executed only once
1081 * during a program's life time, and that concurrent threads are
1082 * blocked until initialization completed. To be used in constructs
1087 * static gsize initialization_value = 0;
1089 * if (g_once_init_enter (&initialization_value))
1091 * gsize setup_value = 42; /<!-- -->* initialization code here *<!-- -->/
1093 * g_once_init_leave (&initialization_value, setup_value);
1096 * /<!-- -->* use initialization_value here *<!-- -->/
1098 * </informalexample>
1103 g_once_init_enter_impl (volatile gsize *value_location)
1105 gboolean need_init = FALSE;
1106 g_mutex_lock (&g_once_mutex);
1107 if (g_atomic_pointer_get (value_location) == NULL)
1109 if (!g_slist_find (g_once_init_list, (void*) value_location))
1112 g_once_init_list = g_slist_prepend (g_once_init_list, (void*) value_location);
1116 g_cond_wait (&g_once_cond, &g_once_mutex);
1117 while (g_slist_find (g_once_init_list, (void*) value_location));
1119 g_mutex_unlock (&g_once_mutex);
1124 * g_once_init_leave:
1125 * @value_location: location of a static initializable variable
1127 * @initialization_value: new non-0 value for *@value_location.
1129 * Counterpart to g_once_init_enter(). Expects a location of a static
1130 * 0-initialized initialization variable, and an initialization value
1131 * other than 0. Sets the variable to the initialization value, and
1132 * releases concurrent threads blocking in g_once_init_enter() on this
1133 * initialization variable.
1138 g_once_init_leave (volatile gsize *value_location,
1139 gsize initialization_value)
1141 g_return_if_fail (g_atomic_pointer_get (value_location) == NULL);
1142 g_return_if_fail (initialization_value != 0);
1143 g_return_if_fail (g_once_init_list != NULL);
1145 g_atomic_pointer_set (value_location, initialization_value);
1146 g_mutex_lock (&g_once_mutex);
1147 g_once_init_list = g_slist_remove (g_once_init_list, (void*) value_location);
1148 g_cond_broadcast (&g_once_cond);
1149 g_mutex_unlock (&g_once_mutex);
1152 /* GStaticMutex {{{1 ------------------------------------------------------ */
1157 * A #GStaticMutex works like a #GMutex, but it has one significant
1158 * advantage. It doesn't need to be created at run-time like a #GMutex,
1159 * but can be defined at compile-time. Here is a shorter, easier and
1160 * safer version of our <function>give_me_next_number()</function>
1165 * Using <structname>GStaticMutex</structname>
1166 * to simplify thread-safe programming
1170 * give_me_next_number (void)
1172 * static int current_number = 0;
1174 * static GStaticMutex mutex = G_STATIC_MUTEX_INIT;
1176 * g_static_mutex_lock (&mutex);
1177 * ret_val = current_number = calc_next_number (current_number);
1178 * g_static_mutex_unlock (&mutex);
1185 * Sometimes you would like to dynamically create a mutex. If you don't
1186 * want to require prior calling to g_thread_init(), because your code
1187 * should also be usable in non-threaded programs, you are not able to
1188 * use g_mutex_new() and thus #GMutex, as that requires a prior call to
1189 * g_thread_init(). In theses cases you can also use a #GStaticMutex.
1190 * It must be initialized with g_static_mutex_init() before using it
1191 * and freed with with g_static_mutex_free() when not needed anymore to
1192 * free up any allocated resources.
1194 * Even though #GStaticMutex is not opaque, it should only be used with
1195 * the following functions, as it is defined differently on different
1198 * All of the <function>g_static_mutex_*</function> functions apart
1199 * from <function>g_static_mutex_get_mutex</function> can also be used
1200 * even if g_thread_init() has not yet been called. Then they do
1201 * nothing, apart from <function>g_static_mutex_trylock</function>,
1202 * which does nothing but returning %TRUE.
1204 * <note><para>All of the <function>g_static_mutex_*</function>
1205 * functions are actually macros. Apart from taking their addresses, you
1206 * can however use them as if they were functions.</para></note>
1210 * G_STATIC_MUTEX_INIT:
1212 * A #GStaticMutex must be initialized with this macro, before it can
1213 * be used. This macro can used be to initialize a variable, but it
1214 * cannot be assigned to a variable. In that case you have to use
1215 * g_static_mutex_init().
1219 * GStaticMutex my_mutex = G_STATIC_MUTEX_INIT;
1221 * </informalexample>
1225 * g_static_mutex_init:
1226 * @mutex: a #GStaticMutex to be initialized.
1228 * Initializes @mutex. Alternatively you can initialize it with
1229 * #G_STATIC_MUTEX_INIT.
1232 g_static_mutex_init (GStaticMutex *mutex)
1234 static const GStaticMutex init_mutex = G_STATIC_MUTEX_INIT;
1236 g_return_if_fail (mutex);
1238 *mutex = init_mutex;
1241 /* IMPLEMENTATION NOTE:
1243 * On some platforms a GStaticMutex is actually a normal GMutex stored
1244 * inside of a structure instead of being allocated dynamically. We can
1245 * only do this for platforms on which we know, in advance, how to
1246 * allocate (size) and initialise (value) that memory.
1248 * On other platforms, a GStaticMutex is nothing more than a pointer to
1249 * a GMutex. In that case, the first access we make to the static mutex
1250 * must first allocate the normal GMutex and store it into the pointer.
1252 * configure.ac writes macros into glibconfig.h to determine if
1253 * g_static_mutex_get_mutex() accesses the structure in memory directly
1254 * (on platforms where we are able to do that) or if it ends up here,
1255 * where we may have to allocate the GMutex before returning it.
1259 * g_static_mutex_get_mutex:
1260 * @mutex: a #GStaticMutex.
1261 * @Returns: the #GMutex corresponding to @mutex.
1263 * For some operations (like g_cond_wait()) you must have a #GMutex
1264 * instead of a #GStaticMutex. This function will return the
1265 * corresponding #GMutex for @mutex.
1268 g_static_mutex_get_mutex_impl (GMutex** mutex)
1272 if (!g_thread_supported ())
1275 result = g_atomic_pointer_get (mutex);
1279 g_mutex_lock (&g_once_mutex);
1284 result = g_mutex_new ();
1285 g_atomic_pointer_set (mutex, result);
1288 g_mutex_unlock (&g_once_mutex);
1294 /* IMPLEMENTATION NOTE:
1296 * g_static_mutex_lock(), g_static_mutex_trylock() and
1297 * g_static_mutex_unlock() are all preprocessor macros that wrap the
1298 * corresponding g_mutex_*() function around a call to
1299 * g_static_mutex_get_mutex().
1303 * g_static_mutex_lock:
1304 * @mutex: a #GStaticMutex.
1306 * Works like g_mutex_lock(), but for a #GStaticMutex.
1310 * g_static_mutex_trylock:
1311 * @mutex: a #GStaticMutex.
1312 * @Returns: %TRUE, if the #GStaticMutex could be locked.
1314 * Works like g_mutex_trylock(), but for a #GStaticMutex.
1318 * g_static_mutex_unlock:
1319 * @mutex: a #GStaticMutex.
1321 * Works like g_mutex_unlock(), but for a #GStaticMutex.
1325 * g_static_mutex_free:
1326 * @mutex: a #GStaticMutex to be freed.
1328 * Releases all resources allocated to @mutex.
1330 * You don't have to call this functions for a #GStaticMutex with an
1331 * unbounded lifetime, i.e. objects declared 'static', but if you have
1332 * a #GStaticMutex as a member of a structure and the structure is
1333 * freed, you should also free the #GStaticMutex.
1335 * <note><para>Calling g_static_mutex_free() on a locked mutex may
1336 * result in undefined behaviour.</para></note>
1339 g_static_mutex_free (GStaticMutex* mutex)
1341 GMutex **runtime_mutex;
1343 g_return_if_fail (mutex);
1345 /* The runtime_mutex is the first (or only) member of GStaticMutex,
1346 * see both versions (of glibconfig.h) in configure.ac. Note, that
1347 * this variable is NULL, if g_thread_init() hasn't been called or
1348 * if we're using the default thread implementation and it provides
1349 * static mutexes. */
1350 runtime_mutex = ((GMutex**)mutex);
1353 g_mutex_free (*runtime_mutex);
1355 *runtime_mutex = NULL;
1358 /* ------------------------------------------------------------------------ */
1363 * A #GStaticRecMutex works like a #GStaticMutex, but it can be locked
1364 * multiple times by one thread. If you enter it n times, you have to
1365 * unlock it n times again to let other threads lock it. An exception
1366 * is the function g_static_rec_mutex_unlock_full(): that allows you to
1367 * unlock a #GStaticRecMutex completely returning the depth, (i.e. the
1368 * number of times this mutex was locked). The depth can later be used
1369 * to restore the state of the #GStaticRecMutex by calling
1370 * g_static_rec_mutex_lock_full().
1372 * Even though #GStaticRecMutex is not opaque, it should only be used
1373 * with the following functions.
1375 * All of the <function>g_static_rec_mutex_*</function> functions can
1376 * be used even if g_thread_init() has not been called. Then they do
1377 * nothing, apart from <function>g_static_rec_mutex_trylock</function>,
1378 * which does nothing but returning %TRUE.
1382 * G_STATIC_REC_MUTEX_INIT:
1384 * A #GStaticRecMutex must be initialized with this macro before it can
1385 * be used. This macro can used be to initialize a variable, but it
1386 * cannot be assigned to a variable. In that case you have to use
1387 * g_static_rec_mutex_init().
1391 * GStaticRecMutex my_mutex = G_STATIC_REC_MUTEX_INIT;
1397 * g_static_rec_mutex_init:
1398 * @mutex: a #GStaticRecMutex to be initialized.
1400 * A #GStaticRecMutex must be initialized with this function before it
1401 * can be used. Alternatively you can initialize it with
1402 * #G_STATIC_REC_MUTEX_INIT.
1405 g_static_rec_mutex_init (GStaticRecMutex *mutex)
1407 static const GStaticRecMutex init_mutex = G_STATIC_REC_MUTEX_INIT;
1409 g_return_if_fail (mutex);
1411 *mutex = init_mutex;
1415 * g_static_rec_mutex_lock:
1416 * @mutex: a #GStaticRecMutex to lock.
1418 * Locks @mutex. If @mutex is already locked by another thread, the
1419 * current thread will block until @mutex is unlocked by the other
1420 * thread. If @mutex is already locked by the calling thread, this
1421 * functions increases the depth of @mutex and returns immediately.
1424 g_static_rec_mutex_lock (GStaticRecMutex* mutex)
1428 g_return_if_fail (mutex);
1430 if (!g_thread_supported ())
1433 G_THREAD_UF (thread_self, (&self));
1435 if (g_system_thread_equal (self, mutex->owner))
1440 g_static_mutex_lock (&mutex->mutex);
1441 g_system_thread_assign (mutex->owner, self);
1446 * g_static_rec_mutex_trylock:
1447 * @mutex: a #GStaticRecMutex to lock.
1448 * @Returns: %TRUE, if @mutex could be locked.
1450 * Tries to lock @mutex. If @mutex is already locked by another thread,
1451 * it immediately returns %FALSE. Otherwise it locks @mutex and returns
1452 * %TRUE. If @mutex is already locked by the calling thread, this
1453 * functions increases the depth of @mutex and immediately returns
1457 g_static_rec_mutex_trylock (GStaticRecMutex* mutex)
1461 g_return_val_if_fail (mutex, FALSE);
1463 if (!g_thread_supported ())
1466 G_THREAD_UF (thread_self, (&self));
1468 if (g_system_thread_equal (self, mutex->owner))
1474 if (!g_static_mutex_trylock (&mutex->mutex))
1477 g_system_thread_assign (mutex->owner, self);
1483 * g_static_rec_mutex_unlock:
1484 * @mutex: a #GStaticRecMutex to unlock.
1486 * Unlocks @mutex. Another thread will be allowed to lock @mutex only
1487 * when it has been unlocked as many times as it had been locked
1488 * before. If @mutex is completely unlocked and another thread is
1489 * blocked in a g_static_rec_mutex_lock() call for @mutex, it will be
1490 * woken and can lock @mutex itself.
1493 g_static_rec_mutex_unlock (GStaticRecMutex* mutex)
1495 g_return_if_fail (mutex);
1497 if (!g_thread_supported ())
1500 if (mutex->depth > 1)
1505 g_system_thread_assign (mutex->owner, zero_thread);
1506 g_static_mutex_unlock (&mutex->mutex);
1510 * g_static_rec_mutex_lock_full:
1511 * @mutex: a #GStaticRecMutex to lock.
1512 * @depth: number of times this mutex has to be unlocked to be
1513 * completely unlocked.
1515 * Works like calling g_static_rec_mutex_lock() for @mutex @depth times.
1518 g_static_rec_mutex_lock_full (GStaticRecMutex *mutex,
1522 g_return_if_fail (mutex);
1524 if (!g_thread_supported ())
1530 G_THREAD_UF (thread_self, (&self));
1532 if (g_system_thread_equal (self, mutex->owner))
1534 mutex->depth += depth;
1537 g_static_mutex_lock (&mutex->mutex);
1538 g_system_thread_assign (mutex->owner, self);
1539 mutex->depth = depth;
1543 * g_static_rec_mutex_unlock_full:
1544 * @mutex: a #GStaticRecMutex to completely unlock.
1545 * @Returns: number of times @mutex has been locked by the current
1548 * Completely unlocks @mutex. If another thread is blocked in a
1549 * g_static_rec_mutex_lock() call for @mutex, it will be woken and can
1550 * lock @mutex itself. This function returns the number of times that
1551 * @mutex has been locked by the current thread. To restore the state
1552 * before the call to g_static_rec_mutex_unlock_full() you can call
1553 * g_static_rec_mutex_lock_full() with the depth returned by this
1557 g_static_rec_mutex_unlock_full (GStaticRecMutex *mutex)
1561 g_return_val_if_fail (mutex, 0);
1563 if (!g_thread_supported ())
1566 depth = mutex->depth;
1568 g_system_thread_assign (mutex->owner, zero_thread);
1570 g_static_mutex_unlock (&mutex->mutex);
1576 * g_static_rec_mutex_free:
1577 * @mutex: a #GStaticRecMutex to be freed.
1579 * Releases all resources allocated to a #GStaticRecMutex.
1581 * You don't have to call this functions for a #GStaticRecMutex with an
1582 * unbounded lifetime, i.e. objects declared 'static', but if you have
1583 * a #GStaticRecMutex as a member of a structure and the structure is
1584 * freed, you should also free the #GStaticRecMutex.
1587 g_static_rec_mutex_free (GStaticRecMutex *mutex)
1589 g_return_if_fail (mutex);
1591 g_static_mutex_free (&mutex->mutex);
1594 /* GStaticPrivate {{{1 ---------------------------------------------------- */
1599 * A #GStaticPrivate works almost like a #GPrivate, but it has one
1600 * significant advantage. It doesn't need to be created at run-time
1601 * like a #GPrivate, but can be defined at compile-time. This is
1602 * similar to the difference between #GMutex and #GStaticMutex. Now
1603 * look at our <function>give_me_next_number()</function> example with
1607 * <title>Using GStaticPrivate for per-thread data</title>
1610 * give_me_next_number (<!-- -->)
1612 * static GStaticPrivate current_number_key = G_STATIC_PRIVATE_INIT;
1613 * int *current_number = g_static_private_get (&current_number_key);
1615 * if (!current_number)
1617 * current_number = g_new (int,1);
1618 * *current_number = 0;
1619 * g_static_private_set (&current_number_key, current_number, g_free);
1622 * *current_number = calc_next_number (*current_number);
1624 * return *current_number;
1631 * G_STATIC_PRIVATE_INIT:
1633 * Every #GStaticPrivate must be initialized with this macro, before it
1638 * GStaticPrivate my_private = G_STATIC_PRIVATE_INIT;
1640 * </informalexample>
1644 * g_static_private_init:
1645 * @private_key: a #GStaticPrivate to be initialized.
1647 * Initializes @private_key. Alternatively you can initialize it with
1648 * #G_STATIC_PRIVATE_INIT.
1651 g_static_private_init (GStaticPrivate *private_key)
1653 private_key->index = 0;
1657 * g_static_private_get:
1658 * @private_key: a #GStaticPrivate.
1659 * @Returns: the corresponding pointer.
1661 * Works like g_private_get() only for a #GStaticPrivate.
1663 * This function works even if g_thread_init() has not yet been called.
1666 g_static_private_get (GStaticPrivate *private_key)
1668 GRealThread *self = (GRealThread*) g_thread_self ();
1670 gpointer ret = NULL;
1672 LOCK_PRIVATE_DATA (self);
1674 array = self->private_data;
1676 if (array && private_key->index != 0 && private_key->index <= array->len)
1677 ret = g_array_index (array, GStaticPrivateNode,
1678 private_key->index - 1).data;
1680 UNLOCK_PRIVATE_DATA (self);
1685 * g_static_private_set:
1686 * @private_key: a #GStaticPrivate.
1687 * @data: the new pointer.
1688 * @notify: a function to be called with the pointer whenever the
1689 * current thread ends or sets this pointer again.
1691 * Sets the pointer keyed to @private_key for the current thread and
1692 * the function @notify to be called with that pointer (%NULL or
1693 * non-%NULL), whenever the pointer is set again or whenever the
1694 * current thread ends.
1696 * This function works even if g_thread_init() has not yet been called.
1697 * If g_thread_init() is called later, the @data keyed to @private_key
1698 * will be inherited only by the main thread, i.e. the one that called
1701 * <note><para>@notify is used quite differently from @destructor in
1702 * g_private_new().</para></note>
1705 g_static_private_set (GStaticPrivate *private_key,
1707 GDestroyNotify notify)
1709 GRealThread *self = (GRealThread*) g_thread_self ();
1711 static guint next_index = 0;
1712 GStaticPrivateNode *node;
1713 gpointer ddata = NULL;
1714 GDestroyNotify ddestroy = NULL;
1716 if (!private_key->index)
1720 if (!private_key->index)
1722 if (g_thread_free_indices)
1724 private_key->index =
1725 GPOINTER_TO_UINT (g_thread_free_indices->data);
1726 g_thread_free_indices =
1727 g_slist_delete_link (g_thread_free_indices,
1728 g_thread_free_indices);
1731 private_key->index = ++next_index;
1734 G_UNLOCK (g_thread);
1737 LOCK_PRIVATE_DATA (self);
1739 array = self->private_data;
1742 array = g_array_new (FALSE, TRUE, sizeof (GStaticPrivateNode));
1743 self->private_data = array;
1746 if (private_key->index > array->len)
1747 g_array_set_size (array, private_key->index);
1749 node = &g_array_index (array, GStaticPrivateNode, private_key->index - 1);
1752 ddestroy = node->destroy;
1755 node->destroy = notify;
1757 UNLOCK_PRIVATE_DATA (self);
1764 * g_static_private_free:
1765 * @private_key: a #GStaticPrivate to be freed.
1767 * Releases all resources allocated to @private_key.
1769 * You don't have to call this functions for a #GStaticPrivate with an
1770 * unbounded lifetime, i.e. objects declared 'static', but if you have
1771 * a #GStaticPrivate as a member of a structure and the structure is
1772 * freed, you should also free the #GStaticPrivate.
1775 g_static_private_free (GStaticPrivate *private_key)
1777 guint idx = private_key->index;
1778 GRealThread *thread, *next;
1779 GArray *garbage = NULL;
1784 private_key->index = 0;
1788 thread = g_thread_all_threads;
1790 for (thread = g_thread_all_threads; thread; thread = next)
1794 next = thread->next;
1796 LOCK_PRIVATE_DATA (thread);
1798 array = thread->private_data;
1800 if (array && idx <= array->len)
1802 GStaticPrivateNode *node = &g_array_index (array,
1805 gpointer ddata = node->data;
1806 GDestroyNotify ddestroy = node->destroy;
1809 node->destroy = NULL;
1813 /* defer non-trivial destruction til after we've finished
1814 * iterating, since we must continue to hold the lock */
1815 if (garbage == NULL)
1816 garbage = g_array_new (FALSE, TRUE,
1817 sizeof (GStaticPrivateNode));
1819 g_array_set_size (garbage, garbage->len + 1);
1821 node = &g_array_index (garbage, GStaticPrivateNode,
1824 node->destroy = ddestroy;
1828 UNLOCK_PRIVATE_DATA (thread);
1830 g_thread_free_indices = g_slist_prepend (g_thread_free_indices,
1831 GUINT_TO_POINTER (idx));
1832 G_UNLOCK (g_thread);
1838 for (i = 0; i < garbage->len; i++)
1840 GStaticPrivateNode *node;
1842 node = &g_array_index (garbage, GStaticPrivateNode, i);
1843 node->destroy (node->data);
1846 g_array_free (garbage, TRUE);
1850 /* GThread Extra Functions {{{1 ------------------------------------------- */
1852 g_thread_cleanup (gpointer data)
1856 GRealThread* thread = data;
1859 LOCK_PRIVATE_DATA (thread);
1860 array = thread->private_data;
1861 thread->private_data = NULL;
1862 UNLOCK_PRIVATE_DATA (thread);
1868 for (i = 0; i < array->len; i++ )
1870 GStaticPrivateNode *node =
1871 &g_array_index (array, GStaticPrivateNode, i);
1873 node->destroy (node->data);
1875 g_array_free (array, TRUE);
1878 /* We only free the thread structure, if it isn't joinable. If
1879 it is, the structure is freed in g_thread_join */
1880 if (!thread->thread.joinable)
1885 for (t = g_thread_all_threads, p = NULL; t; p = t, t = t->next)
1892 g_thread_all_threads = t->next;
1896 G_UNLOCK (g_thread);
1898 /* Just to make sure, this isn't used any more */
1899 g_system_thread_assign (thread->system_thread, zero_thread);
1906 g_thread_fail (void)
1908 g_error ("The thread system is not yet initialized.");
1911 #define G_NSEC_PER_SEC 1000000000
1916 return g_get_monotonic_time () * 1000;
1920 g_thread_create_proxy (gpointer data)
1922 GRealThread* thread = data;
1926 /* This has to happen before G_LOCK, as that might call g_thread_self */
1927 g_private_set (&g_thread_specific_private, data);
1929 /* the lock makes sure, that thread->system_thread is written,
1930 before thread->thread.func is called. See g_thread_create. */
1932 G_UNLOCK (g_thread);
1934 thread->retval = thread->thread.func (thread->thread.data);
1940 * g_thread_create_full:
1941 * @func: a function to execute in the new thread.
1942 * @data: an argument to supply to the new thread.
1943 * @stack_size: a stack size for the new thread.
1944 * @joinable: should this thread be joinable?
1945 * @bound: should this thread be bound to a system thread?
1946 * @priority: a priority for the thread.
1947 * @error: return location for error.
1948 * @Returns: the new #GThread on success.
1950 * This function creates a new thread with the priority @priority. If
1951 * the underlying thread implementation supports it, the thread gets a
1952 * stack size of @stack_size or the default value for the current
1953 * platform, if @stack_size is 0.
1955 * If @joinable is %TRUE, you can wait for this threads termination
1956 * calling g_thread_join(). Otherwise the thread will just disappear
1957 * when it terminates. If @bound is %TRUE, this thread will be
1958 * scheduled in the system scope, otherwise the implementation is free
1959 * to do scheduling in the process scope. The first variant is more
1960 * expensive resource-wise, but generally faster. On some systems (e.g.
1961 * Linux) all threads are bound.
1963 * The new thread executes the function @func with the argument @data.
1964 * If the thread was created successfully, it is returned.
1966 * @error can be %NULL to ignore errors, or non-%NULL to report errors.
1967 * The error is set, if and only if the function returns %NULL.
1969 * <note><para>It is not guaranteed that threads with different priorities
1970 * really behave accordingly. On some systems (e.g. Linux) there are no
1971 * thread priorities. On other systems (e.g. Solaris) there doesn't
1972 * seem to be different scheduling for different priorities. All in all
1973 * try to avoid being dependent on priorities. Use
1974 * %G_THREAD_PRIORITY_NORMAL here as a default.</para></note>
1976 * <note><para>Only use g_thread_create_full() if you really can't use
1977 * g_thread_create() instead. g_thread_create() does not take
1978 * @stack_size, @bound, and @priority as arguments, as they should only
1979 * be used in cases in which it is unavoidable.</para></note>
1982 g_thread_create_full (GThreadFunc func,
1987 GThreadPriority priority,
1990 GRealThread* result;
1991 GError *local_error = NULL;
1992 g_return_val_if_fail (func, NULL);
1993 g_return_val_if_fail (priority >= G_THREAD_PRIORITY_LOW, NULL);
1994 g_return_val_if_fail (priority <= G_THREAD_PRIORITY_URGENT, NULL);
1996 result = g_new0 (GRealThread, 1);
1998 result->thread.joinable = joinable;
1999 result->thread.priority = priority;
2000 result->thread.func = func;
2001 result->thread.data = data;
2002 result->private_data = NULL;
2004 G_THREAD_UF (thread_create, (g_thread_create_proxy, result,
2005 stack_size, joinable, bound, priority,
2006 &result->system_thread, &local_error));
2009 result->next = g_thread_all_threads;
2010 g_thread_all_threads = result;
2012 G_UNLOCK (g_thread);
2016 g_propagate_error (error, local_error);
2021 return (GThread*) result;
2026 * @retval: the return value of this thread.
2028 * Exits the current thread. If another thread is waiting for that
2029 * thread using g_thread_join() and the current thread is joinable, the
2030 * waiting thread will be woken up and get @retval as the return value
2031 * of g_thread_join(). If the current thread is not joinable, @retval
2032 * is ignored. Calling
2036 * g_thread_exit (retval);
2038 * </informalexample>
2040 * is equivalent to returning @retval from the function @func, as given
2041 * to g_thread_create().
2043 * <note><para>Never call g_thread_exit() from within a thread of a
2044 * #GThreadPool, as that will mess up the bookkeeping and lead to funny
2045 * and unwanted results.</para></note>
2048 g_thread_exit (gpointer retval)
2050 GRealThread* real = (GRealThread*) g_thread_self ();
2051 real->retval = retval;
2052 G_THREAD_CF (thread_exit, (void)0, ());
2057 * @thread: a #GThread to be waited for.
2058 * @Returns: the return value of the thread.
2060 * Waits until @thread finishes, i.e. the function @func, as given to
2061 * g_thread_create(), returns or g_thread_exit() is called by @thread.
2062 * All resources of @thread including the #GThread struct are released.
2063 * @thread must have been created with @joinable=%TRUE in
2064 * g_thread_create(). The value returned by @func or given to
2065 * g_thread_exit() by @thread is returned by this function.
2068 g_thread_join (GThread* thread)
2070 GRealThread* real = (GRealThread*) thread;
2074 g_return_val_if_fail (thread, NULL);
2075 g_return_val_if_fail (thread->joinable, NULL);
2076 g_return_val_if_fail (!g_system_thread_equal (real->system_thread,
2077 zero_thread), NULL);
2079 G_THREAD_UF (thread_join, (&real->system_thread));
2081 retval = real->retval;
2084 for (t = g_thread_all_threads, p = NULL; t; p = t, t = t->next)
2086 if (t == (GRealThread*) thread)
2091 g_thread_all_threads = t->next;
2095 G_UNLOCK (g_thread);
2097 /* Just to make sure, this isn't used any more */
2098 thread->joinable = 0;
2099 g_system_thread_assign (real->system_thread, zero_thread);
2101 /* the thread structure for non-joinable threads is freed upon
2102 thread end. We free the memory here. This will leave a loose end,
2103 if a joinable thread is not joined. */
2111 * g_thread_set_priority:
2112 * @thread: a #GThread.
2113 * @priority: a new priority for @thread.
2115 * Changes the priority of @thread to @priority.
2117 * <note><para>It is not guaranteed that threads with different
2118 * priorities really behave accordingly. On some systems (e.g. Linux)
2119 * there are no thread priorities. On other systems (e.g. Solaris) there
2120 * doesn't seem to be different scheduling for different priorities. All
2121 * in all try to avoid being dependent on priorities.</para></note>
2124 g_thread_set_priority (GThread* thread,
2125 GThreadPriority priority)
2127 GRealThread* real = (GRealThread*) thread;
2129 g_return_if_fail (thread);
2130 g_return_if_fail (!g_system_thread_equal (real->system_thread, zero_thread));
2131 g_return_if_fail (priority >= G_THREAD_PRIORITY_LOW);
2132 g_return_if_fail (priority <= G_THREAD_PRIORITY_URGENT);
2134 thread->priority = priority;
2136 G_THREAD_CF (thread_set_priority, (void)0,
2137 (&real->system_thread, priority));
2142 * @Returns: the current thread.
2144 * This functions returns the #GThread corresponding to the calling
2148 g_thread_self (void)
2150 GRealThread* thread = g_private_get (&g_thread_specific_private);
2154 /* If no thread data is available, provide and set one. This
2155 can happen for the main thread and for threads, that are not
2157 thread = g_new0 (GRealThread, 1);
2158 thread->thread.joinable = FALSE; /* This is a save guess */
2159 thread->thread.priority = G_THREAD_PRIORITY_NORMAL; /* This is
2161 thread->thread.func = NULL;
2162 thread->thread.data = NULL;
2163 thread->private_data = NULL;
2165 if (g_thread_supported ())
2166 G_THREAD_UF (thread_self, (&thread->system_thread));
2168 g_private_set (&g_thread_specific_private, thread);
2171 thread->next = g_thread_all_threads;
2172 g_thread_all_threads = thread;
2173 G_UNLOCK (g_thread);
2176 return (GThread*)thread;
2179 /* GStaticRWLock {{{1 ----------------------------------------------------- */
2184 * The #GStaticRWLock struct represents a read-write lock. A read-write
2185 * lock can be used for protecting data that some portions of code only
2186 * read from, while others also write. In such situations it is
2187 * desirable that several readers can read at once, whereas of course
2188 * only one writer may write at a time. Take a look at the following
2192 * <title>An array with access functions</title>
2194 * GStaticRWLock rwlock = G_STATIC_RW_LOCK_INIT;
2198 * my_array_get (guint index)
2200 * gpointer retval = NULL;
2205 * g_static_rw_lock_reader_lock (&rwlock);
2206 * if (index < array->len)
2207 * retval = g_ptr_array_index (array, index);
2208 * g_static_rw_lock_reader_unlock (&rwlock);
2214 * my_array_set (guint index, gpointer data)
2216 * g_static_rw_lock_writer_lock (&rwlock);
2219 * array = g_ptr_array_new (<!-- -->);
2221 * if (index >= array->len)
2222 * g_ptr_array_set_size (array, index+1);
2223 * g_ptr_array_index (array, index) = data;
2225 * g_static_rw_lock_writer_unlock (&rwlock);
2230 * This example shows an array which can be accessed by many readers
2231 * (the <function>my_array_get()</function> function) simultaneously,
2232 * whereas the writers (the <function>my_array_set()</function>
2233 * function) will only be allowed once at a time and only if no readers
2234 * currently access the array. This is because of the potentially
2235 * dangerous resizing of the array. Using these functions is fully
2236 * multi-thread safe now.
2238 * Most of the time, writers should have precedence over readers. That
2239 * means, for this implementation, that as soon as a writer wants to
2240 * lock the data, no other reader is allowed to lock the data, whereas,
2241 * of course, the readers that already have locked the data are allowed
2242 * to finish their operation. As soon as the last reader unlocks the
2243 * data, the writer will lock it.
2245 * Even though #GStaticRWLock is not opaque, it should only be used
2246 * with the following functions.
2248 * All of the <function>g_static_rw_lock_*</function> functions can be
2249 * used even if g_thread_init() has not been called. Then they do
2250 * nothing, apart from <function>g_static_rw_lock_*_trylock</function>,
2251 * which does nothing but returning %TRUE.
2253 * <note><para>A read-write lock has a higher overhead than a mutex. For
2254 * example, both g_static_rw_lock_reader_lock() and
2255 * g_static_rw_lock_reader_unlock() have to lock and unlock a
2256 * #GStaticMutex, so it takes at least twice the time to lock and unlock
2257 * a #GStaticRWLock that it does to lock and unlock a #GStaticMutex. So
2258 * only data structures that are accessed by multiple readers, and which
2259 * keep the lock for a considerable time justify a #GStaticRWLock. The
2260 * above example most probably would fare better with a
2261 * #GStaticMutex.</para></note>
2265 * G_STATIC_RW_LOCK_INIT:
2267 * A #GStaticRWLock must be initialized with this macro before it can
2268 * be used. This macro can used be to initialize a variable, but it
2269 * cannot be assigned to a variable. In that case you have to use
2270 * g_static_rw_lock_init().
2274 * GStaticRWLock my_lock = G_STATIC_RW_LOCK_INIT;
2276 * </informalexample>
2280 * g_static_rw_lock_init:
2281 * @lock: a #GStaticRWLock to be initialized.
2283 * A #GStaticRWLock must be initialized with this function before it
2284 * can be used. Alternatively you can initialize it with
2285 * #G_STATIC_RW_LOCK_INIT.
2288 g_static_rw_lock_init (GStaticRWLock* lock)
2290 static const GStaticRWLock init_lock = G_STATIC_RW_LOCK_INIT;
2292 g_return_if_fail (lock);
2298 g_static_rw_lock_wait (GCond** cond, GStaticMutex* mutex)
2301 *cond = g_cond_new ();
2302 g_cond_wait (*cond, g_static_mutex_get_mutex (mutex));
2306 g_static_rw_lock_signal (GStaticRWLock* lock)
2308 if (lock->want_to_write && lock->write_cond)
2309 g_cond_signal (lock->write_cond);
2310 else if (lock->want_to_read && lock->read_cond)
2311 g_cond_broadcast (lock->read_cond);
2315 * g_static_rw_lock_reader_lock:
2316 * @lock: a #GStaticRWLock to lock for reading.
2318 * Locks @lock for reading. There may be unlimited concurrent locks for
2319 * reading of a #GStaticRWLock at the same time. If @lock is already
2320 * locked for writing by another thread or if another thread is already
2321 * waiting to lock @lock for writing, this function will block until
2322 * @lock is unlocked by the other writing thread and no other writing
2323 * threads want to lock @lock. This lock has to be unlocked by
2324 * g_static_rw_lock_reader_unlock().
2326 * #GStaticRWLock is not recursive. It might seem to be possible to
2327 * recursively lock for reading, but that can result in a deadlock, due
2328 * to writer preference.
2331 g_static_rw_lock_reader_lock (GStaticRWLock* lock)
2333 g_return_if_fail (lock);
2335 if (!g_threads_got_initialized)
2338 g_static_mutex_lock (&lock->mutex);
2339 lock->want_to_read++;
2340 while (lock->have_writer || lock->want_to_write)
2341 g_static_rw_lock_wait (&lock->read_cond, &lock->mutex);
2342 lock->want_to_read--;
2343 lock->read_counter++;
2344 g_static_mutex_unlock (&lock->mutex);
2348 * g_static_rw_lock_reader_trylock:
2349 * @lock: a #GStaticRWLock to lock for reading.
2350 * @Returns: %TRUE, if @lock could be locked for reading.
2352 * Tries to lock @lock for reading. If @lock is already locked for
2353 * writing by another thread or if another thread is already waiting to
2354 * lock @lock for writing, immediately returns %FALSE. Otherwise locks
2355 * @lock for reading and returns %TRUE. This lock has to be unlocked by
2356 * g_static_rw_lock_reader_unlock().
2359 g_static_rw_lock_reader_trylock (GStaticRWLock* lock)
2361 gboolean ret_val = FALSE;
2363 g_return_val_if_fail (lock, FALSE);
2365 if (!g_threads_got_initialized)
2368 g_static_mutex_lock (&lock->mutex);
2369 if (!lock->have_writer && !lock->want_to_write)
2371 lock->read_counter++;
2374 g_static_mutex_unlock (&lock->mutex);
2379 * g_static_rw_lock_reader_unlock:
2380 * @lock: a #GStaticRWLock to unlock after reading.
2382 * Unlocks @lock. If a thread waits to lock @lock for writing and all
2383 * locks for reading have been unlocked, the waiting thread is woken up
2384 * and can lock @lock for writing.
2387 g_static_rw_lock_reader_unlock (GStaticRWLock* lock)
2389 g_return_if_fail (lock);
2391 if (!g_threads_got_initialized)
2394 g_static_mutex_lock (&lock->mutex);
2395 lock->read_counter--;
2396 if (lock->read_counter == 0)
2397 g_static_rw_lock_signal (lock);
2398 g_static_mutex_unlock (&lock->mutex);
2402 * g_static_rw_lock_writer_lock:
2403 * @lock: a #GStaticRWLock to lock for writing.
2405 * Locks @lock for writing. If @lock is already locked for writing or
2406 * reading by other threads, this function will block until @lock is
2407 * completely unlocked and then lock @lock for writing. While this
2408 * functions waits to lock @lock, no other thread can lock @lock for
2409 * reading. When @lock is locked for writing, no other thread can lock
2410 * @lock (neither for reading nor writing). This lock has to be
2411 * unlocked by g_static_rw_lock_writer_unlock().
2414 g_static_rw_lock_writer_lock (GStaticRWLock* lock)
2416 g_return_if_fail (lock);
2418 if (!g_threads_got_initialized)
2421 g_static_mutex_lock (&lock->mutex);
2422 lock->want_to_write++;
2423 while (lock->have_writer || lock->read_counter)
2424 g_static_rw_lock_wait (&lock->write_cond, &lock->mutex);
2425 lock->want_to_write--;
2426 lock->have_writer = TRUE;
2427 g_static_mutex_unlock (&lock->mutex);
2431 * g_static_rw_lock_writer_trylock:
2432 * @lock: a #GStaticRWLock to lock for writing.
2433 * @Returns: %TRUE, if @lock could be locked for writing.
2435 * Tries to lock @lock for writing. If @lock is already locked (for
2436 * either reading or writing) by another thread, it immediately returns
2437 * %FALSE. Otherwise it locks @lock for writing and returns %TRUE. This
2438 * lock has to be unlocked by g_static_rw_lock_writer_unlock().
2441 g_static_rw_lock_writer_trylock (GStaticRWLock* lock)
2443 gboolean ret_val = FALSE;
2445 g_return_val_if_fail (lock, FALSE);
2447 if (!g_threads_got_initialized)
2450 g_static_mutex_lock (&lock->mutex);
2451 if (!lock->have_writer && !lock->read_counter)
2453 lock->have_writer = TRUE;
2456 g_static_mutex_unlock (&lock->mutex);
2461 * g_static_rw_lock_writer_unlock:
2462 * @lock: a #GStaticRWLock to unlock after writing.
2464 * Unlocks @lock. If a thread is waiting to lock @lock for writing and
2465 * all locks for reading have been unlocked, the waiting thread is
2466 * woken up and can lock @lock for writing. If no thread is waiting to
2467 * lock @lock for writing, and some thread or threads are waiting to
2468 * lock @lock for reading, the waiting threads are woken up and can
2469 * lock @lock for reading.
2472 g_static_rw_lock_writer_unlock (GStaticRWLock* lock)
2474 g_return_if_fail (lock);
2476 if (!g_threads_got_initialized)
2479 g_static_mutex_lock (&lock->mutex);
2480 lock->have_writer = FALSE;
2481 g_static_rw_lock_signal (lock);
2482 g_static_mutex_unlock (&lock->mutex);
2486 * g_static_rw_lock_free:
2487 * @lock: a #GStaticRWLock to be freed.
2489 * Releases all resources allocated to @lock.
2491 * You don't have to call this functions for a #GStaticRWLock with an
2492 * unbounded lifetime, i.e. objects declared 'static', but if you have
2493 * a #GStaticRWLock as a member of a structure, and the structure is
2494 * freed, you should also free the #GStaticRWLock.
2497 g_static_rw_lock_free (GStaticRWLock* lock)
2499 g_return_if_fail (lock);
2501 if (lock->read_cond)
2503 g_cond_free (lock->read_cond);
2504 lock->read_cond = NULL;
2506 if (lock->write_cond)
2508 g_cond_free (lock->write_cond);
2509 lock->write_cond = NULL;
2511 g_static_mutex_free (&lock->mutex);
2514 /* Unsorted {{{1 ---------------------------------------------------------- */
2518 * @thread_func: function to call for all GThread structures
2519 * @user_data: second argument to @thread_func
2521 * Call @thread_func on all existing #GThread structures. Note that
2522 * threads may decide to exit while @thread_func is running, so
2523 * without intimate knowledge about the lifetime of foreign threads,
2524 * @thread_func shouldn't access the GThread* pointer passed in as
2525 * first argument. However, @thread_func will not be called for threads
2526 * which are known to have exited already.
2528 * Due to thread lifetime checks, this function has an execution complexity
2529 * which is quadratic in the number of existing threads.
2534 g_thread_foreach (GFunc thread_func,
2537 GSList *slist = NULL;
2538 GRealThread *thread;
2539 g_return_if_fail (thread_func != NULL);
2540 /* snapshot the list of threads for iteration */
2542 for (thread = g_thread_all_threads; thread; thread = thread->next)
2543 slist = g_slist_prepend (slist, thread);
2544 G_UNLOCK (g_thread);
2545 /* walk the list, skipping non-existent threads */
2548 GSList *node = slist;
2550 /* check whether the current thread still exists */
2552 for (thread = g_thread_all_threads; thread; thread = thread->next)
2553 if (thread == node->data)
2555 G_UNLOCK (g_thread);
2557 thread_func (thread, user_data);
2558 g_slist_free_1 (node);
2563 * g_thread_get_initialized
2565 * Indicates if g_thread_init() has been called.
2567 * Returns: %TRUE if threads have been initialized.
2572 g_thread_get_initialized ()
2574 return g_thread_supported ();
2582 mutex = g_slice_new (GMutex);
2583 g_mutex_init (mutex);
2589 g_mutex_free (GMutex *mutex)
2591 g_mutex_clear (mutex);
2592 g_slice_free (GMutex, mutex);
2600 cond = g_slice_new (GCond);
2607 g_cond_free (GCond *cond)
2609 g_cond_clear (cond);
2610 g_slice_free (GCond, cond);