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.
25 /* Prelude {{{1 ----------------------------------------------------------- */
28 * Modified by the GLib Team and others 1997-2000. See the AUTHORS
29 * file for a list of people on the GLib Team. See the ChangeLog
30 * files for a list of changes. These files are distributed with
31 * GLib at ftp://ftp.gtk.org/pub/gtk/.
38 /* implement gthread.h's inline functions */
39 #define G_IMPLEMENT_INLINES 1
40 #define __G_THREAD_C__
44 #include "deprecated/gthread.h"
45 #include "gthreadprivate.h"
58 #endif /* G_OS_WIN32 */
65 #include "gtestutils.h"
71 * @short_description: portable support for threads, mutexes, locks,
72 * conditions and thread private data
73 * @see_also: #GThreadPool, #GAsyncQueue
75 * Threads act almost like processes, but unlike processes all threads
76 * of one process share the same memory. This is good, as it provides
77 * easy communication between the involved threads via this shared
78 * memory, and it is bad, because strange things (so called
79 * "Heisenbugs") might happen if the program is not carefully designed.
80 * In particular, due to the concurrent nature of threads, no
81 * assumptions on the order of execution of code running in different
82 * threads can be made, unless order is explicitly forced by the
83 * programmer through synchronization primitives.
85 * The aim of the thread-related functions in GLib is to provide a
86 * portable means for writing multi-threaded software. There are
87 * primitives for mutexes to protect the access to portions of memory
88 * (#GMutex, #GRecMutex and #GRWLock). There is a facility to use
89 * individual bits for locks (g_bit_lock()). There are primitives
90 * for condition variables to allow synchronization of threads (#GCond).
91 * There are primitives for thread-private data - data that every thread
92 * has a private instance of (#GPrivate, #GStaticPrivate). There are
93 * facilities for one-time initialization (#GOnce, g_once_init_enter()).
94 * Finally there are primitives to create and manage threads (#GThread).
96 * The threading system is initialized with g_thread_init(), which
97 * takes an optional custom thread implementation or %NULL for the
98 * default implementation. If you want to call g_thread_init() with a
99 * non-%NULL argument this must be done before executing any other GLib
100 * functions (except g_mem_set_vtable()). This is a requirement even if
101 * no threads are in fact ever created by the process.
103 * Calling g_thread_init() with a %NULL argument is somewhat more
104 * relaxed. You may call any other glib functions in the main thread
105 * before g_thread_init() as long as g_thread_init() is not called from
106 * a glib callback, or with any locks held. However, many libraries
107 * above glib does not support late initialization of threads, so doing
108 * this should be avoided if possible.
110 * Please note that since version 2.24 the GObject initialization
111 * function g_type_init() initializes threads (with a %NULL argument),
112 * so most applications, including those using GTK+ will run with
113 * threads enabled. If you want a special thread implementation, make
114 * sure you call g_thread_init() before g_type_init() is called.
116 * After calling g_thread_init(), GLib is completely thread safe (all
117 * global data is automatically locked), but individual data structure
118 * instances are not automatically locked for performance reasons. So,
119 * for example you must coordinate accesses to the same #GHashTable
120 * from multiple threads. The two notable exceptions from this rule
121 * are #GMainLoop and #GAsyncQueue, which <emphasis>are</emphasis>
122 * threadsafe and need no further application-level locking to be
123 * accessed from multiple threads.
127 * G_THREADS_IMPL_POSIX:
129 * This macro is defined if POSIX style threads are used.
133 * G_THREADS_IMPL_WIN32:
135 * This macro is defined if Windows 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 guint64 gettime (void);
286 guint64 (*g_thread_gettime) (void) = gettime;
288 /* Global Variables {{{1 -------------------------------------------------- */
290 static GSystemThread zero_thread; /* This is initialized to all zero */
291 gboolean g_thread_use_default_impl = TRUE;
294 * g_thread_supported:
295 * @Returns: %TRUE, if the thread system is initialized.
297 * This function returns %TRUE if the thread system is initialized, and
298 * %FALSE if it is not.
300 * <note><para>This function is actually a macro. Apart from taking the
301 * address of it you can however use it as if it was a
302 * function.</para></note>
305 /* IMPLEMENTATION NOTE:
307 * g_thread_supported() is just returns g_threads_got_initialized
309 gboolean g_threads_got_initialized = FALSE;
312 /* Thread Implementation Virtual Function Table {{{1 ---------------------- */
313 /* Virtual Function Table Documentation {{{2 ------------------------------ */
316 * @mutex_new: virtual function pointer for g_mutex_new()
317 * @mutex_lock: virtual function pointer for g_mutex_lock()
318 * @mutex_trylock: virtual function pointer for g_mutex_trylock()
319 * @mutex_unlock: virtual function pointer for g_mutex_unlock()
320 * @mutex_free: virtual function pointer for g_mutex_free()
321 * @cond_new: virtual function pointer for g_cond_new()
322 * @cond_signal: virtual function pointer for g_cond_signal()
323 * @cond_broadcast: virtual function pointer for g_cond_broadcast()
324 * @cond_wait: virtual function pointer for g_cond_wait()
325 * @cond_timed_wait: virtual function pointer for g_cond_timed_wait()
326 * @cond_free: virtual function pointer for g_cond_free()
327 * @private_new: virtual function pointer for g_private_new()
328 * @private_get: virtual function pointer for g_private_get()
329 * @private_set: virtual function pointer for g_private_set()
330 * @thread_create: virtual function pointer for g_thread_create()
331 * @thread_yield: virtual function pointer for g_thread_yield()
332 * @thread_join: virtual function pointer for g_thread_join()
333 * @thread_exit: virtual function pointer for g_thread_exit()
334 * @thread_set_priority: virtual function pointer for
335 * g_thread_set_priority()
336 * @thread_self: virtual function pointer for g_thread_self()
337 * @thread_equal: used internally by recursive mutex locks and by some
340 * This function table is used by g_thread_init() to initialize the
341 * thread system. The functions in the table are directly used by their
342 * g_* prepended counterparts (described in this document). For
343 * example, if you call g_mutex_new() then mutex_new() from the table
344 * provided to g_thread_init() will be called.
346 * <note><para>Do not use this struct unless you know what you are
347 * doing.</para></note>
350 /* GMutex Virtual Functions {{{2 ------------------------------------------ */
355 * The #GMutex struct is an opaque data structure to represent a mutex
356 * (mutual exclusion). It can be used to protect data against shared
357 * access. Take for example the following function:
360 * <title>A function which will not work in a threaded environment</title>
363 * give_me_next_number (void)
365 * static int current_number = 0;
367 * /<!-- -->* now do a very complicated calculation to calculate the new
368 * * number, this might for example be a random number generator
370 * current_number = calc_next_number (current_number);
372 * return current_number;
377 * It is easy to see that this won't work in a multi-threaded
378 * application. There current_number must be protected against shared
379 * access. A first naive implementation would be:
382 * <title>The wrong way to write a thread-safe function</title>
385 * give_me_next_number (void)
387 * static int current_number = 0;
389 * static GMutex * mutex = NULL;
391 * if (!mutex) mutex = g_mutex_new (<!-- -->);
393 * g_mutex_lock (mutex);
394 * ret_val = current_number = calc_next_number (current_number);
395 * g_mutex_unlock (mutex);
402 * This looks like it would work, but there is a race condition while
403 * constructing the mutex and this code cannot work reliable. Please do
404 * not use such constructs in your own programs! One working solution
408 * <title>A correct thread-safe function</title>
410 * static GMutex *give_me_next_number_mutex = NULL;
412 * /<!-- -->* this function must be called before any call to
413 * * give_me_next_number(<!-- -->)
415 * * it must be called exactly once.
418 * init_give_me_next_number (void)
420 * g_assert (give_me_next_number_mutex == NULL);
421 * give_me_next_number_mutex = g_mutex_new (<!-- -->);
425 * give_me_next_number (void)
427 * static int current_number = 0;
430 * g_mutex_lock (give_me_next_number_mutex);
431 * ret_val = current_number = calc_next_number (current_number);
432 * g_mutex_unlock (give_me_next_number_mutex);
439 * A statically initialized #GMutex provides an even simpler and safer
443 * <title>Using a statically allocated mutex</title>
446 * give_me_next_number (void)
448 * static GMutex mutex = G_MUTEX_INIT;
449 * static int current_number = 0;
452 * g_mutex_lock (&mutex);
453 * ret_val = current_number = calc_next_number (current_number);
454 * g_mutex_unlock (&mutex);
461 * A #GMutex should only be accessed via <function>g_mutex_</function>
465 /* GCond Virtual Functions {{{2 ------------------------------------------ */
470 * The #GCond struct is an opaque data structure that represents a
471 * condition. Threads can block on a #GCond if they find a certain
472 * condition to be false. If other threads change the state of this
473 * condition they signal the #GCond, and that causes the waiting
474 * threads to be woken up.
478 * Using GCond to block a thread until a condition is satisfied
481 * GCond* data_cond = NULL; /<!-- -->* Must be initialized somewhere *<!-- -->/
482 * GMutex* data_mutex = NULL; /<!-- -->* Must be initialized somewhere *<!-- -->/
483 * gpointer current_data = NULL;
486 * push_data (gpointer data)
488 * g_mutex_lock (data_mutex);
489 * current_data = data;
490 * g_cond_signal (data_cond);
491 * g_mutex_unlock (data_mutex);
499 * g_mutex_lock (data_mutex);
500 * while (!current_data)
501 * g_cond_wait (data_cond, data_mutex);
502 * data = current_data;
503 * current_data = NULL;
504 * g_mutex_unlock (data_mutex);
511 * Whenever a thread calls pop_data() now, it will wait until
512 * current_data is non-%NULL, i.e. until some other thread
513 * has called push_data().
515 * <note><para>It is important to use the g_cond_wait() and
516 * g_cond_timed_wait() functions only inside a loop which checks for the
517 * condition to be true. It is not guaranteed that the waiting thread
518 * will find the condition fulfilled after it wakes up, even if the
519 * signaling thread left the condition in that state: another thread may
520 * have altered the condition before the waiting thread got the chance
521 * to be woken up, even if the condition itself is protected by a
522 * #GMutex, like above.</para></note>
524 * A #GCond should only be accessed via the following functions.
527 /* GPrivate Virtual Functions {{{2 --------------------------------------- */
533 * #GStaticPrivate is a better choice for most uses.
536 * The #GPrivate struct is an opaque data structure to represent a
537 * thread private data key. Threads can thereby obtain and set a
538 * pointer which is private to the current thread. Take our
539 * <function>give_me_next_number(<!-- -->)</function> example from
540 * above. Suppose we don't want <literal>current_number</literal> to be
541 * shared between the threads, but instead to be private to each thread.
542 * This can be done as follows:
545 * <title>Using GPrivate for per-thread data</title>
547 * GPrivate* current_number_key = NULL; /<!-- -->* Must be initialized somewhere
548 * with g_private_new (g_free); *<!-- -->/
551 * give_me_next_number (void)
553 * int *current_number = g_private_get (current_number_key);
555 * if (!current_number)
557 * current_number = g_new (int, 1);
558 * *current_number = 0;
559 * g_private_set (current_number_key, current_number);
562 * *current_number = calc_next_number (*current_number);
564 * return *current_number;
569 * Here the pointer belonging to the key
570 * <literal>current_number_key</literal> is read. If it is %NULL, it has
571 * not been set yet. Then get memory for an integer value, assign this
572 * memory to the pointer and write the pointer back. Now we have an
573 * integer value that is private to the current thread.
575 * The #GPrivate struct should only be accessed via the following
578 * <note><para>All of the <function>g_private_*</function> functions are
579 * actually macros. Apart from taking their addresses, you can however
580 * use them as if they were functions.</para></note>
583 /* GThread Virtual Functions {{{2 ---------------------------------------- */
587 * The #GThread struct represents a running thread. It has three public
588 * read-only members, but the underlying struct is bigger, so you must
589 * not copy this struct.
591 * <note><para>Resources for a joinable thread are not fully released
592 * until g_thread_join() is called for that thread.</para></note>
597 * @data: data passed to the thread.
598 * @Returns: the return value of the thread, which will be returned by
601 * Specifies the type of the @func functions passed to
602 * g_thread_create() or g_thread_create_full().
607 * @G_THREAD_PRIORITY_LOW: a priority lower than normal
608 * @G_THREAD_PRIORITY_NORMAL: the default priority
609 * @G_THREAD_PRIORITY_HIGH: a priority higher than normal
610 * @G_THREAD_PRIORITY_URGENT: the highest priority
612 * Deprecated:2.32: thread priorities no longer have any effect.
615 /* Local Data {{{1 -------------------------------------------------------- */
617 static GMutex g_once_mutex = G_MUTEX_INIT;
618 static GCond g_once_cond = G_COND_INIT;
619 static GPrivate g_thread_specific_private;
620 static GRealThread *g_thread_all_threads = NULL;
621 static GSList *g_thread_free_indices = NULL;
622 static GSList* g_once_init_list = NULL;
624 G_LOCK_DEFINE_STATIC (g_thread);
626 /* Initialisation {{{1 ---------------------------------------------------- */
630 * @vtable: a function table of type #GThreadFunctions, that provides
631 * the entry points to the thread system to be used.
633 * If you use GLib from more than one thread, you must initialize the
634 * thread system by calling g_thread_init(). Most of the time you will
635 * only have to call <literal>g_thread_init (NULL)</literal>.
637 * <note><para>Do not call g_thread_init() with a non-%NULL parameter unless
638 * you really know what you are doing.</para></note>
640 * <note><para>g_thread_init() must not be called directly or indirectly as a
641 * callback from GLib. Also no mutexes may be currently locked while
642 * calling g_thread_init().</para></note>
644 * <note><para>g_thread_init() changes the way in which #GTimer measures
645 * elapsed time. As a consequence, timers that are running while
646 * g_thread_init() is called may report unreliable times.</para></note>
648 * Calling g_thread_init() multiple times is allowed (since version
649 * 2.24), but nothing happens except for the first call. If the
650 * argument is non-%NULL on such a call a warning will be printed, but
651 * otherwise the argument is ignored.
653 * If no thread system is available and @vtable is %NULL or if not all
654 * elements of @vtable are non-%NULL, then g_thread_init() will abort.
656 * <note><para>To use g_thread_init() in your program, you have to link with
657 * the libraries that the command <command>pkg-config --libs
658 * gthread-2.0</command> outputs. This is not the case for all the
659 * other thread related functions of GLib. Those can be used without
660 * having to link with the thread libraries.</para></note>
663 /* This must be called only once, before any threads are created.
664 * It will only be called from g_thread_init() in -lgthread.
667 g_thread_init_glib (void)
669 static gboolean already_done;
676 /* We let the main thread (the one that calls g_thread_init) inherit
677 * the static_private data set before calling g_thread_init
679 GRealThread* main_thread = (GRealThread*) g_thread_self ();
681 /* setup the basic threading system */
682 g_threads_got_initialized = TRUE;
683 g_private_init (&g_thread_specific_private, g_thread_cleanup);
684 g_private_set (&g_thread_specific_private, main_thread);
685 g_system_thread_self (&main_thread->system_thread);
687 /* accomplish log system initialization to enable messaging */
688 _g_messages_thread_init_nomessage ();
691 /* The following sections implement: GOnce, GStaticMutex, GStaticRecMutex,
695 /* GOnce {{{1 ------------------------------------------------------------- */
699 * @status: the status of the #GOnce
700 * @retval: the value returned by the call to the function, if @status
701 * is %G_ONCE_STATUS_READY
703 * A #GOnce struct controls a one-time initialization function. Any
704 * one-time initialization function must have its own unique #GOnce
713 * A #GOnce must be initialized with this macro before it can be used.
717 * GOnce my_once = G_ONCE_INIT;
726 * @G_ONCE_STATUS_NOTCALLED: the function has not been called yet.
727 * @G_ONCE_STATUS_PROGRESS: the function call is currently in progress.
728 * @G_ONCE_STATUS_READY: the function has been called.
730 * The possible statuses of a one-time initialization function
731 * controlled by a #GOnce struct.
738 * @once: a #GOnce structure
739 * @func: the #GThreadFunc function associated to @once. This function
740 * is called only once, regardless of the number of times it and
741 * its associated #GOnce struct are passed to g_once().
742 * @arg: data to be passed to @func
744 * The first call to this routine by a process with a given #GOnce
745 * struct calls @func with the given argument. Thereafter, subsequent
746 * calls to g_once() with the same #GOnce struct do not call @func
747 * again, but return the stored result of the first call. On return
748 * from g_once(), the status of @once will be %G_ONCE_STATUS_READY.
750 * For example, a mutex or a thread-specific data key must be created
751 * exactly once. In a threaded environment, calling g_once() ensures
752 * that the initialization is serialized across multiple threads.
754 * <note><para>Calling g_once() recursively on the same #GOnce struct in
755 * @func will lead to a deadlock.</para></note>
760 * get_debug_flags (void)
762 * static GOnce my_once = G_ONCE_INIT;
764 * g_once (&my_once, parse_debug_flags, NULL);
766 * return my_once.retval;
774 g_once_impl (GOnce *once,
778 g_mutex_lock (&g_once_mutex);
780 while (once->status == G_ONCE_STATUS_PROGRESS)
781 g_cond_wait (&g_once_cond, &g_once_mutex);
783 if (once->status != G_ONCE_STATUS_READY)
785 once->status = G_ONCE_STATUS_PROGRESS;
786 g_mutex_unlock (&g_once_mutex);
788 once->retval = func (arg);
790 g_mutex_lock (&g_once_mutex);
791 once->status = G_ONCE_STATUS_READY;
792 g_cond_broadcast (&g_once_cond);
795 g_mutex_unlock (&g_once_mutex);
802 * @value_location: location of a static initializable variable
804 * @Returns: %TRUE if the initialization section should be entered,
805 * %FALSE and blocks otherwise
807 * Function to be called when starting a critical initialization
808 * section. The argument @value_location must point to a static
809 * 0-initialized variable that will be set to a value other than 0 at
810 * the end of the initialization section. In combination with
811 * g_once_init_leave() and the unique address @value_location, it can
812 * be ensured that an initialization section will be executed only once
813 * during a program's life time, and that concurrent threads are
814 * blocked until initialization completed. To be used in constructs
819 * static gsize initialization_value = 0;
821 * if (g_once_init_enter (&initialization_value))
823 * gsize setup_value = 42; /<!-- -->* initialization code here *<!-- -->/
825 * g_once_init_leave (&initialization_value, setup_value);
828 * /<!-- -->* use initialization_value here *<!-- -->/
835 g_once_init_enter_impl (volatile gsize *value_location)
837 gboolean need_init = FALSE;
838 g_mutex_lock (&g_once_mutex);
839 if (g_atomic_pointer_get (value_location) == NULL)
841 if (!g_slist_find (g_once_init_list, (void*) value_location))
844 g_once_init_list = g_slist_prepend (g_once_init_list, (void*) value_location);
848 g_cond_wait (&g_once_cond, &g_once_mutex);
849 while (g_slist_find (g_once_init_list, (void*) value_location));
851 g_mutex_unlock (&g_once_mutex);
857 * @value_location: location of a static initializable variable
859 * @initialization_value: new non-0 value for *@value_location.
861 * Counterpart to g_once_init_enter(). Expects a location of a static
862 * 0-initialized initialization variable, and an initialization value
863 * other than 0. Sets the variable to the initialization value, and
864 * releases concurrent threads blocking in g_once_init_enter() on this
865 * initialization variable.
870 g_once_init_leave (volatile gsize *value_location,
871 gsize initialization_value)
873 g_return_if_fail (g_atomic_pointer_get (value_location) == NULL);
874 g_return_if_fail (initialization_value != 0);
875 g_return_if_fail (g_once_init_list != NULL);
877 g_atomic_pointer_set (value_location, initialization_value);
878 g_mutex_lock (&g_once_mutex);
879 g_once_init_list = g_slist_remove (g_once_init_list, (void*) value_location);
880 g_cond_broadcast (&g_once_cond);
881 g_mutex_unlock (&g_once_mutex);
884 /* GStaticMutex {{{1 ------------------------------------------------------ */
889 * A #GStaticMutex works like a #GMutex.
891 * Prior to GLib 2.32, GStaticMutex had the significant advantage
892 * that it doesn't need to be created at run-time, but can be defined
893 * at compile-time. Since 2.32, #GMutex can be statically allocated
894 * as well, and GStaticMutex has been deprecated.
896 * Here is a version of our give_me_next_number() example using
901 * Using <structname>GStaticMutex</structname>
902 * to simplify thread-safe programming
906 * give_me_next_number (void)
908 * static int current_number = 0;
910 * static GStaticMutex mutex = G_STATIC_MUTEX_INIT;
912 * g_static_mutex_lock (&mutex);
913 * ret_val = current_number = calc_next_number (current_number);
914 * g_static_mutex_unlock (&mutex);
921 * Sometimes you would like to dynamically create a mutex. If you don't
922 * want to require prior calling to g_thread_init(), because your code
923 * should also be usable in non-threaded programs, you are not able to
924 * use g_mutex_new() and thus #GMutex, as that requires a prior call to
925 * g_thread_init(). In theses cases you can also use a #GStaticMutex.
926 * It must be initialized with g_static_mutex_init() before using it
927 * and freed with with g_static_mutex_free() when not needed anymore to
928 * free up any allocated resources.
930 * Even though #GStaticMutex is not opaque, it should only be used with
931 * the following functions, as it is defined differently on different
934 * All of the <function>g_static_mutex_*</function> functions apart
935 * from <function>g_static_mutex_get_mutex</function> can also be used
936 * even if g_thread_init() has not yet been called. Then they do
937 * nothing, apart from <function>g_static_mutex_trylock</function>,
938 * which does nothing but returning %TRUE.
940 * <note><para>All of the <function>g_static_mutex_*</function>
941 * functions are actually macros. Apart from taking their addresses, you
942 * can however use them as if they were functions.</para></note>
946 * G_STATIC_MUTEX_INIT:
948 * A #GStaticMutex must be initialized with this macro, before it can
949 * be used. This macro can used be to initialize a variable, but it
950 * cannot be assigned to a variable. In that case you have to use
951 * g_static_mutex_init().
954 * GStaticMutex my_mutex = G_STATIC_MUTEX_INIT;
959 * g_static_mutex_init:
960 * @mutex: a #GStaticMutex to be initialized.
962 * Initializes @mutex.
963 * Alternatively you can initialize it with #G_STATIC_MUTEX_INIT.
965 * Deprecated: 2.32: Use g_mutex_init()
968 g_static_mutex_init (GStaticMutex *mutex)
970 static const GStaticMutex init_mutex = G_STATIC_MUTEX_INIT;
972 g_return_if_fail (mutex);
977 /* IMPLEMENTATION NOTE:
979 * On some platforms a GStaticMutex is actually a normal GMutex stored
980 * inside of a structure instead of being allocated dynamically. We can
981 * only do this for platforms on which we know, in advance, how to
982 * allocate (size) and initialise (value) that memory.
984 * On other platforms, a GStaticMutex is nothing more than a pointer to
985 * a GMutex. In that case, the first access we make to the static mutex
986 * must first allocate the normal GMutex and store it into the pointer.
988 * configure.ac writes macros into glibconfig.h to determine if
989 * g_static_mutex_get_mutex() accesses the structure in memory directly
990 * (on platforms where we are able to do that) or if it ends up here,
991 * where we may have to allocate the GMutex before returning it.
995 * g_static_mutex_get_mutex:
996 * @mutex: a #GStaticMutex.
997 * @Returns: the #GMutex corresponding to @mutex.
999 * For some operations (like g_cond_wait()) you must have a #GMutex
1000 * instead of a #GStaticMutex. This function will return the
1001 * corresponding #GMutex for @mutex.
1003 * Deprecated: 2.32: Just use a #GMutex
1006 g_static_mutex_get_mutex_impl (GMutex** mutex)
1010 if (!g_thread_supported ())
1013 result = g_atomic_pointer_get (mutex);
1017 g_mutex_lock (&g_once_mutex);
1022 result = g_mutex_new ();
1023 g_atomic_pointer_set (mutex, result);
1026 g_mutex_unlock (&g_once_mutex);
1032 /* IMPLEMENTATION NOTE:
1034 * g_static_mutex_lock(), g_static_mutex_trylock() and
1035 * g_static_mutex_unlock() are all preprocessor macros that wrap the
1036 * corresponding g_mutex_*() function around a call to
1037 * g_static_mutex_get_mutex().
1041 * g_static_mutex_lock:
1042 * @mutex: a #GStaticMutex.
1044 * Works like g_mutex_lock(), but for a #GStaticMutex.
1046 * Deprecated: 2.32: Use g_mutex_lock()
1050 * g_static_mutex_trylock:
1051 * @mutex: a #GStaticMutex.
1052 * @Returns: %TRUE, if the #GStaticMutex could be locked.
1054 * Works like g_mutex_trylock(), but for a #GStaticMutex.
1056 * Deprecated: 2.32: Use g_mutex_trylock()
1060 * g_static_mutex_unlock:
1061 * @mutex: a #GStaticMutex.
1063 * Works like g_mutex_unlock(), but for a #GStaticMutex.
1065 * Deprecated: 2.32: Use g_mutex_unlock()
1069 * g_static_mutex_free:
1070 * @mutex: a #GStaticMutex to be freed.
1072 * Releases all resources allocated to @mutex.
1074 * You don't have to call this functions for a #GStaticMutex with an
1075 * unbounded lifetime, i.e. objects declared 'static', but if you have
1076 * a #GStaticMutex as a member of a structure and the structure is
1077 * freed, you should also free the #GStaticMutex.
1079 * <note><para>Calling g_static_mutex_free() on a locked mutex may
1080 * result in undefined behaviour.</para></note>
1082 * Deprecated: 2.32: Use g_mutex_free()
1085 g_static_mutex_free (GStaticMutex* mutex)
1087 GMutex **runtime_mutex;
1089 g_return_if_fail (mutex);
1091 /* The runtime_mutex is the first (or only) member of GStaticMutex,
1092 * see both versions (of glibconfig.h) in configure.ac. Note, that
1093 * this variable is NULL, if g_thread_init() hasn't been called or
1094 * if we're using the default thread implementation and it provides
1095 * static mutexes. */
1096 runtime_mutex = ((GMutex**)mutex);
1099 g_mutex_free (*runtime_mutex);
1101 *runtime_mutex = NULL;
1104 /* ------------------------------------------------------------------------ */
1109 * A #GStaticRecMutex works like a #GStaticMutex, but it can be locked
1110 * multiple times by one thread. If you enter it n times, you have to
1111 * unlock it n times again to let other threads lock it. An exception
1112 * is the function g_static_rec_mutex_unlock_full(): that allows you to
1113 * unlock a #GStaticRecMutex completely returning the depth, (i.e. the
1114 * number of times this mutex was locked). The depth can later be used
1115 * to restore the state of the #GStaticRecMutex by calling
1116 * g_static_rec_mutex_lock_full(). In GLib 2.32, #GStaticRecMutex has
1117 * been deprecated in favor of #GRecMutex.
1119 * Even though #GStaticRecMutex is not opaque, it should only be used
1120 * with the following functions.
1122 * All of the <function>g_static_rec_mutex_*</function> functions can
1123 * be used even if g_thread_init() has not been called. Then they do
1124 * nothing, apart from <function>g_static_rec_mutex_trylock</function>,
1125 * which does nothing but returning %TRUE.
1129 * G_STATIC_REC_MUTEX_INIT:
1131 * A #GStaticRecMutex must be initialized with this macro before it can
1132 * be used. This macro can used be to initialize a variable, but it
1133 * cannot be assigned to a variable. In that case you have to use
1134 * g_static_rec_mutex_init().
1137 * GStaticRecMutex my_mutex = G_STATIC_REC_MUTEX_INIT;
1142 * g_static_rec_mutex_init:
1143 * @mutex: a #GStaticRecMutex to be initialized.
1145 * A #GStaticRecMutex must be initialized with this function before it
1146 * can be used. Alternatively you can initialize it with
1147 * #G_STATIC_REC_MUTEX_INIT.
1149 * Deprecated: 2.32: Use g_rec_mutex_init()
1152 g_static_rec_mutex_init (GStaticRecMutex *mutex)
1154 static const GStaticRecMutex init_mutex = G_STATIC_REC_MUTEX_INIT;
1156 g_return_if_fail (mutex);
1158 *mutex = init_mutex;
1162 * g_static_rec_mutex_lock:
1163 * @mutex: a #GStaticRecMutex to lock.
1165 * Locks @mutex. If @mutex is already locked by another thread, the
1166 * current thread will block until @mutex is unlocked by the other
1167 * thread. If @mutex is already locked by the calling thread, this
1168 * functions increases the depth of @mutex and returns immediately.
1170 * Deprecated: 2.32: Use g_rec_mutex_lock()
1173 g_static_rec_mutex_lock (GStaticRecMutex* mutex)
1177 g_return_if_fail (mutex);
1179 if (!g_thread_supported ())
1182 g_system_thread_self (&self);
1184 if (g_system_thread_equal (&self, &mutex->owner))
1189 g_static_mutex_lock (&mutex->mutex);
1190 g_system_thread_assign (mutex->owner, self);
1195 * g_static_rec_mutex_trylock:
1196 * @mutex: a #GStaticRecMutex to lock.
1197 * @Returns: %TRUE, if @mutex could be locked.
1199 * Tries to lock @mutex. If @mutex is already locked by another thread,
1200 * it immediately returns %FALSE. Otherwise it locks @mutex and returns
1201 * %TRUE. If @mutex is already locked by the calling thread, this
1202 * functions increases the depth of @mutex and immediately returns
1205 * Deprecated: 2.32: Use g_rec_mutex_trylock()
1208 g_static_rec_mutex_trylock (GStaticRecMutex* mutex)
1212 g_return_val_if_fail (mutex, FALSE);
1214 if (!g_thread_supported ())
1217 g_system_thread_self (&self);
1219 if (g_system_thread_equal (&self, &mutex->owner))
1225 if (!g_static_mutex_trylock (&mutex->mutex))
1228 g_system_thread_assign (mutex->owner, self);
1234 * g_static_rec_mutex_unlock:
1235 * @mutex: a #GStaticRecMutex to unlock.
1237 * Unlocks @mutex. Another thread will be allowed to lock @mutex only
1238 * when it has been unlocked as many times as it had been locked
1239 * before. If @mutex is completely unlocked and another thread is
1240 * blocked in a g_static_rec_mutex_lock() call for @mutex, it will be
1241 * woken and can lock @mutex itself.
1243 * Deprecated: 2.32: Use g_rec_mutex_unlock()
1246 g_static_rec_mutex_unlock (GStaticRecMutex* mutex)
1248 g_return_if_fail (mutex);
1250 if (!g_thread_supported ())
1253 if (mutex->depth > 1)
1258 g_system_thread_assign (mutex->owner, zero_thread);
1259 g_static_mutex_unlock (&mutex->mutex);
1263 * g_static_rec_mutex_lock_full:
1264 * @mutex: a #GStaticRecMutex to lock.
1265 * @depth: number of times this mutex has to be unlocked to be
1266 * completely unlocked.
1268 * Works like calling g_static_rec_mutex_lock() for @mutex @depth times.
1270 * Deprecated: 2.32: Use g_rec_mutex_lock()
1273 g_static_rec_mutex_lock_full (GStaticRecMutex *mutex,
1277 g_return_if_fail (mutex);
1279 if (!g_thread_supported ())
1285 g_system_thread_self (&self);
1287 if (g_system_thread_equal (&self, &mutex->owner))
1289 mutex->depth += depth;
1292 g_static_mutex_lock (&mutex->mutex);
1293 g_system_thread_assign (mutex->owner, self);
1294 mutex->depth = depth;
1298 * g_static_rec_mutex_unlock_full:
1299 * @mutex: a #GStaticRecMutex to completely unlock.
1300 * @Returns: number of times @mutex has been locked by the current
1303 * Completely unlocks @mutex. If another thread is blocked in a
1304 * g_static_rec_mutex_lock() call for @mutex, it will be woken and can
1305 * lock @mutex itself. This function returns the number of times that
1306 * @mutex has been locked by the current thread. To restore the state
1307 * before the call to g_static_rec_mutex_unlock_full() you can call
1308 * g_static_rec_mutex_lock_full() with the depth returned by this
1311 * Deprecated: 2.32: Use g_rec_mutex_unlock()
1314 g_static_rec_mutex_unlock_full (GStaticRecMutex *mutex)
1318 g_return_val_if_fail (mutex, 0);
1320 if (!g_thread_supported ())
1323 depth = mutex->depth;
1325 g_system_thread_assign (mutex->owner, zero_thread);
1327 g_static_mutex_unlock (&mutex->mutex);
1333 * g_static_rec_mutex_free:
1334 * @mutex: a #GStaticRecMutex to be freed.
1336 * Releases all resources allocated to a #GStaticRecMutex.
1338 * You don't have to call this functions for a #GStaticRecMutex with an
1339 * unbounded lifetime, i.e. objects declared 'static', but if you have
1340 * a #GStaticRecMutex as a member of a structure and the structure is
1341 * freed, you should also free the #GStaticRecMutex.
1343 * Deprecated: 2.32: Use g_rec_mutex_clear()
1346 g_static_rec_mutex_free (GStaticRecMutex *mutex)
1348 g_return_if_fail (mutex);
1350 g_static_mutex_free (&mutex->mutex);
1353 /* GStaticPrivate {{{1 ---------------------------------------------------- */
1358 * A #GStaticPrivate works almost like a #GPrivate, but it has one
1359 * significant advantage. It doesn't need to be created at run-time
1360 * like a #GPrivate, but can be defined at compile-time. This is
1361 * similar to the difference between #GMutex and #GStaticMutex. Now
1362 * look at our <function>give_me_next_number()</function> example with
1366 * <title>Using GStaticPrivate for per-thread data</title>
1369 * give_me_next_number (<!-- -->)
1371 * static GStaticPrivate current_number_key = G_STATIC_PRIVATE_INIT;
1372 * int *current_number = g_static_private_get (&current_number_key);
1374 * if (!current_number)
1376 * current_number = g_new (int,1);
1377 * *current_number = 0;
1378 * g_static_private_set (&current_number_key, current_number, g_free);
1381 * *current_number = calc_next_number (*current_number);
1383 * return *current_number;
1390 * G_STATIC_PRIVATE_INIT:
1392 * Every #GStaticPrivate must be initialized with this macro, before it
1396 * GStaticPrivate my_private = G_STATIC_PRIVATE_INIT;
1401 * g_static_private_init:
1402 * @private_key: a #GStaticPrivate to be initialized.
1404 * Initializes @private_key. Alternatively you can initialize it with
1405 * #G_STATIC_PRIVATE_INIT.
1408 g_static_private_init (GStaticPrivate *private_key)
1410 private_key->index = 0;
1414 * g_static_private_get:
1415 * @private_key: a #GStaticPrivate.
1416 * @Returns: the corresponding pointer.
1418 * Works like g_private_get() only for a #GStaticPrivate.
1420 * This function works even if g_thread_init() has not yet been called.
1423 g_static_private_get (GStaticPrivate *private_key)
1425 GRealThread *self = (GRealThread*) g_thread_self ();
1427 gpointer ret = NULL;
1429 LOCK_PRIVATE_DATA (self);
1431 array = self->private_data;
1433 if (array && private_key->index != 0 && private_key->index <= array->len)
1434 ret = g_array_index (array, GStaticPrivateNode,
1435 private_key->index - 1).data;
1437 UNLOCK_PRIVATE_DATA (self);
1442 * g_static_private_set:
1443 * @private_key: a #GStaticPrivate.
1444 * @data: the new pointer.
1445 * @notify: a function to be called with the pointer whenever the
1446 * current thread ends or sets this pointer again.
1448 * Sets the pointer keyed to @private_key for the current thread and
1449 * the function @notify to be called with that pointer (%NULL or
1450 * non-%NULL), whenever the pointer is set again or whenever the
1451 * current thread ends.
1453 * This function works even if g_thread_init() has not yet been called.
1454 * If g_thread_init() is called later, the @data keyed to @private_key
1455 * will be inherited only by the main thread, i.e. the one that called
1458 * <note><para>@notify is used quite differently from @destructor in
1459 * g_private_new().</para></note>
1462 g_static_private_set (GStaticPrivate *private_key,
1464 GDestroyNotify notify)
1466 GRealThread *self = (GRealThread*) g_thread_self ();
1468 static guint next_index = 0;
1469 GStaticPrivateNode *node;
1470 gpointer ddata = NULL;
1471 GDestroyNotify ddestroy = NULL;
1473 if (!private_key->index)
1477 if (!private_key->index)
1479 if (g_thread_free_indices)
1481 private_key->index =
1482 GPOINTER_TO_UINT (g_thread_free_indices->data);
1483 g_thread_free_indices =
1484 g_slist_delete_link (g_thread_free_indices,
1485 g_thread_free_indices);
1488 private_key->index = ++next_index;
1491 G_UNLOCK (g_thread);
1494 LOCK_PRIVATE_DATA (self);
1496 array = self->private_data;
1499 array = g_array_new (FALSE, TRUE, sizeof (GStaticPrivateNode));
1500 self->private_data = array;
1503 if (private_key->index > array->len)
1504 g_array_set_size (array, private_key->index);
1506 node = &g_array_index (array, GStaticPrivateNode, private_key->index - 1);
1509 ddestroy = node->destroy;
1512 node->destroy = notify;
1514 UNLOCK_PRIVATE_DATA (self);
1521 * g_static_private_free:
1522 * @private_key: a #GStaticPrivate to be freed.
1524 * Releases all resources allocated to @private_key.
1526 * You don't have to call this functions for a #GStaticPrivate with an
1527 * unbounded lifetime, i.e. objects declared 'static', but if you have
1528 * a #GStaticPrivate as a member of a structure and the structure is
1529 * freed, you should also free the #GStaticPrivate.
1532 g_static_private_free (GStaticPrivate *private_key)
1534 guint idx = private_key->index;
1535 GRealThread *thread, *next;
1536 GArray *garbage = NULL;
1541 private_key->index = 0;
1545 thread = g_thread_all_threads;
1547 for (thread = g_thread_all_threads; thread; thread = next)
1551 next = thread->next;
1553 LOCK_PRIVATE_DATA (thread);
1555 array = thread->private_data;
1557 if (array && idx <= array->len)
1559 GStaticPrivateNode *node = &g_array_index (array,
1562 gpointer ddata = node->data;
1563 GDestroyNotify ddestroy = node->destroy;
1566 node->destroy = NULL;
1570 /* defer non-trivial destruction til after we've finished
1571 * iterating, since we must continue to hold the lock */
1572 if (garbage == NULL)
1573 garbage = g_array_new (FALSE, TRUE,
1574 sizeof (GStaticPrivateNode));
1576 g_array_set_size (garbage, garbage->len + 1);
1578 node = &g_array_index (garbage, GStaticPrivateNode,
1581 node->destroy = ddestroy;
1585 UNLOCK_PRIVATE_DATA (thread);
1587 g_thread_free_indices = g_slist_prepend (g_thread_free_indices,
1588 GUINT_TO_POINTER (idx));
1589 G_UNLOCK (g_thread);
1595 for (i = 0; i < garbage->len; i++)
1597 GStaticPrivateNode *node;
1599 node = &g_array_index (garbage, GStaticPrivateNode, i);
1600 node->destroy (node->data);
1603 g_array_free (garbage, TRUE);
1607 /* GThread Extra Functions {{{1 ------------------------------------------- */
1609 g_thread_cleanup (gpointer data)
1613 GRealThread* thread = data;
1616 LOCK_PRIVATE_DATA (thread);
1617 array = thread->private_data;
1618 thread->private_data = NULL;
1619 UNLOCK_PRIVATE_DATA (thread);
1625 for (i = 0; i < array->len; i++ )
1627 GStaticPrivateNode *node =
1628 &g_array_index (array, GStaticPrivateNode, i);
1630 node->destroy (node->data);
1632 g_array_free (array, TRUE);
1635 /* We only free the thread structure, if it isn't joinable. If
1636 it is, the structure is freed in g_thread_join */
1637 if (!thread->thread.joinable)
1642 for (t = g_thread_all_threads, p = NULL; t; p = t, t = t->next)
1649 g_thread_all_threads = t->next;
1653 G_UNLOCK (g_thread);
1655 /* Just to make sure, this isn't used any more */
1656 g_system_thread_assign (thread->system_thread, zero_thread);
1662 #define G_NSEC_PER_SEC 1000000000
1667 return g_get_monotonic_time () * 1000;
1671 g_thread_create_proxy (gpointer data)
1673 GRealThread* thread = data;
1677 /* This has to happen before G_LOCK, as that might call g_thread_self */
1678 g_private_set (&g_thread_specific_private, data);
1680 /* the lock makes sure, that thread->system_thread is written,
1681 before thread->thread.func is called. See g_thread_create. */
1683 G_UNLOCK (g_thread);
1685 thread->retval = thread->thread.func (thread->thread.data);
1692 * @func: a function to execute in the new thread
1693 * @data: an argument to supply to the new thread
1694 * @joinable: should this thread be joinable?
1695 * @error: return location for error, or %NULL
1697 * This function creates a new thread.
1699 * If @joinable is %TRUE, you can wait for this threads termination
1700 * calling g_thread_join(). Otherwise the thread will just disappear
1701 * when it terminates.
1703 * The new thread executes the function @func with the argument @data.
1704 * If the thread was created successfully, it is returned.
1706 * @error can be %NULL to ignore errors, or non-%NULL to report errors.
1707 * The error is set, if and only if the function returns %NULL.
1709 * Returns: the new #GThread on success
1712 g_thread_create (GThreadFunc func,
1717 return g_thread_create_with_stack_size (func, data, joinable, 0, error);
1721 * g_thread_create_with_stack_size:
1722 * @func: a function to execute in the new thread.
1723 * @data: an argument to supply to the new thread.
1724 * @joinable: should this thread be joinable?
1725 * @stack_size: a stack size for the new thread.
1726 * @error: return location for error.
1727 * @Returns: the new #GThread on success.
1729 * This function creates a new thread. If the underlying thread
1730 * implementation supports it, the thread gets a stack size of
1731 * @stack_size or the default value for the current platform, if
1734 * If @joinable is %TRUE, you can wait for this threads termination
1735 * calling g_thread_join(). Otherwise the thread will just disappear
1736 * when it terminates.
1738 * The new thread executes the function @func with the argument @data.
1739 * If the thread was created successfully, it is returned.
1741 * @error can be %NULL to ignore errors, or non-%NULL to report errors.
1742 * The error is set, if and only if the function returns %NULL.
1745 * Only use g_thread_create_with_stack_size() if you really can't use
1746 * g_thread_create() instead. g_thread_create() does not take
1747 * @stack_size, as it should only be used in cases in which it is
1752 g_thread_create_with_stack_size (GThreadFunc func,
1758 GRealThread* result;
1759 GError *local_error = NULL;
1760 g_return_val_if_fail (func, NULL);
1762 result = g_new0 (GRealThread, 1);
1764 result->thread.joinable = joinable;
1765 result->thread.func = func;
1766 result->thread.data = data;
1767 result->private_data = NULL;
1769 g_system_thread_create (g_thread_create_proxy, result,
1770 stack_size, joinable,
1771 &result->system_thread, &local_error);
1774 result->next = g_thread_all_threads;
1775 g_thread_all_threads = result;
1777 G_UNLOCK (g_thread);
1781 g_propagate_error (error, local_error);
1786 return (GThread*) result;
1790 * g_thread_create_full:
1791 * @func: a function to execute in the new thread.
1792 * @data: an argument to supply to the new thread.
1793 * @stack_size: a stack size for the new thread.
1794 * @joinable: should this thread be joinable?
1796 * @priority: ignored
1797 * @error: return location for error.
1798 * @Returns: the new #GThread on success.
1800 * This function creates a new thread.
1802 * Deprecated:2.32: The @bound and @priority arguments are now ignored.
1803 * Use g_thread_create() or g_thread_create_with_stack_size() instead.
1806 g_thread_create_full (GThreadFunc func,
1811 GThreadPriority priority,
1814 return g_thread_create_with_stack_size (func, data, joinable, stack_size, error);
1819 * @retval: the return value of this thread.
1821 * Exits the current thread. If another thread is waiting for that
1822 * thread using g_thread_join() and the current thread is joinable, the
1823 * waiting thread will be woken up and get @retval as the return value
1824 * of g_thread_join(). If the current thread is not joinable, @retval
1825 * is ignored. Calling
1828 * g_thread_exit (retval);
1831 * is equivalent to returning @retval from the function @func, as given
1832 * to g_thread_create().
1834 * <note><para>Never call g_thread_exit() from within a thread of a
1835 * #GThreadPool, as that will mess up the bookkeeping and lead to funny
1836 * and unwanted results.</para></note>
1839 g_thread_exit (gpointer retval)
1841 GRealThread* real = (GRealThread*) g_thread_self ();
1842 real->retval = retval;
1844 g_system_thread_exit ();
1849 * @thread: a #GThread to be waited for.
1850 * @Returns: the return value of the thread.
1852 * Waits until @thread finishes, i.e. the function @func, as given to
1853 * g_thread_create(), returns or g_thread_exit() is called by @thread.
1854 * All resources of @thread including the #GThread struct are released.
1855 * @thread must have been created with @joinable=%TRUE in
1856 * g_thread_create(). The value returned by @func or given to
1857 * g_thread_exit() by @thread is returned by this function.
1860 g_thread_join (GThread* thread)
1862 GRealThread* real = (GRealThread*) thread;
1866 g_return_val_if_fail (thread, NULL);
1867 g_return_val_if_fail (thread->joinable, NULL);
1868 g_return_val_if_fail (!g_system_thread_equal (&real->system_thread, &zero_thread), NULL);
1870 g_system_thread_join (&real->system_thread);
1872 retval = real->retval;
1875 for (t = g_thread_all_threads, p = NULL; t; p = t, t = t->next)
1877 if (t == (GRealThread*) thread)
1882 g_thread_all_threads = t->next;
1886 G_UNLOCK (g_thread);
1888 /* Just to make sure, this isn't used any more */
1889 thread->joinable = 0;
1890 g_system_thread_assign (real->system_thread, zero_thread);
1892 /* the thread structure for non-joinable threads is freed upon
1893 thread end. We free the memory here. This will leave a loose end,
1894 if a joinable thread is not joined. */
1902 * g_thread_set_priority:
1903 * @thread: a #GThread.
1904 * @priority: ignored
1906 * This function does nothing.
1908 * Deprecated:2.32: Thread priorities no longer have any effect.
1911 g_thread_set_priority (GThread *thread,
1912 GThreadPriority priority)
1918 * @Returns: the current thread.
1920 * This functions returns the #GThread corresponding to the calling
1924 g_thread_self (void)
1926 GRealThread* thread = g_private_get (&g_thread_specific_private);
1930 /* If no thread data is available, provide and set one. This
1931 can happen for the main thread and for threads, that are not
1933 thread = g_new0 (GRealThread, 1);
1934 thread->thread.joinable = FALSE; /* This is a save guess */
1935 thread->thread.func = NULL;
1936 thread->thread.data = NULL;
1937 thread->private_data = NULL;
1939 g_system_thread_self (&thread->system_thread);
1941 g_private_set (&g_thread_specific_private, thread);
1944 thread->next = g_thread_all_threads;
1945 g_thread_all_threads = thread;
1946 G_UNLOCK (g_thread);
1949 return (GThread*)thread;
1952 /* GStaticRWLock {{{1 ----------------------------------------------------- */
1957 * The #GStaticRWLock struct represents a read-write lock. A read-write
1958 * lock can be used for protecting data that some portions of code only
1959 * read from, while others also write. In such situations it is
1960 * desirable that several readers can read at once, whereas of course
1961 * only one writer may write at a time. Take a look at the following
1965 * <title>An array with access functions</title>
1967 * GStaticRWLock rwlock = G_STATIC_RW_LOCK_INIT;
1971 * my_array_get (guint index)
1973 * gpointer retval = NULL;
1978 * g_static_rw_lock_reader_lock (&rwlock);
1979 * if (index < array->len)
1980 * retval = g_ptr_array_index (array, index);
1981 * g_static_rw_lock_reader_unlock (&rwlock);
1987 * my_array_set (guint index, gpointer data)
1989 * g_static_rw_lock_writer_lock (&rwlock);
1992 * array = g_ptr_array_new (<!-- -->);
1994 * if (index >= array->len)
1995 * g_ptr_array_set_size (array, index+1);
1996 * g_ptr_array_index (array, index) = data;
1998 * g_static_rw_lock_writer_unlock (&rwlock);
2003 * This example shows an array which can be accessed by many readers
2004 * (the <function>my_array_get()</function> function) simultaneously,
2005 * whereas the writers (the <function>my_array_set()</function>
2006 * function) will only be allowed once at a time and only if no readers
2007 * currently access the array. This is because of the potentially
2008 * dangerous resizing of the array. Using these functions is fully
2009 * multi-thread safe now.
2011 * Most of the time, writers should have precedence over readers. That
2012 * means, for this implementation, that as soon as a writer wants to
2013 * lock the data, no other reader is allowed to lock the data, whereas,
2014 * of course, the readers that already have locked the data are allowed
2015 * to finish their operation. As soon as the last reader unlocks the
2016 * data, the writer will lock it.
2018 * Even though #GStaticRWLock is not opaque, it should only be used
2019 * with the following functions.
2021 * All of the <function>g_static_rw_lock_*</function> functions can be
2022 * used even if g_thread_init() has not been called. Then they do
2023 * nothing, apart from <function>g_static_rw_lock_*_trylock</function>,
2024 * which does nothing but returning %TRUE.
2026 * <note><para>A read-write lock has a higher overhead than a mutex. For
2027 * example, both g_static_rw_lock_reader_lock() and
2028 * g_static_rw_lock_reader_unlock() have to lock and unlock a
2029 * #GStaticMutex, so it takes at least twice the time to lock and unlock
2030 * a #GStaticRWLock that it does to lock and unlock a #GStaticMutex. So
2031 * only data structures that are accessed by multiple readers, and which
2032 * keep the lock for a considerable time justify a #GStaticRWLock. The
2033 * above example most probably would fare better with a
2034 * #GStaticMutex.</para></note>
2036 * Deprecated: 2.32: Use a #GRWLock instead
2040 * G_STATIC_RW_LOCK_INIT:
2042 * A #GStaticRWLock must be initialized with this macro before it can
2043 * be used. This macro can used be to initialize a variable, but it
2044 * cannot be assigned to a variable. In that case you have to use
2045 * g_static_rw_lock_init().
2048 * GStaticRWLock my_lock = G_STATIC_RW_LOCK_INIT;
2053 * g_static_rw_lock_init:
2054 * @lock: a #GStaticRWLock to be initialized.
2056 * A #GStaticRWLock must be initialized with this function before it
2057 * can be used. Alternatively you can initialize it with
2058 * #G_STATIC_RW_LOCK_INIT.
2060 * Deprecated: 2.32: Use g_rw_lock_init() instead
2063 g_static_rw_lock_init (GStaticRWLock* lock)
2065 static const GStaticRWLock init_lock = G_STATIC_RW_LOCK_INIT;
2067 g_return_if_fail (lock);
2073 g_static_rw_lock_wait (GCond** cond, GStaticMutex* mutex)
2076 *cond = g_cond_new ();
2077 g_cond_wait (*cond, g_static_mutex_get_mutex (mutex));
2081 g_static_rw_lock_signal (GStaticRWLock* lock)
2083 if (lock->want_to_write && lock->write_cond)
2084 g_cond_signal (lock->write_cond);
2085 else if (lock->want_to_read && lock->read_cond)
2086 g_cond_broadcast (lock->read_cond);
2090 * g_static_rw_lock_reader_lock:
2091 * @lock: a #GStaticRWLock to lock for reading.
2093 * Locks @lock for reading. There may be unlimited concurrent locks for
2094 * reading of a #GStaticRWLock at the same time. If @lock is already
2095 * locked for writing by another thread or if another thread is already
2096 * waiting to lock @lock for writing, this function will block until
2097 * @lock is unlocked by the other writing thread and no other writing
2098 * threads want to lock @lock. This lock has to be unlocked by
2099 * g_static_rw_lock_reader_unlock().
2101 * #GStaticRWLock is not recursive. It might seem to be possible to
2102 * recursively lock for reading, but that can result in a deadlock, due
2103 * to writer preference.
2105 * Deprecated: 2.32: Use g_rw_lock_reader_lock() instead
2108 g_static_rw_lock_reader_lock (GStaticRWLock* lock)
2110 g_return_if_fail (lock);
2112 if (!g_threads_got_initialized)
2115 g_static_mutex_lock (&lock->mutex);
2116 lock->want_to_read++;
2117 while (lock->have_writer || lock->want_to_write)
2118 g_static_rw_lock_wait (&lock->read_cond, &lock->mutex);
2119 lock->want_to_read--;
2120 lock->read_counter++;
2121 g_static_mutex_unlock (&lock->mutex);
2125 * g_static_rw_lock_reader_trylock:
2126 * @lock: a #GStaticRWLock to lock for reading.
2127 * @Returns: %TRUE, if @lock could be locked for reading.
2129 * Tries to lock @lock for reading. If @lock is already locked for
2130 * writing by another thread or if another thread is already waiting to
2131 * lock @lock for writing, immediately returns %FALSE. Otherwise locks
2132 * @lock for reading and returns %TRUE. This lock has to be unlocked by
2133 * g_static_rw_lock_reader_unlock().
2135 * Deprectated: 2.32: Use g_rw_lock_reader_trylock() instead
2138 g_static_rw_lock_reader_trylock (GStaticRWLock* lock)
2140 gboolean ret_val = FALSE;
2142 g_return_val_if_fail (lock, FALSE);
2144 if (!g_threads_got_initialized)
2147 g_static_mutex_lock (&lock->mutex);
2148 if (!lock->have_writer && !lock->want_to_write)
2150 lock->read_counter++;
2153 g_static_mutex_unlock (&lock->mutex);
2158 * g_static_rw_lock_reader_unlock:
2159 * @lock: a #GStaticRWLock to unlock after reading.
2161 * Unlocks @lock. If a thread waits to lock @lock for writing and all
2162 * locks for reading have been unlocked, the waiting thread is woken up
2163 * and can lock @lock for writing.
2165 * Deprectated: 2.32: Use g_rw_lock_reader_unlock() instead
2168 g_static_rw_lock_reader_unlock (GStaticRWLock* lock)
2170 g_return_if_fail (lock);
2172 if (!g_threads_got_initialized)
2175 g_static_mutex_lock (&lock->mutex);
2176 lock->read_counter--;
2177 if (lock->read_counter == 0)
2178 g_static_rw_lock_signal (lock);
2179 g_static_mutex_unlock (&lock->mutex);
2183 * g_static_rw_lock_writer_lock:
2184 * @lock: a #GStaticRWLock to lock for writing.
2186 * Locks @lock for writing. If @lock is already locked for writing or
2187 * reading by other threads, this function will block until @lock is
2188 * completely unlocked and then lock @lock for writing. While this
2189 * functions waits to lock @lock, no other thread can lock @lock for
2190 * reading. When @lock is locked for writing, no other thread can lock
2191 * @lock (neither for reading nor writing). This lock has to be
2192 * unlocked by g_static_rw_lock_writer_unlock().
2194 * Deprectated: 2.32: Use g_rw_lock_writer_lock() instead
2197 g_static_rw_lock_writer_lock (GStaticRWLock* lock)
2199 g_return_if_fail (lock);
2201 if (!g_threads_got_initialized)
2204 g_static_mutex_lock (&lock->mutex);
2205 lock->want_to_write++;
2206 while (lock->have_writer || lock->read_counter)
2207 g_static_rw_lock_wait (&lock->write_cond, &lock->mutex);
2208 lock->want_to_write--;
2209 lock->have_writer = TRUE;
2210 g_static_mutex_unlock (&lock->mutex);
2214 * g_static_rw_lock_writer_trylock:
2215 * @lock: a #GStaticRWLock to lock for writing.
2216 * @Returns: %TRUE, if @lock could be locked for writing.
2218 * Tries to lock @lock for writing. If @lock is already locked (for
2219 * either reading or writing) by another thread, it immediately returns
2220 * %FALSE. Otherwise it locks @lock for writing and returns %TRUE. This
2221 * lock has to be unlocked by g_static_rw_lock_writer_unlock().
2223 * Deprectated: 2.32: Use g_rw_lock_writer_trylock() instead
2226 g_static_rw_lock_writer_trylock (GStaticRWLock* lock)
2228 gboolean ret_val = FALSE;
2230 g_return_val_if_fail (lock, FALSE);
2232 if (!g_threads_got_initialized)
2235 g_static_mutex_lock (&lock->mutex);
2236 if (!lock->have_writer && !lock->read_counter)
2238 lock->have_writer = TRUE;
2241 g_static_mutex_unlock (&lock->mutex);
2246 * g_static_rw_lock_writer_unlock:
2247 * @lock: a #GStaticRWLock to unlock after writing.
2249 * Unlocks @lock. If a thread is waiting to lock @lock for writing and
2250 * all locks for reading have been unlocked, the waiting thread is
2251 * woken up and can lock @lock for writing. If no thread is waiting to
2252 * lock @lock for writing, and some thread or threads are waiting to
2253 * lock @lock for reading, the waiting threads are woken up and can
2254 * lock @lock for reading.
2256 * Deprectated: 2.32: Use g_rw_lock_writer_unlock() instead
2259 g_static_rw_lock_writer_unlock (GStaticRWLock* lock)
2261 g_return_if_fail (lock);
2263 if (!g_threads_got_initialized)
2266 g_static_mutex_lock (&lock->mutex);
2267 lock->have_writer = FALSE;
2268 g_static_rw_lock_signal (lock);
2269 g_static_mutex_unlock (&lock->mutex);
2273 * g_static_rw_lock_free:
2274 * @lock: a #GStaticRWLock to be freed.
2276 * Releases all resources allocated to @lock.
2278 * You don't have to call this functions for a #GStaticRWLock with an
2279 * unbounded lifetime, i.e. objects declared 'static', but if you have
2280 * a #GStaticRWLock as a member of a structure, and the structure is
2281 * freed, you should also free the #GStaticRWLock.
2283 * Deprecated: 2.32: Use a #GRWLock instead
2286 g_static_rw_lock_free (GStaticRWLock* lock)
2288 g_return_if_fail (lock);
2290 if (lock->read_cond)
2292 g_cond_free (lock->read_cond);
2293 lock->read_cond = NULL;
2295 if (lock->write_cond)
2297 g_cond_free (lock->write_cond);
2298 lock->write_cond = NULL;
2300 g_static_mutex_free (&lock->mutex);
2303 /* Unsorted {{{1 ---------------------------------------------------------- */
2307 * @thread_func: function to call for all GThread structures
2308 * @user_data: second argument to @thread_func
2310 * Call @thread_func on all existing #GThread structures. Note that
2311 * threads may decide to exit while @thread_func is running, so
2312 * without intimate knowledge about the lifetime of foreign threads,
2313 * @thread_func shouldn't access the GThread* pointer passed in as
2314 * first argument. However, @thread_func will not be called for threads
2315 * which are known to have exited already.
2317 * Due to thread lifetime checks, this function has an execution complexity
2318 * which is quadratic in the number of existing threads.
2323 g_thread_foreach (GFunc thread_func,
2326 GSList *slist = NULL;
2327 GRealThread *thread;
2328 g_return_if_fail (thread_func != NULL);
2329 /* snapshot the list of threads for iteration */
2331 for (thread = g_thread_all_threads; thread; thread = thread->next)
2332 slist = g_slist_prepend (slist, thread);
2333 G_UNLOCK (g_thread);
2334 /* walk the list, skipping non-existent threads */
2337 GSList *node = slist;
2339 /* check whether the current thread still exists */
2341 for (thread = g_thread_all_threads; thread; thread = thread->next)
2342 if (thread == node->data)
2344 G_UNLOCK (g_thread);
2346 thread_func (thread, user_data);
2347 g_slist_free_1 (node);
2352 * g_thread_get_initialized:
2354 * Indicates if g_thread_init() has been called.
2356 * Returns: %TRUE if threads have been initialized.
2361 g_thread_get_initialized ()
2363 return g_thread_supported ();
2369 * Allocated and initializes a new #GMutex.
2371 * Returns: a newly allocated #GMutex. Use g_mutex_free() to free
2378 mutex = g_slice_new (GMutex);
2379 g_mutex_init (mutex);
2388 * Destroys a @mutex that has been created with g_mutex_new().
2390 * Calling g_mutex_free() on a locked mutex may result
2391 * in undefined behaviour.
2394 g_mutex_free (GMutex *mutex)
2396 g_mutex_clear (mutex);
2397 g_slice_free (GMutex, mutex);
2403 * Allocates and initializes a new #GCond.
2405 * Returns: a newly allocated #GCond. Free with g_cond_free()
2412 cond = g_slice_new (GCond);
2422 * Destroys a #GCond that has been created with g_cond_new().
2425 g_cond_free (GCond *cond)
2427 g_cond_clear (cond);
2428 g_slice_free (GCond, cond);
2433 * @destructor: a function to destroy the data keyed to
2434 * the #GPrivate when a thread ends
2436 * Creates a new #GPrivate. If @destructor is non-%NULL, it is a
2437 * pointer to a destructor function. Whenever a thread ends and the
2438 * corresponding pointer keyed to this instance of #GPrivate is
2439 * non-%NULL, the destructor is called with this pointer as the
2443 * #GStaticPrivate is a better choice for most uses.
2446 * <note><para>@destructor is used quite differently from @notify in
2447 * g_static_private_set().</para></note>
2449 * <note><para>A #GPrivate cannot be freed. Reuse it instead, if you
2450 * can, to avoid shortage, or use #GStaticPrivate.</para></note>
2452 * <note><para>This function will abort if g_thread_init() has not been
2453 * called yet.</para></note>
2455 * Returns: a newly allocated #GPrivate
2458 g_private_new (GDestroyNotify notify)
2462 key = g_slice_new (GPrivate);
2463 g_private_init (key, notify);
2468 GThreadFunctions g_thread_functions_for_glib_use =
2493 /* vim: set foldmethod=marker: */