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().
96 * You may call any other glib functions in the main thread before
97 * g_thread_init() as long as g_thread_init() is not called from
98 * a GLib callback, or with any locks held. However, many libraries
99 * above GLib does not support late initialization of threads, so
100 * doing this should be avoided if possible.
102 * Please note that since version 2.24 the GObject initialization
103 * function g_type_init() initializes threads. Since 2.32, creating
104 * a mainloop will do so too. As a consequence, most applications,
105 * including those using GTK+ will run with threads enabled.
107 * After calling g_thread_init(), GLib is completely thread safe
108 * (all global data is automatically locked), but individual data
109 * structure instances are not automatically locked for performance
110 * reasons. So, for example you must coordinate accesses to the same
111 * #GHashTable from multiple threads. The two notable exceptions from
112 * this rule are #GMainLoop and #GAsyncQueue, which <emphasis>are</emphasis>
113 * threadsafe and need no further application-level locking to be
114 * accessed from multiple threads.
118 * G_THREADS_IMPL_POSIX:
120 * This macro is defined if POSIX style threads are used.
124 * G_THREADS_IMPL_WIN32:
126 * This macro is defined if Windows style threads are used.
129 /* G_LOCK Documentation {{{1 ---------------------------------------------- */
133 * @name: the name of the lock.
135 * The %G_LOCK_* macros provide a convenient interface to #GStaticMutex
136 * with the advantage that they will expand to nothing in programs
137 * compiled against a thread-disabled GLib, saving code and memory
138 * there. #G_LOCK_DEFINE defines a lock. It can appear anywhere
139 * variable definitions may appear in programs, i.e. in the first block
140 * of a function or outside of functions. The @name parameter will be
141 * mangled to get the name of the #GStaticMutex. This means that you
142 * can use names of existing variables as the parameter - e.g. the name
143 * of the variable you intent to protect with the lock. Look at our
144 * <function>give_me_next_number()</function> example using the
148 * <title>Using the %G_LOCK_* convenience macros</title>
150 * G_LOCK_DEFINE (current_number);
153 * give_me_next_number (void)
155 * static int current_number = 0;
158 * G_LOCK (current_number);
159 * ret_val = current_number = calc_next_number (current_number);
160 * G_UNLOCK (current_number);
169 * G_LOCK_DEFINE_STATIC:
170 * @name: the name of the lock.
172 * This works like #G_LOCK_DEFINE, but it creates a static object.
177 * @name: the name of the lock.
179 * This declares a lock, that is defined with #G_LOCK_DEFINE in another
185 * @name: the name of the lock.
187 * Works like g_mutex_lock(), but for a lock defined with
193 * @name: the name of the lock.
194 * @Returns: %TRUE, if the lock could be locked.
196 * Works like g_mutex_trylock(), but for a lock defined with
202 * @name: the name of the lock.
204 * Works like g_mutex_unlock(), but for a lock defined with
208 /* GMutex Documentation {{{1 ------------------------------------------ */
213 * The #GMutex struct is an opaque data structure to represent a mutex
214 * (mutual exclusion). It can be used to protect data against shared
215 * access. Take for example the following function:
218 * <title>A function which will not work in a threaded environment</title>
221 * give_me_next_number (void)
223 * static int current_number = 0;
225 * /<!-- -->* now do a very complicated calculation to calculate the new
226 * * number, this might for example be a random number generator
228 * current_number = calc_next_number (current_number);
230 * return current_number;
235 * It is easy to see that this won't work in a multi-threaded
236 * application. There current_number must be protected against shared
237 * access. A first naive implementation would be:
240 * <title>The wrong way to write a thread-safe function</title>
243 * give_me_next_number (void)
245 * static int current_number = 0;
247 * static GMutex * mutex = NULL;
249 * if (!mutex) mutex = g_mutex_new (<!-- -->);
251 * g_mutex_lock (mutex);
252 * ret_val = current_number = calc_next_number (current_number);
253 * g_mutex_unlock (mutex);
260 * This looks like it would work, but there is a race condition while
261 * constructing the mutex and this code cannot work reliable. Please do
262 * not use such constructs in your own programs! One working solution
266 * <title>A correct thread-safe function</title>
268 * static GMutex *give_me_next_number_mutex = NULL;
270 * /<!-- -->* this function must be called before any call to
271 * * give_me_next_number(<!-- -->)
273 * * it must be called exactly once.
276 * init_give_me_next_number (void)
278 * g_assert (give_me_next_number_mutex == NULL);
279 * give_me_next_number_mutex = g_mutex_new (<!-- -->);
283 * give_me_next_number (void)
285 * static int current_number = 0;
288 * g_mutex_lock (give_me_next_number_mutex);
289 * ret_val = current_number = calc_next_number (current_number);
290 * g_mutex_unlock (give_me_next_number_mutex);
297 * A statically initialized #GMutex provides an even simpler and safer
301 * <title>Using a statically allocated mutex</title>
304 * give_me_next_number (void)
306 * static GMutex mutex = G_MUTEX_INIT;
307 * static int current_number = 0;
310 * g_mutex_lock (&mutex);
311 * ret_val = current_number = calc_next_number (current_number);
312 * g_mutex_unlock (&mutex);
319 * A #GMutex should only be accessed via <function>g_mutex_</function>
326 * Initializer for statically allocated #GMutexes.
327 * Alternatively, g_mutex_init() can be used.
330 * GMutex mutex = G_MUTEX_INIT;
336 /* GRecMutex Documentation {{{1 -------------------------------------- */
341 * The GRecMutex struct is an opaque data structure to represent a
342 * recursive mutex. It is similar to a #GMutex with the difference
343 * that it is possible to lock a GRecMutex multiple times in the same
344 * thread without deadlock. When doing so, care has to be taken to
345 * unlock the recursive mutex as often as it has been locked.
347 * A GRecMutex should only be accessed with the
348 * <function>g_rec_mutex_</function> functions. Before a GRecMutex
349 * can be used, it has to be initialized with #G_REC_MUTEX_INIT or
350 * g_rec_mutex_init().
358 * Initializer for statically allocated #GRecMutexes.
359 * Alternatively, g_rec_mutex_init() can be used.
362 * GRecMutex mutex = G_REC_MUTEX_INIT;
368 /* GRWLock Documentation {{{1 ---------------------------------------- */
373 * The GRWLock struct is an opaque data structure to represent a
374 * reader-writer lock. It is similar to a #GMutex in that it allows
375 * multiple threads to coordinate access to a shared resource.
377 * The difference to a mutex is that a reader-writer lock discriminates
378 * between read-only ('reader') and full ('writer') access. While only
379 * one thread at a time is allowed write access (by holding the 'writer'
380 * lock via g_rw_lock_writer_lock()), multiple threads can gain
381 * simultaneous read-only access (by holding the 'reader' lock via
382 * g_rw_lock_reader_lock()).
385 * <title>An array with access functions</title>
387 * GRWLock lock = G_RW_LOCK_INIT;
391 * my_array_get (guint index)
393 * gpointer retval = NULL;
398 * g_rw_lock_reader_lock (&lock);
399 * if (index < array->len)
400 * retval = g_ptr_array_index (array, index);
401 * g_rw_lock_reader_unlock (&lock);
407 * my_array_set (guint index, gpointer data)
409 * g_rw_lock_writer_lock (&lock);
412 * array = g_ptr_array_new (<!-- -->);
414 * if (index >= array->len)
415 * g_ptr_array_set_size (array, index+1);
416 * g_ptr_array_index (array, index) = data;
418 * g_rw_lock_writer_unlock (&lock);
422 * This example shows an array which can be accessed by many readers
423 * (the <function>my_array_get()</function> function) simultaneously,
424 * whereas the writers (the <function>my_array_set()</function>
425 * function) will only be allowed once at a time and only if no readers
426 * currently access the array. This is because of the potentially
427 * dangerous resizing of the array. Using these functions is fully
428 * multi-thread safe now.
432 * A GRWLock should only be accessed with the
433 * <function>g_rw_lock_</function> functions. Before it can be used,
434 * it has to be initialized with #G_RW_LOCK_INIT or g_rw_lock_init().
442 * Initializer for statically allocated #GRWLocks.
443 * Alternatively, g_rw_lock_init_init() can be used.
446 * GRWLock lock = G_RW_LOCK_INIT;
452 /* GCond Documentation {{{1 ------------------------------------------ */
457 * The #GCond struct is an opaque data structure that represents a
458 * condition. Threads can block on a #GCond if they find a certain
459 * condition to be false. If other threads change the state of this
460 * condition they signal the #GCond, and that causes the waiting
461 * threads to be woken up.
465 * Using GCond to block a thread until a condition is satisfied
468 * GCond* data_cond = NULL; /<!-- -->* Must be initialized somewhere *<!-- -->/
469 * GMutex* data_mutex = NULL; /<!-- -->* Must be initialized somewhere *<!-- -->/
470 * gpointer current_data = NULL;
473 * push_data (gpointer data)
475 * g_mutex_lock (data_mutex);
476 * current_data = data;
477 * g_cond_signal (data_cond);
478 * g_mutex_unlock (data_mutex);
486 * g_mutex_lock (data_mutex);
487 * while (!current_data)
488 * g_cond_wait (data_cond, data_mutex);
489 * data = current_data;
490 * current_data = NULL;
491 * g_mutex_unlock (data_mutex);
498 * Whenever a thread calls pop_data() now, it will wait until
499 * current_data is non-%NULL, i.e. until some other thread
500 * has called push_data().
502 * <note><para>It is important to use the g_cond_wait() and
503 * g_cond_timed_wait() functions only inside a loop which checks for the
504 * condition to be true. It is not guaranteed that the waiting thread
505 * will find the condition fulfilled after it wakes up, even if the
506 * signaling thread left the condition in that state: another thread may
507 * have altered the condition before the waiting thread got the chance
508 * to be woken up, even if the condition itself is protected by a
509 * #GMutex, like above.</para></note>
511 * A #GCond should only be accessed via the <function>g_cond_</function>
518 * Initializer for statically allocated #GConds.
519 * Alternatively, g_cond_init() can be used.
522 * GCond cond = G_COND_INIT;
528 /* GPrivate Documentation {{{1 --------------------------------------- */
534 * #GStaticPrivate is a better choice for most uses.
537 * The #GPrivate struct is an opaque data structure to represent a
538 * thread private data key. Threads can thereby obtain and set a
539 * pointer which is private to the current thread. Take our
540 * <function>give_me_next_number(<!-- -->)</function> example from
541 * above. Suppose we don't want <literal>current_number</literal> to be
542 * shared between the threads, but instead to be private to each thread.
543 * This can be done as follows:
546 * <title>Using GPrivate for per-thread data</title>
548 * GPrivate* current_number_key = NULL; /<!-- -->* Must be initialized somewhere
549 * with g_private_new (g_free); *<!-- -->/
552 * give_me_next_number (void)
554 * int *current_number = g_private_get (current_number_key);
556 * if (!current_number)
558 * current_number = g_new (int, 1);
559 * *current_number = 0;
560 * g_private_set (current_number_key, current_number);
563 * *current_number = calc_next_number (*current_number);
565 * return *current_number;
570 * Here the pointer belonging to the key
571 * <literal>current_number_key</literal> is read. If it is %NULL, it has
572 * not been set yet. Then get memory for an integer value, assign this
573 * memory to the pointer and write the pointer back. Now we have an
574 * integer value that is private to the current thread.
576 * The #GPrivate struct should only be accessed via the
577 * <function>g_private_</function> functions.
580 /* GThread Documentation {{{1 ---------------------------------------- */
585 * The #GThread struct represents a running thread.
587 * Resources for a joinable thread are not fully released
588 * until g_thread_join() is called for that thread.
593 * @data: data passed to the thread
594 * @Returns: the return value of the thread, which will be returned by
597 * Specifies the type of the @func functions passed to
598 * g_thread_create() or g_thread_create_full().
602 * g_thread_supported:
604 * This macro returns %TRUE if the thread system is initialized,
605 * and %FALSE if it is not.
607 * For language bindings, g_thread_get_initialized() provides
608 * the same functionality as a function.
610 * Returns: %TRUE, if the thread system is initialized
613 /* GThreadError {{{1 ------------------------------------------------------- */
616 * @G_THREAD_ERROR_AGAIN: a thread couldn't be created due to resource
617 * shortage. Try again later.
619 * Possible errors of thread related functions.
625 * The error domain of the GLib thread subsystem.
628 g_thread_error_quark (void)
630 return g_quark_from_static_string ("g_thread_error");
633 /* Miscellaneous Structures {{{1 ------------------------------------------ */
635 typedef struct _GRealThread GRealThread;
639 /* Bit 0 protects private_data. To avoid deadlocks,
640 * do not block while holding this (particularly on
641 * the g_thread lock).
643 volatile gint private_data_lock;
644 GArray *private_data;
647 GSystemThread system_thread;
650 #define LOCK_PRIVATE_DATA(self) g_bit_lock (&(self)->private_data_lock, 0)
651 #define UNLOCK_PRIVATE_DATA(self) g_bit_unlock (&(self)->private_data_lock, 0)
653 /* Local Data {{{1 -------------------------------------------------------- */
655 gboolean g_threads_got_initialized = FALSE;
656 GSystemThread zero_thread; /* This is initialized to all zero */
657 GMutex g_once_mutex = G_MUTEX_INIT;
659 static GCond g_once_cond = G_COND_INIT;
660 static GPrivate g_thread_specific_private;
661 static GRealThread *g_thread_all_threads = NULL;
662 static GSList *g_thread_free_indices = NULL;
663 static GSList* g_once_init_list = NULL;
665 G_LOCK_DEFINE_STATIC (g_thread);
667 /* Initialisation {{{1 ---------------------------------------------------- */
671 * @vtable: a function table of type #GThreadFunctions, that provides
672 * the entry points to the thread system to be used. Since 2.32,
673 * this parameter is ignored and should always be %NULL
675 * If you use GLib from more than one thread, you must initialize the
676 * thread system by calling g_thread_init().
678 * Since version 2.24, calling g_thread_init() multiple times is allowed,
679 * but nothing happens except for the first call.
681 * Since version 2.32, GLib does not support custom thread implementations
682 * anymore and the @vtable parameter is ignored and you should pass %NULL.
684 * <note><para>g_thread_init() must not be called directly or indirectly
685 * in a callback from GLib. Also no mutexes may be currently locked while
686 * calling g_thread_init().</para></note>
688 * <note><para>To use g_thread_init() in your program, you have to link
689 * with the libraries that the command <command>pkg-config --libs
690 * gthread-2.0</command> outputs. This is not the case for all the
691 * other thread-related functions of GLib. Those can be used without
692 * having to link with the thread libraries.</para></note>
695 static void g_thread_cleanup (gpointer data);
698 g_thread_init_glib (void)
700 static gboolean already_done;
701 GRealThread* main_thread;
708 /* We let the main thread (the one that calls g_thread_init) inherit
709 * the static_private data set before calling g_thread_init
711 main_thread = (GRealThread*) g_thread_self ();
713 /* setup the basic threading system */
714 g_threads_got_initialized = TRUE;
715 g_private_init (&g_thread_specific_private, g_thread_cleanup);
716 g_private_set (&g_thread_specific_private, main_thread);
717 g_system_thread_self (&main_thread->system_thread);
719 /* accomplish log system initialization to enable messaging */
720 _g_messages_thread_init_nomessage ();
723 /* GOnce {{{1 ------------------------------------------------------------- */
727 * @status: the status of the #GOnce
728 * @retval: the value returned by the call to the function, if @status
729 * is %G_ONCE_STATUS_READY
731 * A #GOnce struct controls a one-time initialization function. Any
732 * one-time initialization function must have its own unique #GOnce
741 * A #GOnce must be initialized with this macro before it can be used.
744 * GOnce my_once = G_ONCE_INIT;
752 * @G_ONCE_STATUS_NOTCALLED: the function has not been called yet.
753 * @G_ONCE_STATUS_PROGRESS: the function call is currently in progress.
754 * @G_ONCE_STATUS_READY: the function has been called.
756 * The possible statuses of a one-time initialization function
757 * controlled by a #GOnce struct.
764 * @once: a #GOnce structure
765 * @func: the #GThreadFunc function associated to @once. This function
766 * is called only once, regardless of the number of times it and
767 * its associated #GOnce struct are passed to g_once().
768 * @arg: data to be passed to @func
770 * The first call to this routine by a process with a given #GOnce
771 * struct calls @func with the given argument. Thereafter, subsequent
772 * calls to g_once() with the same #GOnce struct do not call @func
773 * again, but return the stored result of the first call. On return
774 * from g_once(), the status of @once will be %G_ONCE_STATUS_READY.
776 * For example, a mutex or a thread-specific data key must be created
777 * exactly once. In a threaded environment, calling g_once() ensures
778 * that the initialization is serialized across multiple threads.
780 * Calling g_once() recursively on the same #GOnce struct in
781 * @func will lead to a deadlock.
785 * get_debug_flags (void)
787 * static GOnce my_once = G_ONCE_INIT;
789 * g_once (&my_once, parse_debug_flags, NULL);
791 * return my_once.retval;
798 g_once_impl (GOnce *once,
802 g_mutex_lock (&g_once_mutex);
804 while (once->status == G_ONCE_STATUS_PROGRESS)
805 g_cond_wait (&g_once_cond, &g_once_mutex);
807 if (once->status != G_ONCE_STATUS_READY)
809 once->status = G_ONCE_STATUS_PROGRESS;
810 g_mutex_unlock (&g_once_mutex);
812 once->retval = func (arg);
814 g_mutex_lock (&g_once_mutex);
815 once->status = G_ONCE_STATUS_READY;
816 g_cond_broadcast (&g_once_cond);
819 g_mutex_unlock (&g_once_mutex);
826 * @value_location: location of a static initializable variable
829 * Function to be called when starting a critical initialization
830 * section. The argument @value_location must point to a static
831 * 0-initialized variable that will be set to a value other than 0 at
832 * the end of the initialization section. In combination with
833 * g_once_init_leave() and the unique address @value_location, it can
834 * be ensured that an initialization section will be executed only once
835 * during a program's life time, and that concurrent threads are
836 * blocked until initialization completed. To be used in constructs
840 * static gsize initialization_value = 0;
842 * if (g_once_init_enter (&initialization_value))
844 * gsize setup_value = 42; /** initialization code here **/
846 * g_once_init_leave (&initialization_value, setup_value);
849 * /** use initialization_value here **/
852 * Returns: %TRUE if the initialization section should be entered,
853 * %FALSE and blocks otherwise
858 g_once_init_enter_impl (volatile gsize *value_location)
860 gboolean need_init = FALSE;
861 g_mutex_lock (&g_once_mutex);
862 if (g_atomic_pointer_get (value_location) == NULL)
864 if (!g_slist_find (g_once_init_list, (void*) value_location))
867 g_once_init_list = g_slist_prepend (g_once_init_list, (void*) value_location);
871 g_cond_wait (&g_once_cond, &g_once_mutex);
872 while (g_slist_find (g_once_init_list, (void*) value_location));
874 g_mutex_unlock (&g_once_mutex);
880 * @value_location: location of a static initializable variable
882 * @initialization_value: new non-0 value for *@value_location
884 * Counterpart to g_once_init_enter(). Expects a location of a static
885 * 0-initialized initialization variable, and an initialization value
886 * other than 0. Sets the variable to the initialization value, and
887 * releases concurrent threads blocking in g_once_init_enter() on this
888 * initialization variable.
893 g_once_init_leave (volatile gsize *value_location,
894 gsize initialization_value)
896 g_return_if_fail (g_atomic_pointer_get (value_location) == NULL);
897 g_return_if_fail (initialization_value != 0);
898 g_return_if_fail (g_once_init_list != NULL);
900 g_atomic_pointer_set (value_location, initialization_value);
901 g_mutex_lock (&g_once_mutex);
902 g_once_init_list = g_slist_remove (g_once_init_list, (void*) value_location);
903 g_cond_broadcast (&g_once_cond);
904 g_mutex_unlock (&g_once_mutex);
907 /* GStaticPrivate {{{1 ---------------------------------------------------- */
909 typedef struct _GStaticPrivateNode GStaticPrivateNode;
910 struct _GStaticPrivateNode
913 GDestroyNotify destroy;
919 * A #GStaticPrivate works almost like a #GPrivate, but it has one
920 * significant advantage. It doesn't need to be created at run-time
921 * like a #GPrivate, but can be defined at compile-time. This is
922 * similar to the difference between #GMutex and #GStaticMutex. Now
923 * look at our <function>give_me_next_number()</function> example with
927 * <title>Using GStaticPrivate for per-thread data</title>
930 * give_me_next_number (<!-- -->)
932 * static GStaticPrivate current_number_key = G_STATIC_PRIVATE_INIT;
933 * int *current_number = g_static_private_get (&current_number_key);
935 * if (!current_number)
937 * current_number = g_new (int,1);
938 * *current_number = 0;
939 * g_static_private_set (&current_number_key, current_number, g_free);
942 * *current_number = calc_next_number (*current_number);
944 * return *current_number;
951 * G_STATIC_PRIVATE_INIT:
953 * Every #GStaticPrivate must be initialized with this macro, before it
957 * GStaticPrivate my_private = G_STATIC_PRIVATE_INIT;
962 * g_static_private_init:
963 * @private_key: a #GStaticPrivate to be initialized
965 * Initializes @private_key. Alternatively you can initialize it with
966 * #G_STATIC_PRIVATE_INIT.
969 g_static_private_init (GStaticPrivate *private_key)
971 private_key->index = 0;
975 * g_static_private_get:
976 * @private_key: a #GStaticPrivate
978 * Works like g_private_get() only for a #GStaticPrivate.
980 * This function works even if g_thread_init() has not yet been called.
982 * Returns: the corresponding pointer
985 g_static_private_get (GStaticPrivate *private_key)
987 GRealThread *self = (GRealThread*) g_thread_self ();
991 LOCK_PRIVATE_DATA (self);
993 array = self->private_data;
995 if (array && private_key->index != 0 && private_key->index <= array->len)
996 ret = g_array_index (array, GStaticPrivateNode,
997 private_key->index - 1).data;
999 UNLOCK_PRIVATE_DATA (self);
1004 * g_static_private_set:
1005 * @private_key: a #GStaticPrivate
1006 * @data: the new pointer
1007 * @notify: a function to be called with the pointer whenever the
1008 * current thread ends or sets this pointer again
1010 * Sets the pointer keyed to @private_key for the current thread and
1011 * the function @notify to be called with that pointer (%NULL or
1012 * non-%NULL), whenever the pointer is set again or whenever the
1013 * current thread ends.
1015 * This function works even if g_thread_init() has not yet been called.
1016 * If g_thread_init() is called later, the @data keyed to @private_key
1017 * will be inherited only by the main thread, i.e. the one that called
1020 * <note><para>@notify is used quite differently from @destructor in
1021 * g_private_new().</para></note>
1024 g_static_private_set (GStaticPrivate *private_key,
1026 GDestroyNotify notify)
1028 GRealThread *self = (GRealThread*) g_thread_self ();
1030 static guint next_index = 0;
1031 GStaticPrivateNode *node;
1032 gpointer ddata = NULL;
1033 GDestroyNotify ddestroy = NULL;
1035 if (!private_key->index)
1039 if (!private_key->index)
1041 if (g_thread_free_indices)
1043 private_key->index =
1044 GPOINTER_TO_UINT (g_thread_free_indices->data);
1045 g_thread_free_indices =
1046 g_slist_delete_link (g_thread_free_indices,
1047 g_thread_free_indices);
1050 private_key->index = ++next_index;
1053 G_UNLOCK (g_thread);
1056 LOCK_PRIVATE_DATA (self);
1058 array = self->private_data;
1061 array = g_array_new (FALSE, TRUE, sizeof (GStaticPrivateNode));
1062 self->private_data = array;
1065 if (private_key->index > array->len)
1066 g_array_set_size (array, private_key->index);
1068 node = &g_array_index (array, GStaticPrivateNode, private_key->index - 1);
1071 ddestroy = node->destroy;
1074 node->destroy = notify;
1076 UNLOCK_PRIVATE_DATA (self);
1083 * g_static_private_free:
1084 * @private_key: a #GStaticPrivate to be freed
1086 * Releases all resources allocated to @private_key.
1088 * You don't have to call this functions for a #GStaticPrivate with an
1089 * unbounded lifetime, i.e. objects declared 'static', but if you have
1090 * a #GStaticPrivate as a member of a structure and the structure is
1091 * freed, you should also free the #GStaticPrivate.
1094 g_static_private_free (GStaticPrivate *private_key)
1096 guint idx = private_key->index;
1097 GRealThread *thread, *next;
1098 GArray *garbage = NULL;
1103 private_key->index = 0;
1107 thread = g_thread_all_threads;
1109 for (thread = g_thread_all_threads; thread; thread = next)
1113 next = thread->next;
1115 LOCK_PRIVATE_DATA (thread);
1117 array = thread->private_data;
1119 if (array && idx <= array->len)
1121 GStaticPrivateNode *node = &g_array_index (array,
1124 gpointer ddata = node->data;
1125 GDestroyNotify ddestroy = node->destroy;
1128 node->destroy = NULL;
1132 /* defer non-trivial destruction til after we've finished
1133 * iterating, since we must continue to hold the lock */
1134 if (garbage == NULL)
1135 garbage = g_array_new (FALSE, TRUE,
1136 sizeof (GStaticPrivateNode));
1138 g_array_set_size (garbage, garbage->len + 1);
1140 node = &g_array_index (garbage, GStaticPrivateNode,
1143 node->destroy = ddestroy;
1147 UNLOCK_PRIVATE_DATA (thread);
1149 g_thread_free_indices = g_slist_prepend (g_thread_free_indices,
1150 GUINT_TO_POINTER (idx));
1151 G_UNLOCK (g_thread);
1157 for (i = 0; i < garbage->len; i++)
1159 GStaticPrivateNode *node;
1161 node = &g_array_index (garbage, GStaticPrivateNode, i);
1162 node->destroy (node->data);
1165 g_array_free (garbage, TRUE);
1169 /* GThread Extra Functions {{{1 ------------------------------------------- */
1172 g_thread_cleanup (gpointer data)
1176 GRealThread* thread = data;
1179 LOCK_PRIVATE_DATA (thread);
1180 array = thread->private_data;
1181 thread->private_data = NULL;
1182 UNLOCK_PRIVATE_DATA (thread);
1188 for (i = 0; i < array->len; i++ )
1190 GStaticPrivateNode *node =
1191 &g_array_index (array, GStaticPrivateNode, i);
1193 node->destroy (node->data);
1195 g_array_free (array, TRUE);
1198 /* We only free the thread structure if it isn't joinable.
1199 * If it is, the structure is freed in g_thread_join()
1201 if (!thread->thread.joinable)
1206 for (t = g_thread_all_threads, p = NULL; t; p = t, t = t->next)
1213 g_thread_all_threads = t->next;
1217 G_UNLOCK (g_thread);
1219 /* Just to make sure, this isn't used any more */
1220 g_system_thread_assign (thread->system_thread, zero_thread);
1227 g_thread_create_proxy (gpointer data)
1229 GRealThread* thread = data;
1233 /* This has to happen before G_LOCK, as that might call g_thread_self */
1234 g_private_set (&g_thread_specific_private, data);
1236 /* The lock makes sure that thread->system_thread is written,
1237 * before thread->thread.func is called. See g_thread_create().
1240 G_UNLOCK (g_thread);
1242 thread->retval = thread->thread.func (thread->thread.data);
1249 * @func: a function to execute in the new thread
1250 * @data: an argument to supply to the new thread
1251 * @joinable: should this thread be joinable?
1252 * @error: return location for error, or %NULL
1254 * This function creates a new thread.
1256 * If @joinable is %TRUE, you can wait for this threads termination
1257 * calling g_thread_join(). Otherwise the thread will just disappear
1258 * when it terminates.
1260 * The new thread executes the function @func with the argument @data.
1261 * If the thread was created successfully, it is returned.
1263 * @error can be %NULL to ignore errors, or non-%NULL to report errors.
1264 * The error is set, if and only if the function returns %NULL.
1266 * Returns: the new #GThread on success
1269 g_thread_create (GThreadFunc func,
1274 return g_thread_create_with_stack_size (func, data, joinable, 0, error);
1278 * g_thread_create_with_stack_size:
1279 * @func: a function to execute in the new thread
1280 * @data: an argument to supply to the new thread
1281 * @joinable: should this thread be joinable?
1282 * @stack_size: a stack size for the new thread
1283 * @error: return location for error
1285 * This function creates a new thread. If the underlying thread
1286 * implementation supports it, the thread gets a stack size of
1287 * @stack_size or the default value for the current platform, if
1290 * If @joinable is %TRUE, you can wait for this threads termination
1291 * calling g_thread_join(). Otherwise the thread will just disappear
1292 * when it terminates.
1294 * The new thread executes the function @func with the argument @data.
1295 * If the thread was created successfully, it is returned.
1297 * @error can be %NULL to ignore errors, or non-%NULL to report errors.
1298 * The error is set, if and only if the function returns %NULL.
1300 * <note><para>Only use g_thread_create_with_stack_size() if you
1301 * really can't use g_thread_create() instead. g_thread_create()
1302 * does not take @stack_size, as it should only be used in cases
1303 * in which it is unavoidable.</para></note>
1305 * Returns: the new #GThread on success
1308 g_thread_create_with_stack_size (GThreadFunc func,
1314 GRealThread* result;
1315 GError *local_error = NULL;
1316 g_return_val_if_fail (func, NULL);
1318 result = g_new0 (GRealThread, 1);
1320 result->thread.joinable = joinable;
1321 result->thread.func = func;
1322 result->thread.data = data;
1323 result->private_data = NULL;
1325 g_system_thread_create (g_thread_create_proxy, result,
1326 stack_size, joinable,
1327 &result->system_thread, &local_error);
1330 result->next = g_thread_all_threads;
1331 g_thread_all_threads = result;
1333 G_UNLOCK (g_thread);
1337 g_propagate_error (error, local_error);
1342 return (GThread*) result;
1347 * @retval: the return value of this thread
1349 * Exits the current thread. If another thread is waiting for that
1350 * thread using g_thread_join() and the current thread is joinable, the
1351 * waiting thread will be woken up and get @retval as the return value
1352 * of g_thread_join(). If the current thread is not joinable, @retval
1353 * is ignored. Calling
1356 * g_thread_exit (retval);
1359 * is equivalent to returning @retval from the function @func, as given
1360 * to g_thread_create().
1362 * <note><para>Never call g_thread_exit() from within a thread of a
1363 * #GThreadPool, as that will mess up the bookkeeping and lead to funny
1364 * and unwanted results.</para></note>
1367 g_thread_exit (gpointer retval)
1369 GRealThread* real = (GRealThread*) g_thread_self ();
1370 real->retval = retval;
1372 g_system_thread_exit ();
1377 * @thread: a #GThread to be waited for
1379 * Waits until @thread finishes, i.e. the function @func, as given to
1380 * g_thread_create(), returns or g_thread_exit() is called by @thread.
1381 * All resources of @thread including the #GThread struct are released.
1382 * @thread must have been created with @joinable=%TRUE in
1383 * g_thread_create(). The value returned by @func or given to
1384 * g_thread_exit() by @thread is returned by this function.
1386 * Returns: the return value of the thread
1389 g_thread_join (GThread* thread)
1391 GRealThread* real = (GRealThread*) thread;
1395 g_return_val_if_fail (thread, NULL);
1396 g_return_val_if_fail (thread->joinable, NULL);
1397 g_return_val_if_fail (!g_system_thread_equal (&real->system_thread, &zero_thread), NULL);
1399 g_system_thread_join (&real->system_thread);
1401 retval = real->retval;
1404 for (t = g_thread_all_threads, p = NULL; t; p = t, t = t->next)
1406 if (t == (GRealThread*) thread)
1411 g_thread_all_threads = t->next;
1415 G_UNLOCK (g_thread);
1417 /* Just to make sure, this isn't used any more */
1418 thread->joinable = 0;
1419 g_system_thread_assign (real->system_thread, zero_thread);
1421 /* the thread structure for non-joinable threads is freed upon
1422 * thread end. We free the memory here. This will leave a loose end,
1423 * if a joinable thread is not joined.
1433 * This functions returns the #GThread corresponding to the calling
1436 * Returns: the current thread
1439 g_thread_self (void)
1441 GRealThread* thread = g_private_get (&g_thread_specific_private);
1445 /* If no thread data is available, provide and set one. This
1446 can happen for the main thread and for threads, that are not
1448 thread = g_new0 (GRealThread, 1);
1449 thread->thread.joinable = FALSE; /* This is a save guess */
1450 thread->thread.func = NULL;
1451 thread->thread.data = NULL;
1452 thread->private_data = NULL;
1454 g_system_thread_self (&thread->system_thread);
1456 g_private_set (&g_thread_specific_private, thread);
1459 thread->next = g_thread_all_threads;
1460 g_thread_all_threads = thread;
1461 G_UNLOCK (g_thread);
1464 return (GThread*)thread;
1467 /* Unsorted {{{1 ---------------------------------------------------------- */
1471 * @thread_func: function to call for all #GThread structures
1472 * @user_data: second argument to @thread_func
1474 * Call @thread_func on all existing #GThread structures.
1475 * Note that threads may decide to exit while @thread_func is
1476 * running, so without intimate knowledge about the lifetime of
1477 * foreign threads, @thread_func shouldn't access the GThread*
1478 * pointer passed in as first argument. However, @thread_func will
1479 * not be called for threads which are known to have exited already.
1481 * Due to thread lifetime checks, this function has an execution complexity
1482 * which is quadratic in the number of existing threads.
1487 g_thread_foreach (GFunc thread_func,
1490 GSList *slist = NULL;
1491 GRealThread *thread;
1492 g_return_if_fail (thread_func != NULL);
1493 /* snapshot the list of threads for iteration */
1495 for (thread = g_thread_all_threads; thread; thread = thread->next)
1496 slist = g_slist_prepend (slist, thread);
1497 G_UNLOCK (g_thread);
1498 /* walk the list, skipping non-existent threads */
1501 GSList *node = slist;
1503 /* check whether the current thread still exists */
1505 for (thread = g_thread_all_threads; thread; thread = thread->next)
1506 if (thread == node->data)
1508 G_UNLOCK (g_thread);
1510 thread_func (thread, user_data);
1511 g_slist_free_1 (node);
1516 * g_thread_get_initialized:
1518 * Indicates if g_thread_init() has been called.
1520 * Returns: %TRUE if threads have been initialized.
1525 g_thread_get_initialized (void)
1527 return g_thread_supported ();
1533 * Allocated and initializes a new #GMutex.
1535 * Returns: a newly allocated #GMutex. Use g_mutex_free() to free
1542 mutex = g_slice_new (GMutex);
1543 g_mutex_init (mutex);
1552 * Destroys a @mutex that has been created with g_mutex_new().
1554 * Calling g_mutex_free() on a locked mutex may result
1555 * in undefined behaviour.
1558 g_mutex_free (GMutex *mutex)
1560 g_mutex_clear (mutex);
1561 g_slice_free (GMutex, mutex);
1567 * Allocates and initializes a new #GCond.
1569 * Returns: a newly allocated #GCond. Free with g_cond_free()
1576 cond = g_slice_new (GCond);
1586 * Destroys a #GCond that has been created with g_cond_new().
1589 g_cond_free (GCond *cond)
1591 g_cond_clear (cond);
1592 g_slice_free (GCond, cond);
1597 * @destructor: a function to destroy the data keyed to
1598 * the #GPrivate when a thread ends
1600 * Creates a new #GPrivate. If @destructor is non-%NULL, it is a
1601 * pointer to a destructor function. Whenever a thread ends and the
1602 * corresponding pointer keyed to this instance of #GPrivate is
1603 * non-%NULL, the destructor is called with this pointer as the
1607 * #GStaticPrivate is a better choice for most uses.
1610 * <note><para>@destructor is used quite differently from @notify in
1611 * g_static_private_set().</para></note>
1613 * <note><para>A #GPrivate cannot be freed. Reuse it instead, if you
1614 * can, to avoid shortage, or use #GStaticPrivate.</para></note>
1616 * <note><para>This function will abort if g_thread_init() has not been
1617 * called yet.</para></note>
1619 * Returns: a newly allocated #GPrivate
1622 g_private_new (GDestroyNotify notify)
1626 key = g_slice_new (GPrivate);
1627 g_private_init (key, notify);
1632 /* vim: set foldmethod=marker: */