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"
56 #endif /* G_OS_WIN32 */
63 #include "gtestutils.h"
69 * @short_description: thread abstraction; including threads, different
70 * mutexes, conditions and thread private data
71 * @see_also: #GThreadPool, #GAsyncQueue
73 * Threads act almost like processes, but unlike processes all threads
74 * of one process share the same memory. This is good, as it provides
75 * easy communication between the involved threads via this shared
76 * memory, and it is bad, because strange things (so called
77 * "Heisenbugs") might happen if the program is not carefully designed.
78 * In particular, due to the concurrent nature of threads, no
79 * assumptions on the order of execution of code running in different
80 * threads can be made, unless order is explicitly forced by the
81 * programmer through synchronization primitives.
83 * The aim of the thread related functions in GLib is to provide a
84 * portable means for writing multi-threaded software. There are
85 * primitives for mutexes to protect the access to portions of memory
86 * (#GMutex, #GStaticMutex, #G_LOCK_DEFINE, #GStaticRecMutex and
87 * #GStaticRWLock). There is a facility to use individual bits for
88 * locks (g_bit_lock()). There are primitives for condition variables to
89 * allow synchronization of threads (#GCond). There are primitives for
90 * thread-private data - data that every thread has a private instance
91 * of (#GPrivate, #GStaticPrivate). There are facilities for one-time
92 * initialization (#GOnce, g_once_init_enter()). Last but definitely
93 * not least there are primitives to portably create and manage
96 * The threading system is initialized with g_thread_init(), which
97 * takes an optional custom thread implementation or %NULL for the
98 * default implementation. If you want to call g_thread_init() with a
99 * non-%NULL argument this must be done before executing any other GLib
100 * functions (except g_mem_set_vtable()). This is a requirement even if
101 * no threads are in fact ever created by the process.
103 * Calling g_thread_init() with a %NULL argument is somewhat more
104 * relaxed. You may call any other glib functions in the main thread
105 * before g_thread_init() as long as g_thread_init() is not called from
106 * a glib callback, or with any locks held. However, many libraries
107 * above glib does not support late initialization of threads, so doing
108 * this should be avoided if possible.
110 * Please note that since version 2.24 the GObject initialization
111 * function g_type_init() initializes threads (with a %NULL argument),
112 * so most applications, including those using Gtk+ will run with
113 * threads enabled. If you want a special thread implementation, make
114 * sure you call g_thread_init() before g_type_init() is called.
116 * After calling g_thread_init(), GLib is completely thread safe (all
117 * global data is automatically locked), but individual data structure
118 * instances are not automatically locked for performance reasons. So,
119 * for example you must coordinate accesses to the same #GHashTable
120 * from multiple threads. The two notable exceptions from this rule
121 * are #GMainLoop and #GAsyncQueue, which <emphasis>are</emphasis>
122 * threadsafe and need no further application-level locking to be
123 * accessed from multiple threads.
125 * To help debugging problems in multithreaded applications, GLib
126 * supports error-checking mutexes that will give you helpful error
127 * messages on common problems. To use error-checking mutexes, define
128 * the symbol #G_ERRORCHECK_MUTEXES when compiling the application.
132 * G_THREADS_IMPL_POSIX:
134 * This macro is defined if POSIX style threads are used.
140 * This macro is defined, for backward compatibility, to indicate that
141 * GLib has been compiled with thread support. As of glib 2.28, it is
146 * G_THREADS_IMPL_NONE:
148 * This macro is defined if no thread implementation is used. You can,
149 * however, provide one to g_thread_init() to make GLib multi-thread
153 /* G_LOCK Documentation {{{1 ---------------------------------------------- */
155 /* IMPLEMENTATION NOTE:
157 * G_LOCK_DEFINE and friends are convenience macros defined in
158 * gthread.h. Their documentation lives here.
163 * @name: the name of the lock.
165 * The %G_LOCK_* macros provide a convenient interface to #GStaticMutex
166 * with the advantage that they will expand to nothing in programs
167 * compiled against a thread-disabled GLib, saving code and memory
168 * there. #G_LOCK_DEFINE defines a lock. It can appear anywhere
169 * variable definitions may appear in programs, i.e. in the first block
170 * of a function or outside of functions. The @name parameter will be
171 * mangled to get the name of the #GStaticMutex. This means that you
172 * can use names of existing variables as the parameter - e.g. the name
173 * of the variable you intent to protect with the lock. Look at our
174 * <function>give_me_next_number()</function> example using the
178 * <title>Using the %G_LOCK_* convenience macros</title>
180 * G_LOCK_DEFINE (current_number);
183 * give_me_next_number (void)
185 * static int current_number = 0;
188 * G_LOCK (current_number);
189 * ret_val = current_number = calc_next_number (current_number);
190 * G_UNLOCK (current_number);
199 * G_LOCK_DEFINE_STATIC:
200 * @name: the name of the lock.
202 * This works like #G_LOCK_DEFINE, but it creates a static object.
207 * @name: the name of the lock.
209 * This declares a lock, that is defined with #G_LOCK_DEFINE in another
215 * @name: the name of the lock.
217 * Works like g_mutex_lock(), but for a lock defined with
223 * @name: the name of the lock.
224 * @Returns: %TRUE, if the lock could be locked.
226 * Works like g_mutex_trylock(), but for a lock defined with
232 * @name: the name of the lock.
234 * Works like g_mutex_unlock(), but for a lock defined with
238 /* GThreadError {{{1 ------------------------------------------------------- */
241 * @G_THREAD_ERROR_AGAIN: a thread couldn't be created due to resource
242 * shortage. Try again later.
244 * Possible errors of thread related functions.
250 * The error domain of the GLib thread subsystem.
253 g_thread_error_quark (void)
255 return g_quark_from_static_string ("g_thread_error");
258 /* Miscellaneous Structures {{{1 ------------------------------------------ */
259 typedef struct _GRealThread GRealThread;
263 /* Bit 0 protects private_data. To avoid deadlocks, do not block while
264 * holding this (particularly on the g_thread lock). */
265 volatile gint private_data_lock;
266 GArray *private_data;
269 GSystemThread system_thread;
272 #define LOCK_PRIVATE_DATA(self) g_bit_lock (&(self)->private_data_lock, 0)
273 #define UNLOCK_PRIVATE_DATA(self) g_bit_unlock (&(self)->private_data_lock, 0)
275 typedef struct _GStaticPrivateNode GStaticPrivateNode;
276 struct _GStaticPrivateNode
279 GDestroyNotify destroy;
282 static void g_thread_cleanup (gpointer data);
283 static void g_thread_fail (void);
284 static guint64 gettime (void);
286 guint64 (*g_thread_gettime) (void) = gettime;
288 /* Global Variables {{{1 -------------------------------------------------- */
290 static GSystemThread zero_thread; /* This is initialized to all zero */
291 gboolean g_thread_use_default_impl = TRUE;
294 * g_thread_supported:
295 * @Returns: %TRUE, if the thread system is initialized.
297 * This function returns %TRUE if the thread system is initialized, and
298 * %FALSE if it is not.
300 * <note><para>This function is actually a macro. Apart from taking the
301 * address of it you can however use it as if it was a
302 * function.</para></note>
305 /* IMPLEMENTATION NOTE:
307 * g_thread_supported() is just returns g_threads_got_initialized
309 gboolean g_threads_got_initialized = FALSE;
312 /* Thread Implementation Virtual Function Table {{{1 ---------------------- */
313 /* Virtual Function Table Documentation {{{2 ------------------------------ */
316 * @mutex_new: virtual function pointer for g_mutex_new()
317 * @mutex_lock: virtual function pointer for g_mutex_lock()
318 * @mutex_trylock: virtual function pointer for g_mutex_trylock()
319 * @mutex_unlock: virtual function pointer for g_mutex_unlock()
320 * @mutex_free: virtual function pointer for g_mutex_free()
321 * @cond_new: virtual function pointer for g_cond_new()
322 * @cond_signal: virtual function pointer for g_cond_signal()
323 * @cond_broadcast: virtual function pointer for g_cond_broadcast()
324 * @cond_wait: virtual function pointer for g_cond_wait()
325 * @cond_timed_wait: virtual function pointer for g_cond_timed_wait()
326 * @cond_free: virtual function pointer for g_cond_free()
327 * @private_new: virtual function pointer for g_private_new()
328 * @private_get: virtual function pointer for g_private_get()
329 * @private_set: virtual function pointer for g_private_set()
330 * @thread_create: virtual function pointer for g_thread_create()
331 * @thread_yield: virtual function pointer for g_thread_yield()
332 * @thread_join: virtual function pointer for g_thread_join()
333 * @thread_exit: virtual function pointer for g_thread_exit()
334 * @thread_set_priority: virtual function pointer for
335 * g_thread_set_priority()
336 * @thread_self: virtual function pointer for g_thread_self()
337 * @thread_equal: used internally by recursive mutex locks and by some
340 * This function table is used by g_thread_init() to initialize the
341 * thread system. The functions in the table are directly used by their
342 * g_* prepended counterparts (described in this document). For
343 * example, if you call g_mutex_new() then mutex_new() from the table
344 * provided to g_thread_init() will be called.
346 * <note><para>Do not use this struct unless you know what you are
347 * doing.</para></note>
350 /* IMPLEMENTATION NOTE:
352 * g_thread_functions_for_glib_use is a global symbol that gets used by
353 * most of the "primitive" threading calls. g_mutex_lock(), for
354 * example, is just a macro that calls the appropriate virtual function
357 * For that reason, all of those macros are documented here.
359 GThreadFunctions g_thread_functions_for_glib_use = {
360 /* GMutex Virtual Functions {{{2 ------------------------------------------ */
365 * The #GMutex struct is an opaque data structure to represent a mutex
366 * (mutual exclusion). It can be used to protect data against shared
367 * access. Take for example the following function:
370 * <title>A function which will not work in a threaded environment</title>
373 * give_me_next_number (void)
375 * static int current_number = 0;
377 * /<!-- -->* now do a very complicated calculation to calculate the new
378 * * number, this might for example be a random number generator
380 * current_number = calc_next_number (current_number);
382 * return current_number;
387 * It is easy to see that this won't work in a multi-threaded
388 * application. There current_number must be protected against shared
389 * access. A first naive implementation would be:
392 * <title>The wrong way to write a thread-safe function</title>
395 * give_me_next_number (void)
397 * static int current_number = 0;
399 * static GMutex * mutex = NULL;
401 * if (!mutex) mutex = g_mutex_new (<!-- -->);
403 * g_mutex_lock (mutex);
404 * ret_val = current_number = calc_next_number (current_number);
405 * g_mutex_unlock (mutex);
412 * This looks like it would work, but there is a race condition while
413 * constructing the mutex and this code cannot work reliable. Please do
414 * not use such constructs in your own programs! One working solution
418 * <title>A correct thread-safe function</title>
420 * static GMutex *give_me_next_number_mutex = NULL;
422 * /<!-- -->* this function must be called before any call to
423 * * give_me_next_number(<!-- -->)
425 * * it must be called exactly once.
428 * init_give_me_next_number (void)
430 * g_assert (give_me_next_number_mutex == NULL);
431 * give_me_next_number_mutex = g_mutex_new (<!-- -->);
435 * give_me_next_number (void)
437 * static int current_number = 0;
440 * g_mutex_lock (give_me_next_number_mutex);
441 * ret_val = current_number = calc_next_number (current_number);
442 * g_mutex_unlock (give_me_next_number_mutex);
449 * #GStaticMutex provides a simpler and safer way of doing this.
451 * If you want to use a mutex, and your code should also work without
452 * calling g_thread_init() first, then you cannot use a #GMutex, as
453 * g_mutex_new() requires that the thread system be initialized. Use a
454 * #GStaticMutex instead.
456 * A #GMutex should only be accessed via the following functions.
458 * <note><para>All of the <function>g_mutex_*</function> functions are
459 * actually macros. Apart from taking their addresses, you can however
460 * use them as if they were functions.</para></note>
465 * @Returns: a new #GMutex.
467 * Creates a new #GMutex.
469 * <note><para>This function will abort if g_thread_init() has not been
470 * called yet.</para></note>
472 (GMutex*(*)())g_thread_fail,
478 * Locks @mutex. If @mutex is already locked by another thread, the
479 * current thread will block until @mutex is unlocked by the other
482 * This function can be used even if g_thread_init() has not yet been
483 * called, and, in that case, will do nothing.
485 * <note><para>#GMutex is neither guaranteed to be recursive nor to be
486 * non-recursive, i.e. a thread could deadlock while calling
487 * g_mutex_lock(), if it already has locked @mutex. Use
488 * #GStaticRecMutex, if you need recursive mutexes.</para></note>
495 * @Returns: %TRUE, if @mutex could be locked.
497 * Tries to lock @mutex. If @mutex is already locked by another thread,
498 * it immediately returns %FALSE. Otherwise it locks @mutex and returns
501 * This function can be used even if g_thread_init() has not yet been
502 * called, and, in that case, will immediately return %TRUE.
504 * <note><para>#GMutex is neither guaranteed to be recursive nor to be
505 * non-recursive, i.e. the return value of g_mutex_trylock() could be
506 * both %FALSE or %TRUE, if the current thread already has locked
507 * @mutex. Use #GStaticRecMutex, if you need recursive
508 * mutexes.</para></note>
516 * Unlocks @mutex. If another thread is blocked in a g_mutex_lock()
517 * call for @mutex, it will be woken and can lock @mutex itself.
519 * This function can be used even if g_thread_init() has not yet been
520 * called, and, in that case, will do nothing.
530 * <note><para>Calling g_mutex_free() on a locked mutex may result in
531 * undefined behaviour.</para></note>
535 /* GCond Virtual Functions {{{2 ------------------------------------------ */
540 * The #GCond struct is an opaque data structure that represents a
541 * condition. Threads can block on a #GCond if they find a certain
542 * condition to be false. If other threads change the state of this
543 * condition they signal the #GCond, and that causes the waiting
544 * threads to be woken up.
548 * Using GCond to block a thread until a condition is satisfied
551 * GCond* data_cond = NULL; /<!-- -->* Must be initialized somewhere *<!-- -->/
552 * GMutex* data_mutex = NULL; /<!-- -->* Must be initialized somewhere *<!-- -->/
553 * gpointer current_data = NULL;
556 * push_data (gpointer data)
558 * g_mutex_lock (data_mutex);
559 * current_data = data;
560 * g_cond_signal (data_cond);
561 * g_mutex_unlock (data_mutex);
569 * g_mutex_lock (data_mutex);
570 * while (!current_data)
571 * g_cond_wait (data_cond, data_mutex);
572 * data = current_data;
573 * current_data = NULL;
574 * g_mutex_unlock (data_mutex);
581 * Whenever a thread calls <function>pop_data()</function> now, it will
582 * wait until current_data is non-%NULL, i.e. until some other thread
583 * has called <function>push_data()</function>.
585 * <note><para>It is important to use the g_cond_wait() and
586 * g_cond_timed_wait() functions only inside a loop which checks for the
587 * condition to be true. It is not guaranteed that the waiting thread
588 * will find the condition fulfilled after it wakes up, even if the
589 * signaling thread left the condition in that state: another thread may
590 * have altered the condition before the waiting thread got the chance
591 * to be woken up, even if the condition itself is protected by a
592 * #GMutex, like above.</para></note>
594 * A #GCond should only be accessed via the following functions.
596 * <note><para>All of the <function>g_cond_*</function> functions are
597 * actually macros. Apart from taking their addresses, you can however
598 * use them as if they were functions.</para></note>
603 * @Returns: a new #GCond.
605 * Creates a new #GCond. This function will abort, if g_thread_init()
606 * has not been called yet.
608 (GCond*(*)())g_thread_fail,
614 * If threads are waiting for @cond, exactly one of them is woken up.
615 * It is good practice to hold the same lock as the waiting thread
616 * while calling this function, though not required.
618 * This function can be used even if g_thread_init() has not yet been
619 * called, and, in that case, will do nothing.
627 * If threads are waiting for @cond, all of them are woken up. It is
628 * good practice to lock the same mutex as the waiting threads, while
629 * calling this function, though not required.
631 * This function can be used even if g_thread_init() has not yet been
632 * called, and, in that case, will do nothing.
639 * @mutex: a #GMutex, that is currently locked.
641 * Waits until this thread is woken up on @cond. The @mutex is unlocked
642 * before falling asleep and locked again before resuming.
644 * This function can be used even if g_thread_init() has not yet been
645 * called, and, in that case, will immediately return.
652 * @mutex: a #GMutex that is currently locked.
653 * @abs_time: a #GTimeVal, determining the final time.
654 * @Returns: %TRUE if @cond was signalled, or %FALSE on timeout.
656 * Waits until this thread is woken up on @cond, but not longer than
657 * until the time specified by @abs_time. The @mutex is unlocked before
658 * falling asleep and locked again before resuming.
660 * If @abs_time is %NULL, g_cond_timed_wait() acts like g_cond_wait().
662 * This function can be used even if g_thread_init() has not yet been
663 * called, and, in that case, will immediately return %TRUE.
665 * To easily calculate @abs_time a combination of g_get_current_time()
666 * and g_time_val_add() can be used.
674 * Destroys the #GCond.
678 /* GPrivate Virtual Functions {{{2 --------------------------------------- */
684 * #GStaticPrivate is a better choice for most uses.
687 * The #GPrivate struct is an opaque data structure to represent a
688 * thread private data key. Threads can thereby obtain and set a
689 * pointer which is private to the current thread. Take our
690 * <function>give_me_next_number(<!-- -->)</function> example from
691 * above. Suppose we don't want <literal>current_number</literal> to be
692 * shared between the threads, but instead to be private to each thread.
693 * This can be done as follows:
696 * <title>Using GPrivate for per-thread data</title>
698 * GPrivate* current_number_key = NULL; /<!-- -->* Must be initialized somewhere
699 * with g_private_new (g_free); *<!-- -->/
702 * give_me_next_number (void)
704 * int *current_number = g_private_get (current_number_key);
706 * if (!current_number)
708 * current_number = g_new (int, 1);
709 * *current_number = 0;
710 * g_private_set (current_number_key, current_number);
713 * *current_number = calc_next_number (*current_number);
715 * return *current_number;
720 * Here the pointer belonging to the key
721 * <literal>current_number_key</literal> is read. If it is %NULL, it has
722 * not been set yet. Then get memory for an integer value, assign this
723 * memory to the pointer and write the pointer back. Now we have an
724 * integer value that is private to the current thread.
726 * The #GPrivate struct should only be accessed via the following
729 * <note><para>All of the <function>g_private_*</function> functions are
730 * actually macros. Apart from taking their addresses, you can however
731 * use them as if they were functions.</para></note>
736 * @destructor: a function to destroy the data keyed to #GPrivate when
738 * @Returns: a new #GPrivate.
740 * Creates a new #GPrivate. If @destructor is non-%NULL, it is a
741 * pointer to a destructor function. Whenever a thread ends and the
742 * corresponding pointer keyed to this instance of #GPrivate is
743 * non-%NULL, the destructor is called with this pointer as the
747 * #GStaticPrivate is a better choice for most uses.
750 * <note><para>@destructor is used quite differently from @notify in
751 * g_static_private_set().</para></note>
753 * <note><para>A #GPrivate cannot be freed. Reuse it instead, if you
754 * can, to avoid shortage, or use #GStaticPrivate.</para></note>
756 * <note><para>This function will abort if g_thread_init() has not been
757 * called yet.</para></note>
759 (GPrivate*(*)(GDestroyNotify))g_thread_fail,
763 * @private_key: a #GPrivate.
764 * @Returns: the corresponding pointer.
766 * Returns the pointer keyed to @private_key for the current thread. If
767 * g_private_set() hasn't been called for the current @private_key and
768 * thread yet, this pointer will be %NULL.
770 * This function can be used even if g_thread_init() has not yet been
771 * called, and, in that case, will return the value of @private_key
772 * casted to #gpointer. Note however, that private data set
773 * <emphasis>before</emphasis> g_thread_init() will
774 * <emphasis>not</emphasis> be retained <emphasis>after</emphasis> the
775 * call. Instead, %NULL will be returned in all threads directly after
776 * g_thread_init(), regardless of any g_private_set() calls issued
777 * before threading system intialization.
783 * @private_key: a #GPrivate.
784 * @data: the new pointer.
786 * Sets the pointer keyed to @private_key for the current thread.
788 * This function can be used even if g_thread_init() has not yet been
789 * called, and, in that case, will set @private_key to @data casted to
790 * #GPrivate*. See g_private_get() for resulting caveats.
794 /* GThread Virtual Functions {{{2 ---------------------------------------- */
798 * The #GThread struct represents a running thread. It has three public
799 * read-only members, but the underlying struct is bigger, so you must
800 * not copy this struct.
802 * <note><para>Resources for a joinable thread are not fully released
803 * until g_thread_join() is called for that thread.</para></note>
808 * @data: data passed to the thread.
809 * @Returns: the return value of the thread, which will be returned by
812 * Specifies the type of the @func functions passed to
813 * g_thread_create() or g_thread_create_full().
818 * @G_THREAD_PRIORITY_LOW: a priority lower than normal
819 * @G_THREAD_PRIORITY_NORMAL: the default priority
820 * @G_THREAD_PRIORITY_HIGH: a priority higher than normal
821 * @G_THREAD_PRIORITY_URGENT: the highest priority
823 * Specifies the priority of a thread.
825 * <note><para>It is not guaranteed that threads with different priorities
826 * really behave accordingly. On some systems (e.g. Linux) there are no
827 * thread priorities. On other systems (e.g. Solaris) there doesn't
828 * seem to be different scheduling for different priorities. All in all
829 * try to avoid being dependent on priorities.</para></note>
834 * @func: a function to execute in the new thread.
835 * @data: an argument to supply to the new thread.
836 * @joinable: should this thread be joinable?
837 * @error: return location for error.
838 * @Returns: the new #GThread on success.
840 * This function creates a new thread with the default priority.
842 * If @joinable is %TRUE, you can wait for this threads termination
843 * calling g_thread_join(). Otherwise the thread will just disappear
844 * when it terminates.
846 * The new thread executes the function @func with the argument @data.
847 * If the thread was created successfully, it is returned.
849 * @error can be %NULL to ignore errors, or non-%NULL to report errors.
850 * The error is set, if and only if the function returns %NULL.
852 (void(*)(GThreadFunc, gpointer, gulong,
853 gboolean, gboolean, GThreadPriority,
854 gpointer, GError**))g_thread_fail,
859 * Gives way to other threads waiting to be scheduled.
861 * This function is often used as a method to make busy wait less evil.
862 * But in most cases you will encounter, there are better methods to do
863 * that. So in general you shouldn't use this function.
867 NULL, /* thread_join */
868 NULL, /* thread_exit */
869 NULL, /* thread_set_priority */
870 NULL, /* thread_self */
871 NULL /* thread_equal */
874 /* Local Data {{{1 -------------------------------------------------------- */
876 static GMutex *g_once_mutex = NULL;
877 static GCond *g_once_cond = NULL;
878 static GPrivate *g_thread_specific_private = NULL;
879 static GRealThread *g_thread_all_threads = NULL;
880 static GSList *g_thread_free_indices = NULL;
881 static GSList* g_once_init_list = NULL;
883 G_LOCK_DEFINE_STATIC (g_thread);
885 /* Initialisation {{{1 ---------------------------------------------------- */
889 * @vtable: a function table of type #GThreadFunctions, that provides
890 * the entry points to the thread system to be used.
892 * If you use GLib from more than one thread, you must initialize the
893 * thread system by calling g_thread_init(). Most of the time you will
894 * only have to call <literal>g_thread_init (NULL)</literal>.
896 * <note><para>Do not call g_thread_init() with a non-%NULL parameter unless
897 * you really know what you are doing.</para></note>
899 * <note><para>g_thread_init() must not be called directly or indirectly as a
900 * callback from GLib. Also no mutexes may be currently locked while
901 * calling g_thread_init().</para></note>
903 * <note><para>g_thread_init() changes the way in which #GTimer measures
904 * elapsed time. As a consequence, timers that are running while
905 * g_thread_init() is called may report unreliable times.</para></note>
907 * Calling g_thread_init() multiple times is allowed (since version
908 * 2.24), but nothing happens except for the first call. If the
909 * argument is non-%NULL on such a call a warning will be printed, but
910 * otherwise the argument is ignored.
912 * If no thread system is available and @vtable is %NULL or if not all
913 * elements of @vtable are non-%NULL, then g_thread_init() will abort.
915 * <note><para>To use g_thread_init() in your program, you have to link with
916 * the libraries that the command <command>pkg-config --libs
917 * gthread-2.0</command> outputs. This is not the case for all the
918 * other thread related functions of GLib. Those can be used without
919 * having to link with the thread libraries.</para></note>
922 /* This must be called only once, before any threads are created.
923 * It will only be called from g_thread_init() in -lgthread.
926 g_thread_init_glib (void)
928 /* We let the main thread (the one that calls g_thread_init) inherit
929 * the static_private data set before calling g_thread_init
931 GRealThread* main_thread = (GRealThread*) g_thread_self ();
933 /* mutex and cond creation works without g_threads_got_initialized */
934 g_once_mutex = g_mutex_new ();
935 g_once_cond = g_cond_new ();
937 /* we may only create mutex and cond in here */
938 _g_mem_thread_init_noprivate_nomessage ();
940 /* setup the basic threading system */
941 g_threads_got_initialized = TRUE;
942 g_thread_specific_private = g_private_new (g_thread_cleanup);
943 g_private_set (g_thread_specific_private, main_thread);
944 G_THREAD_UF (thread_self, (&main_thread->system_thread));
946 /* complete memory system initialization, g_private_*() works now */
947 _g_slice_thread_init_nomessage ();
949 /* accomplish log system initialization to enable messaging */
950 _g_messages_thread_init_nomessage ();
952 /* we may run full-fledged initializers from here */
953 _g_convert_thread_init ();
954 _g_rand_thread_init ();
955 _g_main_thread_init ();
956 _g_utils_thread_init ();
957 _g_futex_thread_init ();
959 _g_win32_thread_init ();
963 /* The following sections implement: GOnce, GStaticMutex, GStaticRecMutex,
967 /* GOnce {{{1 ------------------------------------------------------------- */
971 * @status: the status of the #GOnce
972 * @retval: the value returned by the call to the function, if @status
973 * is %G_ONCE_STATUS_READY
975 * A #GOnce struct controls a one-time initialization function. Any
976 * one-time initialization function must have its own unique #GOnce
985 * A #GOnce must be initialized with this macro before it can be used.
989 * GOnce my_once = G_ONCE_INIT;
998 * @G_ONCE_STATUS_NOTCALLED: the function has not been called yet.
999 * @G_ONCE_STATUS_PROGRESS: the function call is currently in progress.
1000 * @G_ONCE_STATUS_READY: the function has been called.
1002 * The possible statuses of a one-time initialization function
1003 * controlled by a #GOnce struct.
1010 * @once: a #GOnce structure
1011 * @func: the #GThreadFunc function associated to @once. This function
1012 * is called only once, regardless of the number of times it and
1013 * its associated #GOnce struct are passed to g_once().
1014 * @arg: data to be passed to @func
1016 * The first call to this routine by a process with a given #GOnce
1017 * struct calls @func with the given argument. Thereafter, subsequent
1018 * calls to g_once() with the same #GOnce struct do not call @func
1019 * again, but return the stored result of the first call. On return
1020 * from g_once(), the status of @once will be %G_ONCE_STATUS_READY.
1022 * For example, a mutex or a thread-specific data key must be created
1023 * exactly once. In a threaded environment, calling g_once() ensures
1024 * that the initialization is serialized across multiple threads.
1026 * <note><para>Calling g_once() recursively on the same #GOnce struct in
1027 * @func will lead to a deadlock.</para></note>
1032 * get_debug_flags (void)
1034 * static GOnce my_once = G_ONCE_INIT;
1036 * g_once (&my_once, parse_debug_flags, NULL);
1038 * return my_once.retval;
1041 * </informalexample>
1046 g_once_impl (GOnce *once,
1050 g_mutex_lock (g_once_mutex);
1052 while (once->status == G_ONCE_STATUS_PROGRESS)
1053 g_cond_wait (g_once_cond, g_once_mutex);
1055 if (once->status != G_ONCE_STATUS_READY)
1057 once->status = G_ONCE_STATUS_PROGRESS;
1058 g_mutex_unlock (g_once_mutex);
1060 once->retval = func (arg);
1062 g_mutex_lock (g_once_mutex);
1063 once->status = G_ONCE_STATUS_READY;
1064 g_cond_broadcast (g_once_cond);
1067 g_mutex_unlock (g_once_mutex);
1069 return once->retval;
1073 * g_once_init_enter:
1074 * @value_location: location of a static initializable variable
1076 * @Returns: %TRUE if the initialization section should be entered,
1077 * %FALSE and blocks otherwise
1079 * Function to be called when starting a critical initialization
1080 * section. The argument @value_location must point to a static
1081 * 0-initialized variable that will be set to a value other than 0 at
1082 * the end of the initialization section. In combination with
1083 * g_once_init_leave() and the unique address @value_location, it can
1084 * be ensured that an initialization section will be executed only once
1085 * during a program's life time, and that concurrent threads are
1086 * blocked until initialization completed. To be used in constructs
1091 * static gsize initialization_value = 0;
1093 * if (g_once_init_enter (&initialization_value))
1095 * gsize setup_value = 42; /<!-- -->* initialization code here *<!-- -->/
1097 * g_once_init_leave (&initialization_value, setup_value);
1100 * /<!-- -->* use initialization_value here *<!-- -->/
1102 * </informalexample>
1107 g_once_init_enter_impl (volatile gsize *value_location)
1109 gboolean need_init = FALSE;
1110 g_mutex_lock (g_once_mutex);
1111 if (g_atomic_pointer_get (value_location) == NULL)
1113 if (!g_slist_find (g_once_init_list, (void*) value_location))
1116 g_once_init_list = g_slist_prepend (g_once_init_list, (void*) value_location);
1120 g_cond_wait (g_once_cond, g_once_mutex);
1121 while (g_slist_find (g_once_init_list, (void*) value_location));
1123 g_mutex_unlock (g_once_mutex);
1128 * g_once_init_leave:
1129 * @value_location: location of a static initializable variable
1131 * @initialization_value: new non-0 value for *@value_location.
1133 * Counterpart to g_once_init_enter(). Expects a location of a static
1134 * 0-initialized initialization variable, and an initialization value
1135 * other than 0. Sets the variable to the initialization value, and
1136 * releases concurrent threads blocking in g_once_init_enter() on this
1137 * initialization variable.
1142 g_once_init_leave (volatile gsize *value_location,
1143 gsize initialization_value)
1145 g_return_if_fail (g_atomic_pointer_get (value_location) == NULL);
1146 g_return_if_fail (initialization_value != 0);
1147 g_return_if_fail (g_once_init_list != NULL);
1149 g_atomic_pointer_set (value_location, initialization_value);
1150 g_mutex_lock (g_once_mutex);
1151 g_once_init_list = g_slist_remove (g_once_init_list, (void*) value_location);
1152 g_cond_broadcast (g_once_cond);
1153 g_mutex_unlock (g_once_mutex);
1156 /* GStaticMutex {{{1 ------------------------------------------------------ */
1161 * A #GStaticMutex works like a #GMutex, but it has one significant
1162 * advantage. It doesn't need to be created at run-time like a #GMutex,
1163 * but can be defined at compile-time. Here is a shorter, easier and
1164 * safer version of our <function>give_me_next_number()</function>
1169 * Using <structname>GStaticMutex</structname>
1170 * to simplify thread-safe programming
1174 * give_me_next_number (void)
1176 * static int current_number = 0;
1178 * static GStaticMutex mutex = G_STATIC_MUTEX_INIT;
1180 * g_static_mutex_lock (&mutex);
1181 * ret_val = current_number = calc_next_number (current_number);
1182 * g_static_mutex_unlock (&mutex);
1189 * Sometimes you would like to dynamically create a mutex. If you don't
1190 * want to require prior calling to g_thread_init(), because your code
1191 * should also be usable in non-threaded programs, you are not able to
1192 * use g_mutex_new() and thus #GMutex, as that requires a prior call to
1193 * g_thread_init(). In theses cases you can also use a #GStaticMutex.
1194 * It must be initialized with g_static_mutex_init() before using it
1195 * and freed with with g_static_mutex_free() when not needed anymore to
1196 * free up any allocated resources.
1198 * Even though #GStaticMutex is not opaque, it should only be used with
1199 * the following functions, as it is defined differently on different
1202 * All of the <function>g_static_mutex_*</function> functions apart
1203 * from <function>g_static_mutex_get_mutex</function> can also be used
1204 * even if g_thread_init() has not yet been called. Then they do
1205 * nothing, apart from <function>g_static_mutex_trylock</function>,
1206 * which does nothing but returning %TRUE.
1208 * <note><para>All of the <function>g_static_mutex_*</function>
1209 * functions are actually macros. Apart from taking their addresses, you
1210 * can however use them as if they were functions.</para></note>
1214 * G_STATIC_MUTEX_INIT:
1216 * A #GStaticMutex must be initialized with this macro, before it can
1217 * be used. This macro can used be to initialize a variable, but it
1218 * cannot be assigned to a variable. In that case you have to use
1219 * g_static_mutex_init().
1223 * GStaticMutex my_mutex = G_STATIC_MUTEX_INIT;
1225 * </informalexample>
1229 * g_static_mutex_init:
1230 * @mutex: a #GStaticMutex to be initialized.
1232 * Initializes @mutex. Alternatively you can initialize it with
1233 * #G_STATIC_MUTEX_INIT.
1236 g_static_mutex_init (GStaticMutex *mutex)
1238 static const GStaticMutex init_mutex = G_STATIC_MUTEX_INIT;
1240 g_return_if_fail (mutex);
1242 *mutex = init_mutex;
1245 /* IMPLEMENTATION NOTE:
1247 * On some platforms a GStaticMutex is actually a normal GMutex stored
1248 * inside of a structure instead of being allocated dynamically. We can
1249 * only do this for platforms on which we know, in advance, how to
1250 * allocate (size) and initialise (value) that memory.
1252 * On other platforms, a GStaticMutex is nothing more than a pointer to
1253 * a GMutex. In that case, the first access we make to the static mutex
1254 * must first allocate the normal GMutex and store it into the pointer.
1256 * configure.ac writes macros into glibconfig.h to determine if
1257 * g_static_mutex_get_mutex() accesses the structure in memory directly
1258 * (on platforms where we are able to do that) or if it ends up here,
1259 * where we may have to allocate the GMutex before returning it.
1263 * g_static_mutex_get_mutex:
1264 * @mutex: a #GStaticMutex.
1265 * @Returns: the #GMutex corresponding to @mutex.
1267 * For some operations (like g_cond_wait()) you must have a #GMutex
1268 * instead of a #GStaticMutex. This function will return the
1269 * corresponding #GMutex for @mutex.
1272 g_static_mutex_get_mutex_impl (GMutex** mutex)
1276 if (!g_thread_supported ())
1279 result = g_atomic_pointer_get (mutex);
1283 g_assert (g_once_mutex);
1285 g_mutex_lock (g_once_mutex);
1290 result = g_mutex_new ();
1291 g_atomic_pointer_set (mutex, result);
1294 g_mutex_unlock (g_once_mutex);
1300 /* IMPLEMENTATION NOTE:
1302 * g_static_mutex_lock(), g_static_mutex_trylock() and
1303 * g_static_mutex_unlock() are all preprocessor macros that wrap the
1304 * corresponding g_mutex_*() function around a call to
1305 * g_static_mutex_get_mutex().
1309 * g_static_mutex_lock:
1310 * @mutex: a #GStaticMutex.
1312 * Works like g_mutex_lock(), but for a #GStaticMutex.
1316 * g_static_mutex_trylock:
1317 * @mutex: a #GStaticMutex.
1318 * @Returns: %TRUE, if the #GStaticMutex could be locked.
1320 * Works like g_mutex_trylock(), but for a #GStaticMutex.
1324 * g_static_mutex_unlock:
1325 * @mutex: a #GStaticMutex.
1327 * Works like g_mutex_unlock(), but for a #GStaticMutex.
1331 * g_static_mutex_free:
1332 * @mutex: a #GStaticMutex to be freed.
1334 * Releases all resources allocated to @mutex.
1336 * You don't have to call this functions for a #GStaticMutex with an
1337 * unbounded lifetime, i.e. objects declared 'static', but if you have
1338 * a #GStaticMutex as a member of a structure and the structure is
1339 * freed, you should also free the #GStaticMutex.
1341 * <note><para>Calling g_static_mutex_free() on a locked mutex may
1342 * result in undefined behaviour.</para></note>
1345 g_static_mutex_free (GStaticMutex* mutex)
1347 GMutex **runtime_mutex;
1349 g_return_if_fail (mutex);
1351 /* The runtime_mutex is the first (or only) member of GStaticMutex,
1352 * see both versions (of glibconfig.h) in configure.ac. Note, that
1353 * this variable is NULL, if g_thread_init() hasn't been called or
1354 * if we're using the default thread implementation and it provides
1355 * static mutexes. */
1356 runtime_mutex = ((GMutex**)mutex);
1359 g_mutex_free (*runtime_mutex);
1361 *runtime_mutex = NULL;
1364 /* ------------------------------------------------------------------------ */
1369 * A #GStaticRecMutex works like a #GStaticMutex, but it can be locked
1370 * multiple times by one thread. If you enter it n times, you have to
1371 * unlock it n times again to let other threads lock it. An exception
1372 * is the function g_static_rec_mutex_unlock_full(): that allows you to
1373 * unlock a #GStaticRecMutex completely returning the depth, (i.e. the
1374 * number of times this mutex was locked). The depth can later be used
1375 * to restore the state of the #GStaticRecMutex by calling
1376 * g_static_rec_mutex_lock_full().
1378 * Even though #GStaticRecMutex is not opaque, it should only be used
1379 * with the following functions.
1381 * All of the <function>g_static_rec_mutex_*</function> functions can
1382 * be used even if g_thread_init() has not been called. Then they do
1383 * nothing, apart from <function>g_static_rec_mutex_trylock</function>,
1384 * which does nothing but returning %TRUE.
1388 * G_STATIC_REC_MUTEX_INIT:
1390 * A #GStaticRecMutex must be initialized with this macro before it can
1391 * be used. This macro can used be to initialize a variable, but it
1392 * cannot be assigned to a variable. In that case you have to use
1393 * g_static_rec_mutex_init().
1397 * GStaticRecMutex my_mutex = G_STATIC_REC_MUTEX_INIT;
1403 * g_static_rec_mutex_init:
1404 * @mutex: a #GStaticRecMutex to be initialized.
1406 * A #GStaticRecMutex must be initialized with this function before it
1407 * can be used. Alternatively you can initialize it with
1408 * #G_STATIC_REC_MUTEX_INIT.
1411 g_static_rec_mutex_init (GStaticRecMutex *mutex)
1413 static const GStaticRecMutex init_mutex = G_STATIC_REC_MUTEX_INIT;
1415 g_return_if_fail (mutex);
1417 *mutex = init_mutex;
1421 * g_static_rec_mutex_lock:
1422 * @mutex: a #GStaticRecMutex to lock.
1424 * Locks @mutex. If @mutex is already locked by another thread, the
1425 * current thread will block until @mutex is unlocked by the other
1426 * thread. If @mutex is already locked by the calling thread, this
1427 * functions increases the depth of @mutex and returns immediately.
1430 g_static_rec_mutex_lock (GStaticRecMutex* mutex)
1434 g_return_if_fail (mutex);
1436 if (!g_thread_supported ())
1439 G_THREAD_UF (thread_self, (&self));
1441 if (g_system_thread_equal (self, mutex->owner))
1446 g_static_mutex_lock (&mutex->mutex);
1447 g_system_thread_assign (mutex->owner, self);
1452 * g_static_rec_mutex_trylock:
1453 * @mutex: a #GStaticRecMutex to lock.
1454 * @Returns: %TRUE, if @mutex could be locked.
1456 * Tries to lock @mutex. If @mutex is already locked by another thread,
1457 * it immediately returns %FALSE. Otherwise it locks @mutex and returns
1458 * %TRUE. If @mutex is already locked by the calling thread, this
1459 * functions increases the depth of @mutex and immediately returns
1463 g_static_rec_mutex_trylock (GStaticRecMutex* mutex)
1467 g_return_val_if_fail (mutex, FALSE);
1469 if (!g_thread_supported ())
1472 G_THREAD_UF (thread_self, (&self));
1474 if (g_system_thread_equal (self, mutex->owner))
1480 if (!g_static_mutex_trylock (&mutex->mutex))
1483 g_system_thread_assign (mutex->owner, self);
1489 * g_static_rec_mutex_unlock:
1490 * @mutex: a #GStaticRecMutex to unlock.
1492 * Unlocks @mutex. Another thread will be allowed to lock @mutex only
1493 * when it has been unlocked as many times as it had been locked
1494 * before. If @mutex is completely unlocked and another thread is
1495 * blocked in a g_static_rec_mutex_lock() call for @mutex, it will be
1496 * woken and can lock @mutex itself.
1499 g_static_rec_mutex_unlock (GStaticRecMutex* mutex)
1501 g_return_if_fail (mutex);
1503 if (!g_thread_supported ())
1506 if (mutex->depth > 1)
1511 g_system_thread_assign (mutex->owner, zero_thread);
1512 g_static_mutex_unlock (&mutex->mutex);
1516 * g_static_rec_mutex_lock_full:
1517 * @mutex: a #GStaticRecMutex to lock.
1518 * @depth: number of times this mutex has to be unlocked to be
1519 * completely unlocked.
1521 * Works like calling g_static_rec_mutex_lock() for @mutex @depth times.
1524 g_static_rec_mutex_lock_full (GStaticRecMutex *mutex,
1528 g_return_if_fail (mutex);
1530 if (!g_thread_supported ())
1536 G_THREAD_UF (thread_self, (&self));
1538 if (g_system_thread_equal (self, mutex->owner))
1540 mutex->depth += depth;
1543 g_static_mutex_lock (&mutex->mutex);
1544 g_system_thread_assign (mutex->owner, self);
1545 mutex->depth = depth;
1549 * g_static_rec_mutex_unlock_full:
1550 * @mutex: a #GStaticRecMutex to completely unlock.
1551 * @Returns: number of times @mutex has been locked by the current
1554 * Completely unlocks @mutex. If another thread is blocked in a
1555 * g_static_rec_mutex_lock() call for @mutex, it will be woken and can
1556 * lock @mutex itself. This function returns the number of times that
1557 * @mutex has been locked by the current thread. To restore the state
1558 * before the call to g_static_rec_mutex_unlock_full() you can call
1559 * g_static_rec_mutex_lock_full() with the depth returned by this
1563 g_static_rec_mutex_unlock_full (GStaticRecMutex *mutex)
1567 g_return_val_if_fail (mutex, 0);
1569 if (!g_thread_supported ())
1572 depth = mutex->depth;
1574 g_system_thread_assign (mutex->owner, zero_thread);
1576 g_static_mutex_unlock (&mutex->mutex);
1582 * g_static_rec_mutex_free:
1583 * @mutex: a #GStaticRecMutex to be freed.
1585 * Releases all resources allocated to a #GStaticRecMutex.
1587 * You don't have to call this functions for a #GStaticRecMutex with an
1588 * unbounded lifetime, i.e. objects declared 'static', but if you have
1589 * a #GStaticRecMutex as a member of a structure and the structure is
1590 * freed, you should also free the #GStaticRecMutex.
1593 g_static_rec_mutex_free (GStaticRecMutex *mutex)
1595 g_return_if_fail (mutex);
1597 g_static_mutex_free (&mutex->mutex);
1600 /* GStaticPrivate {{{1 ---------------------------------------------------- */
1605 * A #GStaticPrivate works almost like a #GPrivate, but it has one
1606 * significant advantage. It doesn't need to be created at run-time
1607 * like a #GPrivate, but can be defined at compile-time. This is
1608 * similar to the difference between #GMutex and #GStaticMutex. Now
1609 * look at our <function>give_me_next_number()</function> example with
1613 * <title>Using GStaticPrivate for per-thread data</title>
1616 * give_me_next_number (<!-- -->)
1618 * static GStaticPrivate current_number_key = G_STATIC_PRIVATE_INIT;
1619 * int *current_number = g_static_private_get (&current_number_key);
1621 * if (!current_number)
1623 * current_number = g_new (int,1);
1624 * *current_number = 0;
1625 * g_static_private_set (&current_number_key, current_number, g_free);
1628 * *current_number = calc_next_number (*current_number);
1630 * return *current_number;
1637 * G_STATIC_PRIVATE_INIT:
1639 * Every #GStaticPrivate must be initialized with this macro, before it
1644 * GStaticPrivate my_private = G_STATIC_PRIVATE_INIT;
1646 * </informalexample>
1650 * g_static_private_init:
1651 * @private_key: a #GStaticPrivate to be initialized.
1653 * Initializes @private_key. Alternatively you can initialize it with
1654 * #G_STATIC_PRIVATE_INIT.
1657 g_static_private_init (GStaticPrivate *private_key)
1659 private_key->index = 0;
1663 * g_static_private_get:
1664 * @private_key: a #GStaticPrivate.
1665 * @Returns: the corresponding pointer.
1667 * Works like g_private_get() only for a #GStaticPrivate.
1669 * This function works even if g_thread_init() has not yet been called.
1672 g_static_private_get (GStaticPrivate *private_key)
1674 GRealThread *self = (GRealThread*) g_thread_self ();
1676 gpointer ret = NULL;
1678 LOCK_PRIVATE_DATA (self);
1680 array = self->private_data;
1682 if (array && private_key->index != 0 && private_key->index <= array->len)
1683 ret = g_array_index (array, GStaticPrivateNode,
1684 private_key->index - 1).data;
1686 UNLOCK_PRIVATE_DATA (self);
1691 * g_static_private_set:
1692 * @private_key: a #GStaticPrivate.
1693 * @data: the new pointer.
1694 * @notify: a function to be called with the pointer whenever the
1695 * current thread ends or sets this pointer again.
1697 * Sets the pointer keyed to @private_key for the current thread and
1698 * the function @notify to be called with that pointer (%NULL or
1699 * non-%NULL), whenever the pointer is set again or whenever the
1700 * current thread ends.
1702 * This function works even if g_thread_init() has not yet been called.
1703 * If g_thread_init() is called later, the @data keyed to @private_key
1704 * will be inherited only by the main thread, i.e. the one that called
1707 * <note><para>@notify is used quite differently from @destructor in
1708 * g_private_new().</para></note>
1711 g_static_private_set (GStaticPrivate *private_key,
1713 GDestroyNotify notify)
1715 GRealThread *self = (GRealThread*) g_thread_self ();
1717 static guint next_index = 0;
1718 GStaticPrivateNode *node;
1719 gpointer ddata = NULL;
1720 GDestroyNotify ddestroy = NULL;
1722 if (!private_key->index)
1726 if (!private_key->index)
1728 if (g_thread_free_indices)
1730 private_key->index =
1731 GPOINTER_TO_UINT (g_thread_free_indices->data);
1732 g_thread_free_indices =
1733 g_slist_delete_link (g_thread_free_indices,
1734 g_thread_free_indices);
1737 private_key->index = ++next_index;
1740 G_UNLOCK (g_thread);
1743 LOCK_PRIVATE_DATA (self);
1745 array = self->private_data;
1748 array = g_array_new (FALSE, TRUE, sizeof (GStaticPrivateNode));
1749 self->private_data = array;
1752 if (private_key->index > array->len)
1753 g_array_set_size (array, private_key->index);
1755 node = &g_array_index (array, GStaticPrivateNode, private_key->index - 1);
1758 ddestroy = node->destroy;
1761 node->destroy = notify;
1763 UNLOCK_PRIVATE_DATA (self);
1770 * g_static_private_free:
1771 * @private_key: a #GStaticPrivate to be freed.
1773 * Releases all resources allocated to @private_key.
1775 * You don't have to call this functions for a #GStaticPrivate with an
1776 * unbounded lifetime, i.e. objects declared 'static', but if you have
1777 * a #GStaticPrivate as a member of a structure and the structure is
1778 * freed, you should also free the #GStaticPrivate.
1781 g_static_private_free (GStaticPrivate *private_key)
1783 guint idx = private_key->index;
1784 GRealThread *thread, *next;
1785 GArray *garbage = NULL;
1790 private_key->index = 0;
1794 thread = g_thread_all_threads;
1796 for (thread = g_thread_all_threads; thread; thread = next)
1800 next = thread->next;
1802 LOCK_PRIVATE_DATA (thread);
1804 array = thread->private_data;
1806 if (array && idx <= array->len)
1808 GStaticPrivateNode *node = &g_array_index (array,
1811 gpointer ddata = node->data;
1812 GDestroyNotify ddestroy = node->destroy;
1815 node->destroy = NULL;
1819 /* defer non-trivial destruction til after we've finished
1820 * iterating, since we must continue to hold the lock */
1821 if (garbage == NULL)
1822 garbage = g_array_new (FALSE, TRUE,
1823 sizeof (GStaticPrivateNode));
1825 g_array_set_size (garbage, garbage->len + 1);
1827 node = &g_array_index (garbage, GStaticPrivateNode,
1830 node->destroy = ddestroy;
1834 UNLOCK_PRIVATE_DATA (thread);
1836 g_thread_free_indices = g_slist_prepend (g_thread_free_indices,
1837 GUINT_TO_POINTER (idx));
1838 G_UNLOCK (g_thread);
1844 for (i = 0; i < garbage->len; i++)
1846 GStaticPrivateNode *node;
1848 node = &g_array_index (garbage, GStaticPrivateNode, i);
1849 node->destroy (node->data);
1852 g_array_free (garbage, TRUE);
1856 /* GThread Extra Functions {{{1 ------------------------------------------- */
1858 g_thread_cleanup (gpointer data)
1862 GRealThread* thread = data;
1865 LOCK_PRIVATE_DATA (thread);
1866 array = thread->private_data;
1867 thread->private_data = NULL;
1868 UNLOCK_PRIVATE_DATA (thread);
1874 for (i = 0; i < array->len; i++ )
1876 GStaticPrivateNode *node =
1877 &g_array_index (array, GStaticPrivateNode, i);
1879 node->destroy (node->data);
1881 g_array_free (array, TRUE);
1884 /* We only free the thread structure, if it isn't joinable. If
1885 it is, the structure is freed in g_thread_join */
1886 if (!thread->thread.joinable)
1891 for (t = g_thread_all_threads, p = NULL; t; p = t, t = t->next)
1898 g_thread_all_threads = t->next;
1902 G_UNLOCK (g_thread);
1904 /* Just to make sure, this isn't used any more */
1905 g_system_thread_assign (thread->system_thread, zero_thread);
1912 g_thread_fail (void)
1914 g_error ("The thread system is not yet initialized.");
1917 #define G_NSEC_PER_SEC 1000000000
1922 return g_get_monotonic_time () * 1000;
1926 g_thread_create_proxy (gpointer data)
1928 GRealThread* thread = data;
1932 /* This has to happen before G_LOCK, as that might call g_thread_self */
1933 g_private_set (g_thread_specific_private, data);
1935 /* the lock makes sure, that thread->system_thread is written,
1936 before thread->thread.func is called. See g_thread_create. */
1938 G_UNLOCK (g_thread);
1940 thread->retval = thread->thread.func (thread->thread.data);
1946 * g_thread_create_full:
1947 * @func: a function to execute in the new thread.
1948 * @data: an argument to supply to the new thread.
1949 * @stack_size: a stack size for the new thread.
1950 * @joinable: should this thread be joinable?
1951 * @bound: should this thread be bound to a system thread?
1952 * @priority: a priority for the thread.
1953 * @error: return location for error.
1954 * @Returns: the new #GThread on success.
1956 * This function creates a new thread with the priority @priority. If
1957 * the underlying thread implementation supports it, the thread gets a
1958 * stack size of @stack_size or the default value for the current
1959 * platform, if @stack_size is 0.
1961 * If @joinable is %TRUE, you can wait for this threads termination
1962 * calling g_thread_join(). Otherwise the thread will just disappear
1963 * when it terminates. If @bound is %TRUE, this thread will be
1964 * scheduled in the system scope, otherwise the implementation is free
1965 * to do scheduling in the process scope. The first variant is more
1966 * expensive resource-wise, but generally faster. On some systems (e.g.
1967 * Linux) all threads are bound.
1969 * The new thread executes the function @func with the argument @data.
1970 * If the thread was created successfully, it is returned.
1972 * @error can be %NULL to ignore errors, or non-%NULL to report errors.
1973 * The error is set, if and only if the function returns %NULL.
1975 * <note><para>It is not guaranteed that threads with different priorities
1976 * really behave accordingly. On some systems (e.g. Linux) there are no
1977 * thread priorities. On other systems (e.g. Solaris) there doesn't
1978 * seem to be different scheduling for different priorities. All in all
1979 * try to avoid being dependent on priorities. Use
1980 * %G_THREAD_PRIORITY_NORMAL here as a default.</para></note>
1982 * <note><para>Only use g_thread_create_full() if you really can't use
1983 * g_thread_create() instead. g_thread_create() does not take
1984 * @stack_size, @bound, and @priority as arguments, as they should only
1985 * be used in cases in which it is unavoidable.</para></note>
1988 g_thread_create_full (GThreadFunc func,
1993 GThreadPriority priority,
1996 GRealThread* result;
1997 GError *local_error = NULL;
1998 g_return_val_if_fail (func, NULL);
1999 g_return_val_if_fail (priority >= G_THREAD_PRIORITY_LOW, NULL);
2000 g_return_val_if_fail (priority <= G_THREAD_PRIORITY_URGENT, NULL);
2002 result = g_new0 (GRealThread, 1);
2004 result->thread.joinable = joinable;
2005 result->thread.priority = priority;
2006 result->thread.func = func;
2007 result->thread.data = data;
2008 result->private_data = NULL;
2010 G_THREAD_UF (thread_create, (g_thread_create_proxy, result,
2011 stack_size, joinable, bound, priority,
2012 &result->system_thread, &local_error));
2015 result->next = g_thread_all_threads;
2016 g_thread_all_threads = result;
2018 G_UNLOCK (g_thread);
2022 g_propagate_error (error, local_error);
2027 return (GThread*) result;
2032 * @retval: the return value of this thread.
2034 * Exits the current thread. If another thread is waiting for that
2035 * thread using g_thread_join() and the current thread is joinable, the
2036 * waiting thread will be woken up and get @retval as the return value
2037 * of g_thread_join(). If the current thread is not joinable, @retval
2038 * is ignored. Calling
2042 * g_thread_exit (retval);
2044 * </informalexample>
2046 * is equivalent to returning @retval from the function @func, as given
2047 * to g_thread_create().
2049 * <note><para>Never call g_thread_exit() from within a thread of a
2050 * #GThreadPool, as that will mess up the bookkeeping and lead to funny
2051 * and unwanted results.</para></note>
2054 g_thread_exit (gpointer retval)
2056 GRealThread* real = (GRealThread*) g_thread_self ();
2057 real->retval = retval;
2058 G_THREAD_CF (thread_exit, (void)0, ());
2063 * @thread: a #GThread to be waited for.
2064 * @Returns: the return value of the thread.
2066 * Waits until @thread finishes, i.e. the function @func, as given to
2067 * g_thread_create(), returns or g_thread_exit() is called by @thread.
2068 * All resources of @thread including the #GThread struct are released.
2069 * @thread must have been created with @joinable=%TRUE in
2070 * g_thread_create(). The value returned by @func or given to
2071 * g_thread_exit() by @thread is returned by this function.
2074 g_thread_join (GThread* thread)
2076 GRealThread* real = (GRealThread*) thread;
2080 g_return_val_if_fail (thread, NULL);
2081 g_return_val_if_fail (thread->joinable, NULL);
2082 g_return_val_if_fail (!g_system_thread_equal (real->system_thread,
2083 zero_thread), NULL);
2085 G_THREAD_UF (thread_join, (&real->system_thread));
2087 retval = real->retval;
2090 for (t = g_thread_all_threads, p = NULL; t; p = t, t = t->next)
2092 if (t == (GRealThread*) thread)
2097 g_thread_all_threads = t->next;
2101 G_UNLOCK (g_thread);
2103 /* Just to make sure, this isn't used any more */
2104 thread->joinable = 0;
2105 g_system_thread_assign (real->system_thread, zero_thread);
2107 /* the thread structure for non-joinable threads is freed upon
2108 thread end. We free the memory here. This will leave a loose end,
2109 if a joinable thread is not joined. */
2117 * g_thread_set_priority:
2118 * @thread: a #GThread.
2119 * @priority: a new priority for @thread.
2121 * Changes the priority of @thread to @priority.
2123 * <note><para>It is not guaranteed that threads with different
2124 * priorities really behave accordingly. On some systems (e.g. Linux)
2125 * there are no thread priorities. On other systems (e.g. Solaris) there
2126 * doesn't seem to be different scheduling for different priorities. All
2127 * in all try to avoid being dependent on priorities.</para></note>
2130 g_thread_set_priority (GThread* thread,
2131 GThreadPriority priority)
2133 GRealThread* real = (GRealThread*) thread;
2135 g_return_if_fail (thread);
2136 g_return_if_fail (!g_system_thread_equal (real->system_thread, zero_thread));
2137 g_return_if_fail (priority >= G_THREAD_PRIORITY_LOW);
2138 g_return_if_fail (priority <= G_THREAD_PRIORITY_URGENT);
2140 thread->priority = priority;
2142 G_THREAD_CF (thread_set_priority, (void)0,
2143 (&real->system_thread, priority));
2148 * @Returns: the current thread.
2150 * This functions returns the #GThread corresponding to the calling
2154 g_thread_self (void)
2156 GRealThread* thread = g_private_get (g_thread_specific_private);
2160 /* If no thread data is available, provide and set one. This
2161 can happen for the main thread and for threads, that are not
2163 thread = g_new0 (GRealThread, 1);
2164 thread->thread.joinable = FALSE; /* This is a save guess */
2165 thread->thread.priority = G_THREAD_PRIORITY_NORMAL; /* This is
2167 thread->thread.func = NULL;
2168 thread->thread.data = NULL;
2169 thread->private_data = NULL;
2171 if (g_thread_supported ())
2172 G_THREAD_UF (thread_self, (&thread->system_thread));
2174 g_private_set (g_thread_specific_private, thread);
2177 thread->next = g_thread_all_threads;
2178 g_thread_all_threads = thread;
2179 G_UNLOCK (g_thread);
2182 return (GThread*)thread;
2185 /* GStaticRWLock {{{1 ----------------------------------------------------- */
2190 * The #GStaticRWLock struct represents a read-write lock. A read-write
2191 * lock can be used for protecting data that some portions of code only
2192 * read from, while others also write. In such situations it is
2193 * desirable that several readers can read at once, whereas of course
2194 * only one writer may write at a time. Take a look at the following
2198 * <title>An array with access functions</title>
2200 * GStaticRWLock rwlock = G_STATIC_RW_LOCK_INIT;
2204 * my_array_get (guint index)
2206 * gpointer retval = NULL;
2211 * g_static_rw_lock_reader_lock (&rwlock);
2212 * if (index < array->len)
2213 * retval = g_ptr_array_index (array, index);
2214 * g_static_rw_lock_reader_unlock (&rwlock);
2220 * my_array_set (guint index, gpointer data)
2222 * g_static_rw_lock_writer_lock (&rwlock);
2225 * array = g_ptr_array_new (<!-- -->);
2227 * if (index >= array->len)
2228 * g_ptr_array_set_size (array, index+1);
2229 * g_ptr_array_index (array, index) = data;
2231 * g_static_rw_lock_writer_unlock (&rwlock);
2236 * This example shows an array which can be accessed by many readers
2237 * (the <function>my_array_get()</function> function) simultaneously,
2238 * whereas the writers (the <function>my_array_set()</function>
2239 * function) will only be allowed once at a time and only if no readers
2240 * currently access the array. This is because of the potentially
2241 * dangerous resizing of the array. Using these functions is fully
2242 * multi-thread safe now.
2244 * Most of the time, writers should have precedence over readers. That
2245 * means, for this implementation, that as soon as a writer wants to
2246 * lock the data, no other reader is allowed to lock the data, whereas,
2247 * of course, the readers that already have locked the data are allowed
2248 * to finish their operation. As soon as the last reader unlocks the
2249 * data, the writer will lock it.
2251 * Even though #GStaticRWLock is not opaque, it should only be used
2252 * with the following functions.
2254 * All of the <function>g_static_rw_lock_*</function> functions can be
2255 * used even if g_thread_init() has not been called. Then they do
2256 * nothing, apart from <function>g_static_rw_lock_*_trylock</function>,
2257 * which does nothing but returning %TRUE.
2259 * <note><para>A read-write lock has a higher overhead than a mutex. For
2260 * example, both g_static_rw_lock_reader_lock() and
2261 * g_static_rw_lock_reader_unlock() have to lock and unlock a
2262 * #GStaticMutex, so it takes at least twice the time to lock and unlock
2263 * a #GStaticRWLock that it does to lock and unlock a #GStaticMutex. So
2264 * only data structures that are accessed by multiple readers, and which
2265 * keep the lock for a considerable time justify a #GStaticRWLock. The
2266 * above example most probably would fare better with a
2267 * #GStaticMutex.</para></note>
2271 * G_STATIC_RW_LOCK_INIT:
2273 * A #GStaticRWLock must be initialized with this macro before it can
2274 * be used. This macro can used be to initialize a variable, but it
2275 * cannot be assigned to a variable. In that case you have to use
2276 * g_static_rw_lock_init().
2280 * GStaticRWLock my_lock = G_STATIC_RW_LOCK_INIT;
2282 * </informalexample>
2286 * g_static_rw_lock_init:
2287 * @lock: a #GStaticRWLock to be initialized.
2289 * A #GStaticRWLock must be initialized with this function before it
2290 * can be used. Alternatively you can initialize it with
2291 * #G_STATIC_RW_LOCK_INIT.
2294 g_static_rw_lock_init (GStaticRWLock* lock)
2296 static const GStaticRWLock init_lock = G_STATIC_RW_LOCK_INIT;
2298 g_return_if_fail (lock);
2304 g_static_rw_lock_wait (GCond** cond, GStaticMutex* mutex)
2307 *cond = g_cond_new ();
2308 g_cond_wait (*cond, g_static_mutex_get_mutex (mutex));
2312 g_static_rw_lock_signal (GStaticRWLock* lock)
2314 if (lock->want_to_write && lock->write_cond)
2315 g_cond_signal (lock->write_cond);
2316 else if (lock->want_to_read && lock->read_cond)
2317 g_cond_broadcast (lock->read_cond);
2321 * g_static_rw_lock_reader_lock:
2322 * @lock: a #GStaticRWLock to lock for reading.
2324 * Locks @lock for reading. There may be unlimited concurrent locks for
2325 * reading of a #GStaticRWLock at the same time. If @lock is already
2326 * locked for writing by another thread or if another thread is already
2327 * waiting to lock @lock for writing, this function will block until
2328 * @lock is unlocked by the other writing thread and no other writing
2329 * threads want to lock @lock. This lock has to be unlocked by
2330 * g_static_rw_lock_reader_unlock().
2332 * #GStaticRWLock is not recursive. It might seem to be possible to
2333 * recursively lock for reading, but that can result in a deadlock, due
2334 * to writer preference.
2337 g_static_rw_lock_reader_lock (GStaticRWLock* lock)
2339 g_return_if_fail (lock);
2341 if (!g_threads_got_initialized)
2344 g_static_mutex_lock (&lock->mutex);
2345 lock->want_to_read++;
2346 while (lock->have_writer || lock->want_to_write)
2347 g_static_rw_lock_wait (&lock->read_cond, &lock->mutex);
2348 lock->want_to_read--;
2349 lock->read_counter++;
2350 g_static_mutex_unlock (&lock->mutex);
2354 * g_static_rw_lock_reader_trylock:
2355 * @lock: a #GStaticRWLock to lock for reading.
2356 * @Returns: %TRUE, if @lock could be locked for reading.
2358 * Tries to lock @lock for reading. If @lock is already locked for
2359 * writing by another thread or if another thread is already waiting to
2360 * lock @lock for writing, immediately returns %FALSE. Otherwise locks
2361 * @lock for reading and returns %TRUE. This lock has to be unlocked by
2362 * g_static_rw_lock_reader_unlock().
2365 g_static_rw_lock_reader_trylock (GStaticRWLock* lock)
2367 gboolean ret_val = FALSE;
2369 g_return_val_if_fail (lock, FALSE);
2371 if (!g_threads_got_initialized)
2374 g_static_mutex_lock (&lock->mutex);
2375 if (!lock->have_writer && !lock->want_to_write)
2377 lock->read_counter++;
2380 g_static_mutex_unlock (&lock->mutex);
2385 * g_static_rw_lock_reader_unlock:
2386 * @lock: a #GStaticRWLock to unlock after reading.
2388 * Unlocks @lock. If a thread waits to lock @lock for writing and all
2389 * locks for reading have been unlocked, the waiting thread is woken up
2390 * and can lock @lock for writing.
2393 g_static_rw_lock_reader_unlock (GStaticRWLock* lock)
2395 g_return_if_fail (lock);
2397 if (!g_threads_got_initialized)
2400 g_static_mutex_lock (&lock->mutex);
2401 lock->read_counter--;
2402 if (lock->read_counter == 0)
2403 g_static_rw_lock_signal (lock);
2404 g_static_mutex_unlock (&lock->mutex);
2408 * g_static_rw_lock_writer_lock:
2409 * @lock: a #GStaticRWLock to lock for writing.
2411 * Locks @lock for writing. If @lock is already locked for writing or
2412 * reading by other threads, this function will block until @lock is
2413 * completely unlocked and then lock @lock for writing. While this
2414 * functions waits to lock @lock, no other thread can lock @lock for
2415 * reading. When @lock is locked for writing, no other thread can lock
2416 * @lock (neither for reading nor writing). This lock has to be
2417 * unlocked by g_static_rw_lock_writer_unlock().
2420 g_static_rw_lock_writer_lock (GStaticRWLock* lock)
2422 g_return_if_fail (lock);
2424 if (!g_threads_got_initialized)
2427 g_static_mutex_lock (&lock->mutex);
2428 lock->want_to_write++;
2429 while (lock->have_writer || lock->read_counter)
2430 g_static_rw_lock_wait (&lock->write_cond, &lock->mutex);
2431 lock->want_to_write--;
2432 lock->have_writer = TRUE;
2433 g_static_mutex_unlock (&lock->mutex);
2437 * g_static_rw_lock_writer_trylock:
2438 * @lock: a #GStaticRWLock to lock for writing.
2439 * @Returns: %TRUE, if @lock could be locked for writing.
2441 * Tries to lock @lock for writing. If @lock is already locked (for
2442 * either reading or writing) by another thread, it immediately returns
2443 * %FALSE. Otherwise it locks @lock for writing and returns %TRUE. This
2444 * lock has to be unlocked by g_static_rw_lock_writer_unlock().
2447 g_static_rw_lock_writer_trylock (GStaticRWLock* lock)
2449 gboolean ret_val = FALSE;
2451 g_return_val_if_fail (lock, FALSE);
2453 if (!g_threads_got_initialized)
2456 g_static_mutex_lock (&lock->mutex);
2457 if (!lock->have_writer && !lock->read_counter)
2459 lock->have_writer = TRUE;
2462 g_static_mutex_unlock (&lock->mutex);
2467 * g_static_rw_lock_writer_unlock:
2468 * @lock: a #GStaticRWLock to unlock after writing.
2470 * Unlocks @lock. If a thread is waiting to lock @lock for writing and
2471 * all locks for reading have been unlocked, the waiting thread is
2472 * woken up and can lock @lock for writing. If no thread is waiting to
2473 * lock @lock for writing, and some thread or threads are waiting to
2474 * lock @lock for reading, the waiting threads are woken up and can
2475 * lock @lock for reading.
2478 g_static_rw_lock_writer_unlock (GStaticRWLock* lock)
2480 g_return_if_fail (lock);
2482 if (!g_threads_got_initialized)
2485 g_static_mutex_lock (&lock->mutex);
2486 lock->have_writer = FALSE;
2487 g_static_rw_lock_signal (lock);
2488 g_static_mutex_unlock (&lock->mutex);
2492 * g_static_rw_lock_free:
2493 * @lock: a #GStaticRWLock to be freed.
2495 * Releases all resources allocated to @lock.
2497 * You don't have to call this functions for a #GStaticRWLock with an
2498 * unbounded lifetime, i.e. objects declared 'static', but if you have
2499 * a #GStaticRWLock as a member of a structure, and the structure is
2500 * freed, you should also free the #GStaticRWLock.
2503 g_static_rw_lock_free (GStaticRWLock* lock)
2505 g_return_if_fail (lock);
2507 if (lock->read_cond)
2509 g_cond_free (lock->read_cond);
2510 lock->read_cond = NULL;
2512 if (lock->write_cond)
2514 g_cond_free (lock->write_cond);
2515 lock->write_cond = NULL;
2517 g_static_mutex_free (&lock->mutex);
2520 /* Unsorted {{{1 ---------------------------------------------------------- */
2524 * @thread_func: function to call for all GThread structures
2525 * @user_data: second argument to @thread_func
2527 * Call @thread_func on all existing #GThread structures. Note that
2528 * threads may decide to exit while @thread_func is running, so
2529 * without intimate knowledge about the lifetime of foreign threads,
2530 * @thread_func shouldn't access the GThread* pointer passed in as
2531 * first argument. However, @thread_func will not be called for threads
2532 * which are known to have exited already.
2534 * Due to thread lifetime checks, this function has an execution complexity
2535 * which is quadratic in the number of existing threads.
2540 g_thread_foreach (GFunc thread_func,
2543 GSList *slist = NULL;
2544 GRealThread *thread;
2545 g_return_if_fail (thread_func != NULL);
2546 /* snapshot the list of threads for iteration */
2548 for (thread = g_thread_all_threads; thread; thread = thread->next)
2549 slist = g_slist_prepend (slist, thread);
2550 G_UNLOCK (g_thread);
2551 /* walk the list, skipping non-existent threads */
2554 GSList *node = slist;
2556 /* check whether the current thread still exists */
2558 for (thread = g_thread_all_threads; thread; thread = thread->next)
2559 if (thread == node->data)
2561 G_UNLOCK (g_thread);
2563 thread_func (thread, user_data);
2564 g_slist_free_1 (node);
2569 * g_thread_get_initialized
2571 * Indicates if g_thread_init() has been called.
2573 * Returns: %TRUE if threads have been initialized.
2578 g_thread_get_initialized ()
2580 return g_thread_supported ();