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 */
61 #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 /* Keep this in sync with GRealThread in gmain.c! */
262 typedef struct _GRealThread GRealThread;
266 gpointer private_data;
269 GSystemThread system_thread;
272 typedef struct _GStaticPrivateNode GStaticPrivateNode;
273 struct _GStaticPrivateNode
276 GDestroyNotify destroy;
279 static void g_thread_cleanup (gpointer data);
280 static void g_thread_fail (void);
281 static guint64 gettime (void);
283 guint64 (*g_thread_gettime) (void) = gettime;
285 /* Global Variables {{{1 -------------------------------------------------- */
287 static GSystemThread zero_thread; /* This is initialized to all zero */
288 gboolean g_thread_use_default_impl = TRUE;
291 * g_thread_supported:
292 * @Returns: %TRUE, if the thread system is initialized.
294 * This function returns %TRUE if the thread system is initialized, and
295 * %FALSE if it is not.
297 * <note><para>This function is actually a macro. Apart from taking the
298 * address of it you can however use it as if it was a
299 * function.</para></note>
302 /* IMPLEMENTATION NOTE:
304 * g_thread_supported() is just returns g_threads_got_initialized
306 gboolean g_threads_got_initialized = FALSE;
309 /* Thread Implementation Virtual Function Table {{{1 ---------------------- */
310 /* Virtual Function Table Documentation {{{2 ------------------------------ */
313 * @mutex_new: virtual function pointer for g_mutex_new()
314 * @mutex_lock: virtual function pointer for g_mutex_lock()
315 * @mutex_trylock: virtual function pointer for g_mutex_trylock()
316 * @mutex_unlock: virtual function pointer for g_mutex_unlock()
317 * @mutex_free: virtual function pointer for g_mutex_free()
318 * @cond_new: virtual function pointer for g_cond_new()
319 * @cond_signal: virtual function pointer for g_cond_signal()
320 * @cond_broadcast: virtual function pointer for g_cond_broadcast()
321 * @cond_wait: virtual function pointer for g_cond_wait()
322 * @cond_timed_wait: virtual function pointer for g_cond_timed_wait()
323 * @cond_free: virtual function pointer for g_cond_free()
324 * @private_new: virtual function pointer for g_private_new()
325 * @private_get: virtual function pointer for g_private_get()
326 * @private_set: virtual function pointer for g_private_set()
327 * @thread_create: virtual function pointer for g_thread_create()
328 * @thread_yield: virtual function pointer for g_thread_yield()
329 * @thread_join: virtual function pointer for g_thread_join()
330 * @thread_exit: virtual function pointer for g_thread_exit()
331 * @thread_set_priority: virtual function pointer for
332 * g_thread_set_priority()
333 * @thread_self: virtual function pointer for g_thread_self()
334 * @thread_equal: used internally by recursive mutex locks and by some
337 * This function table is used by g_thread_init() to initialize the
338 * thread system. The functions in the table are directly used by their
339 * g_* prepended counterparts (described in this document). For
340 * example, if you call g_mutex_new() then mutex_new() from the table
341 * provided to g_thread_init() will be called.
343 * <note><para>Do not use this struct unless you know what you are
344 * doing.</para></note>
347 /* IMPLEMENTATION NOTE:
349 * g_thread_functions_for_glib_use is a global symbol that gets used by
350 * most of the "primative" threading calls. g_mutex_lock(), for
351 * example, is just a macro that calls the appropriate virtual function
354 * For that reason, all of those macros are documented here.
356 GThreadFunctions g_thread_functions_for_glib_use = {
357 /* GMutex Virtual Functions {{{2 ------------------------------------------ */
362 * The #GMutex struct is an opaque data structure to represent a mutex
363 * (mutual exclusion). It can be used to protect data against shared
364 * access. Take for example the following function:
367 * <title>A function which will not work in a threaded environment</title>
370 * give_me_next_number (void)
372 * static int current_number = 0;
374 * /<!-- -->* now do a very complicated calculation to calculate the new
375 * * number, this might for example be a random number generator
377 * current_number = calc_next_number (current_number);
379 * return current_number;
384 * It is easy to see that this won't work in a multi-threaded
385 * application. There current_number must be protected against shared
386 * access. A first naive implementation would be:
389 * <title>The wrong way to write a thread-safe function</title>
392 * give_me_next_number (void)
394 * static int current_number = 0;
396 * static GMutex * mutex = NULL;
398 * if (!mutex) mutex = g_mutex_new (<!-- -->);
400 * g_mutex_lock (mutex);
401 * ret_val = current_number = calc_next_number (current_number);
402 * g_mutex_unlock (mutex);
409 * This looks like it would work, but there is a race condition while
410 * constructing the mutex and this code cannot work reliable. Please do
411 * not use such constructs in your own programs! One working solution
415 * <title>A correct thread-safe function</title>
417 * static GMutex *give_me_next_number_mutex = NULL;
419 * /<!-- -->* this function must be called before any call to
420 * * give_me_next_number(<!-- -->)
422 * * it must be called exactly once.
425 * init_give_me_next_number (void)
427 * g_assert (give_me_next_number_mutex == NULL);
428 * give_me_next_number_mutex = g_mutex_new (<!-- -->);
432 * give_me_next_number (void)
434 * static int current_number = 0;
437 * g_mutex_lock (give_me_next_number_mutex);
438 * ret_val = current_number = calc_next_number (current_number);
439 * g_mutex_unlock (give_me_next_number_mutex);
446 * #GStaticMutex provides a simpler and safer way of doing this.
448 * If you want to use a mutex, and your code should also work without
449 * calling g_thread_init() first, then you cannot use a #GMutex, as
450 * g_mutex_new() requires that the thread system be initialized. Use a
451 * #GStaticMutex instead.
453 * A #GMutex should only be accessed via the following functions.
455 * <note><para>All of the <function>g_mutex_*</function> functions are
456 * actually macros. Apart from taking their addresses, you can however
457 * use them as if they were functions.</para></note>
462 * @Returns: a new #GMutex.
464 * Creates a new #GMutex.
466 * <note><para>This function will abort if g_thread_init() has not been
467 * called yet.</para></note>
469 (GMutex*(*)())g_thread_fail,
475 * Locks @mutex. If @mutex is already locked by another thread, the
476 * current thread will block until @mutex is unlocked by the other
479 * This function can be used even if g_thread_init() has not yet been
480 * called, and, in that case, will do nothing.
482 * <note><para>#GMutex is neither guaranteed to be recursive nor to be
483 * non-recursive, i.e. a thread could deadlock while calling
484 * g_mutex_lock(), if it already has locked @mutex. Use
485 * #GStaticRecMutex, if you need recursive mutexes.</para></note>
492 * @Returns: %TRUE, if @mutex could be locked.
494 * Tries to lock @mutex. If @mutex is already locked by another thread,
495 * it immediately returns %FALSE. Otherwise it locks @mutex and returns
498 * This function can be used even if g_thread_init() has not yet been
499 * called, and, in that case, will immediately return %TRUE.
501 * <note><para>#GMutex is neither guaranteed to be recursive nor to be
502 * non-recursive, i.e. the return value of g_mutex_trylock() could be
503 * both %FALSE or %TRUE, if the current thread already has locked
504 * @mutex. Use #GStaticRecMutex, if you need recursive
505 * mutexes.</para></note>
513 * Unlocks @mutex. If another thread is blocked in a g_mutex_lock()
514 * call for @mutex, it will be woken and can lock @mutex itself.
516 * This function can be used even if g_thread_init() has not yet been
517 * called, and, in that case, will do nothing.
527 * <note><para>Calling g_mutex_free() on a locked mutex may result in
528 * undefined behaviour.</para></note>
532 /* GCond Virtual Functions {{{2 ------------------------------------------ */
537 * The #GCond struct is an opaque data structure that represents a
538 * condition. Threads can block on a #GCond if they find a certain
539 * condition to be false. If other threads change the state of this
540 * condition they signal the #GCond, and that causes the waiting
541 * threads to be woken up.
545 * Using GCond to block a thread until a condition is satisfied
548 * GCond* data_cond = NULL; /<!-- -->* Must be initialized somewhere *<!-- -->/
549 * GMutex* data_mutex = NULL; /<!-- -->* Must be initialized somewhere *<!-- -->/
550 * gpointer current_data = NULL;
553 * push_data (gpointer data)
555 * g_mutex_lock (data_mutex);
556 * current_data = data;
557 * g_cond_signal (data_cond);
558 * g_mutex_unlock (data_mutex);
566 * g_mutex_lock (data_mutex);
567 * while (!current_data)
568 * g_cond_wait (data_cond, data_mutex);
569 * data = current_data;
570 * current_data = NULL;
571 * g_mutex_unlock (data_mutex);
578 * Whenever a thread calls <function>pop_data()</function> now, it will
579 * wait until current_data is non-%NULL, i.e. until some other thread
580 * has called <function>push_data()</function>.
582 * <note><para>It is important to use the g_cond_wait() and
583 * g_cond_timed_wait() functions only inside a loop which checks for the
584 * condition to be true. It is not guaranteed that the waiting thread
585 * will find the condition fulfilled after it wakes up, even if the
586 * signaling thread left the condition in that state: another thread may
587 * have altered the condition before the waiting thread got the chance
588 * to be woken up, even if the condition itself is protected by a
589 * #GMutex, like above.</para></note>
591 * A #GCond should only be accessed via the following functions.
593 * <note><para>All of the <function>g_cond_*</function> functions are
594 * actually macros. Apart from taking their addresses, you can however
595 * use them as if they were functions.</para></note>
600 * @Returns: a new #GCond.
602 * Creates a new #GCond. This function will abort, if g_thread_init()
603 * has not been called yet.
605 (GCond*(*)())g_thread_fail,
611 * If threads are waiting for @cond, exactly one of them is woken up.
612 * It is good practice to hold the same lock as the waiting thread
613 * while calling this function, though not required.
615 * This function can be used even if g_thread_init() has not yet been
616 * called, and, in that case, will do nothing.
624 * If threads are waiting for @cond, all of them are woken up. It is
625 * good practice to lock the same mutex as the waiting threads, while
626 * calling this function, though not required.
628 * This function can be used even if g_thread_init() has not yet been
629 * called, and, in that case, will do nothing.
636 * @mutex: a #GMutex, that is currently locked.
638 * Waits until this thread is woken up on @cond. The @mutex is unlocked
639 * before falling asleep and locked again before resuming.
641 * This function can be used even if g_thread_init() has not yet been
642 * called, and, in that case, will immediately return.
649 * @mutex: a #GMutex that is currently locked.
650 * @abs_time: a #GTimeVal, determining the final time.
651 * @Returns: %TRUE if @cond was signalled, or %FALSE on timeout.
653 * Waits until this thread is woken up on @cond, but not longer than
654 * until the time specified by @abs_time. The @mutex is unlocked before
655 * falling asleep and locked again before resuming.
657 * If @abs_time is %NULL, g_cond_timed_wait() acts like g_cond_wait().
659 * This function can be used even if g_thread_init() has not yet been
660 * called, and, in that case, will immediately return %TRUE.
662 * To easily calculate @abs_time a combination of g_get_current_time()
663 * and g_time_val_add() can be used.
671 * Destroys the #GCond.
675 /* GPrivate Virtual Functions {{{2 --------------------------------------- */
680 * The #GPrivate struct is an opaque data structure to represent a
681 * thread private data key. Threads can thereby obtain and set a
682 * pointer which is private to the current thread. Take our
683 * <function>give_me_next_number(<!-- -->)</function> example from
684 * above. Suppose we don't want <literal>current_number</literal> to be
685 * shared between the threads, but instead to be private to each thread.
686 * This can be done as follows:
689 * <title>Using GPrivate for per-thread data</title>
691 * GPrivate* current_number_key = NULL; /<!-- -->* Must be initialized somewhere
692 * with g_private_new (g_free); *<!-- -->/
695 * give_me_next_number (void)
697 * int *current_number = g_private_get (current_number_key);
699 * if (!current_number)
701 * current_number = g_new (int, 1);
702 * *current_number = 0;
703 * g_private_set (current_number_key, current_number);
706 * *current_number = calc_next_number (*current_number);
708 * return *current_number;
713 * Here the pointer belonging to the key
714 * <literal>current_number_key</literal> is read. If it is %NULL, it has
715 * not been set yet. Then get memory for an integer value, assign this
716 * memory to the pointer and write the pointer back. Now we have an
717 * integer value that is private to the current thread.
719 * The #GPrivate struct should only be accessed via the following
722 * <note><para>All of the <function>g_private_*</function> functions are
723 * actually macros. Apart from taking their addresses, you can however
724 * use them as if they were functions.</para></note>
729 * @destructor: a function to destroy the data keyed to #GPrivate when
731 * @Returns: a new #GPrivate.
733 * Creates a new #GPrivate. If @destructor is non-%NULL, it is a
734 * pointer to a destructor function. Whenever a thread ends and the
735 * corresponding pointer keyed to this instance of #GPrivate is
736 * non-%NULL, the destructor is called with this pointer as the
739 * <note><para>@destructor is used quite differently from @notify in
740 * g_static_private_set().</para></note>
742 * <note><para>A #GPrivate cannot be freed. Reuse it instead, if you
743 * can, to avoid shortage, or use #GStaticPrivate.</para></note>
745 * <note><para>This function will abort if g_thread_init() has not been
746 * called yet.</para></note>
748 (GPrivate*(*)(GDestroyNotify))g_thread_fail,
752 * @private_key: a #GPrivate.
753 * @Returns: the corresponding pointer.
755 * Returns the pointer keyed to @private_key for the current thread. If
756 * g_private_set() hasn't been called for the current @private_key and
757 * thread yet, this pointer will be %NULL.
759 * This function can be used even if g_thread_init() has not yet been
760 * called, and, in that case, will return the value of @private_key
761 * casted to #gpointer. Note however, that private data set
762 * <emphasis>before</emphasis> g_thread_init() will
763 * <emphasis>not</emphasis> be retained <emphasis>after</emphasis> the
764 * call. Instead, %NULL will be returned in all threads directly after
765 * g_thread_init(), regardless of any g_private_set() calls issued
766 * before threading system intialization.
772 * @private_key: a #GPrivate.
773 * @data: the new pointer.
775 * Sets the pointer keyed to @private_key for the current thread.
777 * This function can be used even if g_thread_init() has not yet been
778 * called, and, in that case, will set @private_key to @data casted to
779 * #GPrivate*. See g_private_get() for resulting caveats.
783 /* GThread Virtual Functions {{{2 ---------------------------------------- */
787 * The #GThread struct represents a running thread. It has three public
788 * read-only members, but the underlying struct is bigger, so you must
789 * not copy this struct.
791 * <note><para>Resources for a joinable thread are not fully released
792 * until g_thread_join() is called for that thread.</para></note>
797 * @data: data passed to the thread.
798 * @Returns: the return value of the thread, which will be returned by
801 * Specifies the type of the @func functions passed to
802 * g_thread_create() or g_thread_create_full().
807 * @G_THREAD_PRIORITY_LOW: a priority lower than normal
808 * @G_THREAD_PRIORITY_NORMAL: the default priority
809 * @G_THREAD_PRIORITY_HIGH: a priority higher than normal
810 * @G_THREAD_PRIORITY_URGENT: the highest priority
812 * Specifies the priority of a thread.
814 * <note><para>It is not guaranteed that threads with different priorities
815 * really behave accordingly. On some systems (e.g. Linux) there are no
816 * thread priorities. On other systems (e.g. Solaris) there doesn't
817 * seem to be different scheduling for different priorities. All in all
818 * try to avoid being dependent on priorities.</para></note>
823 * @func: a function to execute in the new thread.
824 * @data: an argument to supply to the new thread.
825 * @joinable: should this thread be joinable?
826 * @error: return location for error.
827 * @Returns: the new #GThread on success.
829 * This function creates a new thread with the default priority.
831 * If @joinable is %TRUE, you can wait for this threads termination
832 * calling g_thread_join(). Otherwise the thread will just disappear
833 * when it terminates.
835 * The new thread executes the function @func with the argument @data.
836 * If the thread was created successfully, it is returned.
838 * @error can be %NULL to ignore errors, or non-%NULL to report errors.
839 * The error is set, if and only if the function returns %NULL.
841 (void(*)(GThreadFunc, gpointer, gulong,
842 gboolean, gboolean, GThreadPriority,
843 gpointer, GError**))g_thread_fail,
848 * Gives way to other threads waiting to be scheduled.
850 * This function is often used as a method to make busy wait less evil.
851 * But in most cases you will encounter, there are better methods to do
852 * that. So in general you shouldn't use this function.
856 NULL, /* thread_join */
857 NULL, /* thread_exit */
858 NULL, /* thread_set_priority */
859 NULL, /* thread_self */
860 NULL /* thread_equal */
863 /* Local Data {{{1 -------------------------------------------------------- */
865 static GMutex *g_once_mutex = NULL;
866 static GCond *g_once_cond = NULL;
867 static GPrivate *g_thread_specific_private = NULL;
868 static GRealThread *g_thread_all_threads = NULL;
869 static GSList *g_thread_free_indeces = NULL;
870 static GSList* g_once_init_list = NULL;
872 G_LOCK_DEFINE_STATIC (g_thread);
874 /* Initialisation {{{1 ---------------------------------------------------- */
876 #ifdef G_THREADS_ENABLED
879 * @vtable: a function table of type #GThreadFunctions, that provides
880 * the entry points to the thread system to be used.
882 * If you use GLib from more than one thread, you must initialize the
883 * thread system by calling g_thread_init(). Most of the time you will
884 * only have to call <literal>g_thread_init (NULL)</literal>.
886 * <note><para>Do not call g_thread_init() with a non-%NULL parameter unless
887 * you really know what you are doing.</para></note>
889 * <note><para>g_thread_init() must not be called directly or indirectly as a
890 * callback from GLib. Also no mutexes may be currently locked while
891 * calling g_thread_init().</para></note>
893 * <note><para>g_thread_init() changes the way in which #GTimer measures
894 * elapsed time. As a consequence, timers that are running while
895 * g_thread_init() is called may report unreliable times.</para></note>
897 * Calling g_thread_init() multiple times is allowed (since version
898 * 2.24), but nothing happens except for the first call. If the
899 * argument is non-%NULL on such a call a warning will be printed, but
900 * otherwise the argument is ignored.
902 * If no thread system is available and @vtable is %NULL or if not all
903 * elements of @vtable are non-%NULL, then g_thread_init() will abort.
905 * <note><para>To use g_thread_init() in your program, you have to link with
906 * the libraries that the command <command>pkg-config --libs
907 * gthread-2.0</command> outputs. This is not the case for all the
908 * other thread related functions of GLib. Those can be used without
909 * having to link with the thread libraries.</para></note>
912 /* This must be called only once, before any threads are created.
913 * It will only be called from g_thread_init() in -lgthread.
916 g_thread_init_glib (void)
918 /* We let the main thread (the one that calls g_thread_init) inherit
919 * the static_private data set before calling g_thread_init
921 GRealThread* main_thread = (GRealThread*) g_thread_self ();
923 /* mutex and cond creation works without g_threads_got_initialized */
924 g_once_mutex = g_mutex_new ();
925 g_once_cond = g_cond_new ();
927 /* we may only create mutex and cond in here */
928 _g_mem_thread_init_noprivate_nomessage ();
930 /* setup the basic threading system */
931 g_threads_got_initialized = TRUE;
932 g_thread_specific_private = g_private_new (g_thread_cleanup);
933 g_private_set (g_thread_specific_private, main_thread);
934 G_THREAD_UF (thread_self, (&main_thread->system_thread));
936 /* complete memory system initialization, g_private_*() works now */
937 _g_slice_thread_init_nomessage ();
939 /* accomplish log system initialization to enable messaging */
940 _g_messages_thread_init_nomessage ();
942 /* we may run full-fledged initializers from here */
943 _g_atomic_thread_init ();
944 _g_convert_thread_init ();
945 _g_rand_thread_init ();
946 _g_main_thread_init ();
947 _g_utils_thread_init ();
948 _g_futex_thread_init ();
950 _g_win32_thread_init ();
953 #endif /* G_THREADS_ENABLED */
955 /* The following sections implement: GOnce, GStaticMutex, GStaticRecMutex,
959 /* GOnce {{{1 ------------------------------------------------------------- */
963 * @status: the status of the #GOnce
964 * @retval: the value returned by the call to the function, if @status
965 * is %G_ONCE_STATUS_READY
967 * A #GOnce struct controls a one-time initialization function. Any
968 * one-time initialization function must have its own unique #GOnce
977 * A #GOnce must be initialized with this macro before it can be used.
981 * GOnce my_once = G_ONCE_INIT;
990 * @G_ONCE_STATUS_NOTCALLED: the function has not been called yet.
991 * @G_ONCE_STATUS_PROGRESS: the function call is currently in progress.
992 * @G_ONCE_STATUS_READY: the function has been called.
994 * The possible statuses of a one-time initialization function
995 * controlled by a #GOnce struct.
1002 * @once: a #GOnce structure
1003 * @func: the #GThreadFunc function associated to @once. This function
1004 * is called only once, regardless of the number of times it and
1005 * its associated #GOnce struct are passed to g_once().
1006 * @arg: data to be passed to @func
1008 * The first call to this routine by a process with a given #GOnce
1009 * struct calls @func with the given argument. Thereafter, subsequent
1010 * calls to g_once() with the same #GOnce struct do not call @func
1011 * again, but return the stored result of the first call. On return
1012 * from g_once(), the status of @once will be %G_ONCE_STATUS_READY.
1014 * For example, a mutex or a thread-specific data key must be created
1015 * exactly once. In a threaded environment, calling g_once() ensures
1016 * that the initialization is serialized across multiple threads.
1018 * <note><para>Calling g_once() recursively on the same #GOnce struct in
1019 * @func will lead to a deadlock.</para></note>
1024 * get_debug_flags (void)
1026 * static GOnce my_once = G_ONCE_INIT;
1028 * g_once (&my_once, parse_debug_flags, NULL);
1030 * return my_once.retval;
1033 * </informalexample>
1038 g_once_impl (GOnce *once,
1042 g_mutex_lock (g_once_mutex);
1044 while (once->status == G_ONCE_STATUS_PROGRESS)
1045 g_cond_wait (g_once_cond, g_once_mutex);
1047 if (once->status != G_ONCE_STATUS_READY)
1049 once->status = G_ONCE_STATUS_PROGRESS;
1050 g_mutex_unlock (g_once_mutex);
1052 once->retval = func (arg);
1054 g_mutex_lock (g_once_mutex);
1055 once->status = G_ONCE_STATUS_READY;
1056 g_cond_broadcast (g_once_cond);
1059 g_mutex_unlock (g_once_mutex);
1061 return once->retval;
1065 * g_once_init_enter:
1066 * @value_location: location of a static initializable variable
1068 * @Returns: %TRUE if the initialization section should be entered,
1069 * %FALSE and blocks otherwise
1071 * Function to be called when starting a critical initialization
1072 * section. The argument @value_location must point to a static
1073 * 0-initialized variable that will be set to a value other than 0 at
1074 * the end of the initialization section. In combination with
1075 * g_once_init_leave() and the unique address @value_location, it can
1076 * be ensured that an initialization section will be executed only once
1077 * during a program's life time, and that concurrent threads are
1078 * blocked until initialization completed. To be used in constructs
1083 * static gsize initialization_value = 0;
1085 * if (g_once_init_enter (&initialization_value))
1087 * gsize setup_value = 42; /<!-- -->* initialization code here *<!-- -->/
1089 * g_once_init_leave (&initialization_value, setup_value);
1092 * /<!-- -->* use initialization_value here *<!-- -->/
1094 * </informalexample>
1099 g_once_init_enter_impl (volatile gsize *value_location)
1101 gboolean need_init = FALSE;
1102 g_mutex_lock (g_once_mutex);
1103 if (g_atomic_pointer_get (value_location) == NULL)
1105 if (!g_slist_find (g_once_init_list, (void*) value_location))
1108 g_once_init_list = g_slist_prepend (g_once_init_list, (void*) value_location);
1112 g_cond_wait (g_once_cond, g_once_mutex);
1113 while (g_slist_find (g_once_init_list, (void*) value_location));
1115 g_mutex_unlock (g_once_mutex);
1120 * g_once_init_leave:
1121 * @value_location: location of a static initializable variable
1123 * @initialization_value: new non-0 value for *@value_location.
1125 * Counterpart to g_once_init_enter(). Expects a location of a static
1126 * 0-initialized initialization variable, and an initialization value
1127 * other than 0. Sets the variable to the initialization value, and
1128 * releases concurrent threads blocking in g_once_init_enter() on this
1129 * initialization variable.
1134 g_once_init_leave (volatile gsize *value_location,
1135 gsize initialization_value)
1137 g_return_if_fail (g_atomic_pointer_get (value_location) == NULL);
1138 g_return_if_fail (initialization_value != 0);
1139 g_return_if_fail (g_once_init_list != NULL);
1141 g_atomic_pointer_set ((void**)value_location, (void*) initialization_value);
1142 g_mutex_lock (g_once_mutex);
1143 g_once_init_list = g_slist_remove (g_once_init_list, (void*) value_location);
1144 g_cond_broadcast (g_once_cond);
1145 g_mutex_unlock (g_once_mutex);
1148 /* GStaticMutex {{{1 ------------------------------------------------------ */
1153 * A #GStaticMutex works like a #GMutex, but it has one significant
1154 * advantage. It doesn't need to be created at run-time like a #GMutex,
1155 * but can be defined at compile-time. Here is a shorter, easier and
1156 * safer version of our <function>give_me_next_number()</function>
1161 * Using <structname>GStaticMutex</structname>
1162 * to simplify thread-safe programming
1166 * give_me_next_number (void)
1168 * static int current_number = 0;
1170 * static GStaticMutex mutex = G_STATIC_MUTEX_INIT;
1172 * g_static_mutex_lock (&mutex);
1173 * ret_val = current_number = calc_next_number (current_number);
1174 * g_static_mutex_unlock (&mutex);
1181 * Sometimes you would like to dynamically create a mutex. If you don't
1182 * want to require prior calling to g_thread_init(), because your code
1183 * should also be usable in non-threaded programs, you are not able to
1184 * use g_mutex_new() and thus #GMutex, as that requires a prior call to
1185 * g_thread_init(). In theses cases you can also use a #GStaticMutex.
1186 * It must be initialized with g_static_mutex_init() before using it
1187 * and freed with with g_static_mutex_free() when not needed anymore to
1188 * free up any allocated resources.
1190 * Even though #GStaticMutex is not opaque, it should only be used with
1191 * the following functions, as it is defined differently on different
1194 * All of the <function>g_static_mutex_*</function> functions apart
1195 * from <function>g_static_mutex_get_mutex</function> can also be used
1196 * even if g_thread_init() has not yet been called. Then they do
1197 * nothing, apart from <function>g_static_mutex_trylock</function>,
1198 * which does nothing but returning %TRUE.
1200 * <note><para>All of the <function>g_static_mutex_*</function>
1201 * functions are actually macros. Apart from taking their addresses, you
1202 * can however use them as if they were functions.</para></note>
1206 * G_STATIC_MUTEX_INIT:
1208 * A #GStaticMutex must be initialized with this macro, before it can
1209 * be used. This macro can used be to initialize a variable, but it
1210 * cannot be assigned to a variable. In that case you have to use
1211 * g_static_mutex_init().
1215 * GStaticMutex my_mutex = G_STATIC_MUTEX_INIT;
1217 * </informalexample>
1221 * g_static_mutex_init:
1222 * @mutex: a #GStaticMutex to be initialized.
1224 * Initializes @mutex. Alternatively you can initialize it with
1225 * #G_STATIC_MUTEX_INIT.
1228 g_static_mutex_init (GStaticMutex *mutex)
1230 static const GStaticMutex init_mutex = G_STATIC_MUTEX_INIT;
1232 g_return_if_fail (mutex);
1234 *mutex = init_mutex;
1237 /* IMPLEMENTATION NOTE:
1239 * On some platforms a GStaticMutex is actually a normal GMutex stored
1240 * inside of a structure instead of being allocated dynamically. We can
1241 * only do this for platforms on which we know, in advance, how to
1242 * allocate (size) and initialise (value) that memory.
1244 * On other platforms, a GStaticMutex is nothing more than a pointer to
1245 * a GMutex. In that case, the first access we make to the static mutex
1246 * must first allocate the normal GMutex and store it into the pointer.
1248 * configure.ac writes macros into glibconfig.h to determine if
1249 * g_static_mutex_get_mutex() accesses the sturcture in memory directly
1250 * (on platforms where we are able to do that) or if it ends up here,
1251 * where we may have to allocate the GMutex before returning it.
1255 * g_static_mutex_get_mutex:
1256 * @mutex: a #GStaticMutex.
1257 * @Returns: the #GMutex corresponding to @mutex.
1259 * For some operations (like g_cond_wait()) you must have a #GMutex
1260 * instead of a #GStaticMutex. This function will return the
1261 * corresponding #GMutex for @mutex.
1264 g_static_mutex_get_mutex_impl (GMutex** mutex)
1266 if (!g_thread_supported ())
1269 g_assert (g_once_mutex);
1271 g_mutex_lock (g_once_mutex);
1274 g_atomic_pointer_set (mutex, g_mutex_new());
1276 g_mutex_unlock (g_once_mutex);
1281 /* IMPLEMENTATION NOTE:
1283 * g_static_mutex_lock(), g_static_mutex_trylock() and
1284 * g_static_mutex_unlock() are all preprocessor macros that wrap the
1285 * corresponding g_mutex_*() function around a call to
1286 * g_static_mutex_get_mutex().
1290 * g_static_mutex_lock:
1291 * @mutex: a #GStaticMutex.
1293 * Works like g_mutex_lock(), but for a #GStaticMutex.
1297 * g_static_mutex_trylock:
1298 * @mutex: a #GStaticMutex.
1299 * @Returns: %TRUE, if the #GStaticMutex could be locked.
1301 * Works like g_mutex_trylock(), but for a #GStaticMutex.
1305 * g_static_mutex_unlock:
1306 * @mutex: a #GStaticMutex.
1308 * Works like g_mutex_unlock(), but for a #GStaticMutex.
1312 * g_static_mutex_free:
1313 * @mutex: a #GStaticMutex to be freed.
1315 * Releases all resources allocated to @mutex.
1317 * You don't have to call this functions for a #GStaticMutex with an
1318 * unbounded lifetime, i.e. objects declared 'static', but if you have
1319 * a #GStaticMutex as a member of a structure and the structure is
1320 * freed, you should also free the #GStaticMutex.
1322 * <note><para>Calling g_static_mutex_free() on a locked mutex may
1323 * result in undefined behaviour.</para></note>
1326 g_static_mutex_free (GStaticMutex* mutex)
1328 GMutex **runtime_mutex;
1330 g_return_if_fail (mutex);
1332 /* The runtime_mutex is the first (or only) member of GStaticMutex,
1333 * see both versions (of glibconfig.h) in configure.ac. Note, that
1334 * this variable is NULL, if g_thread_init() hasn't been called or
1335 * if we're using the default thread implementation and it provides
1336 * static mutexes. */
1337 runtime_mutex = ((GMutex**)mutex);
1340 g_mutex_free (*runtime_mutex);
1342 *runtime_mutex = NULL;
1345 /* ------------------------------------------------------------------------ */
1350 * A #GStaticRecMutex works like a #GStaticMutex, but it can be locked
1351 * multiple times by one thread. If you enter it n times, you have to
1352 * unlock it n times again to let other threads lock it. An exception
1353 * is the function g_static_rec_mutex_unlock_full(): that allows you to
1354 * unlock a #GStaticRecMutex completely returning the depth, (i.e. the
1355 * number of times this mutex was locked). The depth can later be used
1356 * to restore the state of the #GStaticRecMutex by calling
1357 * g_static_rec_mutex_lock_full().
1359 * Even though #GStaticRecMutex is not opaque, it should only be used
1360 * with the following functions.
1362 * All of the <function>g_static_rec_mutex_*</function> functions can
1363 * be used even if g_thread_init() has not been called. Then they do
1364 * nothing, apart from <function>g_static_rec_mutex_trylock</function>,
1365 * which does nothing but returning %TRUE.
1369 * G_STATIC_REC_MUTEX_INIT:
1371 * A #GStaticRecMutex must be initialized with this macro before it can
1372 * be used. This macro can used be to initialize a variable, but it
1373 * cannot be assigned to a variable. In that case you have to use
1374 * g_static_rec_mutex_init().
1378 * GStaticRecMutex my_mutex = G_STATIC_REC_MUTEX_INIT;
1384 * g_static_rec_mutex_init:
1385 * @mutex: a #GStaticRecMutex to be initialized.
1387 * A #GStaticRecMutex must be initialized with this function before it
1388 * can be used. Alternatively you can initialize it with
1389 * #G_STATIC_REC_MUTEX_INIT.
1392 g_static_rec_mutex_init (GStaticRecMutex *mutex)
1394 static const GStaticRecMutex init_mutex = G_STATIC_REC_MUTEX_INIT;
1396 g_return_if_fail (mutex);
1398 *mutex = init_mutex;
1402 * g_static_rec_mutex_lock:
1403 * @mutex: a #GStaticRecMutex to lock.
1405 * Locks @mutex. If @mutex is already locked by another thread, the
1406 * current thread will block until @mutex is unlocked by the other
1407 * thread. If @mutex is already locked by the calling thread, this
1408 * functions increases the depth of @mutex and returns immediately.
1411 g_static_rec_mutex_lock (GStaticRecMutex* mutex)
1415 g_return_if_fail (mutex);
1417 if (!g_thread_supported ())
1420 G_THREAD_UF (thread_self, (&self));
1422 if (g_system_thread_equal (self, mutex->owner))
1427 g_static_mutex_lock (&mutex->mutex);
1428 g_system_thread_assign (mutex->owner, self);
1433 * g_static_rec_mutex_trylock:
1434 * @mutex: a #GStaticRecMutex to lock.
1435 * @Returns: %TRUE, if @mutex could be locked.
1437 * Tries to lock @mutex. If @mutex is already locked by another thread,
1438 * it immediately returns %FALSE. Otherwise it locks @mutex and returns
1439 * %TRUE. If @mutex is already locked by the calling thread, this
1440 * functions increases the depth of @mutex and immediately returns
1444 g_static_rec_mutex_trylock (GStaticRecMutex* mutex)
1448 g_return_val_if_fail (mutex, FALSE);
1450 if (!g_thread_supported ())
1453 G_THREAD_UF (thread_self, (&self));
1455 if (g_system_thread_equal (self, mutex->owner))
1461 if (!g_static_mutex_trylock (&mutex->mutex))
1464 g_system_thread_assign (mutex->owner, self);
1470 * g_static_rec_mutex_unlock:
1471 * @mutex: a #GStaticRecMutex to unlock.
1473 * Unlocks @mutex. Another thread will be allowed to lock @mutex only
1474 * when it has been unlocked as many times as it had been locked
1475 * before. If @mutex is completely unlocked and another thread is
1476 * blocked in a g_static_rec_mutex_lock() call for @mutex, it will be
1477 * woken and can lock @mutex itself.
1480 g_static_rec_mutex_unlock (GStaticRecMutex* mutex)
1482 g_return_if_fail (mutex);
1484 if (!g_thread_supported ())
1487 if (mutex->depth > 1)
1492 g_system_thread_assign (mutex->owner, zero_thread);
1493 g_static_mutex_unlock (&mutex->mutex);
1497 * g_static_rec_mutex_lock_full:
1498 * @mutex: a #GStaticRecMutex to lock.
1499 * @depth: number of times this mutex has to be unlocked to be
1500 * completely unlocked.
1502 * Works like calling g_static_rec_mutex_lock() for @mutex @depth times.
1505 g_static_rec_mutex_lock_full (GStaticRecMutex *mutex,
1509 g_return_if_fail (mutex);
1511 if (!g_thread_supported ())
1517 G_THREAD_UF (thread_self, (&self));
1519 if (g_system_thread_equal (self, mutex->owner))
1521 mutex->depth += depth;
1524 g_static_mutex_lock (&mutex->mutex);
1525 g_system_thread_assign (mutex->owner, self);
1526 mutex->depth = depth;
1530 * g_static_rec_mutex_unlock_full:
1531 * @mutex: a #GStaticRecMutex to completely unlock.
1532 * @Returns: number of times @mutex has been locked by the current
1535 * Completely unlocks @mutex. If another thread is blocked in a
1536 * g_static_rec_mutex_lock() call for @mutex, it will be woken and can
1537 * lock @mutex itself. This function returns the number of times that
1538 * @mutex has been locked by the current thread. To restore the state
1539 * before the call to g_static_rec_mutex_unlock_full() you can call
1540 * g_static_rec_mutex_lock_full() with the depth returned by this
1544 g_static_rec_mutex_unlock_full (GStaticRecMutex *mutex)
1548 g_return_val_if_fail (mutex, 0);
1550 if (!g_thread_supported ())
1553 depth = mutex->depth;
1555 g_system_thread_assign (mutex->owner, zero_thread);
1557 g_static_mutex_unlock (&mutex->mutex);
1563 * g_static_rec_mutex_free:
1564 * @mutex: a #GStaticRecMutex to be freed.
1566 * Releases all resources allocated to a #GStaticRecMutex.
1568 * You don't have to call this functions for a #GStaticRecMutex with an
1569 * unbounded lifetime, i.e. objects declared 'static', but if you have
1570 * a #GStaticRecMutex as a member of a structure and the structure is
1571 * freed, you should also free the #GStaticRecMutex.
1574 g_static_rec_mutex_free (GStaticRecMutex *mutex)
1576 g_return_if_fail (mutex);
1578 g_static_mutex_free (&mutex->mutex);
1581 /* GStaticPrivate {{{1 ---------------------------------------------------- */
1586 * A #GStaticPrivate works almost like a #GPrivate, but it has one
1587 * significant advantage. It doesn't need to be created at run-time
1588 * like a #GPrivate, but can be defined at compile-time. This is
1589 * similar to the difference between #GMutex and #GStaticMutex. Now
1590 * look at our <function>give_me_next_number()</function> example with
1594 * <title>Using GStaticPrivate for per-thread data</title>
1597 * give_me_next_number (<!-- -->)
1599 * static GStaticPrivate current_number_key = G_STATIC_PRIVATE_INIT;
1600 * int *current_number = g_static_private_get (&current_number_key);
1602 * if (!current_number)
1604 * current_number = g_new (int,1);
1605 * *current_number = 0;
1606 * g_static_private_set (&current_number_key, current_number, g_free);
1609 * *current_number = calc_next_number (*current_number);
1611 * return *current_number;
1618 * G_STATIC_PRIVATE_INIT:
1620 * Every #GStaticPrivate must be initialized with this macro, before it
1625 * GStaticPrivate my_private = G_STATIC_PRIVATE_INIT;
1627 * </informalexample>
1631 * g_static_private_init:
1632 * @private_key: a #GStaticPrivate to be initialized.
1634 * Initializes @private_key. Alternatively you can initialize it with
1635 * #G_STATIC_PRIVATE_INIT.
1638 g_static_private_init (GStaticPrivate *private_key)
1640 private_key->index = 0;
1644 * g_static_private_get:
1645 * @private_key: a #GStaticPrivate.
1646 * @Returns: the corresponding pointer.
1648 * Works like g_private_get() only for a #GStaticPrivate.
1650 * This function works even if g_thread_init() has not yet been called.
1653 g_static_private_get (GStaticPrivate *private_key)
1655 GRealThread *self = (GRealThread*) g_thread_self ();
1658 array = self->private_data;
1662 if (!private_key->index)
1664 else if (private_key->index <= array->len)
1665 return g_array_index (array, GStaticPrivateNode,
1666 private_key->index - 1).data;
1672 * g_static_private_set:
1673 * @private_key: a #GStaticPrivate.
1674 * @data: the new pointer.
1675 * @notify: a function to be called with the pointer whenever the
1676 * current thread ends or sets this pointer again.
1678 * Sets the pointer keyed to @private_key for the current thread and
1679 * the function @notify to be called with that pointer (%NULL or
1680 * non-%NULL), whenever the pointer is set again or whenever the
1681 * current thread ends.
1683 * This function works even if g_thread_init() has not yet been called.
1684 * If g_thread_init() is called later, the @data keyed to @private_key
1685 * will be inherited only by the main thread, i.e. the one that called
1688 * <note><para>@notify is used quite differently from @destructor in
1689 * g_private_new().</para></note>
1692 g_static_private_set (GStaticPrivate *private_key,
1694 GDestroyNotify notify)
1696 GRealThread *self = (GRealThread*) g_thread_self ();
1698 static guint next_index = 0;
1699 GStaticPrivateNode *node;
1701 array = self->private_data;
1704 array = g_array_new (FALSE, TRUE, sizeof (GStaticPrivateNode));
1705 self->private_data = array;
1708 if (!private_key->index)
1712 if (!private_key->index)
1714 if (g_thread_free_indeces)
1716 private_key->index =
1717 GPOINTER_TO_UINT (g_thread_free_indeces->data);
1718 g_thread_free_indeces =
1719 g_slist_delete_link (g_thread_free_indeces,
1720 g_thread_free_indeces);
1723 private_key->index = ++next_index;
1726 G_UNLOCK (g_thread);
1729 if (private_key->index > array->len)
1730 g_array_set_size (array, private_key->index);
1732 node = &g_array_index (array, GStaticPrivateNode, private_key->index - 1);
1735 gpointer ddata = node->data;
1736 GDestroyNotify ddestroy = node->destroy;
1739 node->destroy = notify;
1746 node->destroy = notify;
1751 * g_static_private_free:
1752 * @private_key: a #GStaticPrivate to be freed.
1754 * Releases all resources allocated to @private_key.
1756 * You don't have to call this functions for a #GStaticPrivate with an
1757 * unbounded lifetime, i.e. objects declared 'static', but if you have
1758 * a #GStaticPrivate as a member of a structure and the structure is
1759 * freed, you should also free the #GStaticPrivate.
1762 g_static_private_free (GStaticPrivate *private_key)
1764 guint idx = private_key->index;
1765 GRealThread *thread;
1770 private_key->index = 0;
1774 thread = g_thread_all_threads;
1777 GArray *array = thread->private_data;
1778 thread = thread->next;
1780 if (array && idx <= array->len)
1782 GStaticPrivateNode *node = &g_array_index (array,
1785 gpointer ddata = node->data;
1786 GDestroyNotify ddestroy = node->destroy;
1789 node->destroy = NULL;
1793 G_UNLOCK (g_thread);
1799 g_thread_free_indeces = g_slist_prepend (g_thread_free_indeces,
1800 GUINT_TO_POINTER (idx));
1801 G_UNLOCK (g_thread);
1804 /* GThread Extra Functions {{{1 ------------------------------------------- */
1806 g_thread_cleanup (gpointer data)
1810 GRealThread* thread = data;
1811 if (thread->private_data)
1813 GArray* array = thread->private_data;
1816 for (i = 0; i < array->len; i++ )
1818 GStaticPrivateNode *node =
1819 &g_array_index (array, GStaticPrivateNode, i);
1821 node->destroy (node->data);
1823 g_array_free (array, TRUE);
1826 /* We only free the thread structure, if it isn't joinable. If
1827 it is, the structure is freed in g_thread_join */
1828 if (!thread->thread.joinable)
1833 for (t = g_thread_all_threads, p = NULL; t; p = t, t = t->next)
1840 g_thread_all_threads = t->next;
1844 G_UNLOCK (g_thread);
1846 /* Just to make sure, this isn't used any more */
1847 g_system_thread_assign (thread->system_thread, zero_thread);
1854 g_thread_fail (void)
1856 g_error ("The thread system is not yet initialized.");
1859 #define G_NSEC_PER_SEC 1000000000
1867 /* Returns 100s of nanoseconds since start of 1601 */
1868 GetSystemTimeAsFileTime ((FILETIME *)&v);
1870 /* Offset to Unix epoch */
1871 v -= G_GINT64_CONSTANT (116444736000000000);
1872 /* Convert to nanoseconds */
1879 gettimeofday (&tv, NULL);
1881 return (guint64) tv.tv_sec * G_NSEC_PER_SEC + tv.tv_usec * (G_NSEC_PER_SEC / G_USEC_PER_SEC);
1886 g_thread_create_proxy (gpointer data)
1888 GRealThread* thread = data;
1892 /* This has to happen before G_LOCK, as that might call g_thread_self */
1893 g_private_set (g_thread_specific_private, data);
1895 /* the lock makes sure, that thread->system_thread is written,
1896 before thread->thread.func is called. See g_thread_create. */
1898 G_UNLOCK (g_thread);
1900 thread->retval = thread->thread.func (thread->thread.data);
1906 * g_thread_create_full:
1907 * @func: a function to execute in the new thread.
1908 * @data: an argument to supply to the new thread.
1909 * @stack_size: a stack size for the new thread.
1910 * @joinable: should this thread be joinable?
1911 * @bound: should this thread be bound to a system thread?
1912 * @priority: a priority for the thread.
1913 * @error: return location for error.
1914 * @Returns: the new #GThread on success.
1916 * This function creates a new thread with the priority @priority. If
1917 * the underlying thread implementation supports it, the thread gets a
1918 * stack size of @stack_size or the default value for the current
1919 * platform, if @stack_size is 0.
1921 * If @joinable is %TRUE, you can wait for this threads termination
1922 * calling g_thread_join(). Otherwise the thread will just disappear
1923 * when it terminates. If @bound is %TRUE, this thread will be
1924 * scheduled in the system scope, otherwise the implementation is free
1925 * to do scheduling in the process scope. The first variant is more
1926 * expensive resource-wise, but generally faster. On some systems (e.g.
1927 * Linux) all threads are bound.
1929 * The new thread executes the function @func with the argument @data.
1930 * If the thread was created successfully, it is returned.
1932 * @error can be %NULL to ignore errors, or non-%NULL to report errors.
1933 * The error is set, if and only if the function returns %NULL.
1935 * <note><para>It is not guaranteed that threads with different priorities
1936 * really behave accordingly. On some systems (e.g. Linux) there are no
1937 * thread priorities. On other systems (e.g. Solaris) there doesn't
1938 * seem to be different scheduling for different priorities. All in all
1939 * try to avoid being dependent on priorities. Use
1940 * %G_THREAD_PRIORITY_NORMAL here as a default.</para></note>
1942 * <note><para>Only use g_thread_create_full() if you really can't use
1943 * g_thread_create() instead. g_thread_create() does not take
1944 * @stack_size, @bound, and @priority as arguments, as they should only
1945 * be used in cases in which it is unavoidable.</para></note>
1948 g_thread_create_full (GThreadFunc func,
1953 GThreadPriority priority,
1956 GRealThread* result;
1957 GError *local_error = NULL;
1958 g_return_val_if_fail (func, NULL);
1959 g_return_val_if_fail (priority >= G_THREAD_PRIORITY_LOW, NULL);
1960 g_return_val_if_fail (priority <= G_THREAD_PRIORITY_URGENT, NULL);
1962 result = g_new0 (GRealThread, 1);
1964 result->thread.joinable = joinable;
1965 result->thread.priority = priority;
1966 result->thread.func = func;
1967 result->thread.data = data;
1968 result->private_data = NULL;
1970 G_THREAD_UF (thread_create, (g_thread_create_proxy, result,
1971 stack_size, joinable, bound, priority,
1972 &result->system_thread, &local_error));
1975 result->next = g_thread_all_threads;
1976 g_thread_all_threads = result;
1978 G_UNLOCK (g_thread);
1982 g_propagate_error (error, local_error);
1987 return (GThread*) result;
1992 * @retval: the return value of this thread.
1994 * Exits the current thread. If another thread is waiting for that
1995 * thread using g_thread_join() and the current thread is joinable, the
1996 * waiting thread will be woken up and get @retval as the return value
1997 * of g_thread_join(). If the current thread is not joinable, @retval
1998 * is ignored. Calling
2002 * g_thread_exit (retval);
2004 * </informalexample>
2006 * is equivalent to returning @retval from the function @func, as given
2007 * to g_thread_create().
2009 * <note><para>Never call g_thread_exit() from within a thread of a
2010 * #GThreadPool, as that will mess up the bookkeeping and lead to funny
2011 * and unwanted results.</para></note>
2014 g_thread_exit (gpointer retval)
2016 GRealThread* real = (GRealThread*) g_thread_self ();
2017 real->retval = retval;
2018 G_THREAD_CF (thread_exit, (void)0, ());
2023 * @thread: a #GThread to be waited for.
2024 * @Returns: the return value of the thread.
2026 * Waits until @thread finishes, i.e. the function @func, as given to
2027 * g_thread_create(), returns or g_thread_exit() is called by @thread.
2028 * All resources of @thread including the #GThread struct are released.
2029 * @thread must have been created with @joinable=%TRUE in
2030 * g_thread_create(). The value returned by @func or given to
2031 * g_thread_exit() by @thread is returned by this function.
2034 g_thread_join (GThread* thread)
2036 GRealThread* real = (GRealThread*) thread;
2040 g_return_val_if_fail (thread, NULL);
2041 g_return_val_if_fail (thread->joinable, NULL);
2042 g_return_val_if_fail (!g_system_thread_equal (real->system_thread,
2043 zero_thread), NULL);
2045 G_THREAD_UF (thread_join, (&real->system_thread));
2047 retval = real->retval;
2050 for (t = g_thread_all_threads, p = NULL; t; p = t, t = t->next)
2052 if (t == (GRealThread*) thread)
2057 g_thread_all_threads = t->next;
2061 G_UNLOCK (g_thread);
2063 /* Just to make sure, this isn't used any more */
2064 thread->joinable = 0;
2065 g_system_thread_assign (real->system_thread, zero_thread);
2067 /* the thread structure for non-joinable threads is freed upon
2068 thread end. We free the memory here. This will leave a loose end,
2069 if a joinable thread is not joined. */
2077 * g_thread_set_priority:
2078 * @thread: a #GThread.
2079 * @priority: a new priority for @thread.
2081 * Changes the priority of @thread to @priority.
2083 * <note><para>It is not guaranteed that threads with different
2084 * priorities really behave accordingly. On some systems (e.g. Linux)
2085 * there are no thread priorities. On other systems (e.g. Solaris) there
2086 * doesn't seem to be different scheduling for different priorities. All
2087 * in all try to avoid being dependent on priorities.</para></note>
2090 g_thread_set_priority (GThread* thread,
2091 GThreadPriority priority)
2093 GRealThread* real = (GRealThread*) thread;
2095 g_return_if_fail (thread);
2096 g_return_if_fail (!g_system_thread_equal (real->system_thread, zero_thread));
2097 g_return_if_fail (priority >= G_THREAD_PRIORITY_LOW);
2098 g_return_if_fail (priority <= G_THREAD_PRIORITY_URGENT);
2100 thread->priority = priority;
2102 G_THREAD_CF (thread_set_priority, (void)0,
2103 (&real->system_thread, priority));
2108 * @Returns: the current thread.
2110 * This functions returns the #GThread corresponding to the calling
2114 g_thread_self (void)
2116 GRealThread* thread = g_private_get (g_thread_specific_private);
2120 /* If no thread data is available, provide and set one. This
2121 can happen for the main thread and for threads, that are not
2123 thread = g_new0 (GRealThread, 1);
2124 thread->thread.joinable = FALSE; /* This is a save guess */
2125 thread->thread.priority = G_THREAD_PRIORITY_NORMAL; /* This is
2127 thread->thread.func = NULL;
2128 thread->thread.data = NULL;
2129 thread->private_data = NULL;
2131 if (g_thread_supported ())
2132 G_THREAD_UF (thread_self, (&thread->system_thread));
2134 g_private_set (g_thread_specific_private, thread);
2137 thread->next = g_thread_all_threads;
2138 g_thread_all_threads = thread;
2139 G_UNLOCK (g_thread);
2142 return (GThread*)thread;
2145 /* GStaticRWLock {{{1 ----------------------------------------------------- */
2150 * The #GStaticRWLock struct represents a read-write lock. A read-write
2151 * lock can be used for protecting data that some portions of code only
2152 * read from, while others also write. In such situations it is
2153 * desirable that several readers can read at once, whereas of course
2154 * only one writer may write at a time. Take a look at the following
2158 * <title>An array with access functions</title>
2160 * GStaticRWLock rwlock = G_STATIC_RW_LOCK_INIT;
2164 * my_array_get (guint index)
2166 * gpointer retval = NULL;
2171 * g_static_rw_lock_reader_lock (&rwlock);
2172 * if (index < array->len)
2173 * retval = g_ptr_array_index (array, index);
2174 * g_static_rw_lock_reader_unlock (&rwlock);
2180 * my_array_set (guint index, gpointer data)
2182 * g_static_rw_lock_writer_lock (&rwlock);
2185 * array = g_ptr_array_new (<!-- -->);
2187 * if (index >= array->len)
2188 * g_ptr_array_set_size (array, index+1);
2189 * g_ptr_array_index (array, index) = data;
2191 * g_static_rw_lock_writer_unlock (&rwlock);
2196 * This example shows an array which can be accessed by many readers
2197 * (the <function>my_array_get()</function> function) simultaneously,
2198 * whereas the writers (the <function>my_array_set()</function>
2199 * function) will only be allowed once at a time and only if no readers
2200 * currently access the array. This is because of the potentially
2201 * dangerous resizing of the array. Using these functions is fully
2202 * multi-thread safe now.
2204 * Most of the time, writers should have precedence over readers. That
2205 * means, for this implementation, that as soon as a writer wants to
2206 * lock the data, no other reader is allowed to lock the data, whereas,
2207 * of course, the readers that already have locked the data are allowed
2208 * to finish their operation. As soon as the last reader unlocks the
2209 * data, the writer will lock it.
2211 * Even though #GStaticRWLock is not opaque, it should only be used
2212 * with the following functions.
2214 * All of the <function>g_static_rw_lock_*</function> functions can be
2215 * used even if g_thread_init() has not been called. Then they do
2216 * nothing, apart from <function>g_static_rw_lock_*_trylock</function>,
2217 * which does nothing but returning %TRUE.
2219 * <note><para>A read-write lock has a higher overhead than a mutex. For
2220 * example, both g_static_rw_lock_reader_lock() and
2221 * g_static_rw_lock_reader_unlock() have to lock and unlock a
2222 * #GStaticMutex, so it takes at least twice the time to lock and unlock
2223 * a #GStaticRWLock that it does to lock and unlock a #GStaticMutex. So
2224 * only data structures that are accessed by multiple readers, and which
2225 * keep the lock for a considerable time justify a #GStaticRWLock. The
2226 * above example most probably would fare better with a
2227 * #GStaticMutex.</para></note>
2231 * G_STATIC_RW_LOCK_INIT:
2233 * A #GStaticRWLock must be initialized with this macro before it can
2234 * be used. This macro can used be to initialize a variable, but it
2235 * cannot be assigned to a variable. In that case you have to use
2236 * g_static_rw_lock_init().
2240 * GStaticRWLock my_lock = G_STATIC_RW_LOCK_INIT;
2242 * </informalexample>
2246 * g_static_rw_lock_init:
2247 * @lock: a #GStaticRWLock to be initialized.
2249 * A #GStaticRWLock must be initialized with this function before it
2250 * can be used. Alternatively you can initialize it with
2251 * #G_STATIC_RW_LOCK_INIT.
2254 g_static_rw_lock_init (GStaticRWLock* lock)
2256 static const GStaticRWLock init_lock = G_STATIC_RW_LOCK_INIT;
2258 g_return_if_fail (lock);
2264 g_static_rw_lock_wait (GCond** cond, GStaticMutex* mutex)
2267 *cond = g_cond_new ();
2268 g_cond_wait (*cond, g_static_mutex_get_mutex (mutex));
2272 g_static_rw_lock_signal (GStaticRWLock* lock)
2274 if (lock->want_to_write && lock->write_cond)
2275 g_cond_signal (lock->write_cond);
2276 else if (lock->want_to_read && lock->read_cond)
2277 g_cond_broadcast (lock->read_cond);
2281 * g_static_rw_lock_reader_lock:
2282 * @lock: a #GStaticRWLock to lock for reading.
2284 * Locks @lock for reading. There may be unlimited concurrent locks for
2285 * reading of a #GStaticRWLock at the same time. If @lock is already
2286 * locked for writing by another thread or if another thread is already
2287 * waiting to lock @lock for writing, this function will block until
2288 * @lock is unlocked by the other writing thread and no other writing
2289 * threads want to lock @lock. This lock has to be unlocked by
2290 * g_static_rw_lock_reader_unlock().
2292 * #GStaticRWLock is not recursive. It might seem to be possible to
2293 * recursively lock for reading, but that can result in a deadlock, due
2294 * to writer preference.
2297 g_static_rw_lock_reader_lock (GStaticRWLock* lock)
2299 g_return_if_fail (lock);
2301 if (!g_threads_got_initialized)
2304 g_static_mutex_lock (&lock->mutex);
2305 lock->want_to_read++;
2306 while (lock->have_writer || lock->want_to_write)
2307 g_static_rw_lock_wait (&lock->read_cond, &lock->mutex);
2308 lock->want_to_read--;
2309 lock->read_counter++;
2310 g_static_mutex_unlock (&lock->mutex);
2314 * g_static_rw_lock_reader_trylock:
2315 * @lock: a #GStaticRWLock to lock for reading.
2316 * @Returns: %TRUE, if @lock could be locked for reading.
2318 * Tries to lock @lock for reading. If @lock is already locked for
2319 * writing by another thread or if another thread is already waiting to
2320 * lock @lock for writing, immediately returns %FALSE. Otherwise locks
2321 * @lock for reading and returns %TRUE. This lock has to be unlocked by
2322 * g_static_rw_lock_reader_unlock().
2325 g_static_rw_lock_reader_trylock (GStaticRWLock* lock)
2327 gboolean ret_val = FALSE;
2329 g_return_val_if_fail (lock, FALSE);
2331 if (!g_threads_got_initialized)
2334 g_static_mutex_lock (&lock->mutex);
2335 if (!lock->have_writer && !lock->want_to_write)
2337 lock->read_counter++;
2340 g_static_mutex_unlock (&lock->mutex);
2345 * g_static_rw_lock_reader_unlock:
2346 * @lock: a #GStaticRWLock to unlock after reading.
2348 * Unlocks @lock. If a thread waits to lock @lock for writing and all
2349 * locks for reading have been unlocked, the waiting thread is woken up
2350 * and can lock @lock for writing.
2353 g_static_rw_lock_reader_unlock (GStaticRWLock* lock)
2355 g_return_if_fail (lock);
2357 if (!g_threads_got_initialized)
2360 g_static_mutex_lock (&lock->mutex);
2361 lock->read_counter--;
2362 if (lock->read_counter == 0)
2363 g_static_rw_lock_signal (lock);
2364 g_static_mutex_unlock (&lock->mutex);
2368 * g_static_rw_lock_writer_lock:
2369 * @lock: a #GStaticRWLock to lock for writing.
2371 * Locks @lock for writing. If @lock is already locked for writing or
2372 * reading by other threads, this function will block until @lock is
2373 * completely unlocked and then lock @lock for writing. While this
2374 * functions waits to lock @lock, no other thread can lock @lock for
2375 * reading. When @lock is locked for writing, no other thread can lock
2376 * @lock (neither for reading nor writing). This lock has to be
2377 * unlocked by g_static_rw_lock_writer_unlock().
2380 g_static_rw_lock_writer_lock (GStaticRWLock* lock)
2382 g_return_if_fail (lock);
2384 if (!g_threads_got_initialized)
2387 g_static_mutex_lock (&lock->mutex);
2388 lock->want_to_write++;
2389 while (lock->have_writer || lock->read_counter)
2390 g_static_rw_lock_wait (&lock->write_cond, &lock->mutex);
2391 lock->want_to_write--;
2392 lock->have_writer = TRUE;
2393 g_static_mutex_unlock (&lock->mutex);
2397 * g_static_rw_lock_writer_trylock:
2398 * @lock: a #GStaticRWLock to lock for writing.
2399 * @Returns: %TRUE, if @lock could be locked for writing.
2401 * Tries to lock @lock for writing. If @lock is already locked (for
2402 * either reading or writing) by another thread, it immediately returns
2403 * %FALSE. Otherwise it locks @lock for writing and returns %TRUE. This
2404 * lock has to be unlocked by g_static_rw_lock_writer_unlock().
2407 g_static_rw_lock_writer_trylock (GStaticRWLock* lock)
2409 gboolean ret_val = FALSE;
2411 g_return_val_if_fail (lock, FALSE);
2413 if (!g_threads_got_initialized)
2416 g_static_mutex_lock (&lock->mutex);
2417 if (!lock->have_writer && !lock->read_counter)
2419 lock->have_writer = TRUE;
2422 g_static_mutex_unlock (&lock->mutex);
2427 * g_static_rw_lock_writer_unlock:
2428 * @lock: a #GStaticRWLock to unlock after writing.
2430 * Unlocks @lock. If a thread is waiting to lock @lock for writing and
2431 * all locks for reading have been unlocked, the waiting thread is
2432 * woken up and can lock @lock for writing. If no thread is waiting to
2433 * lock @lock for writing, and some thread or threads are waiting to
2434 * lock @lock for reading, the waiting threads are woken up and can
2435 * lock @lock for reading.
2438 g_static_rw_lock_writer_unlock (GStaticRWLock* lock)
2440 g_return_if_fail (lock);
2442 if (!g_threads_got_initialized)
2445 g_static_mutex_lock (&lock->mutex);
2446 lock->have_writer = FALSE;
2447 g_static_rw_lock_signal (lock);
2448 g_static_mutex_unlock (&lock->mutex);
2452 * g_static_rw_lock_free:
2453 * @lock: a #GStaticRWLock to be freed.
2455 * Releases all resources allocated to @lock.
2457 * You don't have to call this functions for a #GStaticRWLock with an
2458 * unbounded lifetime, i.e. objects declared 'static', but if you have
2459 * a #GStaticRWLock as a member of a structure, and the structure is
2460 * freed, you should also free the #GStaticRWLock.
2463 g_static_rw_lock_free (GStaticRWLock* lock)
2465 g_return_if_fail (lock);
2467 if (lock->read_cond)
2469 g_cond_free (lock->read_cond);
2470 lock->read_cond = NULL;
2472 if (lock->write_cond)
2474 g_cond_free (lock->write_cond);
2475 lock->write_cond = NULL;
2477 g_static_mutex_free (&lock->mutex);
2480 /* Unsorted {{{1 ---------------------------------------------------------- */
2484 * @thread_func: function to call for all GThread structures
2485 * @user_data: second argument to @thread_func
2487 * Call @thread_func on all existing #GThread structures. Note that
2488 * threads may decide to exit while @thread_func is running, so
2489 * without intimate knowledge about the lifetime of foreign threads,
2490 * @thread_func shouldn't access the GThread* pointer passed in as
2491 * first argument. However, @thread_func will not be called for threads
2492 * which are known to have exited already.
2494 * Due to thread lifetime checks, this function has an execution complexity
2495 * which is quadratic in the number of existing threads.
2500 g_thread_foreach (GFunc thread_func,
2503 GSList *slist = NULL;
2504 GRealThread *thread;
2505 g_return_if_fail (thread_func != NULL);
2506 /* snapshot the list of threads for iteration */
2508 for (thread = g_thread_all_threads; thread; thread = thread->next)
2509 slist = g_slist_prepend (slist, thread);
2510 G_UNLOCK (g_thread);
2511 /* walk the list, skipping non-existant threads */
2514 GSList *node = slist;
2516 /* check whether the current thread still exists */
2518 for (thread = g_thread_all_threads; thread; thread = thread->next)
2519 if (thread == node->data)
2521 G_UNLOCK (g_thread);
2523 thread_func (thread, user_data);
2524 g_slist_free_1 (node);
2529 * g_thread_get_initialized
2531 * Indicates if g_thread_init() has been called.
2533 * Returns: %TRUE if threads have been initialized.
2538 g_thread_get_initialized ()
2540 return g_thread_supported ();