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"
55 #endif /* G_OS_WIN32 */
62 #include "gtestutils.h"
68 * @short_description: thread abstraction; including threads, different
69 * mutexes, conditions and thread private data
70 * @see_also: #GThreadPool, #GAsyncQueue
72 * Threads act almost like processes, but unlike processes all threads
73 * of one process share the same memory. This is good, as it provides
74 * easy communication between the involved threads via this shared
75 * memory, and it is bad, because strange things (so called
76 * "Heisenbugs") might happen if the program is not carefully designed.
77 * In particular, due to the concurrent nature of threads, no
78 * assumptions on the order of execution of code running in different
79 * threads can be made, unless order is explicitly forced by the
80 * programmer through synchronization primitives.
82 * The aim of the thread related functions in GLib is to provide a
83 * portable means for writing multi-threaded software. There are
84 * primitives for mutexes to protect the access to portions of memory
85 * (#GMutex, #GStaticMutex, #G_LOCK_DEFINE, #GStaticRecMutex and
86 * #GStaticRWLock). There is a facility to use individual bits for
87 * locks (g_bit_lock()). There are primitives for condition variables to
88 * allow synchronization of threads (#GCond). There are primitives for
89 * thread-private data - data that every thread has a private instance
90 * of (#GPrivate, #GStaticPrivate). There are facilities for one-time
91 * initialization (#GOnce, g_once_init_enter()). Last but definitely
92 * not least there are primitives to portably create and manage
95 * The threading system is initialized with g_thread_init(), which
96 * takes an optional custom thread implementation or %NULL for the
97 * default implementation. If you want to call g_thread_init() with a
98 * non-%NULL argument this must be done before executing any other GLib
99 * functions (except g_mem_set_vtable()). This is a requirement even if
100 * no threads are in fact ever created by the process.
102 * Calling g_thread_init() with a %NULL argument is somewhat more
103 * relaxed. You may call any other glib functions in the main thread
104 * before g_thread_init() as long as g_thread_init() is not called from
105 * a glib callback, or with any locks held. However, many libraries
106 * above glib does not support late initialization of threads, so doing
107 * this should be avoided if possible.
109 * Please note that since version 2.24 the GObject initialization
110 * function g_type_init() initializes threads (with a %NULL argument),
111 * so most applications, including those using Gtk+ will run with
112 * threads enabled. If you want a special thread implementation, make
113 * sure you call g_thread_init() before g_type_init() is called.
115 * After calling g_thread_init(), GLib is completely thread safe (all
116 * global data is automatically locked), but individual data structure
117 * instances are not automatically locked for performance reasons. So,
118 * for example you must coordinate accesses to the same #GHashTable
119 * from multiple threads. The two notable exceptions from this rule
120 * are #GMainLoop and #GAsyncQueue, which <emphasis>are</emphasis>
121 * threadsafe and need no further application-level locking to be
122 * accessed from multiple threads.
124 * To help debugging problems in multithreaded applications, GLib
125 * supports error-checking mutexes that will give you helpful error
126 * messages on common problems. To use error-checking mutexes, define
127 * the symbol #G_ERRORCHECK_MUTEXES when compiling the application.
131 * G_THREADS_IMPL_POSIX:
133 * This macro is defined if POSIX style threads are used.
139 * This macro is defined if GLib was compiled with thread support. This
140 * does not necessarily mean that there is a thread implementation
141 * available, but it does mean that the infrastructure is in place and
142 * that once you provide a thread implementation to g_thread_init(),
143 * GLib will be multi-thread safe. If #G_THREADS_ENABLED is not
144 * defined, then Glib is not, and cannot be, multi-thread safe.
148 * G_THREADS_IMPL_NONE:
150 * This macro is defined if no thread implementation is used. You can,
151 * however, provide one to g_thread_init() to make GLib multi-thread
155 /* G_LOCK Documentation {{{1 ---------------------------------------------- */
157 /* IMPLEMENTATION NOTE:
159 * G_LOCK_DEFINE and friends are convenience macros defined in
160 * gthread.h. Their documentation lives here.
165 * @name: the name of the lock.
167 * The %G_LOCK_* macros provide a convenient interface to #GStaticMutex
168 * with the advantage that they will expand to nothing in programs
169 * compiled against a thread-disabled GLib, saving code and memory
170 * there. #G_LOCK_DEFINE defines a lock. It can appear anywhere
171 * variable definitions may appear in programs, i.e. in the first block
172 * of a function or outside of functions. The @name parameter will be
173 * mangled to get the name of the #GStaticMutex. This means that you
174 * can use names of existing variables as the parameter - e.g. the name
175 * of the variable you intent to protect with the lock. Look at our
176 * <function>give_me_next_number()</function> example using the
180 * <title>Using the %G_LOCK_* convenience macros</title>
182 * G_LOCK_DEFINE (current_number);
185 * give_me_next_number (void)
187 * static int current_number = 0;
190 * G_LOCK (current_number);
191 * ret_val = current_number = calc_next_number (current_number);
192 * G_UNLOCK (current_number);
201 * G_LOCK_DEFINE_STATIC:
202 * @name: the name of the lock.
204 * This works like #G_LOCK_DEFINE, but it creates a static object.
209 * @name: the name of the lock.
211 * This declares a lock, that is defined with #G_LOCK_DEFINE in another
217 * @name: the name of the lock.
219 * Works like g_mutex_lock(), but for a lock defined with
225 * @name: the name of the lock.
226 * @Returns: %TRUE, if the lock could be locked.
228 * Works like g_mutex_trylock(), but for a lock defined with
234 * @name: the name of the lock.
236 * Works like g_mutex_unlock(), but for a lock defined with
240 /* GThreadError {{{1 ------------------------------------------------------- */
243 * @G_THREAD_ERROR_AGAIN: a thread couldn't be created due to resource
244 * shortage. Try again later.
246 * Possible errors of thread related functions.
252 * The error domain of the GLib thread subsystem.
255 g_thread_error_quark (void)
257 return g_quark_from_static_string ("g_thread_error");
260 /* Miscellaneous Structures {{{1 ------------------------------------------ */
261 typedef struct _GRealThread GRealThread;
265 /* Bit 0 protects private_data. To avoid deadlocks, do not block while
266 * holding this (particularly on the g_thread lock). */
267 volatile gint private_data_lock;
268 GArray *private_data;
271 GSystemThread system_thread;
274 #define LOCK_PRIVATE_DATA(self) g_bit_lock (&(self)->private_data_lock, 0)
275 #define UNLOCK_PRIVATE_DATA(self) g_bit_unlock (&(self)->private_data_lock, 0)
277 typedef struct _GStaticPrivateNode GStaticPrivateNode;
278 struct _GStaticPrivateNode
281 GDestroyNotify destroy;
284 static void g_thread_cleanup (gpointer data);
285 static void g_thread_fail (void);
286 static guint64 gettime (void);
288 guint64 (*g_thread_gettime) (void) = gettime;
290 /* Global Variables {{{1 -------------------------------------------------- */
292 static GSystemThread zero_thread; /* This is initialized to all zero */
293 gboolean g_thread_use_default_impl = TRUE;
296 * g_thread_supported:
297 * @Returns: %TRUE, if the thread system is initialized.
299 * This function returns %TRUE if the thread system is initialized, and
300 * %FALSE if it is not.
302 * <note><para>This function is actually a macro. Apart from taking the
303 * address of it you can however use it as if it was a
304 * function.</para></note>
307 /* IMPLEMENTATION NOTE:
309 * g_thread_supported() is just returns g_threads_got_initialized
311 gboolean g_threads_got_initialized = FALSE;
314 /* Thread Implementation Virtual Function Table {{{1 ---------------------- */
315 /* Virtual Function Table Documentation {{{2 ------------------------------ */
318 * @mutex_new: virtual function pointer for g_mutex_new()
319 * @mutex_lock: virtual function pointer for g_mutex_lock()
320 * @mutex_trylock: virtual function pointer for g_mutex_trylock()
321 * @mutex_unlock: virtual function pointer for g_mutex_unlock()
322 * @mutex_free: virtual function pointer for g_mutex_free()
323 * @cond_new: virtual function pointer for g_cond_new()
324 * @cond_signal: virtual function pointer for g_cond_signal()
325 * @cond_broadcast: virtual function pointer for g_cond_broadcast()
326 * @cond_wait: virtual function pointer for g_cond_wait()
327 * @cond_timed_wait: virtual function pointer for g_cond_timed_wait()
328 * @cond_free: virtual function pointer for g_cond_free()
329 * @private_new: virtual function pointer for g_private_new()
330 * @private_get: virtual function pointer for g_private_get()
331 * @private_set: virtual function pointer for g_private_set()
332 * @thread_create: virtual function pointer for g_thread_create()
333 * @thread_yield: virtual function pointer for g_thread_yield()
334 * @thread_join: virtual function pointer for g_thread_join()
335 * @thread_exit: virtual function pointer for g_thread_exit()
336 * @thread_set_priority: virtual function pointer for
337 * g_thread_set_priority()
338 * @thread_self: virtual function pointer for g_thread_self()
339 * @thread_equal: used internally by recursive mutex locks and by some
342 * This function table is used by g_thread_init() to initialize the
343 * thread system. The functions in the table are directly used by their
344 * g_* prepended counterparts (described in this document). For
345 * example, if you call g_mutex_new() then mutex_new() from the table
346 * provided to g_thread_init() will be called.
348 * <note><para>Do not use this struct unless you know what you are
349 * doing.</para></note>
352 /* IMPLEMENTATION NOTE:
354 * g_thread_functions_for_glib_use is a global symbol that gets used by
355 * most of the "primitive" threading calls. g_mutex_lock(), for
356 * example, is just a macro that calls the appropriate virtual function
359 * For that reason, all of those macros are documented here.
361 GThreadFunctions g_thread_functions_for_glib_use = {
362 /* GMutex Virtual Functions {{{2 ------------------------------------------ */
367 * The #GMutex struct is an opaque data structure to represent a mutex
368 * (mutual exclusion). It can be used to protect data against shared
369 * access. Take for example the following function:
372 * <title>A function which will not work in a threaded environment</title>
375 * give_me_next_number (void)
377 * static int current_number = 0;
379 * /<!-- -->* now do a very complicated calculation to calculate the new
380 * * number, this might for example be a random number generator
382 * current_number = calc_next_number (current_number);
384 * return current_number;
389 * It is easy to see that this won't work in a multi-threaded
390 * application. There current_number must be protected against shared
391 * access. A first naive implementation would be:
394 * <title>The wrong way to write a thread-safe function</title>
397 * give_me_next_number (void)
399 * static int current_number = 0;
401 * static GMutex * mutex = NULL;
403 * if (!mutex) mutex = g_mutex_new (<!-- -->);
405 * g_mutex_lock (mutex);
406 * ret_val = current_number = calc_next_number (current_number);
407 * g_mutex_unlock (mutex);
414 * This looks like it would work, but there is a race condition while
415 * constructing the mutex and this code cannot work reliable. Please do
416 * not use such constructs in your own programs! One working solution
420 * <title>A correct thread-safe function</title>
422 * static GMutex *give_me_next_number_mutex = NULL;
424 * /<!-- -->* this function must be called before any call to
425 * * give_me_next_number(<!-- -->)
427 * * it must be called exactly once.
430 * init_give_me_next_number (void)
432 * g_assert (give_me_next_number_mutex == NULL);
433 * give_me_next_number_mutex = g_mutex_new (<!-- -->);
437 * give_me_next_number (void)
439 * static int current_number = 0;
442 * g_mutex_lock (give_me_next_number_mutex);
443 * ret_val = current_number = calc_next_number (current_number);
444 * g_mutex_unlock (give_me_next_number_mutex);
451 * #GStaticMutex provides a simpler and safer way of doing this.
453 * If you want to use a mutex, and your code should also work without
454 * calling g_thread_init() first, then you cannot use a #GMutex, as
455 * g_mutex_new() requires that the thread system be initialized. Use a
456 * #GStaticMutex instead.
458 * A #GMutex should only be accessed via the following functions.
460 * <note><para>All of the <function>g_mutex_*</function> functions are
461 * actually macros. Apart from taking their addresses, you can however
462 * use them as if they were functions.</para></note>
467 * @Returns: a new #GMutex.
469 * Creates a new #GMutex.
471 * <note><para>This function will abort if g_thread_init() has not been
472 * called yet.</para></note>
474 (GMutex*(*)())g_thread_fail,
480 * Locks @mutex. If @mutex is already locked by another thread, the
481 * current thread will block until @mutex is unlocked by the other
484 * This function can be used even if g_thread_init() has not yet been
485 * called, and, in that case, will do nothing.
487 * <note><para>#GMutex is neither guaranteed to be recursive nor to be
488 * non-recursive, i.e. a thread could deadlock while calling
489 * g_mutex_lock(), if it already has locked @mutex. Use
490 * #GStaticRecMutex, if you need recursive mutexes.</para></note>
497 * @Returns: %TRUE, if @mutex could be locked.
499 * Tries to lock @mutex. If @mutex is already locked by another thread,
500 * it immediately returns %FALSE. Otherwise it locks @mutex and returns
503 * This function can be used even if g_thread_init() has not yet been
504 * called, and, in that case, will immediately return %TRUE.
506 * <note><para>#GMutex is neither guaranteed to be recursive nor to be
507 * non-recursive, i.e. the return value of g_mutex_trylock() could be
508 * both %FALSE or %TRUE, if the current thread already has locked
509 * @mutex. Use #GStaticRecMutex, if you need recursive
510 * mutexes.</para></note>
518 * Unlocks @mutex. If another thread is blocked in a g_mutex_lock()
519 * call for @mutex, it will be woken and can lock @mutex itself.
521 * This function can be used even if g_thread_init() has not yet been
522 * called, and, in that case, will do nothing.
532 * <note><para>Calling g_mutex_free() on a locked mutex may result in
533 * undefined behaviour.</para></note>
537 /* GCond Virtual Functions {{{2 ------------------------------------------ */
542 * The #GCond struct is an opaque data structure that represents a
543 * condition. Threads can block on a #GCond if they find a certain
544 * condition to be false. If other threads change the state of this
545 * condition they signal the #GCond, and that causes the waiting
546 * threads to be woken up.
550 * Using GCond to block a thread until a condition is satisfied
553 * GCond* data_cond = NULL; /<!-- -->* Must be initialized somewhere *<!-- -->/
554 * GMutex* data_mutex = NULL; /<!-- -->* Must be initialized somewhere *<!-- -->/
555 * gpointer current_data = NULL;
558 * push_data (gpointer data)
560 * g_mutex_lock (data_mutex);
561 * current_data = data;
562 * g_cond_signal (data_cond);
563 * g_mutex_unlock (data_mutex);
571 * g_mutex_lock (data_mutex);
572 * while (!current_data)
573 * g_cond_wait (data_cond, data_mutex);
574 * data = current_data;
575 * current_data = NULL;
576 * g_mutex_unlock (data_mutex);
583 * Whenever a thread calls <function>pop_data()</function> now, it will
584 * wait until current_data is non-%NULL, i.e. until some other thread
585 * has called <function>push_data()</function>.
587 * <note><para>It is important to use the g_cond_wait() and
588 * g_cond_timed_wait() functions only inside a loop which checks for the
589 * condition to be true. It is not guaranteed that the waiting thread
590 * will find the condition fulfilled after it wakes up, even if the
591 * signaling thread left the condition in that state: another thread may
592 * have altered the condition before the waiting thread got the chance
593 * to be woken up, even if the condition itself is protected by a
594 * #GMutex, like above.</para></note>
596 * A #GCond should only be accessed via the following functions.
598 * <note><para>All of the <function>g_cond_*</function> functions are
599 * actually macros. Apart from taking their addresses, you can however
600 * use them as if they were functions.</para></note>
605 * @Returns: a new #GCond.
607 * Creates a new #GCond. This function will abort, if g_thread_init()
608 * has not been called yet.
610 (GCond*(*)())g_thread_fail,
616 * If threads are waiting for @cond, exactly one of them is woken up.
617 * It is good practice to hold the same lock as the waiting thread
618 * while calling this function, though not required.
620 * This function can be used even if g_thread_init() has not yet been
621 * called, and, in that case, will do nothing.
629 * If threads are waiting for @cond, all of them are woken up. It is
630 * good practice to lock the same mutex as the waiting threads, while
631 * calling this function, though not required.
633 * This function can be used even if g_thread_init() has not yet been
634 * called, and, in that case, will do nothing.
641 * @mutex: a #GMutex, that is currently locked.
643 * Waits until this thread is woken up on @cond. The @mutex is unlocked
644 * before falling asleep and locked again before resuming.
646 * This function can be used even if g_thread_init() has not yet been
647 * called, and, in that case, will immediately return.
654 * @mutex: a #GMutex that is currently locked.
655 * @abs_time: a #GTimeVal, determining the final time.
656 * @Returns: %TRUE if @cond was signalled, or %FALSE on timeout.
658 * Waits until this thread is woken up on @cond, but not longer than
659 * until the time specified by @abs_time. The @mutex is unlocked before
660 * falling asleep and locked again before resuming.
662 * If @abs_time is %NULL, g_cond_timed_wait() acts like g_cond_wait().
664 * This function can be used even if g_thread_init() has not yet been
665 * called, and, in that case, will immediately return %TRUE.
667 * To easily calculate @abs_time a combination of g_get_current_time()
668 * and g_time_val_add() can be used.
676 * Destroys the #GCond.
680 /* GPrivate Virtual Functions {{{2 --------------------------------------- */
686 * #GStaticPrivate is a better choice for most uses.
689 * The #GPrivate struct is an opaque data structure to represent a
690 * thread private data key. Threads can thereby obtain and set a
691 * pointer which is private to the current thread. Take our
692 * <function>give_me_next_number(<!-- -->)</function> example from
693 * above. Suppose we don't want <literal>current_number</literal> to be
694 * shared between the threads, but instead to be private to each thread.
695 * This can be done as follows:
698 * <title>Using GPrivate for per-thread data</title>
700 * GPrivate* current_number_key = NULL; /<!-- -->* Must be initialized somewhere
701 * with g_private_new (g_free); *<!-- -->/
704 * give_me_next_number (void)
706 * int *current_number = g_private_get (current_number_key);
708 * if (!current_number)
710 * current_number = g_new (int, 1);
711 * *current_number = 0;
712 * g_private_set (current_number_key, current_number);
715 * *current_number = calc_next_number (*current_number);
717 * return *current_number;
722 * Here the pointer belonging to the key
723 * <literal>current_number_key</literal> is read. If it is %NULL, it has
724 * not been set yet. Then get memory for an integer value, assign this
725 * memory to the pointer and write the pointer back. Now we have an
726 * integer value that is private to the current thread.
728 * The #GPrivate struct should only be accessed via the following
731 * <note><para>All of the <function>g_private_*</function> functions are
732 * actually macros. Apart from taking their addresses, you can however
733 * use them as if they were functions.</para></note>
738 * @destructor: a function to destroy the data keyed to #GPrivate when
740 * @Returns: a new #GPrivate.
742 * Creates a new #GPrivate. If @destructor is non-%NULL, it is a
743 * pointer to a destructor function. Whenever a thread ends and the
744 * corresponding pointer keyed to this instance of #GPrivate is
745 * non-%NULL, the destructor is called with this pointer as the
749 * #GStaticPrivate is a better choice for most uses.
752 * <note><para>@destructor is used quite differently from @notify in
753 * g_static_private_set().</para></note>
755 * <note><para>A #GPrivate cannot be freed. Reuse it instead, if you
756 * can, to avoid shortage, or use #GStaticPrivate.</para></note>
758 * <note><para>This function will abort if g_thread_init() has not been
759 * called yet.</para></note>
761 (GPrivate*(*)(GDestroyNotify))g_thread_fail,
765 * @private_key: a #GPrivate.
766 * @Returns: the corresponding pointer.
768 * Returns the pointer keyed to @private_key for the current thread. If
769 * g_private_set() hasn't been called for the current @private_key and
770 * thread yet, this pointer will be %NULL.
772 * This function can be used even if g_thread_init() has not yet been
773 * called, and, in that case, will return the value of @private_key
774 * casted to #gpointer. Note however, that private data set
775 * <emphasis>before</emphasis> g_thread_init() will
776 * <emphasis>not</emphasis> be retained <emphasis>after</emphasis> the
777 * call. Instead, %NULL will be returned in all threads directly after
778 * g_thread_init(), regardless of any g_private_set() calls issued
779 * before threading system intialization.
785 * @private_key: a #GPrivate.
786 * @data: the new pointer.
788 * Sets the pointer keyed to @private_key for the current thread.
790 * This function can be used even if g_thread_init() has not yet been
791 * called, and, in that case, will set @private_key to @data casted to
792 * #GPrivate*. See g_private_get() for resulting caveats.
796 /* GThread Virtual Functions {{{2 ---------------------------------------- */
800 * The #GThread struct represents a running thread. It has three public
801 * read-only members, but the underlying struct is bigger, so you must
802 * not copy this struct.
804 * <note><para>Resources for a joinable thread are not fully released
805 * until g_thread_join() is called for that thread.</para></note>
810 * @data: data passed to the thread.
811 * @Returns: the return value of the thread, which will be returned by
814 * Specifies the type of the @func functions passed to
815 * g_thread_create() or g_thread_create_full().
820 * @G_THREAD_PRIORITY_LOW: a priority lower than normal
821 * @G_THREAD_PRIORITY_NORMAL: the default priority
822 * @G_THREAD_PRIORITY_HIGH: a priority higher than normal
823 * @G_THREAD_PRIORITY_URGENT: the highest priority
825 * Specifies the priority of a thread.
827 * <note><para>It is not guaranteed that threads with different priorities
828 * really behave accordingly. On some systems (e.g. Linux) there are no
829 * thread priorities. On other systems (e.g. Solaris) there doesn't
830 * seem to be different scheduling for different priorities. All in all
831 * try to avoid being dependent on priorities.</para></note>
836 * @func: a function to execute in the new thread.
837 * @data: an argument to supply to the new thread.
838 * @joinable: should this thread be joinable?
839 * @error: return location for error.
840 * @Returns: the new #GThread on success.
842 * This function creates a new thread with the default priority.
844 * If @joinable is %TRUE, you can wait for this threads termination
845 * calling g_thread_join(). Otherwise the thread will just disappear
846 * when it terminates.
848 * The new thread executes the function @func with the argument @data.
849 * If the thread was created successfully, it is returned.
851 * @error can be %NULL to ignore errors, or non-%NULL to report errors.
852 * The error is set, if and only if the function returns %NULL.
854 (void(*)(GThreadFunc, gpointer, gulong,
855 gboolean, gboolean, GThreadPriority,
856 gpointer, GError**))g_thread_fail,
861 * Gives way to other threads waiting to be scheduled.
863 * This function is often used as a method to make busy wait less evil.
864 * But in most cases you will encounter, there are better methods to do
865 * that. So in general you shouldn't use this function.
869 NULL, /* thread_join */
870 NULL, /* thread_exit */
871 NULL, /* thread_set_priority */
872 NULL, /* thread_self */
873 NULL /* thread_equal */
876 /* Local Data {{{1 -------------------------------------------------------- */
878 static GMutex *g_once_mutex = NULL;
879 static GCond *g_once_cond = NULL;
880 static GPrivate *g_thread_specific_private = NULL;
881 static GRealThread *g_thread_all_threads = NULL;
882 static GSList *g_thread_free_indices = NULL;
883 static GSList* g_once_init_list = NULL;
885 G_LOCK_DEFINE_STATIC (g_thread);
887 /* Initialisation {{{1 ---------------------------------------------------- */
889 #ifdef G_THREADS_ENABLED
892 * @vtable: a function table of type #GThreadFunctions, that provides
893 * the entry points to the thread system to be used.
895 * If you use GLib from more than one thread, you must initialize the
896 * thread system by calling g_thread_init(). Most of the time you will
897 * only have to call <literal>g_thread_init (NULL)</literal>.
899 * <note><para>Do not call g_thread_init() with a non-%NULL parameter unless
900 * you really know what you are doing.</para></note>
902 * <note><para>g_thread_init() must not be called directly or indirectly as a
903 * callback from GLib. Also no mutexes may be currently locked while
904 * calling g_thread_init().</para></note>
906 * <note><para>g_thread_init() changes the way in which #GTimer measures
907 * elapsed time. As a consequence, timers that are running while
908 * g_thread_init() is called may report unreliable times.</para></note>
910 * Calling g_thread_init() multiple times is allowed (since version
911 * 2.24), but nothing happens except for the first call. If the
912 * argument is non-%NULL on such a call a warning will be printed, but
913 * otherwise the argument is ignored.
915 * If no thread system is available and @vtable is %NULL or if not all
916 * elements of @vtable are non-%NULL, then g_thread_init() will abort.
918 * <note><para>To use g_thread_init() in your program, you have to link with
919 * the libraries that the command <command>pkg-config --libs
920 * gthread-2.0</command> outputs. This is not the case for all the
921 * other thread related functions of GLib. Those can be used without
922 * having to link with the thread libraries.</para></note>
925 /* This must be called only once, before any threads are created.
926 * It will only be called from g_thread_init() in -lgthread.
929 g_thread_init_glib (void)
931 /* We let the main thread (the one that calls g_thread_init) inherit
932 * the static_private data set before calling g_thread_init
934 GRealThread* main_thread = (GRealThread*) g_thread_self ();
936 /* mutex and cond creation works without g_threads_got_initialized */
937 g_once_mutex = g_mutex_new ();
938 g_once_cond = g_cond_new ();
940 /* we may only create mutex and cond in here */
941 _g_mem_thread_init_noprivate_nomessage ();
943 /* setup the basic threading system */
944 g_threads_got_initialized = TRUE;
945 g_thread_specific_private = g_private_new (g_thread_cleanup);
946 g_private_set (g_thread_specific_private, main_thread);
947 G_THREAD_UF (thread_self, (&main_thread->system_thread));
949 /* complete memory system initialization, g_private_*() works now */
950 _g_slice_thread_init_nomessage ();
952 /* accomplish log system initialization to enable messaging */
953 _g_messages_thread_init_nomessage ();
955 /* we may run full-fledged initializers from here */
956 _g_convert_thread_init ();
957 _g_rand_thread_init ();
958 _g_main_thread_init ();
959 _g_utils_thread_init ();
960 _g_futex_thread_init ();
962 _g_win32_thread_init ();
965 #endif /* G_THREADS_ENABLED */
967 /* The following sections implement: GOnce, GStaticMutex, GStaticRecMutex,
971 /* GOnce {{{1 ------------------------------------------------------------- */
975 * @status: the status of the #GOnce
976 * @retval: the value returned by the call to the function, if @status
977 * is %G_ONCE_STATUS_READY
979 * A #GOnce struct controls a one-time initialization function. Any
980 * one-time initialization function must have its own unique #GOnce
989 * A #GOnce must be initialized with this macro before it can be used.
993 * GOnce my_once = G_ONCE_INIT;
1002 * @G_ONCE_STATUS_NOTCALLED: the function has not been called yet.
1003 * @G_ONCE_STATUS_PROGRESS: the function call is currently in progress.
1004 * @G_ONCE_STATUS_READY: the function has been called.
1006 * The possible statuses of a one-time initialization function
1007 * controlled by a #GOnce struct.
1014 * @once: a #GOnce structure
1015 * @func: the #GThreadFunc function associated to @once. This function
1016 * is called only once, regardless of the number of times it and
1017 * its associated #GOnce struct are passed to g_once().
1018 * @arg: data to be passed to @func
1020 * The first call to this routine by a process with a given #GOnce
1021 * struct calls @func with the given argument. Thereafter, subsequent
1022 * calls to g_once() with the same #GOnce struct do not call @func
1023 * again, but return the stored result of the first call. On return
1024 * from g_once(), the status of @once will be %G_ONCE_STATUS_READY.
1026 * For example, a mutex or a thread-specific data key must be created
1027 * exactly once. In a threaded environment, calling g_once() ensures
1028 * that the initialization is serialized across multiple threads.
1030 * <note><para>Calling g_once() recursively on the same #GOnce struct in
1031 * @func will lead to a deadlock.</para></note>
1036 * get_debug_flags (void)
1038 * static GOnce my_once = G_ONCE_INIT;
1040 * g_once (&my_once, parse_debug_flags, NULL);
1042 * return my_once.retval;
1045 * </informalexample>
1050 g_once_impl (GOnce *once,
1054 g_mutex_lock (g_once_mutex);
1056 while (once->status == G_ONCE_STATUS_PROGRESS)
1057 g_cond_wait (g_once_cond, g_once_mutex);
1059 if (once->status != G_ONCE_STATUS_READY)
1061 once->status = G_ONCE_STATUS_PROGRESS;
1062 g_mutex_unlock (g_once_mutex);
1064 once->retval = func (arg);
1066 g_mutex_lock (g_once_mutex);
1067 once->status = G_ONCE_STATUS_READY;
1068 g_cond_broadcast (g_once_cond);
1071 g_mutex_unlock (g_once_mutex);
1073 return once->retval;
1077 * g_once_init_enter:
1078 * @value_location: location of a static initializable variable
1080 * @Returns: %TRUE if the initialization section should be entered,
1081 * %FALSE and blocks otherwise
1083 * Function to be called when starting a critical initialization
1084 * section. The argument @value_location must point to a static
1085 * 0-initialized variable that will be set to a value other than 0 at
1086 * the end of the initialization section. In combination with
1087 * g_once_init_leave() and the unique address @value_location, it can
1088 * be ensured that an initialization section will be executed only once
1089 * during a program's life time, and that concurrent threads are
1090 * blocked until initialization completed. To be used in constructs
1095 * static gsize initialization_value = 0;
1097 * if (g_once_init_enter (&initialization_value))
1099 * gsize setup_value = 42; /<!-- -->* initialization code here *<!-- -->/
1101 * g_once_init_leave (&initialization_value, setup_value);
1104 * /<!-- -->* use initialization_value here *<!-- -->/
1106 * </informalexample>
1111 g_once_init_enter_impl (volatile gsize *value_location)
1113 gboolean need_init = FALSE;
1114 g_mutex_lock (g_once_mutex);
1115 if (g_atomic_pointer_get (value_location) == NULL)
1117 if (!g_slist_find (g_once_init_list, (void*) value_location))
1120 g_once_init_list = g_slist_prepend (g_once_init_list, (void*) value_location);
1124 g_cond_wait (g_once_cond, g_once_mutex);
1125 while (g_slist_find (g_once_init_list, (void*) value_location));
1127 g_mutex_unlock (g_once_mutex);
1132 * g_once_init_leave:
1133 * @value_location: location of a static initializable variable
1135 * @initialization_value: new non-0 value for *@value_location.
1137 * Counterpart to g_once_init_enter(). Expects a location of a static
1138 * 0-initialized initialization variable, and an initialization value
1139 * other than 0. Sets the variable to the initialization value, and
1140 * releases concurrent threads blocking in g_once_init_enter() on this
1141 * initialization variable.
1146 g_once_init_leave (volatile gsize *value_location,
1147 gsize initialization_value)
1149 g_return_if_fail (g_atomic_pointer_get (value_location) == NULL);
1150 g_return_if_fail (initialization_value != 0);
1151 g_return_if_fail (g_once_init_list != NULL);
1153 g_atomic_pointer_set (value_location, initialization_value);
1154 g_mutex_lock (g_once_mutex);
1155 g_once_init_list = g_slist_remove (g_once_init_list, (void*) value_location);
1156 g_cond_broadcast (g_once_cond);
1157 g_mutex_unlock (g_once_mutex);
1160 /* GStaticMutex {{{1 ------------------------------------------------------ */
1165 * A #GStaticMutex works like a #GMutex, but it has one significant
1166 * advantage. It doesn't need to be created at run-time like a #GMutex,
1167 * but can be defined at compile-time. Here is a shorter, easier and
1168 * safer version of our <function>give_me_next_number()</function>
1173 * Using <structname>GStaticMutex</structname>
1174 * to simplify thread-safe programming
1178 * give_me_next_number (void)
1180 * static int current_number = 0;
1182 * static GStaticMutex mutex = G_STATIC_MUTEX_INIT;
1184 * g_static_mutex_lock (&mutex);
1185 * ret_val = current_number = calc_next_number (current_number);
1186 * g_static_mutex_unlock (&mutex);
1193 * Sometimes you would like to dynamically create a mutex. If you don't
1194 * want to require prior calling to g_thread_init(), because your code
1195 * should also be usable in non-threaded programs, you are not able to
1196 * use g_mutex_new() and thus #GMutex, as that requires a prior call to
1197 * g_thread_init(). In theses cases you can also use a #GStaticMutex.
1198 * It must be initialized with g_static_mutex_init() before using it
1199 * and freed with with g_static_mutex_free() when not needed anymore to
1200 * free up any allocated resources.
1202 * Even though #GStaticMutex is not opaque, it should only be used with
1203 * the following functions, as it is defined differently on different
1206 * All of the <function>g_static_mutex_*</function> functions apart
1207 * from <function>g_static_mutex_get_mutex</function> can also be used
1208 * even if g_thread_init() has not yet been called. Then they do
1209 * nothing, apart from <function>g_static_mutex_trylock</function>,
1210 * which does nothing but returning %TRUE.
1212 * <note><para>All of the <function>g_static_mutex_*</function>
1213 * functions are actually macros. Apart from taking their addresses, you
1214 * can however use them as if they were functions.</para></note>
1218 * G_STATIC_MUTEX_INIT:
1220 * A #GStaticMutex must be initialized with this macro, before it can
1221 * be used. This macro can used be to initialize a variable, but it
1222 * cannot be assigned to a variable. In that case you have to use
1223 * g_static_mutex_init().
1227 * GStaticMutex my_mutex = G_STATIC_MUTEX_INIT;
1229 * </informalexample>
1233 * g_static_mutex_init:
1234 * @mutex: a #GStaticMutex to be initialized.
1236 * Initializes @mutex. Alternatively you can initialize it with
1237 * #G_STATIC_MUTEX_INIT.
1240 g_static_mutex_init (GStaticMutex *mutex)
1242 static const GStaticMutex init_mutex = G_STATIC_MUTEX_INIT;
1244 g_return_if_fail (mutex);
1246 *mutex = init_mutex;
1249 /* IMPLEMENTATION NOTE:
1251 * On some platforms a GStaticMutex is actually a normal GMutex stored
1252 * inside of a structure instead of being allocated dynamically. We can
1253 * only do this for platforms on which we know, in advance, how to
1254 * allocate (size) and initialise (value) that memory.
1256 * On other platforms, a GStaticMutex is nothing more than a pointer to
1257 * a GMutex. In that case, the first access we make to the static mutex
1258 * must first allocate the normal GMutex and store it into the pointer.
1260 * configure.ac writes macros into glibconfig.h to determine if
1261 * g_static_mutex_get_mutex() accesses the structure in memory directly
1262 * (on platforms where we are able to do that) or if it ends up here,
1263 * where we may have to allocate the GMutex before returning it.
1267 * g_static_mutex_get_mutex:
1268 * @mutex: a #GStaticMutex.
1269 * @Returns: the #GMutex corresponding to @mutex.
1271 * For some operations (like g_cond_wait()) you must have a #GMutex
1272 * instead of a #GStaticMutex. This function will return the
1273 * corresponding #GMutex for @mutex.
1276 g_static_mutex_get_mutex_impl (GMutex** mutex)
1280 if (!g_thread_supported ())
1283 result = g_atomic_pointer_get (mutex);
1287 g_assert (g_once_mutex);
1289 g_mutex_lock (g_once_mutex);
1294 result = g_mutex_new ();
1295 g_atomic_pointer_set (mutex, result);
1298 g_mutex_unlock (g_once_mutex);
1304 /* IMPLEMENTATION NOTE:
1306 * g_static_mutex_lock(), g_static_mutex_trylock() and
1307 * g_static_mutex_unlock() are all preprocessor macros that wrap the
1308 * corresponding g_mutex_*() function around a call to
1309 * g_static_mutex_get_mutex().
1313 * g_static_mutex_lock:
1314 * @mutex: a #GStaticMutex.
1316 * Works like g_mutex_lock(), but for a #GStaticMutex.
1320 * g_static_mutex_trylock:
1321 * @mutex: a #GStaticMutex.
1322 * @Returns: %TRUE, if the #GStaticMutex could be locked.
1324 * Works like g_mutex_trylock(), but for a #GStaticMutex.
1328 * g_static_mutex_unlock:
1329 * @mutex: a #GStaticMutex.
1331 * Works like g_mutex_unlock(), but for a #GStaticMutex.
1335 * g_static_mutex_free:
1336 * @mutex: a #GStaticMutex to be freed.
1338 * Releases all resources allocated to @mutex.
1340 * You don't have to call this functions for a #GStaticMutex with an
1341 * unbounded lifetime, i.e. objects declared 'static', but if you have
1342 * a #GStaticMutex as a member of a structure and the structure is
1343 * freed, you should also free the #GStaticMutex.
1345 * <note><para>Calling g_static_mutex_free() on a locked mutex may
1346 * result in undefined behaviour.</para></note>
1349 g_static_mutex_free (GStaticMutex* mutex)
1351 GMutex **runtime_mutex;
1353 g_return_if_fail (mutex);
1355 /* The runtime_mutex is the first (or only) member of GStaticMutex,
1356 * see both versions (of glibconfig.h) in configure.ac. Note, that
1357 * this variable is NULL, if g_thread_init() hasn't been called or
1358 * if we're using the default thread implementation and it provides
1359 * static mutexes. */
1360 runtime_mutex = ((GMutex**)mutex);
1363 g_mutex_free (*runtime_mutex);
1365 *runtime_mutex = NULL;
1368 /* ------------------------------------------------------------------------ */
1373 * A #GStaticRecMutex works like a #GStaticMutex, but it can be locked
1374 * multiple times by one thread. If you enter it n times, you have to
1375 * unlock it n times again to let other threads lock it. An exception
1376 * is the function g_static_rec_mutex_unlock_full(): that allows you to
1377 * unlock a #GStaticRecMutex completely returning the depth, (i.e. the
1378 * number of times this mutex was locked). The depth can later be used
1379 * to restore the state of the #GStaticRecMutex by calling
1380 * g_static_rec_mutex_lock_full().
1382 * Even though #GStaticRecMutex is not opaque, it should only be used
1383 * with the following functions.
1385 * All of the <function>g_static_rec_mutex_*</function> functions can
1386 * be used even if g_thread_init() has not been called. Then they do
1387 * nothing, apart from <function>g_static_rec_mutex_trylock</function>,
1388 * which does nothing but returning %TRUE.
1392 * G_STATIC_REC_MUTEX_INIT:
1394 * A #GStaticRecMutex must be initialized with this macro before it can
1395 * be used. This macro can used be to initialize a variable, but it
1396 * cannot be assigned to a variable. In that case you have to use
1397 * g_static_rec_mutex_init().
1401 * GStaticRecMutex my_mutex = G_STATIC_REC_MUTEX_INIT;
1407 * g_static_rec_mutex_init:
1408 * @mutex: a #GStaticRecMutex to be initialized.
1410 * A #GStaticRecMutex must be initialized with this function before it
1411 * can be used. Alternatively you can initialize it with
1412 * #G_STATIC_REC_MUTEX_INIT.
1415 g_static_rec_mutex_init (GStaticRecMutex *mutex)
1417 static const GStaticRecMutex init_mutex = G_STATIC_REC_MUTEX_INIT;
1419 g_return_if_fail (mutex);
1421 *mutex = init_mutex;
1425 * g_static_rec_mutex_lock:
1426 * @mutex: a #GStaticRecMutex to lock.
1428 * Locks @mutex. If @mutex is already locked by another thread, the
1429 * current thread will block until @mutex is unlocked by the other
1430 * thread. If @mutex is already locked by the calling thread, this
1431 * functions increases the depth of @mutex and returns immediately.
1434 g_static_rec_mutex_lock (GStaticRecMutex* mutex)
1438 g_return_if_fail (mutex);
1440 if (!g_thread_supported ())
1443 G_THREAD_UF (thread_self, (&self));
1445 if (g_system_thread_equal (self, mutex->owner))
1450 g_static_mutex_lock (&mutex->mutex);
1451 g_system_thread_assign (mutex->owner, self);
1456 * g_static_rec_mutex_trylock:
1457 * @mutex: a #GStaticRecMutex to lock.
1458 * @Returns: %TRUE, if @mutex could be locked.
1460 * Tries to lock @mutex. If @mutex is already locked by another thread,
1461 * it immediately returns %FALSE. Otherwise it locks @mutex and returns
1462 * %TRUE. If @mutex is already locked by the calling thread, this
1463 * functions increases the depth of @mutex and immediately returns
1467 g_static_rec_mutex_trylock (GStaticRecMutex* mutex)
1471 g_return_val_if_fail (mutex, FALSE);
1473 if (!g_thread_supported ())
1476 G_THREAD_UF (thread_self, (&self));
1478 if (g_system_thread_equal (self, mutex->owner))
1484 if (!g_static_mutex_trylock (&mutex->mutex))
1487 g_system_thread_assign (mutex->owner, self);
1493 * g_static_rec_mutex_unlock:
1494 * @mutex: a #GStaticRecMutex to unlock.
1496 * Unlocks @mutex. Another thread will be allowed to lock @mutex only
1497 * when it has been unlocked as many times as it had been locked
1498 * before. If @mutex is completely unlocked and another thread is
1499 * blocked in a g_static_rec_mutex_lock() call for @mutex, it will be
1500 * woken and can lock @mutex itself.
1503 g_static_rec_mutex_unlock (GStaticRecMutex* mutex)
1505 g_return_if_fail (mutex);
1507 if (!g_thread_supported ())
1510 if (mutex->depth > 1)
1515 g_system_thread_assign (mutex->owner, zero_thread);
1516 g_static_mutex_unlock (&mutex->mutex);
1520 * g_static_rec_mutex_lock_full:
1521 * @mutex: a #GStaticRecMutex to lock.
1522 * @depth: number of times this mutex has to be unlocked to be
1523 * completely unlocked.
1525 * Works like calling g_static_rec_mutex_lock() for @mutex @depth times.
1528 g_static_rec_mutex_lock_full (GStaticRecMutex *mutex,
1532 g_return_if_fail (mutex);
1534 if (!g_thread_supported ())
1540 G_THREAD_UF (thread_self, (&self));
1542 if (g_system_thread_equal (self, mutex->owner))
1544 mutex->depth += depth;
1547 g_static_mutex_lock (&mutex->mutex);
1548 g_system_thread_assign (mutex->owner, self);
1549 mutex->depth = depth;
1553 * g_static_rec_mutex_unlock_full:
1554 * @mutex: a #GStaticRecMutex to completely unlock.
1555 * @Returns: number of times @mutex has been locked by the current
1558 * Completely unlocks @mutex. If another thread is blocked in a
1559 * g_static_rec_mutex_lock() call for @mutex, it will be woken and can
1560 * lock @mutex itself. This function returns the number of times that
1561 * @mutex has been locked by the current thread. To restore the state
1562 * before the call to g_static_rec_mutex_unlock_full() you can call
1563 * g_static_rec_mutex_lock_full() with the depth returned by this
1567 g_static_rec_mutex_unlock_full (GStaticRecMutex *mutex)
1571 g_return_val_if_fail (mutex, 0);
1573 if (!g_thread_supported ())
1576 depth = mutex->depth;
1578 g_system_thread_assign (mutex->owner, zero_thread);
1580 g_static_mutex_unlock (&mutex->mutex);
1586 * g_static_rec_mutex_free:
1587 * @mutex: a #GStaticRecMutex to be freed.
1589 * Releases all resources allocated to a #GStaticRecMutex.
1591 * You don't have to call this functions for a #GStaticRecMutex with an
1592 * unbounded lifetime, i.e. objects declared 'static', but if you have
1593 * a #GStaticRecMutex as a member of a structure and the structure is
1594 * freed, you should also free the #GStaticRecMutex.
1597 g_static_rec_mutex_free (GStaticRecMutex *mutex)
1599 g_return_if_fail (mutex);
1601 g_static_mutex_free (&mutex->mutex);
1604 /* GStaticPrivate {{{1 ---------------------------------------------------- */
1609 * A #GStaticPrivate works almost like a #GPrivate, but it has one
1610 * significant advantage. It doesn't need to be created at run-time
1611 * like a #GPrivate, but can be defined at compile-time. This is
1612 * similar to the difference between #GMutex and #GStaticMutex. Now
1613 * look at our <function>give_me_next_number()</function> example with
1617 * <title>Using GStaticPrivate for per-thread data</title>
1620 * give_me_next_number (<!-- -->)
1622 * static GStaticPrivate current_number_key = G_STATIC_PRIVATE_INIT;
1623 * int *current_number = g_static_private_get (&current_number_key);
1625 * if (!current_number)
1627 * current_number = g_new (int,1);
1628 * *current_number = 0;
1629 * g_static_private_set (&current_number_key, current_number, g_free);
1632 * *current_number = calc_next_number (*current_number);
1634 * return *current_number;
1641 * G_STATIC_PRIVATE_INIT:
1643 * Every #GStaticPrivate must be initialized with this macro, before it
1648 * GStaticPrivate my_private = G_STATIC_PRIVATE_INIT;
1650 * </informalexample>
1654 * g_static_private_init:
1655 * @private_key: a #GStaticPrivate to be initialized.
1657 * Initializes @private_key. Alternatively you can initialize it with
1658 * #G_STATIC_PRIVATE_INIT.
1661 g_static_private_init (GStaticPrivate *private_key)
1663 private_key->index = 0;
1667 * g_static_private_get:
1668 * @private_key: a #GStaticPrivate.
1669 * @Returns: the corresponding pointer.
1671 * Works like g_private_get() only for a #GStaticPrivate.
1673 * This function works even if g_thread_init() has not yet been called.
1676 g_static_private_get (GStaticPrivate *private_key)
1678 GRealThread *self = (GRealThread*) g_thread_self ();
1680 gpointer ret = NULL;
1682 LOCK_PRIVATE_DATA (self);
1684 array = self->private_data;
1686 if (array && private_key->index != 0 && private_key->index <= array->len)
1687 ret = g_array_index (array, GStaticPrivateNode,
1688 private_key->index - 1).data;
1690 UNLOCK_PRIVATE_DATA (self);
1695 * g_static_private_set:
1696 * @private_key: a #GStaticPrivate.
1697 * @data: the new pointer.
1698 * @notify: a function to be called with the pointer whenever the
1699 * current thread ends or sets this pointer again.
1701 * Sets the pointer keyed to @private_key for the current thread and
1702 * the function @notify to be called with that pointer (%NULL or
1703 * non-%NULL), whenever the pointer is set again or whenever the
1704 * current thread ends.
1706 * This function works even if g_thread_init() has not yet been called.
1707 * If g_thread_init() is called later, the @data keyed to @private_key
1708 * will be inherited only by the main thread, i.e. the one that called
1711 * <note><para>@notify is used quite differently from @destructor in
1712 * g_private_new().</para></note>
1715 g_static_private_set (GStaticPrivate *private_key,
1717 GDestroyNotify notify)
1719 GRealThread *self = (GRealThread*) g_thread_self ();
1721 static guint next_index = 0;
1722 GStaticPrivateNode *node;
1723 gpointer ddata = NULL;
1724 GDestroyNotify ddestroy = NULL;
1726 if (!private_key->index)
1730 if (!private_key->index)
1732 if (g_thread_free_indices)
1734 private_key->index =
1735 GPOINTER_TO_UINT (g_thread_free_indices->data);
1736 g_thread_free_indices =
1737 g_slist_delete_link (g_thread_free_indices,
1738 g_thread_free_indices);
1741 private_key->index = ++next_index;
1744 G_UNLOCK (g_thread);
1747 LOCK_PRIVATE_DATA (self);
1749 array = self->private_data;
1752 array = g_array_new (FALSE, TRUE, sizeof (GStaticPrivateNode));
1753 self->private_data = array;
1756 if (private_key->index > array->len)
1757 g_array_set_size (array, private_key->index);
1759 node = &g_array_index (array, GStaticPrivateNode, private_key->index - 1);
1762 ddestroy = node->destroy;
1765 node->destroy = notify;
1767 UNLOCK_PRIVATE_DATA (self);
1774 * g_static_private_free:
1775 * @private_key: a #GStaticPrivate to be freed.
1777 * Releases all resources allocated to @private_key.
1779 * You don't have to call this functions for a #GStaticPrivate with an
1780 * unbounded lifetime, i.e. objects declared 'static', but if you have
1781 * a #GStaticPrivate as a member of a structure and the structure is
1782 * freed, you should also free the #GStaticPrivate.
1785 g_static_private_free (GStaticPrivate *private_key)
1787 guint idx = private_key->index;
1788 GRealThread *thread, *next;
1789 GArray *garbage = NULL;
1794 private_key->index = 0;
1798 thread = g_thread_all_threads;
1800 for (thread = g_thread_all_threads; thread; thread = next)
1804 next = thread->next;
1806 LOCK_PRIVATE_DATA (thread);
1808 array = thread->private_data;
1810 if (array && idx <= array->len)
1812 GStaticPrivateNode *node = &g_array_index (array,
1815 gpointer ddata = node->data;
1816 GDestroyNotify ddestroy = node->destroy;
1819 node->destroy = NULL;
1823 /* defer non-trivial destruction til after we've finished
1824 * iterating, since we must continue to hold the lock */
1825 if (garbage == NULL)
1826 garbage = g_array_new (FALSE, TRUE,
1827 sizeof (GStaticPrivateNode));
1829 g_array_set_size (garbage, garbage->len + 1);
1831 node = &g_array_index (garbage, GStaticPrivateNode,
1834 node->destroy = ddestroy;
1838 UNLOCK_PRIVATE_DATA (thread);
1840 g_thread_free_indices = g_slist_prepend (g_thread_free_indices,
1841 GUINT_TO_POINTER (idx));
1842 G_UNLOCK (g_thread);
1848 for (i = 0; i < garbage->len; i++)
1850 GStaticPrivateNode *node;
1852 node = &g_array_index (garbage, GStaticPrivateNode, i);
1853 node->destroy (node->data);
1856 g_array_free (garbage, TRUE);
1860 /* GThread Extra Functions {{{1 ------------------------------------------- */
1862 g_thread_cleanup (gpointer data)
1866 GRealThread* thread = data;
1869 LOCK_PRIVATE_DATA (thread);
1870 array = thread->private_data;
1871 thread->private_data = NULL;
1872 UNLOCK_PRIVATE_DATA (thread);
1878 for (i = 0; i < array->len; i++ )
1880 GStaticPrivateNode *node =
1881 &g_array_index (array, GStaticPrivateNode, i);
1883 node->destroy (node->data);
1885 g_array_free (array, TRUE);
1888 /* We only free the thread structure, if it isn't joinable. If
1889 it is, the structure is freed in g_thread_join */
1890 if (!thread->thread.joinable)
1895 for (t = g_thread_all_threads, p = NULL; t; p = t, t = t->next)
1902 g_thread_all_threads = t->next;
1906 G_UNLOCK (g_thread);
1908 /* Just to make sure, this isn't used any more */
1909 g_system_thread_assign (thread->system_thread, zero_thread);
1916 g_thread_fail (void)
1918 g_error ("The thread system is not yet initialized.");
1921 #define G_NSEC_PER_SEC 1000000000
1929 /* Returns 100s of nanoseconds since start of 1601 */
1930 GetSystemTimeAsFileTime ((FILETIME *)&v);
1932 /* Offset to Unix epoch */
1933 v -= G_GINT64_CONSTANT (116444736000000000);
1934 /* Convert to nanoseconds */
1941 gettimeofday (&tv, NULL);
1943 return (guint64) tv.tv_sec * G_NSEC_PER_SEC + tv.tv_usec * (G_NSEC_PER_SEC / G_USEC_PER_SEC);
1948 g_thread_create_proxy (gpointer data)
1950 GRealThread* thread = data;
1954 /* This has to happen before G_LOCK, as that might call g_thread_self */
1955 g_private_set (g_thread_specific_private, data);
1957 /* the lock makes sure, that thread->system_thread is written,
1958 before thread->thread.func is called. See g_thread_create. */
1960 G_UNLOCK (g_thread);
1962 thread->retval = thread->thread.func (thread->thread.data);
1968 * g_thread_create_full:
1969 * @func: a function to execute in the new thread.
1970 * @data: an argument to supply to the new thread.
1971 * @stack_size: a stack size for the new thread.
1972 * @joinable: should this thread be joinable?
1973 * @bound: should this thread be bound to a system thread?
1974 * @priority: a priority for the thread.
1975 * @error: return location for error.
1976 * @Returns: the new #GThread on success.
1978 * This function creates a new thread with the priority @priority. If
1979 * the underlying thread implementation supports it, the thread gets a
1980 * stack size of @stack_size or the default value for the current
1981 * platform, if @stack_size is 0.
1983 * If @joinable is %TRUE, you can wait for this threads termination
1984 * calling g_thread_join(). Otherwise the thread will just disappear
1985 * when it terminates. If @bound is %TRUE, this thread will be
1986 * scheduled in the system scope, otherwise the implementation is free
1987 * to do scheduling in the process scope. The first variant is more
1988 * expensive resource-wise, but generally faster. On some systems (e.g.
1989 * Linux) all threads are bound.
1991 * The new thread executes the function @func with the argument @data.
1992 * If the thread was created successfully, it is returned.
1994 * @error can be %NULL to ignore errors, or non-%NULL to report errors.
1995 * The error is set, if and only if the function returns %NULL.
1997 * <note><para>It is not guaranteed that threads with different priorities
1998 * really behave accordingly. On some systems (e.g. Linux) there are no
1999 * thread priorities. On other systems (e.g. Solaris) there doesn't
2000 * seem to be different scheduling for different priorities. All in all
2001 * try to avoid being dependent on priorities. Use
2002 * %G_THREAD_PRIORITY_NORMAL here as a default.</para></note>
2004 * <note><para>Only use g_thread_create_full() if you really can't use
2005 * g_thread_create() instead. g_thread_create() does not take
2006 * @stack_size, @bound, and @priority as arguments, as they should only
2007 * be used in cases in which it is unavoidable.</para></note>
2010 g_thread_create_full (GThreadFunc func,
2015 GThreadPriority priority,
2018 GRealThread* result;
2019 GError *local_error = NULL;
2020 g_return_val_if_fail (func, NULL);
2021 g_return_val_if_fail (priority >= G_THREAD_PRIORITY_LOW, NULL);
2022 g_return_val_if_fail (priority <= G_THREAD_PRIORITY_URGENT, NULL);
2024 result = g_new0 (GRealThread, 1);
2026 result->thread.joinable = joinable;
2027 result->thread.priority = priority;
2028 result->thread.func = func;
2029 result->thread.data = data;
2030 result->private_data = NULL;
2032 G_THREAD_UF (thread_create, (g_thread_create_proxy, result,
2033 stack_size, joinable, bound, priority,
2034 &result->system_thread, &local_error));
2037 result->next = g_thread_all_threads;
2038 g_thread_all_threads = result;
2040 G_UNLOCK (g_thread);
2044 g_propagate_error (error, local_error);
2049 return (GThread*) result;
2054 * @retval: the return value of this thread.
2056 * Exits the current thread. If another thread is waiting for that
2057 * thread using g_thread_join() and the current thread is joinable, the
2058 * waiting thread will be woken up and get @retval as the return value
2059 * of g_thread_join(). If the current thread is not joinable, @retval
2060 * is ignored. Calling
2064 * g_thread_exit (retval);
2066 * </informalexample>
2068 * is equivalent to returning @retval from the function @func, as given
2069 * to g_thread_create().
2071 * <note><para>Never call g_thread_exit() from within a thread of a
2072 * #GThreadPool, as that will mess up the bookkeeping and lead to funny
2073 * and unwanted results.</para></note>
2076 g_thread_exit (gpointer retval)
2078 GRealThread* real = (GRealThread*) g_thread_self ();
2079 real->retval = retval;
2080 G_THREAD_CF (thread_exit, (void)0, ());
2085 * @thread: a #GThread to be waited for.
2086 * @Returns: the return value of the thread.
2088 * Waits until @thread finishes, i.e. the function @func, as given to
2089 * g_thread_create(), returns or g_thread_exit() is called by @thread.
2090 * All resources of @thread including the #GThread struct are released.
2091 * @thread must have been created with @joinable=%TRUE in
2092 * g_thread_create(). The value returned by @func or given to
2093 * g_thread_exit() by @thread is returned by this function.
2096 g_thread_join (GThread* thread)
2098 GRealThread* real = (GRealThread*) thread;
2102 g_return_val_if_fail (thread, NULL);
2103 g_return_val_if_fail (thread->joinable, NULL);
2104 g_return_val_if_fail (!g_system_thread_equal (real->system_thread,
2105 zero_thread), NULL);
2107 G_THREAD_UF (thread_join, (&real->system_thread));
2109 retval = real->retval;
2112 for (t = g_thread_all_threads, p = NULL; t; p = t, t = t->next)
2114 if (t == (GRealThread*) thread)
2119 g_thread_all_threads = t->next;
2123 G_UNLOCK (g_thread);
2125 /* Just to make sure, this isn't used any more */
2126 thread->joinable = 0;
2127 g_system_thread_assign (real->system_thread, zero_thread);
2129 /* the thread structure for non-joinable threads is freed upon
2130 thread end. We free the memory here. This will leave a loose end,
2131 if a joinable thread is not joined. */
2139 * g_thread_set_priority:
2140 * @thread: a #GThread.
2141 * @priority: a new priority for @thread.
2143 * Changes the priority of @thread to @priority.
2145 * <note><para>It is not guaranteed that threads with different
2146 * priorities really behave accordingly. On some systems (e.g. Linux)
2147 * there are no thread priorities. On other systems (e.g. Solaris) there
2148 * doesn't seem to be different scheduling for different priorities. All
2149 * in all try to avoid being dependent on priorities.</para></note>
2152 g_thread_set_priority (GThread* thread,
2153 GThreadPriority priority)
2155 GRealThread* real = (GRealThread*) thread;
2157 g_return_if_fail (thread);
2158 g_return_if_fail (!g_system_thread_equal (real->system_thread, zero_thread));
2159 g_return_if_fail (priority >= G_THREAD_PRIORITY_LOW);
2160 g_return_if_fail (priority <= G_THREAD_PRIORITY_URGENT);
2162 thread->priority = priority;
2164 G_THREAD_CF (thread_set_priority, (void)0,
2165 (&real->system_thread, priority));
2170 * @Returns: the current thread.
2172 * This functions returns the #GThread corresponding to the calling
2176 g_thread_self (void)
2178 GRealThread* thread = g_private_get (g_thread_specific_private);
2182 /* If no thread data is available, provide and set one. This
2183 can happen for the main thread and for threads, that are not
2185 thread = g_new0 (GRealThread, 1);
2186 thread->thread.joinable = FALSE; /* This is a save guess */
2187 thread->thread.priority = G_THREAD_PRIORITY_NORMAL; /* This is
2189 thread->thread.func = NULL;
2190 thread->thread.data = NULL;
2191 thread->private_data = NULL;
2193 if (g_thread_supported ())
2194 G_THREAD_UF (thread_self, (&thread->system_thread));
2196 g_private_set (g_thread_specific_private, thread);
2199 thread->next = g_thread_all_threads;
2200 g_thread_all_threads = thread;
2201 G_UNLOCK (g_thread);
2204 return (GThread*)thread;
2207 /* GStaticRWLock {{{1 ----------------------------------------------------- */
2212 * The #GStaticRWLock struct represents a read-write lock. A read-write
2213 * lock can be used for protecting data that some portions of code only
2214 * read from, while others also write. In such situations it is
2215 * desirable that several readers can read at once, whereas of course
2216 * only one writer may write at a time. Take a look at the following
2220 * <title>An array with access functions</title>
2222 * GStaticRWLock rwlock = G_STATIC_RW_LOCK_INIT;
2226 * my_array_get (guint index)
2228 * gpointer retval = NULL;
2233 * g_static_rw_lock_reader_lock (&rwlock);
2234 * if (index < array->len)
2235 * retval = g_ptr_array_index (array, index);
2236 * g_static_rw_lock_reader_unlock (&rwlock);
2242 * my_array_set (guint index, gpointer data)
2244 * g_static_rw_lock_writer_lock (&rwlock);
2247 * array = g_ptr_array_new (<!-- -->);
2249 * if (index >= array->len)
2250 * g_ptr_array_set_size (array, index+1);
2251 * g_ptr_array_index (array, index) = data;
2253 * g_static_rw_lock_writer_unlock (&rwlock);
2258 * This example shows an array which can be accessed by many readers
2259 * (the <function>my_array_get()</function> function) simultaneously,
2260 * whereas the writers (the <function>my_array_set()</function>
2261 * function) will only be allowed once at a time and only if no readers
2262 * currently access the array. This is because of the potentially
2263 * dangerous resizing of the array. Using these functions is fully
2264 * multi-thread safe now.
2266 * Most of the time, writers should have precedence over readers. That
2267 * means, for this implementation, that as soon as a writer wants to
2268 * lock the data, no other reader is allowed to lock the data, whereas,
2269 * of course, the readers that already have locked the data are allowed
2270 * to finish their operation. As soon as the last reader unlocks the
2271 * data, the writer will lock it.
2273 * Even though #GStaticRWLock is not opaque, it should only be used
2274 * with the following functions.
2276 * All of the <function>g_static_rw_lock_*</function> functions can be
2277 * used even if g_thread_init() has not been called. Then they do
2278 * nothing, apart from <function>g_static_rw_lock_*_trylock</function>,
2279 * which does nothing but returning %TRUE.
2281 * <note><para>A read-write lock has a higher overhead than a mutex. For
2282 * example, both g_static_rw_lock_reader_lock() and
2283 * g_static_rw_lock_reader_unlock() have to lock and unlock a
2284 * #GStaticMutex, so it takes at least twice the time to lock and unlock
2285 * a #GStaticRWLock that it does to lock and unlock a #GStaticMutex. So
2286 * only data structures that are accessed by multiple readers, and which
2287 * keep the lock for a considerable time justify a #GStaticRWLock. The
2288 * above example most probably would fare better with a
2289 * #GStaticMutex.</para></note>
2293 * G_STATIC_RW_LOCK_INIT:
2295 * A #GStaticRWLock must be initialized with this macro before it can
2296 * be used. This macro can used be to initialize a variable, but it
2297 * cannot be assigned to a variable. In that case you have to use
2298 * g_static_rw_lock_init().
2302 * GStaticRWLock my_lock = G_STATIC_RW_LOCK_INIT;
2304 * </informalexample>
2308 * g_static_rw_lock_init:
2309 * @lock: a #GStaticRWLock to be initialized.
2311 * A #GStaticRWLock must be initialized with this function before it
2312 * can be used. Alternatively you can initialize it with
2313 * #G_STATIC_RW_LOCK_INIT.
2316 g_static_rw_lock_init (GStaticRWLock* lock)
2318 static const GStaticRWLock init_lock = G_STATIC_RW_LOCK_INIT;
2320 g_return_if_fail (lock);
2326 g_static_rw_lock_wait (GCond** cond, GStaticMutex* mutex)
2329 *cond = g_cond_new ();
2330 g_cond_wait (*cond, g_static_mutex_get_mutex (mutex));
2334 g_static_rw_lock_signal (GStaticRWLock* lock)
2336 if (lock->want_to_write && lock->write_cond)
2337 g_cond_signal (lock->write_cond);
2338 else if (lock->want_to_read && lock->read_cond)
2339 g_cond_broadcast (lock->read_cond);
2343 * g_static_rw_lock_reader_lock:
2344 * @lock: a #GStaticRWLock to lock for reading.
2346 * Locks @lock for reading. There may be unlimited concurrent locks for
2347 * reading of a #GStaticRWLock at the same time. If @lock is already
2348 * locked for writing by another thread or if another thread is already
2349 * waiting to lock @lock for writing, this function will block until
2350 * @lock is unlocked by the other writing thread and no other writing
2351 * threads want to lock @lock. This lock has to be unlocked by
2352 * g_static_rw_lock_reader_unlock().
2354 * #GStaticRWLock is not recursive. It might seem to be possible to
2355 * recursively lock for reading, but that can result in a deadlock, due
2356 * to writer preference.
2359 g_static_rw_lock_reader_lock (GStaticRWLock* lock)
2361 g_return_if_fail (lock);
2363 if (!g_threads_got_initialized)
2366 g_static_mutex_lock (&lock->mutex);
2367 lock->want_to_read++;
2368 while (lock->have_writer || lock->want_to_write)
2369 g_static_rw_lock_wait (&lock->read_cond, &lock->mutex);
2370 lock->want_to_read--;
2371 lock->read_counter++;
2372 g_static_mutex_unlock (&lock->mutex);
2376 * g_static_rw_lock_reader_trylock:
2377 * @lock: a #GStaticRWLock to lock for reading.
2378 * @Returns: %TRUE, if @lock could be locked for reading.
2380 * Tries to lock @lock for reading. If @lock is already locked for
2381 * writing by another thread or if another thread is already waiting to
2382 * lock @lock for writing, immediately returns %FALSE. Otherwise locks
2383 * @lock for reading and returns %TRUE. This lock has to be unlocked by
2384 * g_static_rw_lock_reader_unlock().
2387 g_static_rw_lock_reader_trylock (GStaticRWLock* lock)
2389 gboolean ret_val = FALSE;
2391 g_return_val_if_fail (lock, FALSE);
2393 if (!g_threads_got_initialized)
2396 g_static_mutex_lock (&lock->mutex);
2397 if (!lock->have_writer && !lock->want_to_write)
2399 lock->read_counter++;
2402 g_static_mutex_unlock (&lock->mutex);
2407 * g_static_rw_lock_reader_unlock:
2408 * @lock: a #GStaticRWLock to unlock after reading.
2410 * Unlocks @lock. If a thread waits to lock @lock for writing and all
2411 * locks for reading have been unlocked, the waiting thread is woken up
2412 * and can lock @lock for writing.
2415 g_static_rw_lock_reader_unlock (GStaticRWLock* lock)
2417 g_return_if_fail (lock);
2419 if (!g_threads_got_initialized)
2422 g_static_mutex_lock (&lock->mutex);
2423 lock->read_counter--;
2424 if (lock->read_counter == 0)
2425 g_static_rw_lock_signal (lock);
2426 g_static_mutex_unlock (&lock->mutex);
2430 * g_static_rw_lock_writer_lock:
2431 * @lock: a #GStaticRWLock to lock for writing.
2433 * Locks @lock for writing. If @lock is already locked for writing or
2434 * reading by other threads, this function will block until @lock is
2435 * completely unlocked and then lock @lock for writing. While this
2436 * functions waits to lock @lock, no other thread can lock @lock for
2437 * reading. When @lock is locked for writing, no other thread can lock
2438 * @lock (neither for reading nor writing). This lock has to be
2439 * unlocked by g_static_rw_lock_writer_unlock().
2442 g_static_rw_lock_writer_lock (GStaticRWLock* lock)
2444 g_return_if_fail (lock);
2446 if (!g_threads_got_initialized)
2449 g_static_mutex_lock (&lock->mutex);
2450 lock->want_to_write++;
2451 while (lock->have_writer || lock->read_counter)
2452 g_static_rw_lock_wait (&lock->write_cond, &lock->mutex);
2453 lock->want_to_write--;
2454 lock->have_writer = TRUE;
2455 g_static_mutex_unlock (&lock->mutex);
2459 * g_static_rw_lock_writer_trylock:
2460 * @lock: a #GStaticRWLock to lock for writing.
2461 * @Returns: %TRUE, if @lock could be locked for writing.
2463 * Tries to lock @lock for writing. If @lock is already locked (for
2464 * either reading or writing) by another thread, it immediately returns
2465 * %FALSE. Otherwise it locks @lock for writing and returns %TRUE. This
2466 * lock has to be unlocked by g_static_rw_lock_writer_unlock().
2469 g_static_rw_lock_writer_trylock (GStaticRWLock* lock)
2471 gboolean ret_val = FALSE;
2473 g_return_val_if_fail (lock, FALSE);
2475 if (!g_threads_got_initialized)
2478 g_static_mutex_lock (&lock->mutex);
2479 if (!lock->have_writer && !lock->read_counter)
2481 lock->have_writer = TRUE;
2484 g_static_mutex_unlock (&lock->mutex);
2489 * g_static_rw_lock_writer_unlock:
2490 * @lock: a #GStaticRWLock to unlock after writing.
2492 * Unlocks @lock. If a thread is waiting to lock @lock for writing and
2493 * all locks for reading have been unlocked, the waiting thread is
2494 * woken up and can lock @lock for writing. If no thread is waiting to
2495 * lock @lock for writing, and some thread or threads are waiting to
2496 * lock @lock for reading, the waiting threads are woken up and can
2497 * lock @lock for reading.
2500 g_static_rw_lock_writer_unlock (GStaticRWLock* lock)
2502 g_return_if_fail (lock);
2504 if (!g_threads_got_initialized)
2507 g_static_mutex_lock (&lock->mutex);
2508 lock->have_writer = FALSE;
2509 g_static_rw_lock_signal (lock);
2510 g_static_mutex_unlock (&lock->mutex);
2514 * g_static_rw_lock_free:
2515 * @lock: a #GStaticRWLock to be freed.
2517 * Releases all resources allocated to @lock.
2519 * You don't have to call this functions for a #GStaticRWLock with an
2520 * unbounded lifetime, i.e. objects declared 'static', but if you have
2521 * a #GStaticRWLock as a member of a structure, and the structure is
2522 * freed, you should also free the #GStaticRWLock.
2525 g_static_rw_lock_free (GStaticRWLock* lock)
2527 g_return_if_fail (lock);
2529 if (lock->read_cond)
2531 g_cond_free (lock->read_cond);
2532 lock->read_cond = NULL;
2534 if (lock->write_cond)
2536 g_cond_free (lock->write_cond);
2537 lock->write_cond = NULL;
2539 g_static_mutex_free (&lock->mutex);
2542 /* Unsorted {{{1 ---------------------------------------------------------- */
2546 * @thread_func: function to call for all GThread structures
2547 * @user_data: second argument to @thread_func
2549 * Call @thread_func on all existing #GThread structures. Note that
2550 * threads may decide to exit while @thread_func is running, so
2551 * without intimate knowledge about the lifetime of foreign threads,
2552 * @thread_func shouldn't access the GThread* pointer passed in as
2553 * first argument. However, @thread_func will not be called for threads
2554 * which are known to have exited already.
2556 * Due to thread lifetime checks, this function has an execution complexity
2557 * which is quadratic in the number of existing threads.
2562 g_thread_foreach (GFunc thread_func,
2565 GSList *slist = NULL;
2566 GRealThread *thread;
2567 g_return_if_fail (thread_func != NULL);
2568 /* snapshot the list of threads for iteration */
2570 for (thread = g_thread_all_threads; thread; thread = thread->next)
2571 slist = g_slist_prepend (slist, thread);
2572 G_UNLOCK (g_thread);
2573 /* walk the list, skipping non-existent threads */
2576 GSList *node = slist;
2578 /* check whether the current thread still exists */
2580 for (thread = g_thread_all_threads; thread; thread = thread->next)
2581 if (thread == node->data)
2583 G_UNLOCK (g_thread);
2585 thread_func (thread, user_data);
2586 g_slist_free_1 (node);
2591 * g_thread_get_initialized
2593 * Indicates if g_thread_init() has been called.
2595 * Returns: %TRUE if threads have been initialized.
2600 g_thread_get_initialized ()
2602 return g_thread_supported ();