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__
43 #include "deprecated/gthread.h"
44 #include "gthreadprivate.h"
57 #endif /* G_OS_WIN32 */
64 #include "gtestutils.h"
70 * @short_description: portable support for threads, mutexes, locks,
71 * 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, #GRecMutex and #GRWLock). There is a facility to use
88 * individual bits for locks (g_bit_lock()). There are primitives
89 * for condition variables to allow synchronization of threads (#GCond).
90 * There are primitives for thread-private data - data that every thread
91 * has a private instance of (#GPrivate, #GStaticPrivate). There are
92 * facilities for one-time initialization (#GOnce, g_once_init_enter()).
93 * Finally there are primitives to create and manage threads (#GThread).
95 * The threading system is initialized with g_thread_init(), which
96 * takes an optional custom thread implementation or %NULL for the
97 * default implementation. If you want to call g_thread_init() with a
98 * non-%NULL argument this must be done before executing any other GLib
99 * functions (except g_mem_set_vtable()). This is a requirement even if
100 * no threads are in fact ever created by the process.
102 * Calling g_thread_init() with a %NULL argument is somewhat more
103 * relaxed. You may call any other glib functions in the main thread
104 * before g_thread_init() as long as g_thread_init() is not called from
105 * a glib callback, or with any locks held. However, many libraries
106 * above glib does not support late initialization of threads, so doing
107 * this should be avoided if possible.
109 * Please note that since version 2.24 the GObject initialization
110 * function g_type_init() initializes threads (with a %NULL argument),
111 * so most applications, including those using GTK+ will run with
112 * threads enabled. If you want a special thread implementation, make
113 * sure you call g_thread_init() before g_type_init() is called.
115 * After calling g_thread_init(), GLib is completely thread safe (all
116 * global data is automatically locked), but individual data structure
117 * instances are not automatically locked for performance reasons. So,
118 * for example you must coordinate accesses to the same #GHashTable
119 * from multiple threads. The two notable exceptions from this rule
120 * are #GMainLoop and #GAsyncQueue, which <emphasis>are</emphasis>
121 * threadsafe and need no further application-level locking to be
122 * accessed from multiple threads.
126 * G_THREADS_IMPL_POSIX:
128 * This macro is defined if POSIX style threads are used.
132 * G_THREADS_IMPL_WIN32:
134 * This macro is defined if Windows style threads are used.
140 * This macro is defined, for backward compatibility, to indicate that
141 * GLib has been compiled with thread support. As of GLib 2.28, it is
145 /* G_LOCK Documentation {{{1 ---------------------------------------------- */
147 /* IMPLEMENTATION NOTE:
149 * G_LOCK_DEFINE and friends are convenience macros defined in
150 * gthread.h. Their documentation lives here.
155 * @name: the name of the lock.
157 * The %G_LOCK_* macros provide a convenient interface to #GStaticMutex
158 * with the advantage that they will expand to nothing in programs
159 * compiled against a thread-disabled GLib, saving code and memory
160 * there. #G_LOCK_DEFINE defines a lock. It can appear anywhere
161 * variable definitions may appear in programs, i.e. in the first block
162 * of a function or outside of functions. The @name parameter will be
163 * mangled to get the name of the #GStaticMutex. This means that you
164 * can use names of existing variables as the parameter - e.g. the name
165 * of the variable you intent to protect with the lock. Look at our
166 * <function>give_me_next_number()</function> example using the
170 * <title>Using the %G_LOCK_* convenience macros</title>
172 * G_LOCK_DEFINE (current_number);
175 * give_me_next_number (void)
177 * static int current_number = 0;
180 * G_LOCK (current_number);
181 * ret_val = current_number = calc_next_number (current_number);
182 * G_UNLOCK (current_number);
191 * G_LOCK_DEFINE_STATIC:
192 * @name: the name of the lock.
194 * This works like #G_LOCK_DEFINE, but it creates a static object.
199 * @name: the name of the lock.
201 * This declares a lock, that is defined with #G_LOCK_DEFINE in another
207 * @name: the name of the lock.
209 * Works like g_mutex_lock(), but for a lock defined with
215 * @name: the name of the lock.
216 * @Returns: %TRUE, if the lock could be locked.
218 * Works like g_mutex_trylock(), but for a lock defined with
224 * @name: the name of the lock.
226 * Works like g_mutex_unlock(), but for a lock defined with
231 /* GMutex Documentation {{{1 ------------------------------------------ */
236 * The #GMutex struct is an opaque data structure to represent a mutex
237 * (mutual exclusion). It can be used to protect data against shared
238 * access. Take for example the following function:
241 * <title>A function which will not work in a threaded environment</title>
244 * give_me_next_number (void)
246 * static int current_number = 0;
248 * /<!-- -->* now do a very complicated calculation to calculate the new
249 * * number, this might for example be a random number generator
251 * current_number = calc_next_number (current_number);
253 * return current_number;
258 * It is easy to see that this won't work in a multi-threaded
259 * application. There current_number must be protected against shared
260 * access. A first naive implementation would be:
263 * <title>The wrong way to write a thread-safe function</title>
266 * give_me_next_number (void)
268 * static int current_number = 0;
270 * static GMutex * mutex = NULL;
272 * if (!mutex) mutex = g_mutex_new (<!-- -->);
274 * g_mutex_lock (mutex);
275 * ret_val = current_number = calc_next_number (current_number);
276 * g_mutex_unlock (mutex);
283 * This looks like it would work, but there is a race condition while
284 * constructing the mutex and this code cannot work reliable. Please do
285 * not use such constructs in your own programs! One working solution
289 * <title>A correct thread-safe function</title>
291 * static GMutex *give_me_next_number_mutex = NULL;
293 * /<!-- -->* this function must be called before any call to
294 * * give_me_next_number(<!-- -->)
296 * * it must be called exactly once.
299 * init_give_me_next_number (void)
301 * g_assert (give_me_next_number_mutex == NULL);
302 * give_me_next_number_mutex = g_mutex_new (<!-- -->);
306 * give_me_next_number (void)
308 * static int current_number = 0;
311 * g_mutex_lock (give_me_next_number_mutex);
312 * ret_val = current_number = calc_next_number (current_number);
313 * g_mutex_unlock (give_me_next_number_mutex);
320 * A statically initialized #GMutex provides an even simpler and safer
324 * <title>Using a statically allocated mutex</title>
327 * give_me_next_number (void)
329 * static GMutex mutex = G_MUTEX_INIT;
330 * static int current_number = 0;
333 * g_mutex_lock (&mutex);
334 * ret_val = current_number = calc_next_number (current_number);
335 * g_mutex_unlock (&mutex);
342 * A #GMutex should only be accessed via <function>g_mutex_</function>
349 * Initializer for statically allocated #GMutexes.
350 * Alternatively, g_mutex_init() can be used.
353 * GMutex mutex = G_MUTEX_INIT;
359 /* GRecMutex Documentation {{{1 -------------------------------------- */
364 * The GRecMutex struct is an opaque data structure to represent a
365 * recursive mutex. It is similar to a #GMutex with the difference
366 * that it is possible to lock a GRecMutex multiple times in the same
367 * thread without deadlock. When doing so, care has to be taken to
368 * unlock the recursive mutex as often as it has been locked.
370 * A GRecMutex should only be accessed with the
371 * <function>g_rec_mutex_</function> functions. Before a GRecMutex
372 * can be used, it has to be initialized with #G_REC_MUTEX_INIT or
373 * g_rec_mutex_init().
381 * Initializer for statically allocated #GRecMutexes.
382 * Alternatively, g_rec_mutex_init() can be used.
385 * GRecMutex mutex = G_REC_MUTEX_INIT;
391 /* GRWLock Documentation {{{1 ---------------------------------------- */
396 * The GRWLock struct is an opaque data structure to represent a
397 * reader-writer lock. It is similar to a #GMutex in that it allows
398 * multiple threads to coordinate access to a shared resource.
400 * The difference to a mutex is that a reader-writer lock discriminates
401 * between read-only ('reader') and full ('writer') access. While only
402 * one thread at a time is allowed write access (by holding the 'writer'
403 * lock via g_rw_lock_writer_lock()), multiple threads can gain
404 * simultaneous read-only access (by holding the 'reader' lock via
405 * g_rw_lock_reader_lock()).
408 * <title>An array with access functions</title>
410 * GRWLock lock = G_RW_LOCK_INIT;
414 * my_array_get (guint index)
416 * gpointer retval = NULL;
421 * g_rw_lock_reader_lock (&lock);
422 * if (index < array->len)
423 * retval = g_ptr_array_index (array, index);
424 * g_rw_lock_reader_unlock (&lock);
430 * my_array_set (guint index, gpointer data)
432 * g_rw_lock_writer_lock (&lock);
435 * array = g_ptr_array_new (<!-- -->);
437 * if (index >= array->len)
438 * g_ptr_array_set_size (array, index+1);
439 * g_ptr_array_index (array, index) = data;
441 * g_rw_lock_writer_unlock (&lock);
445 * This example shows an array which can be accessed by many readers
446 * (the <function>my_array_get()</function> function) simultaneously,
447 * whereas the writers (the <function>my_array_set()</function>
448 * function) will only be allowed once at a time and only if no readers
449 * currently access the array. This is because of the potentially
450 * dangerous resizing of the array. Using these functions is fully
451 * multi-thread safe now.
455 * A GRWLock should only be accessed with the
456 * <function>g_rw_lock_</function> functions. Before it can be used,
457 * it has to be initialized with #G_RW_LOCK_INIT or g_rw_lock_init().
465 * Initializer for statically allocated #GRWLocks.
466 * Alternatively, g_rw_lock_init_init() can be used.
469 * GRWLock lock = G_RW_LOCK_INIT;
475 /* GCond Documentation {{{1 ------------------------------------------ */
480 * The #GCond struct is an opaque data structure that represents a
481 * condition. Threads can block on a #GCond if they find a certain
482 * condition to be false. If other threads change the state of this
483 * condition they signal the #GCond, and that causes the waiting
484 * threads to be woken up.
488 * Using GCond to block a thread until a condition is satisfied
491 * GCond* data_cond = NULL; /<!-- -->* Must be initialized somewhere *<!-- -->/
492 * GMutex* data_mutex = NULL; /<!-- -->* Must be initialized somewhere *<!-- -->/
493 * gpointer current_data = NULL;
496 * push_data (gpointer data)
498 * g_mutex_lock (data_mutex);
499 * current_data = data;
500 * g_cond_signal (data_cond);
501 * g_mutex_unlock (data_mutex);
509 * g_mutex_lock (data_mutex);
510 * while (!current_data)
511 * g_cond_wait (data_cond, data_mutex);
512 * data = current_data;
513 * current_data = NULL;
514 * g_mutex_unlock (data_mutex);
521 * Whenever a thread calls pop_data() now, it will wait until
522 * current_data is non-%NULL, i.e. until some other thread
523 * has called push_data().
525 * <note><para>It is important to use the g_cond_wait() and
526 * g_cond_timed_wait() functions only inside a loop which checks for the
527 * condition to be true. It is not guaranteed that the waiting thread
528 * will find the condition fulfilled after it wakes up, even if the
529 * signaling thread left the condition in that state: another thread may
530 * have altered the condition before the waiting thread got the chance
531 * to be woken up, even if the condition itself is protected by a
532 * #GMutex, like above.</para></note>
534 * A #GCond should only be accessed via the <function>g_cond_</function>
541 * Initializer for statically allocated #GConds.
542 * Alternatively, g_cond_init() can be used.
545 * GCond cond = G_COND_INIT;
551 /* GPrivate Documentation {{{1 --------------------------------------- */
557 * #GStaticPrivate is a better choice for most uses.
560 * The #GPrivate struct is an opaque data structure to represent a
561 * thread private data key. Threads can thereby obtain and set a
562 * pointer which is private to the current thread. Take our
563 * <function>give_me_next_number(<!-- -->)</function> example from
564 * above. Suppose we don't want <literal>current_number</literal> to be
565 * shared between the threads, but instead to be private to each thread.
566 * This can be done as follows:
569 * <title>Using GPrivate for per-thread data</title>
571 * GPrivate* current_number_key = NULL; /<!-- -->* Must be initialized somewhere
572 * with g_private_new (g_free); *<!-- -->/
575 * give_me_next_number (void)
577 * int *current_number = g_private_get (current_number_key);
579 * if (!current_number)
581 * current_number = g_new (int, 1);
582 * *current_number = 0;
583 * g_private_set (current_number_key, current_number);
586 * *current_number = calc_next_number (*current_number);
588 * return *current_number;
593 * Here the pointer belonging to the key
594 * <literal>current_number_key</literal> is read. If it is %NULL, it has
595 * not been set yet. Then get memory for an integer value, assign this
596 * memory to the pointer and write the pointer back. Now we have an
597 * integer value that is private to the current thread.
599 * The #GPrivate struct should only be accessed via the
600 * <function>g_private_</function> functions.
603 /* GThread Documentation {{{1 ---------------------------------------- */
607 * The #GThread struct represents a running thread. It has three public
608 * read-only members, but the underlying struct is bigger, so you must
609 * not copy this struct.
611 * <note><para>Resources for a joinable thread are not fully released
612 * until g_thread_join() is called for that thread.</para></note>
617 * @data: data passed to the thread.
618 * @Returns: the return value of the thread, which will be returned by
621 * Specifies the type of the @func functions passed to
622 * g_thread_create() or g_thread_create_full().
625 /* GThreadError {{{1 ------------------------------------------------------- */
628 * @G_THREAD_ERROR_AGAIN: a thread couldn't be created due to resource
629 * shortage. Try again later.
631 * Possible errors of thread related functions.
637 * The error domain of the GLib thread subsystem.
640 g_thread_error_quark (void)
642 return g_quark_from_static_string ("g_thread_error");
645 /* Miscellaneous Structures {{{1 ------------------------------------------ */
647 typedef struct _GRealThread GRealThread;
651 /* Bit 0 protects private_data. To avoid deadlocks, do not block while
652 * holding this (particularly on the g_thread lock). */
653 volatile gint private_data_lock;
654 GArray *private_data;
657 GSystemThread system_thread;
660 #define LOCK_PRIVATE_DATA(self) g_bit_lock (&(self)->private_data_lock, 0)
661 #define UNLOCK_PRIVATE_DATA(self) g_bit_unlock (&(self)->private_data_lock, 0)
663 static void g_thread_cleanup (gpointer data);
666 * g_thread_supported:
667 * @Returns: %TRUE, if the thread system is initialized.
669 * This function returns %TRUE if the thread system is initialized, and
670 * %FALSE if it is not.
672 * <note><para>This function is actually a macro. Apart from taking the
673 * address of it you can however use it as if it was a
674 * function.</para></note>
676 /* Local Data {{{1 -------------------------------------------------------- */
678 gboolean g_threads_got_initialized = FALSE;
679 GSystemThread zero_thread; /* This is initialized to all zero */
680 GMutex g_once_mutex = G_MUTEX_INIT;
682 static GCond g_once_cond = G_COND_INIT;
683 static GPrivate g_thread_specific_private;
684 static GRealThread *g_thread_all_threads = NULL;
685 static GSList *g_thread_free_indices = NULL;
686 static GSList* g_once_init_list = NULL;
688 G_LOCK_DEFINE_STATIC (g_thread);
690 /* Initialisation {{{1 ---------------------------------------------------- */
694 * @vtable: a function table of type #GThreadFunctions, that provides
695 * the entry points to the thread system to be used. Since 2.32,
696 * this parameter is ignored and should always be %NULL
698 * If you use GLib from more than one thread, you must initialize the
699 * thread system by calling g_thread_init().
701 * Since version 2.24, calling g_thread_init() multiple times is allowed,
702 * but nothing happens except for the first call.
704 * Since version 2.32, GLib does not support custom thread implementations
705 * anymore and the @vtable parameter is ignored and you should pass %NULL.
707 * <note><para>g_thread_init() must not be called directly or indirectly
708 * in a callback from GLib. Also no mutexes may be currently locked while
709 * calling g_thread_init().</para></note>
711 * <note><para>To use g_thread_init() in your program, you have to link
712 * with the libraries that the command <command>pkg-config --libs
713 * gthread-2.0</command> outputs. This is not the case for all the
714 * other thread-related functions of GLib. Those can be used without
715 * having to link with the thread libraries.</para></note>
719 g_thread_init_glib (void)
721 static gboolean already_done;
722 GRealThread* main_thread;
729 /* We let the main thread (the one that calls g_thread_init) inherit
730 * the static_private data set before calling g_thread_init
732 main_thread = (GRealThread*) g_thread_self ();
734 /* setup the basic threading system */
735 g_threads_got_initialized = TRUE;
736 g_private_init (&g_thread_specific_private, g_thread_cleanup);
737 g_private_set (&g_thread_specific_private, main_thread);
738 g_system_thread_self (&main_thread->system_thread);
740 /* accomplish log system initialization to enable messaging */
741 _g_messages_thread_init_nomessage ();
744 /* GOnce {{{1 ------------------------------------------------------------- */
748 * @status: the status of the #GOnce
749 * @retval: the value returned by the call to the function, if @status
750 * is %G_ONCE_STATUS_READY
752 * A #GOnce struct controls a one-time initialization function. Any
753 * one-time initialization function must have its own unique #GOnce
762 * A #GOnce must be initialized with this macro before it can be used.
766 * GOnce my_once = G_ONCE_INIT;
775 * @G_ONCE_STATUS_NOTCALLED: the function has not been called yet.
776 * @G_ONCE_STATUS_PROGRESS: the function call is currently in progress.
777 * @G_ONCE_STATUS_READY: the function has been called.
779 * The possible statuses of a one-time initialization function
780 * controlled by a #GOnce struct.
787 * @once: a #GOnce structure
788 * @func: the #GThreadFunc function associated to @once. This function
789 * is called only once, regardless of the number of times it and
790 * its associated #GOnce struct are passed to g_once().
791 * @arg: data to be passed to @func
793 * The first call to this routine by a process with a given #GOnce
794 * struct calls @func with the given argument. Thereafter, subsequent
795 * calls to g_once() with the same #GOnce struct do not call @func
796 * again, but return the stored result of the first call. On return
797 * from g_once(), the status of @once will be %G_ONCE_STATUS_READY.
799 * For example, a mutex or a thread-specific data key must be created
800 * exactly once. In a threaded environment, calling g_once() ensures
801 * that the initialization is serialized across multiple threads.
803 * <note><para>Calling g_once() recursively on the same #GOnce struct in
804 * @func will lead to a deadlock.</para></note>
809 * get_debug_flags (void)
811 * static GOnce my_once = G_ONCE_INIT;
813 * g_once (&my_once, parse_debug_flags, NULL);
815 * return my_once.retval;
823 g_once_impl (GOnce *once,
827 g_mutex_lock (&g_once_mutex);
829 while (once->status == G_ONCE_STATUS_PROGRESS)
830 g_cond_wait (&g_once_cond, &g_once_mutex);
832 if (once->status != G_ONCE_STATUS_READY)
834 once->status = G_ONCE_STATUS_PROGRESS;
835 g_mutex_unlock (&g_once_mutex);
837 once->retval = func (arg);
839 g_mutex_lock (&g_once_mutex);
840 once->status = G_ONCE_STATUS_READY;
841 g_cond_broadcast (&g_once_cond);
844 g_mutex_unlock (&g_once_mutex);
851 * @value_location: location of a static initializable variable
853 * @Returns: %TRUE if the initialization section should be entered,
854 * %FALSE and blocks otherwise
856 * Function to be called when starting a critical initialization
857 * section. The argument @value_location must point to a static
858 * 0-initialized variable that will be set to a value other than 0 at
859 * the end of the initialization section. In combination with
860 * g_once_init_leave() and the unique address @value_location, it can
861 * be ensured that an initialization section will be executed only once
862 * during a program's life time, and that concurrent threads are
863 * blocked until initialization completed. To be used in constructs
868 * static gsize initialization_value = 0;
870 * if (g_once_init_enter (&initialization_value))
872 * gsize setup_value = 42; /<!-- -->* initialization code here *<!-- -->/
874 * g_once_init_leave (&initialization_value, setup_value);
877 * /<!-- -->* use initialization_value here *<!-- -->/
884 g_once_init_enter_impl (volatile gsize *value_location)
886 gboolean need_init = FALSE;
887 g_mutex_lock (&g_once_mutex);
888 if (g_atomic_pointer_get (value_location) == NULL)
890 if (!g_slist_find (g_once_init_list, (void*) value_location))
893 g_once_init_list = g_slist_prepend (g_once_init_list, (void*) value_location);
897 g_cond_wait (&g_once_cond, &g_once_mutex);
898 while (g_slist_find (g_once_init_list, (void*) value_location));
900 g_mutex_unlock (&g_once_mutex);
906 * @value_location: location of a static initializable variable
908 * @initialization_value: new non-0 value for *@value_location.
910 * Counterpart to g_once_init_enter(). Expects a location of a static
911 * 0-initialized initialization variable, and an initialization value
912 * other than 0. Sets the variable to the initialization value, and
913 * releases concurrent threads blocking in g_once_init_enter() on this
914 * initialization variable.
919 g_once_init_leave (volatile gsize *value_location,
920 gsize initialization_value)
922 g_return_if_fail (g_atomic_pointer_get (value_location) == NULL);
923 g_return_if_fail (initialization_value != 0);
924 g_return_if_fail (g_once_init_list != NULL);
926 g_atomic_pointer_set (value_location, initialization_value);
927 g_mutex_lock (&g_once_mutex);
928 g_once_init_list = g_slist_remove (g_once_init_list, (void*) value_location);
929 g_cond_broadcast (&g_once_cond);
930 g_mutex_unlock (&g_once_mutex);
933 /* GStaticPrivate {{{1 ---------------------------------------------------- */
935 typedef struct _GStaticPrivateNode GStaticPrivateNode;
936 struct _GStaticPrivateNode
939 GDestroyNotify destroy;
945 * A #GStaticPrivate works almost like a #GPrivate, but it has one
946 * significant advantage. It doesn't need to be created at run-time
947 * like a #GPrivate, but can be defined at compile-time. This is
948 * similar to the difference between #GMutex and #GStaticMutex. Now
949 * look at our <function>give_me_next_number()</function> example with
953 * <title>Using GStaticPrivate for per-thread data</title>
956 * give_me_next_number (<!-- -->)
958 * static GStaticPrivate current_number_key = G_STATIC_PRIVATE_INIT;
959 * int *current_number = g_static_private_get (&current_number_key);
961 * if (!current_number)
963 * current_number = g_new (int,1);
964 * *current_number = 0;
965 * g_static_private_set (&current_number_key, current_number, g_free);
968 * *current_number = calc_next_number (*current_number);
970 * return *current_number;
977 * G_STATIC_PRIVATE_INIT:
979 * Every #GStaticPrivate must be initialized with this macro, before it
983 * GStaticPrivate my_private = G_STATIC_PRIVATE_INIT;
988 * g_static_private_init:
989 * @private_key: a #GStaticPrivate to be initialized.
991 * Initializes @private_key. Alternatively you can initialize it with
992 * #G_STATIC_PRIVATE_INIT.
995 g_static_private_init (GStaticPrivate *private_key)
997 private_key->index = 0;
1001 * g_static_private_get:
1002 * @private_key: a #GStaticPrivate.
1003 * @Returns: the corresponding pointer.
1005 * Works like g_private_get() only for a #GStaticPrivate.
1007 * This function works even if g_thread_init() has not yet been called.
1010 g_static_private_get (GStaticPrivate *private_key)
1012 GRealThread *self = (GRealThread*) g_thread_self ();
1014 gpointer ret = NULL;
1016 LOCK_PRIVATE_DATA (self);
1018 array = self->private_data;
1020 if (array && private_key->index != 0 && private_key->index <= array->len)
1021 ret = g_array_index (array, GStaticPrivateNode,
1022 private_key->index - 1).data;
1024 UNLOCK_PRIVATE_DATA (self);
1029 * g_static_private_set:
1030 * @private_key: a #GStaticPrivate.
1031 * @data: the new pointer.
1032 * @notify: a function to be called with the pointer whenever the
1033 * current thread ends or sets this pointer again.
1035 * Sets the pointer keyed to @private_key for the current thread and
1036 * the function @notify to be called with that pointer (%NULL or
1037 * non-%NULL), whenever the pointer is set again or whenever the
1038 * current thread ends.
1040 * This function works even if g_thread_init() has not yet been called.
1041 * If g_thread_init() is called later, the @data keyed to @private_key
1042 * will be inherited only by the main thread, i.e. the one that called
1045 * <note><para>@notify is used quite differently from @destructor in
1046 * g_private_new().</para></note>
1049 g_static_private_set (GStaticPrivate *private_key,
1051 GDestroyNotify notify)
1053 GRealThread *self = (GRealThread*) g_thread_self ();
1055 static guint next_index = 0;
1056 GStaticPrivateNode *node;
1057 gpointer ddata = NULL;
1058 GDestroyNotify ddestroy = NULL;
1060 if (!private_key->index)
1064 if (!private_key->index)
1066 if (g_thread_free_indices)
1068 private_key->index =
1069 GPOINTER_TO_UINT (g_thread_free_indices->data);
1070 g_thread_free_indices =
1071 g_slist_delete_link (g_thread_free_indices,
1072 g_thread_free_indices);
1075 private_key->index = ++next_index;
1078 G_UNLOCK (g_thread);
1081 LOCK_PRIVATE_DATA (self);
1083 array = self->private_data;
1086 array = g_array_new (FALSE, TRUE, sizeof (GStaticPrivateNode));
1087 self->private_data = array;
1090 if (private_key->index > array->len)
1091 g_array_set_size (array, private_key->index);
1093 node = &g_array_index (array, GStaticPrivateNode, private_key->index - 1);
1096 ddestroy = node->destroy;
1099 node->destroy = notify;
1101 UNLOCK_PRIVATE_DATA (self);
1108 * g_static_private_free:
1109 * @private_key: a #GStaticPrivate to be freed.
1111 * Releases all resources allocated to @private_key.
1113 * You don't have to call this functions for a #GStaticPrivate with an
1114 * unbounded lifetime, i.e. objects declared 'static', but if you have
1115 * a #GStaticPrivate as a member of a structure and the structure is
1116 * freed, you should also free the #GStaticPrivate.
1119 g_static_private_free (GStaticPrivate *private_key)
1121 guint idx = private_key->index;
1122 GRealThread *thread, *next;
1123 GArray *garbage = NULL;
1128 private_key->index = 0;
1132 thread = g_thread_all_threads;
1134 for (thread = g_thread_all_threads; thread; thread = next)
1138 next = thread->next;
1140 LOCK_PRIVATE_DATA (thread);
1142 array = thread->private_data;
1144 if (array && idx <= array->len)
1146 GStaticPrivateNode *node = &g_array_index (array,
1149 gpointer ddata = node->data;
1150 GDestroyNotify ddestroy = node->destroy;
1153 node->destroy = NULL;
1157 /* defer non-trivial destruction til after we've finished
1158 * iterating, since we must continue to hold the lock */
1159 if (garbage == NULL)
1160 garbage = g_array_new (FALSE, TRUE,
1161 sizeof (GStaticPrivateNode));
1163 g_array_set_size (garbage, garbage->len + 1);
1165 node = &g_array_index (garbage, GStaticPrivateNode,
1168 node->destroy = ddestroy;
1172 UNLOCK_PRIVATE_DATA (thread);
1174 g_thread_free_indices = g_slist_prepend (g_thread_free_indices,
1175 GUINT_TO_POINTER (idx));
1176 G_UNLOCK (g_thread);
1182 for (i = 0; i < garbage->len; i++)
1184 GStaticPrivateNode *node;
1186 node = &g_array_index (garbage, GStaticPrivateNode, i);
1187 node->destroy (node->data);
1190 g_array_free (garbage, TRUE);
1194 /* GThread Extra Functions {{{1 ------------------------------------------- */
1196 g_thread_cleanup (gpointer data)
1200 GRealThread* thread = data;
1203 LOCK_PRIVATE_DATA (thread);
1204 array = thread->private_data;
1205 thread->private_data = NULL;
1206 UNLOCK_PRIVATE_DATA (thread);
1212 for (i = 0; i < array->len; i++ )
1214 GStaticPrivateNode *node =
1215 &g_array_index (array, GStaticPrivateNode, i);
1217 node->destroy (node->data);
1219 g_array_free (array, TRUE);
1222 /* We only free the thread structure, if it isn't joinable. If
1223 it is, the structure is freed in g_thread_join */
1224 if (!thread->thread.joinable)
1229 for (t = g_thread_all_threads, p = NULL; t; p = t, t = t->next)
1236 g_thread_all_threads = t->next;
1240 G_UNLOCK (g_thread);
1242 /* Just to make sure, this isn't used any more */
1243 g_system_thread_assign (thread->system_thread, zero_thread);
1250 g_thread_create_proxy (gpointer data)
1252 GRealThread* thread = data;
1256 /* This has to happen before G_LOCK, as that might call g_thread_self */
1257 g_private_set (&g_thread_specific_private, data);
1259 /* the lock makes sure, that thread->system_thread is written,
1260 * before thread->thread.func is called. See g_thread_create.
1263 G_UNLOCK (g_thread);
1265 thread->retval = thread->thread.func (thread->thread.data);
1272 * @func: a function to execute in the new thread
1273 * @data: an argument to supply to the new thread
1274 * @joinable: should this thread be joinable?
1275 * @error: return location for error, or %NULL
1277 * This function creates a new thread.
1279 * If @joinable is %TRUE, you can wait for this threads termination
1280 * calling g_thread_join(). Otherwise the thread will just disappear
1281 * when it terminates.
1283 * The new thread executes the function @func with the argument @data.
1284 * If the thread was created successfully, it is returned.
1286 * @error can be %NULL to ignore errors, or non-%NULL to report errors.
1287 * The error is set, if and only if the function returns %NULL.
1289 * Returns: the new #GThread on success
1292 g_thread_create (GThreadFunc func,
1297 return g_thread_create_with_stack_size (func, data, joinable, 0, error);
1301 * g_thread_create_with_stack_size:
1302 * @func: a function to execute in the new thread.
1303 * @data: an argument to supply to the new thread.
1304 * @joinable: should this thread be joinable?
1305 * @stack_size: a stack size for the new thread.
1306 * @error: return location for error.
1307 * @Returns: the new #GThread on success.
1309 * This function creates a new thread. If the underlying thread
1310 * implementation supports it, the thread gets a stack size of
1311 * @stack_size or the default value for the current platform, if
1314 * If @joinable is %TRUE, you can wait for this threads termination
1315 * calling g_thread_join(). Otherwise the thread will just disappear
1316 * when it terminates.
1318 * The new thread executes the function @func with the argument @data.
1319 * If the thread was created successfully, it is returned.
1321 * @error can be %NULL to ignore errors, or non-%NULL to report errors.
1322 * The error is set, if and only if the function returns %NULL.
1325 * Only use g_thread_create_with_stack_size() if you really can't use
1326 * g_thread_create() instead. g_thread_create() does not take
1327 * @stack_size, as it should only be used in cases in which it is
1332 g_thread_create_with_stack_size (GThreadFunc func,
1338 GRealThread* result;
1339 GError *local_error = NULL;
1340 g_return_val_if_fail (func, NULL);
1342 result = g_new0 (GRealThread, 1);
1344 result->thread.joinable = joinable;
1345 result->thread.func = func;
1346 result->thread.data = data;
1347 result->private_data = NULL;
1349 g_system_thread_create (g_thread_create_proxy, result,
1350 stack_size, joinable,
1351 &result->system_thread, &local_error);
1354 result->next = g_thread_all_threads;
1355 g_thread_all_threads = result;
1357 G_UNLOCK (g_thread);
1361 g_propagate_error (error, local_error);
1366 return (GThread*) result;
1371 * @retval: the return value of this thread.
1373 * Exits the current thread. If another thread is waiting for that
1374 * thread using g_thread_join() and the current thread is joinable, the
1375 * waiting thread will be woken up and get @retval as the return value
1376 * of g_thread_join(). If the current thread is not joinable, @retval
1377 * is ignored. Calling
1380 * g_thread_exit (retval);
1383 * is equivalent to returning @retval from the function @func, as given
1384 * to g_thread_create().
1386 * <note><para>Never call g_thread_exit() from within a thread of a
1387 * #GThreadPool, as that will mess up the bookkeeping and lead to funny
1388 * and unwanted results.</para></note>
1391 g_thread_exit (gpointer retval)
1393 GRealThread* real = (GRealThread*) g_thread_self ();
1394 real->retval = retval;
1396 g_system_thread_exit ();
1401 * @thread: a #GThread to be waited for.
1402 * @Returns: the return value of the thread.
1404 * Waits until @thread finishes, i.e. the function @func, as given to
1405 * g_thread_create(), returns or g_thread_exit() is called by @thread.
1406 * All resources of @thread including the #GThread struct are released.
1407 * @thread must have been created with @joinable=%TRUE in
1408 * g_thread_create(). The value returned by @func or given to
1409 * g_thread_exit() by @thread is returned by this function.
1412 g_thread_join (GThread* thread)
1414 GRealThread* real = (GRealThread*) thread;
1418 g_return_val_if_fail (thread, NULL);
1419 g_return_val_if_fail (thread->joinable, NULL);
1420 g_return_val_if_fail (!g_system_thread_equal (&real->system_thread, &zero_thread), NULL);
1422 g_system_thread_join (&real->system_thread);
1424 retval = real->retval;
1427 for (t = g_thread_all_threads, p = NULL; t; p = t, t = t->next)
1429 if (t == (GRealThread*) thread)
1434 g_thread_all_threads = t->next;
1438 G_UNLOCK (g_thread);
1440 /* Just to make sure, this isn't used any more */
1441 thread->joinable = 0;
1442 g_system_thread_assign (real->system_thread, zero_thread);
1444 /* the thread structure for non-joinable threads is freed upon
1445 * thread end. We free the memory here. This will leave a loose end,
1446 * if a joinable thread is not joined.
1455 * @Returns: the current thread.
1457 * This functions returns the #GThread corresponding to the calling
1461 g_thread_self (void)
1463 GRealThread* thread = g_private_get (&g_thread_specific_private);
1467 /* If no thread data is available, provide and set one. This
1468 can happen for the main thread and for threads, that are not
1470 thread = g_new0 (GRealThread, 1);
1471 thread->thread.joinable = FALSE; /* This is a save guess */
1472 thread->thread.func = NULL;
1473 thread->thread.data = NULL;
1474 thread->private_data = NULL;
1476 g_system_thread_self (&thread->system_thread);
1478 g_private_set (&g_thread_specific_private, thread);
1481 thread->next = g_thread_all_threads;
1482 g_thread_all_threads = thread;
1483 G_UNLOCK (g_thread);
1486 return (GThread*)thread;
1489 /* Unsorted {{{1 ---------------------------------------------------------- */
1493 * @thread_func: function to call for all GThread structures
1494 * @user_data: second argument to @thread_func
1496 * Call @thread_func on all existing #GThread structures. Note that
1497 * threads may decide to exit while @thread_func is running, so
1498 * without intimate knowledge about the lifetime of foreign threads,
1499 * @thread_func shouldn't access the GThread* pointer passed in as
1500 * first argument. However, @thread_func will not be called for threads
1501 * which are known to have exited already.
1503 * Due to thread lifetime checks, this function has an execution complexity
1504 * which is quadratic in the number of existing threads.
1509 g_thread_foreach (GFunc thread_func,
1512 GSList *slist = NULL;
1513 GRealThread *thread;
1514 g_return_if_fail (thread_func != NULL);
1515 /* snapshot the list of threads for iteration */
1517 for (thread = g_thread_all_threads; thread; thread = thread->next)
1518 slist = g_slist_prepend (slist, thread);
1519 G_UNLOCK (g_thread);
1520 /* walk the list, skipping non-existent threads */
1523 GSList *node = slist;
1525 /* check whether the current thread still exists */
1527 for (thread = g_thread_all_threads; thread; thread = thread->next)
1528 if (thread == node->data)
1530 G_UNLOCK (g_thread);
1532 thread_func (thread, user_data);
1533 g_slist_free_1 (node);
1538 * g_thread_get_initialized:
1540 * Indicates if g_thread_init() has been called.
1542 * Returns: %TRUE if threads have been initialized.
1547 g_thread_get_initialized ()
1549 return g_thread_supported ();
1555 * Allocated and initializes a new #GMutex.
1557 * Returns: a newly allocated #GMutex. Use g_mutex_free() to free
1564 mutex = g_slice_new (GMutex);
1565 g_mutex_init (mutex);
1574 * Destroys a @mutex that has been created with g_mutex_new().
1576 * Calling g_mutex_free() on a locked mutex may result
1577 * in undefined behaviour.
1580 g_mutex_free (GMutex *mutex)
1582 g_mutex_clear (mutex);
1583 g_slice_free (GMutex, mutex);
1589 * Allocates and initializes a new #GCond.
1591 * Returns: a newly allocated #GCond. Free with g_cond_free()
1598 cond = g_slice_new (GCond);
1608 * Destroys a #GCond that has been created with g_cond_new().
1611 g_cond_free (GCond *cond)
1613 g_cond_clear (cond);
1614 g_slice_free (GCond, cond);
1619 * @destructor: a function to destroy the data keyed to
1620 * the #GPrivate when a thread ends
1622 * Creates a new #GPrivate. If @destructor is non-%NULL, it is a
1623 * pointer to a destructor function. Whenever a thread ends and the
1624 * corresponding pointer keyed to this instance of #GPrivate is
1625 * non-%NULL, the destructor is called with this pointer as the
1629 * #GStaticPrivate is a better choice for most uses.
1632 * <note><para>@destructor is used quite differently from @notify in
1633 * g_static_private_set().</para></note>
1635 * <note><para>A #GPrivate cannot be freed. Reuse it instead, if you
1636 * can, to avoid shortage, or use #GStaticPrivate.</para></note>
1638 * <note><para>This function will abort if g_thread_init() has not been
1639 * called yet.</para></note>
1641 * Returns: a newly allocated #GPrivate
1644 g_private_new (GDestroyNotify notify)
1648 key = g_slice_new (GPrivate);
1649 g_private_init (key, notify);
1654 /* vim: set foldmethod=marker: */