1 /* GLIB - Library of useful routines for C programming
2 * Copyright (C) 1995-1997 Peter Mattis, Spencer Kimball and Josh MacDonald
4 * gthread.c: MT safety related functions
5 * Copyright 1998 Sebastian Wilhelmi; University of Karlsruhe
8 * This library is free software; you can redistribute it and/or
9 * modify it under the terms of the GNU Lesser General Public
10 * License as published by the Free Software Foundation; either
11 * version 2 of the License, or (at your option) any later version.
13 * This library is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16 * Lesser General Public License for more details.
18 * You should have received a copy of the GNU Lesser General Public
19 * License along with this library; if not, write to the
20 * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
21 * Boston, MA 02111-1307, USA.
24 /* Prelude {{{1 ----------------------------------------------------------- */
27 * Modified by the GLib Team and others 1997-2000. See the AUTHORS
28 * file for a list of people on the GLib Team. See the ChangeLog
29 * files for a list of changes. These files are distributed with
30 * GLib at ftp://ftp.gtk.org/pub/gtk/.
37 /* implement gthread.h's inline functions */
38 #define G_IMPLEMENT_INLINES 1
39 #define __G_THREAD_C__
44 #include "gthreadprivate.h"
57 #endif /* G_OS_WIN32 */
64 #include "gtestutils.h"
70 * @short_description: thread abstraction; including threads, different
71 * mutexes, conditions and thread private data
72 * @see_also: #GThreadPool, #GAsyncQueue
74 * Threads act almost like processes, but unlike processes all threads
75 * of one process share the same memory. This is good, as it provides
76 * easy communication between the involved threads via this shared
77 * memory, and it is bad, because strange things (so called
78 * "Heisenbugs") might happen if the program is not carefully designed.
79 * In particular, due to the concurrent nature of threads, no
80 * assumptions on the order of execution of code running in different
81 * threads can be made, unless order is explicitly forced by the
82 * programmer through synchronization primitives.
84 * The aim of the thread related functions in GLib is to provide a
85 * portable means for writing multi-threaded software. There are
86 * primitives for mutexes to protect the access to portions of memory
87 * (#GMutex, #GStaticMutex, #G_LOCK_DEFINE, #GStaticRecMutex and
88 * #GStaticRWLock). There is a facility to use individual bits for
89 * locks (g_bit_lock()). There are primitives for condition variables to
90 * allow synchronization of threads (#GCond). There are primitives for
91 * thread-private data - data that every thread has a private instance
92 * of (#GPrivate, #GStaticPrivate). There are facilities for one-time
93 * initialization (#GOnce, g_once_init_enter()). Last but definitely
94 * not least there are primitives to portably create and manage
97 * The threading system is initialized with g_thread_init(), which
98 * takes an optional custom thread implementation or %NULL for the
99 * default implementation. If you want to call g_thread_init() with a
100 * non-%NULL argument this must be done before executing any other GLib
101 * functions (except g_mem_set_vtable()). This is a requirement even if
102 * no threads are in fact ever created by the process.
104 * Calling g_thread_init() with a %NULL argument is somewhat more
105 * relaxed. You may call any other glib functions in the main thread
106 * before g_thread_init() as long as g_thread_init() is not called from
107 * a glib callback, or with any locks held. However, many libraries
108 * above glib does not support late initialization of threads, so doing
109 * this should be avoided if possible.
111 * Please note that since version 2.24 the GObject initialization
112 * function g_type_init() initializes threads (with a %NULL argument),
113 * so most applications, including those using Gtk+ will run with
114 * threads enabled. If you want a special thread implementation, make
115 * sure you call g_thread_init() before g_type_init() is called.
117 * After calling g_thread_init(), GLib is completely thread safe (all
118 * global data is automatically locked), but individual data structure
119 * instances are not automatically locked for performance reasons. So,
120 * for example you must coordinate accesses to the same #GHashTable
121 * from multiple threads. The two notable exceptions from this rule
122 * are #GMainLoop and #GAsyncQueue, which <emphasis>are</emphasis>
123 * threadsafe and need no further application-level locking to be
124 * accessed from multiple threads.
126 * To help debugging problems in multithreaded applications, GLib
127 * supports error-checking mutexes that will give you helpful error
128 * messages on common problems. To use error-checking mutexes, define
129 * the symbol #G_ERRORCHECK_MUTEXES when compiling the application.
133 * G_THREADS_IMPL_POSIX:
135 * This macro is defined if POSIX style threads are used.
141 * This macro is defined, for backward compatibility, to indicate that
142 * GLib has been compiled with thread support. As of glib 2.28, it is
147 * G_THREADS_IMPL_NONE:
149 * This macro is defined if no thread implementation is used. You can,
150 * however, provide one to g_thread_init() to make GLib multi-thread
154 /* G_LOCK Documentation {{{1 ---------------------------------------------- */
156 /* IMPLEMENTATION NOTE:
158 * G_LOCK_DEFINE and friends are convenience macros defined in
159 * gthread.h. Their documentation lives here.
164 * @name: the name of the lock.
166 * The %G_LOCK_* macros provide a convenient interface to #GStaticMutex
167 * with the advantage that they will expand to nothing in programs
168 * compiled against a thread-disabled GLib, saving code and memory
169 * there. #G_LOCK_DEFINE defines a lock. It can appear anywhere
170 * variable definitions may appear in programs, i.e. in the first block
171 * of a function or outside of functions. The @name parameter will be
172 * mangled to get the name of the #GStaticMutex. This means that you
173 * can use names of existing variables as the parameter - e.g. the name
174 * of the variable you intent to protect with the lock. Look at our
175 * <function>give_me_next_number()</function> example using the
179 * <title>Using the %G_LOCK_* convenience macros</title>
181 * G_LOCK_DEFINE (current_number);
184 * give_me_next_number (void)
186 * static int current_number = 0;
189 * G_LOCK (current_number);
190 * ret_val = current_number = calc_next_number (current_number);
191 * G_UNLOCK (current_number);
200 * G_LOCK_DEFINE_STATIC:
201 * @name: the name of the lock.
203 * This works like #G_LOCK_DEFINE, but it creates a static object.
208 * @name: the name of the lock.
210 * This declares a lock, that is defined with #G_LOCK_DEFINE in another
216 * @name: the name of the lock.
218 * Works like g_mutex_lock(), but for a lock defined with
224 * @name: the name of the lock.
225 * @Returns: %TRUE, if the lock could be locked.
227 * Works like g_mutex_trylock(), but for a lock defined with
233 * @name: the name of the lock.
235 * Works like g_mutex_unlock(), but for a lock defined with
239 /* GThreadError {{{1 ------------------------------------------------------- */
242 * @G_THREAD_ERROR_AGAIN: a thread couldn't be created due to resource
243 * shortage. Try again later.
245 * Possible errors of thread related functions.
251 * The error domain of the GLib thread subsystem.
254 g_thread_error_quark (void)
256 return g_quark_from_static_string ("g_thread_error");
259 /* Miscellaneous Structures {{{1 ------------------------------------------ */
260 typedef struct _GRealThread GRealThread;
264 /* Bit 0 protects private_data. To avoid deadlocks, do not block while
265 * holding this (particularly on the g_thread lock). */
266 volatile gint private_data_lock;
267 GArray *private_data;
270 GSystemThread system_thread;
273 #define LOCK_PRIVATE_DATA(self) g_bit_lock (&(self)->private_data_lock, 0)
274 #define UNLOCK_PRIVATE_DATA(self) g_bit_unlock (&(self)->private_data_lock, 0)
276 typedef struct _GStaticPrivateNode GStaticPrivateNode;
277 struct _GStaticPrivateNode
280 GDestroyNotify destroy;
283 static void g_thread_cleanup (gpointer data);
284 static void g_thread_fail (void);
285 static guint64 gettime (void);
287 guint64 (*g_thread_gettime) (void) = gettime;
289 /* Global Variables {{{1 -------------------------------------------------- */
291 static GSystemThread zero_thread; /* This is initialized to all zero */
292 gboolean g_thread_use_default_impl = TRUE;
295 * g_thread_supported:
296 * @Returns: %TRUE, if the thread system is initialized.
298 * This function returns %TRUE if the thread system is initialized, and
299 * %FALSE if it is not.
301 * <note><para>This function is actually a macro. Apart from taking the
302 * address of it you can however use it as if it was a
303 * function.</para></note>
306 /* IMPLEMENTATION NOTE:
308 * g_thread_supported() is just returns g_threads_got_initialized
310 gboolean g_threads_got_initialized = FALSE;
313 /* Thread Implementation Virtual Function Table {{{1 ---------------------- */
314 /* Virtual Function Table Documentation {{{2 ------------------------------ */
317 * @mutex_new: virtual function pointer for g_mutex_new()
318 * @mutex_lock: virtual function pointer for g_mutex_lock()
319 * @mutex_trylock: virtual function pointer for g_mutex_trylock()
320 * @mutex_unlock: virtual function pointer for g_mutex_unlock()
321 * @mutex_free: virtual function pointer for g_mutex_free()
322 * @cond_new: virtual function pointer for g_cond_new()
323 * @cond_signal: virtual function pointer for g_cond_signal()
324 * @cond_broadcast: virtual function pointer for g_cond_broadcast()
325 * @cond_wait: virtual function pointer for g_cond_wait()
326 * @cond_timed_wait: virtual function pointer for g_cond_timed_wait()
327 * @cond_free: virtual function pointer for g_cond_free()
328 * @private_new: virtual function pointer for g_private_new()
329 * @private_get: virtual function pointer for g_private_get()
330 * @private_set: virtual function pointer for g_private_set()
331 * @thread_create: virtual function pointer for g_thread_create()
332 * @thread_yield: virtual function pointer for g_thread_yield()
333 * @thread_join: virtual function pointer for g_thread_join()
334 * @thread_exit: virtual function pointer for g_thread_exit()
335 * @thread_set_priority: virtual function pointer for
336 * g_thread_set_priority()
337 * @thread_self: virtual function pointer for g_thread_self()
338 * @thread_equal: used internally by recursive mutex locks and by some
341 * This function table is used by g_thread_init() to initialize the
342 * thread system. The functions in the table are directly used by their
343 * g_* prepended counterparts (described in this document). For
344 * example, if you call g_mutex_new() then mutex_new() from the table
345 * provided to g_thread_init() will be called.
347 * <note><para>Do not use this struct unless you know what you are
348 * doing.</para></note>
351 /* GMutex Virtual Functions {{{2 ------------------------------------------ */
356 * The #GMutex struct is an opaque data structure to represent a mutex
357 * (mutual exclusion). It can be used to protect data against shared
358 * access. Take for example the following function:
361 * <title>A function which will not work in a threaded environment</title>
364 * give_me_next_number (void)
366 * static int current_number = 0;
368 * /<!-- -->* now do a very complicated calculation to calculate the new
369 * * number, this might for example be a random number generator
371 * current_number = calc_next_number (current_number);
373 * return current_number;
378 * It is easy to see that this won't work in a multi-threaded
379 * application. There current_number must be protected against shared
380 * access. A first naive implementation would be:
383 * <title>The wrong way to write a thread-safe function</title>
386 * give_me_next_number (void)
388 * static int current_number = 0;
390 * static GMutex * mutex = NULL;
392 * if (!mutex) mutex = g_mutex_new (<!-- -->);
394 * g_mutex_lock (mutex);
395 * ret_val = current_number = calc_next_number (current_number);
396 * g_mutex_unlock (mutex);
403 * This looks like it would work, but there is a race condition while
404 * constructing the mutex and this code cannot work reliable. Please do
405 * not use such constructs in your own programs! One working solution
409 * <title>A correct thread-safe function</title>
411 * static GMutex *give_me_next_number_mutex = NULL;
413 * /<!-- -->* this function must be called before any call to
414 * * give_me_next_number(<!-- -->)
416 * * it must be called exactly once.
419 * init_give_me_next_number (void)
421 * g_assert (give_me_next_number_mutex == NULL);
422 * give_me_next_number_mutex = g_mutex_new (<!-- -->);
426 * give_me_next_number (void)
428 * static int current_number = 0;
431 * g_mutex_lock (give_me_next_number_mutex);
432 * ret_val = current_number = calc_next_number (current_number);
433 * g_mutex_unlock (give_me_next_number_mutex);
440 * #GStaticMutex provides a simpler and safer way of doing this.
442 * If you want to use a mutex, and your code should also work without
443 * calling g_thread_init() first, then you cannot use a #GMutex, as
444 * g_mutex_new() requires that the thread system be initialized. Use a
445 * #GStaticMutex instead.
447 * A #GMutex should only be accessed via the following functions.
450 /* GCond Virtual Functions {{{2 ------------------------------------------ */
455 * The #GCond struct is an opaque data structure that represents a
456 * condition. Threads can block on a #GCond if they find a certain
457 * condition to be false. If other threads change the state of this
458 * condition they signal the #GCond, and that causes the waiting
459 * threads to be woken up.
463 * Using GCond to block a thread until a condition is satisfied
466 * GCond* data_cond = NULL; /<!-- -->* Must be initialized somewhere *<!-- -->/
467 * GMutex* data_mutex = NULL; /<!-- -->* Must be initialized somewhere *<!-- -->/
468 * gpointer current_data = NULL;
471 * push_data (gpointer data)
473 * g_mutex_lock (data_mutex);
474 * current_data = data;
475 * g_cond_signal (data_cond);
476 * g_mutex_unlock (data_mutex);
484 * g_mutex_lock (data_mutex);
485 * while (!current_data)
486 * g_cond_wait (data_cond, data_mutex);
487 * data = current_data;
488 * current_data = NULL;
489 * g_mutex_unlock (data_mutex);
496 * Whenever a thread calls <function>pop_data()</function> now, it will
497 * wait until current_data is non-%NULL, i.e. until some other thread
498 * has called <function>push_data()</function>.
500 * <note><para>It is important to use the g_cond_wait() and
501 * g_cond_timed_wait() functions only inside a loop which checks for the
502 * condition to be true. It is not guaranteed that the waiting thread
503 * will find the condition fulfilled after it wakes up, even if the
504 * signaling thread left the condition in that state: another thread may
505 * have altered the condition before the waiting thread got the chance
506 * to be woken up, even if the condition itself is protected by a
507 * #GMutex, like above.</para></note>
509 * A #GCond should only be accessed via the following functions.
512 /* GPrivate Virtual Functions {{{2 --------------------------------------- */
518 * #GStaticPrivate is a better choice for most uses.
521 * The #GPrivate struct is an opaque data structure to represent a
522 * thread private data key. Threads can thereby obtain and set a
523 * pointer which is private to the current thread. Take our
524 * <function>give_me_next_number(<!-- -->)</function> example from
525 * above. Suppose we don't want <literal>current_number</literal> to be
526 * shared between the threads, but instead to be private to each thread.
527 * This can be done as follows:
530 * <title>Using GPrivate for per-thread data</title>
532 * GPrivate* current_number_key = NULL; /<!-- -->* Must be initialized somewhere
533 * with g_private_new (g_free); *<!-- -->/
536 * give_me_next_number (void)
538 * int *current_number = g_private_get (current_number_key);
540 * if (!current_number)
542 * current_number = g_new (int, 1);
543 * *current_number = 0;
544 * g_private_set (current_number_key, current_number);
547 * *current_number = calc_next_number (*current_number);
549 * return *current_number;
554 * Here the pointer belonging to the key
555 * <literal>current_number_key</literal> is read. If it is %NULL, it has
556 * not been set yet. Then get memory for an integer value, assign this
557 * memory to the pointer and write the pointer back. Now we have an
558 * integer value that is private to the current thread.
560 * The #GPrivate struct should only be accessed via the following
563 * <note><para>All of the <function>g_private_*</function> functions are
564 * actually macros. Apart from taking their addresses, you can however
565 * use them as if they were functions.</para></note>
568 /* GThread Virtual Functions {{{2 ---------------------------------------- */
572 * The #GThread struct represents a running thread. It has three public
573 * read-only members, but the underlying struct is bigger, so you must
574 * not copy this struct.
576 * <note><para>Resources for a joinable thread are not fully released
577 * until g_thread_join() is called for that thread.</para></note>
582 * @data: data passed to the thread.
583 * @Returns: the return value of the thread, which will be returned by
586 * Specifies the type of the @func functions passed to
587 * g_thread_create() or g_thread_create_full().
592 * @G_THREAD_PRIORITY_LOW: a priority lower than normal
593 * @G_THREAD_PRIORITY_NORMAL: the default priority
594 * @G_THREAD_PRIORITY_HIGH: a priority higher than normal
595 * @G_THREAD_PRIORITY_URGENT: the highest priority
597 * Deprecated:2.32: thread priorities no longer have any effect.
600 /* Local Data {{{1 -------------------------------------------------------- */
602 static GMutex g_once_mutex = G_MUTEX_INIT;
603 static GCond g_once_cond = G_COND_INIT;
604 static GPrivate g_thread_specific_private;
605 static GRealThread *g_thread_all_threads = NULL;
606 static GSList *g_thread_free_indices = NULL;
607 static GSList* g_once_init_list = NULL;
609 G_LOCK_DEFINE_STATIC (g_thread);
611 /* Initialisation {{{1 ---------------------------------------------------- */
615 * @vtable: a function table of type #GThreadFunctions, that provides
616 * the entry points to the thread system to be used.
618 * If you use GLib from more than one thread, you must initialize the
619 * thread system by calling g_thread_init(). Most of the time you will
620 * only have to call <literal>g_thread_init (NULL)</literal>.
622 * <note><para>Do not call g_thread_init() with a non-%NULL parameter unless
623 * you really know what you are doing.</para></note>
625 * <note><para>g_thread_init() must not be called directly or indirectly as a
626 * callback from GLib. Also no mutexes may be currently locked while
627 * calling g_thread_init().</para></note>
629 * <note><para>g_thread_init() changes the way in which #GTimer measures
630 * elapsed time. As a consequence, timers that are running while
631 * g_thread_init() is called may report unreliable times.</para></note>
633 * Calling g_thread_init() multiple times is allowed (since version
634 * 2.24), but nothing happens except for the first call. If the
635 * argument is non-%NULL on such a call a warning will be printed, but
636 * otherwise the argument is ignored.
638 * If no thread system is available and @vtable is %NULL or if not all
639 * elements of @vtable are non-%NULL, then g_thread_init() will abort.
641 * <note><para>To use g_thread_init() in your program, you have to link with
642 * the libraries that the command <command>pkg-config --libs
643 * gthread-2.0</command> outputs. This is not the case for all the
644 * other thread related functions of GLib. Those can be used without
645 * having to link with the thread libraries.</para></note>
648 /* This must be called only once, before any threads are created.
649 * It will only be called from g_thread_init() in -lgthread.
652 g_thread_init_glib (void)
654 static gboolean already_done;
661 _g_thread_impl_init ();
663 /* We let the main thread (the one that calls g_thread_init) inherit
664 * the static_private data set before calling g_thread_init
666 GRealThread* main_thread = (GRealThread*) g_thread_self ();
668 /* setup the basic threading system */
669 g_threads_got_initialized = TRUE;
670 g_private_init (&g_thread_specific_private, g_thread_cleanup);
671 g_private_set (&g_thread_specific_private, main_thread);
672 g_system_thread_self (&main_thread->system_thread);
674 /* accomplish log system initialization to enable messaging */
675 _g_messages_thread_init_nomessage ();
678 /* The following sections implement: GOnce, GStaticMutex, GStaticRecMutex,
682 /* GOnce {{{1 ------------------------------------------------------------- */
686 * @status: the status of the #GOnce
687 * @retval: the value returned by the call to the function, if @status
688 * is %G_ONCE_STATUS_READY
690 * A #GOnce struct controls a one-time initialization function. Any
691 * one-time initialization function must have its own unique #GOnce
700 * A #GOnce must be initialized with this macro before it can be used.
704 * GOnce my_once = G_ONCE_INIT;
713 * @G_ONCE_STATUS_NOTCALLED: the function has not been called yet.
714 * @G_ONCE_STATUS_PROGRESS: the function call is currently in progress.
715 * @G_ONCE_STATUS_READY: the function has been called.
717 * The possible statuses of a one-time initialization function
718 * controlled by a #GOnce struct.
725 * @once: a #GOnce structure
726 * @func: the #GThreadFunc function associated to @once. This function
727 * is called only once, regardless of the number of times it and
728 * its associated #GOnce struct are passed to g_once().
729 * @arg: data to be passed to @func
731 * The first call to this routine by a process with a given #GOnce
732 * struct calls @func with the given argument. Thereafter, subsequent
733 * calls to g_once() with the same #GOnce struct do not call @func
734 * again, but return the stored result of the first call. On return
735 * from g_once(), the status of @once will be %G_ONCE_STATUS_READY.
737 * For example, a mutex or a thread-specific data key must be created
738 * exactly once. In a threaded environment, calling g_once() ensures
739 * that the initialization is serialized across multiple threads.
741 * <note><para>Calling g_once() recursively on the same #GOnce struct in
742 * @func will lead to a deadlock.</para></note>
747 * get_debug_flags (void)
749 * static GOnce my_once = G_ONCE_INIT;
751 * g_once (&my_once, parse_debug_flags, NULL);
753 * return my_once.retval;
761 g_once_impl (GOnce *once,
765 g_mutex_lock (&g_once_mutex);
767 while (once->status == G_ONCE_STATUS_PROGRESS)
768 g_cond_wait (&g_once_cond, &g_once_mutex);
770 if (once->status != G_ONCE_STATUS_READY)
772 once->status = G_ONCE_STATUS_PROGRESS;
773 g_mutex_unlock (&g_once_mutex);
775 once->retval = func (arg);
777 g_mutex_lock (&g_once_mutex);
778 once->status = G_ONCE_STATUS_READY;
779 g_cond_broadcast (&g_once_cond);
782 g_mutex_unlock (&g_once_mutex);
789 * @value_location: location of a static initializable variable
791 * @Returns: %TRUE if the initialization section should be entered,
792 * %FALSE and blocks otherwise
794 * Function to be called when starting a critical initialization
795 * section. The argument @value_location must point to a static
796 * 0-initialized variable that will be set to a value other than 0 at
797 * the end of the initialization section. In combination with
798 * g_once_init_leave() and the unique address @value_location, it can
799 * be ensured that an initialization section will be executed only once
800 * during a program's life time, and that concurrent threads are
801 * blocked until initialization completed. To be used in constructs
806 * static gsize initialization_value = 0;
808 * if (g_once_init_enter (&initialization_value))
810 * gsize setup_value = 42; /<!-- -->* initialization code here *<!-- -->/
812 * g_once_init_leave (&initialization_value, setup_value);
815 * /<!-- -->* use initialization_value here *<!-- -->/
822 g_once_init_enter_impl (volatile gsize *value_location)
824 gboolean need_init = FALSE;
825 g_mutex_lock (&g_once_mutex);
826 if (g_atomic_pointer_get (value_location) == NULL)
828 if (!g_slist_find (g_once_init_list, (void*) value_location))
831 g_once_init_list = g_slist_prepend (g_once_init_list, (void*) value_location);
835 g_cond_wait (&g_once_cond, &g_once_mutex);
836 while (g_slist_find (g_once_init_list, (void*) value_location));
838 g_mutex_unlock (&g_once_mutex);
844 * @value_location: location of a static initializable variable
846 * @initialization_value: new non-0 value for *@value_location.
848 * Counterpart to g_once_init_enter(). Expects a location of a static
849 * 0-initialized initialization variable, and an initialization value
850 * other than 0. Sets the variable to the initialization value, and
851 * releases concurrent threads blocking in g_once_init_enter() on this
852 * initialization variable.
857 g_once_init_leave (volatile gsize *value_location,
858 gsize initialization_value)
860 g_return_if_fail (g_atomic_pointer_get (value_location) == NULL);
861 g_return_if_fail (initialization_value != 0);
862 g_return_if_fail (g_once_init_list != NULL);
864 g_atomic_pointer_set (value_location, initialization_value);
865 g_mutex_lock (&g_once_mutex);
866 g_once_init_list = g_slist_remove (g_once_init_list, (void*) value_location);
867 g_cond_broadcast (&g_once_cond);
868 g_mutex_unlock (&g_once_mutex);
871 /* GStaticMutex {{{1 ------------------------------------------------------ */
876 * A #GStaticMutex works like a #GMutex, but it has one significant
877 * advantage. It doesn't need to be created at run-time like a #GMutex,
878 * but can be defined at compile-time. Here is a shorter, easier and
879 * safer version of our <function>give_me_next_number()</function>
884 * Using <structname>GStaticMutex</structname>
885 * to simplify thread-safe programming
889 * give_me_next_number (void)
891 * static int current_number = 0;
893 * static GStaticMutex mutex = G_STATIC_MUTEX_INIT;
895 * g_static_mutex_lock (&mutex);
896 * ret_val = current_number = calc_next_number (current_number);
897 * g_static_mutex_unlock (&mutex);
904 * Sometimes you would like to dynamically create a mutex. If you don't
905 * want to require prior calling to g_thread_init(), because your code
906 * should also be usable in non-threaded programs, you are not able to
907 * use g_mutex_new() and thus #GMutex, as that requires a prior call to
908 * g_thread_init(). In theses cases you can also use a #GStaticMutex.
909 * It must be initialized with g_static_mutex_init() before using it
910 * and freed with with g_static_mutex_free() when not needed anymore to
911 * free up any allocated resources.
913 * Even though #GStaticMutex is not opaque, it should only be used with
914 * the following functions, as it is defined differently on different
917 * All of the <function>g_static_mutex_*</function> functions apart
918 * from <function>g_static_mutex_get_mutex</function> can also be used
919 * even if g_thread_init() has not yet been called. Then they do
920 * nothing, apart from <function>g_static_mutex_trylock</function>,
921 * which does nothing but returning %TRUE.
923 * <note><para>All of the <function>g_static_mutex_*</function>
924 * functions are actually macros. Apart from taking their addresses, you
925 * can however use them as if they were functions.</para></note>
929 * G_STATIC_MUTEX_INIT:
931 * A #GStaticMutex must be initialized with this macro, before it can
932 * be used. This macro can used be to initialize a variable, but it
933 * cannot be assigned to a variable. In that case you have to use
934 * g_static_mutex_init().
938 * GStaticMutex my_mutex = G_STATIC_MUTEX_INIT;
944 * g_static_mutex_init:
945 * @mutex: a #GStaticMutex to be initialized.
947 * Initializes @mutex. Alternatively you can initialize it with
948 * #G_STATIC_MUTEX_INIT.
951 g_static_mutex_init (GStaticMutex *mutex)
953 static const GStaticMutex init_mutex = G_STATIC_MUTEX_INIT;
955 g_return_if_fail (mutex);
960 /* IMPLEMENTATION NOTE:
962 * On some platforms a GStaticMutex is actually a normal GMutex stored
963 * inside of a structure instead of being allocated dynamically. We can
964 * only do this for platforms on which we know, in advance, how to
965 * allocate (size) and initialise (value) that memory.
967 * On other platforms, a GStaticMutex is nothing more than a pointer to
968 * a GMutex. In that case, the first access we make to the static mutex
969 * must first allocate the normal GMutex and store it into the pointer.
971 * configure.ac writes macros into glibconfig.h to determine if
972 * g_static_mutex_get_mutex() accesses the structure in memory directly
973 * (on platforms where we are able to do that) or if it ends up here,
974 * where we may have to allocate the GMutex before returning it.
978 * g_static_mutex_get_mutex:
979 * @mutex: a #GStaticMutex.
980 * @Returns: the #GMutex corresponding to @mutex.
982 * For some operations (like g_cond_wait()) you must have a #GMutex
983 * instead of a #GStaticMutex. This function will return the
984 * corresponding #GMutex for @mutex.
987 g_static_mutex_get_mutex_impl (GMutex** mutex)
991 if (!g_thread_supported ())
994 result = g_atomic_pointer_get (mutex);
998 g_mutex_lock (&g_once_mutex);
1003 result = g_mutex_new ();
1004 g_atomic_pointer_set (mutex, result);
1007 g_mutex_unlock (&g_once_mutex);
1013 /* IMPLEMENTATION NOTE:
1015 * g_static_mutex_lock(), g_static_mutex_trylock() and
1016 * g_static_mutex_unlock() are all preprocessor macros that wrap the
1017 * corresponding g_mutex_*() function around a call to
1018 * g_static_mutex_get_mutex().
1022 * g_static_mutex_lock:
1023 * @mutex: a #GStaticMutex.
1025 * Works like g_mutex_lock(), but for a #GStaticMutex.
1029 * g_static_mutex_trylock:
1030 * @mutex: a #GStaticMutex.
1031 * @Returns: %TRUE, if the #GStaticMutex could be locked.
1033 * Works like g_mutex_trylock(), but for a #GStaticMutex.
1037 * g_static_mutex_unlock:
1038 * @mutex: a #GStaticMutex.
1040 * Works like g_mutex_unlock(), but for a #GStaticMutex.
1044 * g_static_mutex_free:
1045 * @mutex: a #GStaticMutex to be freed.
1047 * Releases all resources allocated to @mutex.
1049 * You don't have to call this functions for a #GStaticMutex with an
1050 * unbounded lifetime, i.e. objects declared 'static', but if you have
1051 * a #GStaticMutex as a member of a structure and the structure is
1052 * freed, you should also free the #GStaticMutex.
1054 * <note><para>Calling g_static_mutex_free() on a locked mutex may
1055 * result in undefined behaviour.</para></note>
1058 g_static_mutex_free (GStaticMutex* mutex)
1060 GMutex **runtime_mutex;
1062 g_return_if_fail (mutex);
1064 /* The runtime_mutex is the first (or only) member of GStaticMutex,
1065 * see both versions (of glibconfig.h) in configure.ac. Note, that
1066 * this variable is NULL, if g_thread_init() hasn't been called or
1067 * if we're using the default thread implementation and it provides
1068 * static mutexes. */
1069 runtime_mutex = ((GMutex**)mutex);
1072 g_mutex_free (*runtime_mutex);
1074 *runtime_mutex = NULL;
1077 /* ------------------------------------------------------------------------ */
1082 * A #GStaticRecMutex works like a #GStaticMutex, but it can be locked
1083 * multiple times by one thread. If you enter it n times, you have to
1084 * unlock it n times again to let other threads lock it. An exception
1085 * is the function g_static_rec_mutex_unlock_full(): that allows you to
1086 * unlock a #GStaticRecMutex completely returning the depth, (i.e. the
1087 * number of times this mutex was locked). The depth can later be used
1088 * to restore the state of the #GStaticRecMutex by calling
1089 * g_static_rec_mutex_lock_full().
1091 * Even though #GStaticRecMutex is not opaque, it should only be used
1092 * with the following functions.
1094 * All of the <function>g_static_rec_mutex_*</function> functions can
1095 * be used even if g_thread_init() has not been called. Then they do
1096 * nothing, apart from <function>g_static_rec_mutex_trylock</function>,
1097 * which does nothing but returning %TRUE.
1101 * G_STATIC_REC_MUTEX_INIT:
1103 * A #GStaticRecMutex must be initialized with this macro before it can
1104 * be used. This macro can used be to initialize a variable, but it
1105 * cannot be assigned to a variable. In that case you have to use
1106 * g_static_rec_mutex_init().
1110 * GStaticRecMutex my_mutex = G_STATIC_REC_MUTEX_INIT;
1116 * g_static_rec_mutex_init:
1117 * @mutex: a #GStaticRecMutex to be initialized.
1119 * A #GStaticRecMutex must be initialized with this function before it
1120 * can be used. Alternatively you can initialize it with
1121 * #G_STATIC_REC_MUTEX_INIT.
1124 g_static_rec_mutex_init (GStaticRecMutex *mutex)
1126 static const GStaticRecMutex init_mutex = G_STATIC_REC_MUTEX_INIT;
1128 g_return_if_fail (mutex);
1130 *mutex = init_mutex;
1134 * g_static_rec_mutex_lock:
1135 * @mutex: a #GStaticRecMutex to lock.
1137 * Locks @mutex. If @mutex is already locked by another thread, the
1138 * current thread will block until @mutex is unlocked by the other
1139 * thread. If @mutex is already locked by the calling thread, this
1140 * functions increases the depth of @mutex and returns immediately.
1143 g_static_rec_mutex_lock (GStaticRecMutex* mutex)
1147 g_return_if_fail (mutex);
1149 if (!g_thread_supported ())
1152 g_system_thread_self (&self);
1154 if (g_system_thread_equal (&self, &mutex->owner))
1159 g_static_mutex_lock (&mutex->mutex);
1160 g_system_thread_assign (mutex->owner, self);
1165 * g_static_rec_mutex_trylock:
1166 * @mutex: a #GStaticRecMutex to lock.
1167 * @Returns: %TRUE, if @mutex could be locked.
1169 * Tries to lock @mutex. If @mutex is already locked by another thread,
1170 * it immediately returns %FALSE. Otherwise it locks @mutex and returns
1171 * %TRUE. If @mutex is already locked by the calling thread, this
1172 * functions increases the depth of @mutex and immediately returns
1176 g_static_rec_mutex_trylock (GStaticRecMutex* mutex)
1180 g_return_val_if_fail (mutex, FALSE);
1182 if (!g_thread_supported ())
1185 g_system_thread_self (&self);
1187 if (g_system_thread_equal (&self, &mutex->owner))
1193 if (!g_static_mutex_trylock (&mutex->mutex))
1196 g_system_thread_assign (mutex->owner, self);
1202 * g_static_rec_mutex_unlock:
1203 * @mutex: a #GStaticRecMutex to unlock.
1205 * Unlocks @mutex. Another thread will be allowed to lock @mutex only
1206 * when it has been unlocked as many times as it had been locked
1207 * before. If @mutex is completely unlocked and another thread is
1208 * blocked in a g_static_rec_mutex_lock() call for @mutex, it will be
1209 * woken and can lock @mutex itself.
1212 g_static_rec_mutex_unlock (GStaticRecMutex* mutex)
1214 g_return_if_fail (mutex);
1216 if (!g_thread_supported ())
1219 if (mutex->depth > 1)
1224 g_system_thread_assign (mutex->owner, zero_thread);
1225 g_static_mutex_unlock (&mutex->mutex);
1229 * g_static_rec_mutex_lock_full:
1230 * @mutex: a #GStaticRecMutex to lock.
1231 * @depth: number of times this mutex has to be unlocked to be
1232 * completely unlocked.
1234 * Works like calling g_static_rec_mutex_lock() for @mutex @depth times.
1237 g_static_rec_mutex_lock_full (GStaticRecMutex *mutex,
1241 g_return_if_fail (mutex);
1243 if (!g_thread_supported ())
1249 g_system_thread_self (&self);
1251 if (g_system_thread_equal (&self, &mutex->owner))
1253 mutex->depth += depth;
1256 g_static_mutex_lock (&mutex->mutex);
1257 g_system_thread_assign (mutex->owner, self);
1258 mutex->depth = depth;
1262 * g_static_rec_mutex_unlock_full:
1263 * @mutex: a #GStaticRecMutex to completely unlock.
1264 * @Returns: number of times @mutex has been locked by the current
1267 * Completely unlocks @mutex. If another thread is blocked in a
1268 * g_static_rec_mutex_lock() call for @mutex, it will be woken and can
1269 * lock @mutex itself. This function returns the number of times that
1270 * @mutex has been locked by the current thread. To restore the state
1271 * before the call to g_static_rec_mutex_unlock_full() you can call
1272 * g_static_rec_mutex_lock_full() with the depth returned by this
1276 g_static_rec_mutex_unlock_full (GStaticRecMutex *mutex)
1280 g_return_val_if_fail (mutex, 0);
1282 if (!g_thread_supported ())
1285 depth = mutex->depth;
1287 g_system_thread_assign (mutex->owner, zero_thread);
1289 g_static_mutex_unlock (&mutex->mutex);
1295 * g_static_rec_mutex_free:
1296 * @mutex: a #GStaticRecMutex to be freed.
1298 * Releases all resources allocated to a #GStaticRecMutex.
1300 * You don't have to call this functions for a #GStaticRecMutex with an
1301 * unbounded lifetime, i.e. objects declared 'static', but if you have
1302 * a #GStaticRecMutex as a member of a structure and the structure is
1303 * freed, you should also free the #GStaticRecMutex.
1306 g_static_rec_mutex_free (GStaticRecMutex *mutex)
1308 g_return_if_fail (mutex);
1310 g_static_mutex_free (&mutex->mutex);
1313 /* GStaticPrivate {{{1 ---------------------------------------------------- */
1318 * A #GStaticPrivate works almost like a #GPrivate, but it has one
1319 * significant advantage. It doesn't need to be created at run-time
1320 * like a #GPrivate, but can be defined at compile-time. This is
1321 * similar to the difference between #GMutex and #GStaticMutex. Now
1322 * look at our <function>give_me_next_number()</function> example with
1326 * <title>Using GStaticPrivate for per-thread data</title>
1329 * give_me_next_number (<!-- -->)
1331 * static GStaticPrivate current_number_key = G_STATIC_PRIVATE_INIT;
1332 * int *current_number = g_static_private_get (&current_number_key);
1334 * if (!current_number)
1336 * current_number = g_new (int,1);
1337 * *current_number = 0;
1338 * g_static_private_set (&current_number_key, current_number, g_free);
1341 * *current_number = calc_next_number (*current_number);
1343 * return *current_number;
1350 * G_STATIC_PRIVATE_INIT:
1352 * Every #GStaticPrivate must be initialized with this macro, before it
1357 * GStaticPrivate my_private = G_STATIC_PRIVATE_INIT;
1359 * </informalexample>
1363 * g_static_private_init:
1364 * @private_key: a #GStaticPrivate to be initialized.
1366 * Initializes @private_key. Alternatively you can initialize it with
1367 * #G_STATIC_PRIVATE_INIT.
1370 g_static_private_init (GStaticPrivate *private_key)
1372 private_key->index = 0;
1376 * g_static_private_get:
1377 * @private_key: a #GStaticPrivate.
1378 * @Returns: the corresponding pointer.
1380 * Works like g_private_get() only for a #GStaticPrivate.
1382 * This function works even if g_thread_init() has not yet been called.
1385 g_static_private_get (GStaticPrivate *private_key)
1387 GRealThread *self = (GRealThread*) g_thread_self ();
1389 gpointer ret = NULL;
1391 LOCK_PRIVATE_DATA (self);
1393 array = self->private_data;
1395 if (array && private_key->index != 0 && private_key->index <= array->len)
1396 ret = g_array_index (array, GStaticPrivateNode,
1397 private_key->index - 1).data;
1399 UNLOCK_PRIVATE_DATA (self);
1404 * g_static_private_set:
1405 * @private_key: a #GStaticPrivate.
1406 * @data: the new pointer.
1407 * @notify: a function to be called with the pointer whenever the
1408 * current thread ends or sets this pointer again.
1410 * Sets the pointer keyed to @private_key for the current thread and
1411 * the function @notify to be called with that pointer (%NULL or
1412 * non-%NULL), whenever the pointer is set again or whenever the
1413 * current thread ends.
1415 * This function works even if g_thread_init() has not yet been called.
1416 * If g_thread_init() is called later, the @data keyed to @private_key
1417 * will be inherited only by the main thread, i.e. the one that called
1420 * <note><para>@notify is used quite differently from @destructor in
1421 * g_private_new().</para></note>
1424 g_static_private_set (GStaticPrivate *private_key,
1426 GDestroyNotify notify)
1428 GRealThread *self = (GRealThread*) g_thread_self ();
1430 static guint next_index = 0;
1431 GStaticPrivateNode *node;
1432 gpointer ddata = NULL;
1433 GDestroyNotify ddestroy = NULL;
1435 if (!private_key->index)
1439 if (!private_key->index)
1441 if (g_thread_free_indices)
1443 private_key->index =
1444 GPOINTER_TO_UINT (g_thread_free_indices->data);
1445 g_thread_free_indices =
1446 g_slist_delete_link (g_thread_free_indices,
1447 g_thread_free_indices);
1450 private_key->index = ++next_index;
1453 G_UNLOCK (g_thread);
1456 LOCK_PRIVATE_DATA (self);
1458 array = self->private_data;
1461 array = g_array_new (FALSE, TRUE, sizeof (GStaticPrivateNode));
1462 self->private_data = array;
1465 if (private_key->index > array->len)
1466 g_array_set_size (array, private_key->index);
1468 node = &g_array_index (array, GStaticPrivateNode, private_key->index - 1);
1471 ddestroy = node->destroy;
1474 node->destroy = notify;
1476 UNLOCK_PRIVATE_DATA (self);
1483 * g_static_private_free:
1484 * @private_key: a #GStaticPrivate to be freed.
1486 * Releases all resources allocated to @private_key.
1488 * You don't have to call this functions for a #GStaticPrivate with an
1489 * unbounded lifetime, i.e. objects declared 'static', but if you have
1490 * a #GStaticPrivate as a member of a structure and the structure is
1491 * freed, you should also free the #GStaticPrivate.
1494 g_static_private_free (GStaticPrivate *private_key)
1496 guint idx = private_key->index;
1497 GRealThread *thread, *next;
1498 GArray *garbage = NULL;
1503 private_key->index = 0;
1507 thread = g_thread_all_threads;
1509 for (thread = g_thread_all_threads; thread; thread = next)
1513 next = thread->next;
1515 LOCK_PRIVATE_DATA (thread);
1517 array = thread->private_data;
1519 if (array && idx <= array->len)
1521 GStaticPrivateNode *node = &g_array_index (array,
1524 gpointer ddata = node->data;
1525 GDestroyNotify ddestroy = node->destroy;
1528 node->destroy = NULL;
1532 /* defer non-trivial destruction til after we've finished
1533 * iterating, since we must continue to hold the lock */
1534 if (garbage == NULL)
1535 garbage = g_array_new (FALSE, TRUE,
1536 sizeof (GStaticPrivateNode));
1538 g_array_set_size (garbage, garbage->len + 1);
1540 node = &g_array_index (garbage, GStaticPrivateNode,
1543 node->destroy = ddestroy;
1547 UNLOCK_PRIVATE_DATA (thread);
1549 g_thread_free_indices = g_slist_prepend (g_thread_free_indices,
1550 GUINT_TO_POINTER (idx));
1551 G_UNLOCK (g_thread);
1557 for (i = 0; i < garbage->len; i++)
1559 GStaticPrivateNode *node;
1561 node = &g_array_index (garbage, GStaticPrivateNode, i);
1562 node->destroy (node->data);
1565 g_array_free (garbage, TRUE);
1569 /* GThread Extra Functions {{{1 ------------------------------------------- */
1571 g_thread_cleanup (gpointer data)
1575 GRealThread* thread = data;
1578 LOCK_PRIVATE_DATA (thread);
1579 array = thread->private_data;
1580 thread->private_data = NULL;
1581 UNLOCK_PRIVATE_DATA (thread);
1587 for (i = 0; i < array->len; i++ )
1589 GStaticPrivateNode *node =
1590 &g_array_index (array, GStaticPrivateNode, i);
1592 node->destroy (node->data);
1594 g_array_free (array, TRUE);
1597 /* We only free the thread structure, if it isn't joinable. If
1598 it is, the structure is freed in g_thread_join */
1599 if (!thread->thread.joinable)
1604 for (t = g_thread_all_threads, p = NULL; t; p = t, t = t->next)
1611 g_thread_all_threads = t->next;
1615 G_UNLOCK (g_thread);
1617 /* Just to make sure, this isn't used any more */
1618 g_system_thread_assign (thread->system_thread, zero_thread);
1625 g_thread_fail (void)
1627 g_error ("The thread system is not yet initialized.");
1630 #define G_NSEC_PER_SEC 1000000000
1635 return g_get_monotonic_time () * 1000;
1639 g_thread_create_proxy (gpointer data)
1641 GRealThread* thread = data;
1645 /* This has to happen before G_LOCK, as that might call g_thread_self */
1646 g_private_set (&g_thread_specific_private, data);
1648 /* the lock makes sure, that thread->system_thread is written,
1649 before thread->thread.func is called. See g_thread_create. */
1651 G_UNLOCK (g_thread);
1653 thread->retval = thread->thread.func (thread->thread.data);
1660 * @func: a function to execute in the new thread
1661 * @data: an argument to supply to the new thread
1662 * @joinable: should this thread be joinable?
1663 * @error: return location for error, or %NULL
1665 * This function creates a new thread.
1667 * If @joinable is %TRUE, you can wait for this threads termination
1668 * calling g_thread_join(). Otherwise the thread will just disappear
1669 * when it terminates.
1671 * The new thread executes the function @func with the argument @data.
1672 * If the thread was created successfully, it is returned.
1674 * @error can be %NULL to ignore errors, or non-%NULL to report errors.
1675 * The error is set, if and only if the function returns %NULL.
1677 * Returns: the new #GThread on success
1681 * g_thread_create_full:
1682 * @func: a function to execute in the new thread.
1683 * @data: an argument to supply to the new thread.
1684 * @stack_size: a stack size for the new thread.
1685 * @joinable: should this thread be joinable?
1687 * @priority: ignored
1688 * @error: return location for error.
1689 * @Returns: the new #GThread on success.
1691 * This function creates a new thread. If the underlying thread
1692 * implementation supports it, the thread gets a stack size of
1693 * @stack_size or the default value for the current platform, if
1696 * If @joinable is %TRUE, you can wait for this threads termination
1697 * calling g_thread_join(). Otherwise the thread will just disappear
1698 * when it terminates.
1700 * The new thread executes the function @func with the argument @data.
1701 * If the thread was created successfully, it is returned.
1703 * @error can be %NULL to ignore errors, or non-%NULL to report errors.
1704 * The error is set, if and only if the function returns %NULL.
1706 * <note><para>Only use g_thread_create_full() if you really can't use
1707 * g_thread_create() instead. g_thread_create() does not take
1708 * @stack_size, @bound, and @priority as arguments, as they should only
1709 * be used in cases in which it is unavoidable.</para></note>
1712 g_thread_create_full (GThreadFunc func,
1717 GThreadPriority priority,
1720 GRealThread* result;
1721 GError *local_error = NULL;
1722 g_return_val_if_fail (func, NULL);
1724 result = g_new0 (GRealThread, 1);
1726 result->thread.joinable = joinable;
1727 result->thread.func = func;
1728 result->thread.data = data;
1729 result->private_data = NULL;
1731 g_system_thread_create (g_thread_create_proxy, result,
1732 stack_size, joinable, 0, 0,
1733 &result->system_thread, &local_error);
1736 result->next = g_thread_all_threads;
1737 g_thread_all_threads = result;
1739 G_UNLOCK (g_thread);
1743 g_propagate_error (error, local_error);
1748 return (GThread*) result;
1753 * @retval: the return value of this thread.
1755 * Exits the current thread. If another thread is waiting for that
1756 * thread using g_thread_join() and the current thread is joinable, the
1757 * waiting thread will be woken up and get @retval as the return value
1758 * of g_thread_join(). If the current thread is not joinable, @retval
1759 * is ignored. Calling
1762 * g_thread_exit (retval);
1765 * is equivalent to returning @retval from the function @func, as given
1766 * to g_thread_create().
1768 * <note><para>Never call g_thread_exit() from within a thread of a
1769 * #GThreadPool, as that will mess up the bookkeeping and lead to funny
1770 * and unwanted results.</para></note>
1773 g_thread_exit (gpointer retval)
1775 GRealThread* real = (GRealThread*) g_thread_self ();
1776 real->retval = retval;
1778 g_system_thread_exit ();
1783 * @thread: a #GThread to be waited for.
1784 * @Returns: the return value of the thread.
1786 * Waits until @thread finishes, i.e. the function @func, as given to
1787 * g_thread_create(), returns or g_thread_exit() is called by @thread.
1788 * All resources of @thread including the #GThread struct are released.
1789 * @thread must have been created with @joinable=%TRUE in
1790 * g_thread_create(). The value returned by @func or given to
1791 * g_thread_exit() by @thread is returned by this function.
1794 g_thread_join (GThread* thread)
1796 GRealThread* real = (GRealThread*) thread;
1800 g_return_val_if_fail (thread, NULL);
1801 g_return_val_if_fail (thread->joinable, NULL);
1802 g_return_val_if_fail (!g_system_thread_equal (&real->system_thread, &zero_thread), NULL);
1804 g_system_thread_join (&real->system_thread);
1806 retval = real->retval;
1809 for (t = g_thread_all_threads, p = NULL; t; p = t, t = t->next)
1811 if (t == (GRealThread*) thread)
1816 g_thread_all_threads = t->next;
1820 G_UNLOCK (g_thread);
1822 /* Just to make sure, this isn't used any more */
1823 thread->joinable = 0;
1824 g_system_thread_assign (real->system_thread, zero_thread);
1826 /* the thread structure for non-joinable threads is freed upon
1827 thread end. We free the memory here. This will leave a loose end,
1828 if a joinable thread is not joined. */
1836 * g_thread_set_priority:
1837 * @thread: a #GThread.
1838 * @priority: ignored
1840 * This function does nothing.
1842 * Deprecated:2.32: Thread priorities no longer have any effect.
1845 g_thread_set_priority (GThread *thread,
1846 GThreadPriority priority)
1852 * @Returns: the current thread.
1854 * This functions returns the #GThread corresponding to the calling
1858 g_thread_self (void)
1860 GRealThread* thread = g_private_get (&g_thread_specific_private);
1864 /* If no thread data is available, provide and set one. This
1865 can happen for the main thread and for threads, that are not
1867 thread = g_new0 (GRealThread, 1);
1868 thread->thread.joinable = FALSE; /* This is a save guess */
1869 thread->thread.func = NULL;
1870 thread->thread.data = NULL;
1871 thread->private_data = NULL;
1873 g_system_thread_self (&thread->system_thread);
1875 g_private_set (&g_thread_specific_private, thread);
1878 thread->next = g_thread_all_threads;
1879 g_thread_all_threads = thread;
1880 G_UNLOCK (g_thread);
1883 return (GThread*)thread;
1886 /* GStaticRWLock {{{1 ----------------------------------------------------- */
1891 * The #GStaticRWLock struct represents a read-write lock. A read-write
1892 * lock can be used for protecting data that some portions of code only
1893 * read from, while others also write. In such situations it is
1894 * desirable that several readers can read at once, whereas of course
1895 * only one writer may write at a time. Take a look at the following
1899 * <title>An array with access functions</title>
1901 * GStaticRWLock rwlock = G_STATIC_RW_LOCK_INIT;
1905 * my_array_get (guint index)
1907 * gpointer retval = NULL;
1912 * g_static_rw_lock_reader_lock (&rwlock);
1913 * if (index < array->len)
1914 * retval = g_ptr_array_index (array, index);
1915 * g_static_rw_lock_reader_unlock (&rwlock);
1921 * my_array_set (guint index, gpointer data)
1923 * g_static_rw_lock_writer_lock (&rwlock);
1926 * array = g_ptr_array_new (<!-- -->);
1928 * if (index >= array->len)
1929 * g_ptr_array_set_size (array, index+1);
1930 * g_ptr_array_index (array, index) = data;
1932 * g_static_rw_lock_writer_unlock (&rwlock);
1937 * This example shows an array which can be accessed by many readers
1938 * (the <function>my_array_get()</function> function) simultaneously,
1939 * whereas the writers (the <function>my_array_set()</function>
1940 * function) will only be allowed once at a time and only if no readers
1941 * currently access the array. This is because of the potentially
1942 * dangerous resizing of the array. Using these functions is fully
1943 * multi-thread safe now.
1945 * Most of the time, writers should have precedence over readers. That
1946 * means, for this implementation, that as soon as a writer wants to
1947 * lock the data, no other reader is allowed to lock the data, whereas,
1948 * of course, the readers that already have locked the data are allowed
1949 * to finish their operation. As soon as the last reader unlocks the
1950 * data, the writer will lock it.
1952 * Even though #GStaticRWLock is not opaque, it should only be used
1953 * with the following functions.
1955 * All of the <function>g_static_rw_lock_*</function> functions can be
1956 * used even if g_thread_init() has not been called. Then they do
1957 * nothing, apart from <function>g_static_rw_lock_*_trylock</function>,
1958 * which does nothing but returning %TRUE.
1960 * <note><para>A read-write lock has a higher overhead than a mutex. For
1961 * example, both g_static_rw_lock_reader_lock() and
1962 * g_static_rw_lock_reader_unlock() have to lock and unlock a
1963 * #GStaticMutex, so it takes at least twice the time to lock and unlock
1964 * a #GStaticRWLock that it does to lock and unlock a #GStaticMutex. So
1965 * only data structures that are accessed by multiple readers, and which
1966 * keep the lock for a considerable time justify a #GStaticRWLock. The
1967 * above example most probably would fare better with a
1968 * #GStaticMutex.</para></note>
1972 * G_STATIC_RW_LOCK_INIT:
1974 * A #GStaticRWLock must be initialized with this macro before it can
1975 * be used. This macro can used be to initialize a variable, but it
1976 * cannot be assigned to a variable. In that case you have to use
1977 * g_static_rw_lock_init().
1981 * GStaticRWLock my_lock = G_STATIC_RW_LOCK_INIT;
1983 * </informalexample>
1987 * g_static_rw_lock_init:
1988 * @lock: a #GStaticRWLock to be initialized.
1990 * A #GStaticRWLock must be initialized with this function before it
1991 * can be used. Alternatively you can initialize it with
1992 * #G_STATIC_RW_LOCK_INIT.
1995 g_static_rw_lock_init (GStaticRWLock* lock)
1997 static const GStaticRWLock init_lock = G_STATIC_RW_LOCK_INIT;
1999 g_return_if_fail (lock);
2005 g_static_rw_lock_wait (GCond** cond, GStaticMutex* mutex)
2008 *cond = g_cond_new ();
2009 g_cond_wait (*cond, g_static_mutex_get_mutex (mutex));
2013 g_static_rw_lock_signal (GStaticRWLock* lock)
2015 if (lock->want_to_write && lock->write_cond)
2016 g_cond_signal (lock->write_cond);
2017 else if (lock->want_to_read && lock->read_cond)
2018 g_cond_broadcast (lock->read_cond);
2022 * g_static_rw_lock_reader_lock:
2023 * @lock: a #GStaticRWLock to lock for reading.
2025 * Locks @lock for reading. There may be unlimited concurrent locks for
2026 * reading of a #GStaticRWLock at the same time. If @lock is already
2027 * locked for writing by another thread or if another thread is already
2028 * waiting to lock @lock for writing, this function will block until
2029 * @lock is unlocked by the other writing thread and no other writing
2030 * threads want to lock @lock. This lock has to be unlocked by
2031 * g_static_rw_lock_reader_unlock().
2033 * #GStaticRWLock is not recursive. It might seem to be possible to
2034 * recursively lock for reading, but that can result in a deadlock, due
2035 * to writer preference.
2038 g_static_rw_lock_reader_lock (GStaticRWLock* lock)
2040 g_return_if_fail (lock);
2042 if (!g_threads_got_initialized)
2045 g_static_mutex_lock (&lock->mutex);
2046 lock->want_to_read++;
2047 while (lock->have_writer || lock->want_to_write)
2048 g_static_rw_lock_wait (&lock->read_cond, &lock->mutex);
2049 lock->want_to_read--;
2050 lock->read_counter++;
2051 g_static_mutex_unlock (&lock->mutex);
2055 * g_static_rw_lock_reader_trylock:
2056 * @lock: a #GStaticRWLock to lock for reading.
2057 * @Returns: %TRUE, if @lock could be locked for reading.
2059 * Tries to lock @lock for reading. If @lock is already locked for
2060 * writing by another thread or if another thread is already waiting to
2061 * lock @lock for writing, immediately returns %FALSE. Otherwise locks
2062 * @lock for reading and returns %TRUE. This lock has to be unlocked by
2063 * g_static_rw_lock_reader_unlock().
2066 g_static_rw_lock_reader_trylock (GStaticRWLock* lock)
2068 gboolean ret_val = FALSE;
2070 g_return_val_if_fail (lock, FALSE);
2072 if (!g_threads_got_initialized)
2075 g_static_mutex_lock (&lock->mutex);
2076 if (!lock->have_writer && !lock->want_to_write)
2078 lock->read_counter++;
2081 g_static_mutex_unlock (&lock->mutex);
2086 * g_static_rw_lock_reader_unlock:
2087 * @lock: a #GStaticRWLock to unlock after reading.
2089 * Unlocks @lock. If a thread waits to lock @lock for writing and all
2090 * locks for reading have been unlocked, the waiting thread is woken up
2091 * and can lock @lock for writing.
2094 g_static_rw_lock_reader_unlock (GStaticRWLock* lock)
2096 g_return_if_fail (lock);
2098 if (!g_threads_got_initialized)
2101 g_static_mutex_lock (&lock->mutex);
2102 lock->read_counter--;
2103 if (lock->read_counter == 0)
2104 g_static_rw_lock_signal (lock);
2105 g_static_mutex_unlock (&lock->mutex);
2109 * g_static_rw_lock_writer_lock:
2110 * @lock: a #GStaticRWLock to lock for writing.
2112 * Locks @lock for writing. If @lock is already locked for writing or
2113 * reading by other threads, this function will block until @lock is
2114 * completely unlocked and then lock @lock for writing. While this
2115 * functions waits to lock @lock, no other thread can lock @lock for
2116 * reading. When @lock is locked for writing, no other thread can lock
2117 * @lock (neither for reading nor writing). This lock has to be
2118 * unlocked by g_static_rw_lock_writer_unlock().
2121 g_static_rw_lock_writer_lock (GStaticRWLock* lock)
2123 g_return_if_fail (lock);
2125 if (!g_threads_got_initialized)
2128 g_static_mutex_lock (&lock->mutex);
2129 lock->want_to_write++;
2130 while (lock->have_writer || lock->read_counter)
2131 g_static_rw_lock_wait (&lock->write_cond, &lock->mutex);
2132 lock->want_to_write--;
2133 lock->have_writer = TRUE;
2134 g_static_mutex_unlock (&lock->mutex);
2138 * g_static_rw_lock_writer_trylock:
2139 * @lock: a #GStaticRWLock to lock for writing.
2140 * @Returns: %TRUE, if @lock could be locked for writing.
2142 * Tries to lock @lock for writing. If @lock is already locked (for
2143 * either reading or writing) by another thread, it immediately returns
2144 * %FALSE. Otherwise it locks @lock for writing and returns %TRUE. This
2145 * lock has to be unlocked by g_static_rw_lock_writer_unlock().
2148 g_static_rw_lock_writer_trylock (GStaticRWLock* lock)
2150 gboolean ret_val = FALSE;
2152 g_return_val_if_fail (lock, FALSE);
2154 if (!g_threads_got_initialized)
2157 g_static_mutex_lock (&lock->mutex);
2158 if (!lock->have_writer && !lock->read_counter)
2160 lock->have_writer = TRUE;
2163 g_static_mutex_unlock (&lock->mutex);
2168 * g_static_rw_lock_writer_unlock:
2169 * @lock: a #GStaticRWLock to unlock after writing.
2171 * Unlocks @lock. If a thread is waiting to lock @lock for writing and
2172 * all locks for reading have been unlocked, the waiting thread is
2173 * woken up and can lock @lock for writing. If no thread is waiting to
2174 * lock @lock for writing, and some thread or threads are waiting to
2175 * lock @lock for reading, the waiting threads are woken up and can
2176 * lock @lock for reading.
2179 g_static_rw_lock_writer_unlock (GStaticRWLock* lock)
2181 g_return_if_fail (lock);
2183 if (!g_threads_got_initialized)
2186 g_static_mutex_lock (&lock->mutex);
2187 lock->have_writer = FALSE;
2188 g_static_rw_lock_signal (lock);
2189 g_static_mutex_unlock (&lock->mutex);
2193 * g_static_rw_lock_free:
2194 * @lock: a #GStaticRWLock to be freed.
2196 * Releases all resources allocated to @lock.
2198 * You don't have to call this functions for a #GStaticRWLock with an
2199 * unbounded lifetime, i.e. objects declared 'static', but if you have
2200 * a #GStaticRWLock as a member of a structure, and the structure is
2201 * freed, you should also free the #GStaticRWLock.
2204 g_static_rw_lock_free (GStaticRWLock* lock)
2206 g_return_if_fail (lock);
2208 if (lock->read_cond)
2210 g_cond_free (lock->read_cond);
2211 lock->read_cond = NULL;
2213 if (lock->write_cond)
2215 g_cond_free (lock->write_cond);
2216 lock->write_cond = NULL;
2218 g_static_mutex_free (&lock->mutex);
2221 /* Unsorted {{{1 ---------------------------------------------------------- */
2225 * @thread_func: function to call for all GThread structures
2226 * @user_data: second argument to @thread_func
2228 * Call @thread_func on all existing #GThread structures. Note that
2229 * threads may decide to exit while @thread_func is running, so
2230 * without intimate knowledge about the lifetime of foreign threads,
2231 * @thread_func shouldn't access the GThread* pointer passed in as
2232 * first argument. However, @thread_func will not be called for threads
2233 * which are known to have exited already.
2235 * Due to thread lifetime checks, this function has an execution complexity
2236 * which is quadratic in the number of existing threads.
2241 g_thread_foreach (GFunc thread_func,
2244 GSList *slist = NULL;
2245 GRealThread *thread;
2246 g_return_if_fail (thread_func != NULL);
2247 /* snapshot the list of threads for iteration */
2249 for (thread = g_thread_all_threads; thread; thread = thread->next)
2250 slist = g_slist_prepend (slist, thread);
2251 G_UNLOCK (g_thread);
2252 /* walk the list, skipping non-existent threads */
2255 GSList *node = slist;
2257 /* check whether the current thread still exists */
2259 for (thread = g_thread_all_threads; thread; thread = thread->next)
2260 if (thread == node->data)
2262 G_UNLOCK (g_thread);
2264 thread_func (thread, user_data);
2265 g_slist_free_1 (node);
2270 * g_thread_get_initialized:
2272 * Indicates if g_thread_init() has been called.
2274 * Returns: %TRUE if threads have been initialized.
2279 g_thread_get_initialized ()
2281 return g_thread_supported ();
2287 * Creates a new #GMutex.
2289 * Returns: a newly allocated #GMutex. Use g_mutex_free() to free
2296 mutex = g_slice_new (GMutex);
2297 g_mutex_init (mutex);
2306 * Destroys a @mutex that has been created with g_mutex_new().
2308 * <note>Calling g_mutex_free() on a locked mutex may result
2309 * in undefined behaviour.</note>
2312 g_mutex_free (GMutex *mutex)
2314 g_mutex_clear (mutex);
2315 g_slice_free (GMutex, mutex);
2321 * Creates a new #GCond.
2323 * Returns: a newly allocated #GCond. Free with g_cond_free()
2330 cond = g_slice_new (GCond);
2340 * Destroys a #GCond that has been created with g_cond_new().
2343 g_cond_free (GCond *cond)
2345 g_cond_clear (cond);
2346 g_slice_free (GCond, cond);
2351 * @destructor: a function to destroy the data keyed to
2352 * the #GPrivate when a thread ends
2354 * Creates a new #GPrivate. If @destructor is non-%NULL, it is a
2355 * pointer to a destructor function. Whenever a thread ends and the
2356 * corresponding pointer keyed to this instance of #GPrivate is
2357 * non-%NULL, the destructor is called with this pointer as the
2361 * #GStaticPrivate is a better choice for most uses.
2364 * <note><para>@destructor is used quite differently from @notify in
2365 * g_static_private_set().</para></note>
2367 * <note><para>A #GPrivate cannot be freed. Reuse it instead, if you
2368 * can, to avoid shortage, or use #GStaticPrivate.</para></note>
2370 * <note><para>This function will abort if g_thread_init() has not been
2371 * called yet.</para></note>
2373 * Returns: a newly allocated #GPrivate
2376 g_private_new (GDestroyNotify notify)
2380 key = g_slice_new (GPrivate);
2381 g_private_init (key, notify);
2386 GThreadFunctions g_thread_functions_for_glib_use =