1 /* GLIB - Library of useful routines for C programming
2 * Copyright (C) 1995-1997 Peter Mattis, Spencer Kimball and Josh MacDonald
4 * gthread.c: MT safety related functions
5 * Copyright 1998 Sebastian Wilhelmi; University of Karlsruhe
8 * This library is free software; you can redistribute it and/or
9 * modify it under the terms of the GNU Lesser General Public
10 * License as published by the Free Software Foundation; either
11 * version 2 of the License, or (at your option) any later version.
13 * This library is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16 * Lesser General Public License for more details.
18 * You should have received a copy of the GNU Lesser General Public
19 * License along with this library; if not, write to the
20 * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
21 * Boston, MA 02111-1307, USA.
24 /* Prelude {{{1 ----------------------------------------------------------- */
27 * Modified by the GLib Team and others 1997-2000. See the AUTHORS
28 * file for a list of people on the GLib Team. See the ChangeLog
29 * files for a list of changes. These files are distributed with
30 * GLib at ftp://ftp.gtk.org/pub/gtk/.
37 /* implement gthread.h's inline functions */
38 #define G_IMPLEMENT_INLINES 1
39 #define __G_THREAD_C__
44 #include "gthreadprivate.h"
45 #include "deprecated/gthread.h"
58 #endif /* G_OS_WIN32 */
63 #include "gtestutils.h"
68 * @short_description: portable support for threads, mutexes, locks,
69 * conditions and thread private data
70 * @see_also: #GThreadPool, #GAsyncQueue
72 * Threads act almost like processes, but unlike processes all threads
73 * of one process share the same memory. This is good, as it provides
74 * easy communication between the involved threads via this shared
75 * memory, and it is bad, because strange things (so called
76 * "Heisenbugs") might happen if the program is not carefully designed.
77 * In particular, due to the concurrent nature of threads, no
78 * assumptions on the order of execution of code running in different
79 * threads can be made, unless order is explicitly forced by the
80 * programmer through synchronization primitives.
82 * The aim of the thread-related functions in GLib is to provide a
83 * portable means for writing multi-threaded software. There are
84 * primitives for mutexes to protect the access to portions of memory
85 * (#GMutex, #GRecMutex and #GRWLock). There is a facility to use
86 * individual bits for locks (g_bit_lock()). There are primitives
87 * for condition variables to allow synchronization of threads (#GCond).
88 * There are primitives for thread-private data - data that every thread
89 * has a private instance of (#GPrivate, #GStaticPrivate). There are
90 * facilities for one-time initialization (#GOnce, g_once_init_enter()).
91 * Finally there are primitives to create and manage threads (#GThread).
93 * The threading system is initialized with g_thread_init().
94 * You may call any other glib functions in the main thread before
95 * g_thread_init() as long as g_thread_init() is not called from
96 * a GLib callback, or with any locks held. However, many libraries
97 * above GLib does not support late initialization of threads, so
98 * doing this should be avoided if possible.
100 * Please note that since version 2.24 the GObject initialization
101 * function g_type_init() initializes threads. Since 2.32, creating
102 * a mainloop will do so too. As a consequence, most applications,
103 * including those using GTK+ will run with threads enabled.
105 * After calling g_thread_init(), GLib is completely thread safe
106 * (all global data is automatically locked), but individual data
107 * structure instances are not automatically locked for performance
108 * reasons. So, for example you must coordinate accesses to the same
109 * #GHashTable from multiple threads. The two notable exceptions from
110 * this rule are #GMainLoop and #GAsyncQueue, which <emphasis>are</emphasis>
111 * threadsafe and need no further application-level locking to be
112 * accessed from multiple threads.
116 * G_THREADS_IMPL_POSIX:
118 * This macro is defined if POSIX style threads are used.
122 * G_THREADS_IMPL_WIN32:
124 * This macro is defined if Windows style threads are used.
127 /* G_LOCK Documentation {{{1 ---------------------------------------------- */
131 * @name: the name of the lock.
133 * The %G_LOCK_* macros provide a convenient interface to #GMutex
134 * with the advantage that they will expand to nothing in programs
135 * compiled against a thread-disabled GLib, saving code and memory
136 * there. #G_LOCK_DEFINE defines a lock. It can appear anywhere
137 * variable definitions may appear in programs, i.e. in the first block
138 * of a function or outside of functions. The @name parameter will be
139 * mangled to get the name of the #GMutex. This means that you
140 * can use names of existing variables as the parameter - e.g. the name
141 * of the variable you intent to protect with the lock. Look at our
142 * <function>give_me_next_number()</function> example using the
146 * <title>Using the %G_LOCK_* convenience macros</title>
148 * G_LOCK_DEFINE (current_number);
151 * give_me_next_number (void)
153 * static int current_number = 0;
156 * G_LOCK (current_number);
157 * ret_val = current_number = calc_next_number (current_number);
158 * G_UNLOCK (current_number);
167 * G_LOCK_DEFINE_STATIC:
168 * @name: the name of the lock.
170 * This works like #G_LOCK_DEFINE, but it creates a static object.
175 * @name: the name of the lock.
177 * This declares a lock, that is defined with #G_LOCK_DEFINE in another
183 * @name: the name of the lock.
185 * Works like g_mutex_lock(), but for a lock defined with
191 * @name: the name of the lock.
192 * @Returns: %TRUE, if the lock could be locked.
194 * Works like g_mutex_trylock(), but for a lock defined with
200 * @name: the name of the lock.
202 * Works like g_mutex_unlock(), but for a lock defined with
206 /* GMutex Documentation {{{1 ------------------------------------------ */
211 * The #GMutex struct is an opaque data structure to represent a mutex
212 * (mutual exclusion). It can be used to protect data against shared
213 * access. Take for example the following function:
216 * <title>A function which will not work in a threaded environment</title>
219 * give_me_next_number (void)
221 * static int current_number = 0;
223 * /<!-- -->* now do a very complicated calculation to calculate the new
224 * * number, this might for example be a random number generator
226 * current_number = calc_next_number (current_number);
228 * return current_number;
233 * It is easy to see that this won't work in a multi-threaded
234 * application. There current_number must be protected against shared
235 * access. A first naive implementation would be:
238 * <title>The wrong way to write a thread-safe function</title>
241 * give_me_next_number (void)
243 * static int current_number = 0;
245 * static GMutex * mutex = NULL;
247 * if (!mutex) mutex = g_mutex_new (<!-- -->);
249 * g_mutex_lock (mutex);
250 * ret_val = current_number = calc_next_number (current_number);
251 * g_mutex_unlock (mutex);
258 * This looks like it would work, but there is a race condition while
259 * constructing the mutex and this code cannot work reliable. Please do
260 * not use such constructs in your own programs! One working solution
264 * <title>A correct thread-safe function</title>
266 * static GMutex *give_me_next_number_mutex = NULL;
268 * /<!-- -->* this function must be called before any call to
269 * * give_me_next_number(<!-- -->)
271 * * it must be called exactly once.
274 * init_give_me_next_number (void)
276 * g_assert (give_me_next_number_mutex == NULL);
277 * give_me_next_number_mutex = g_mutex_new (<!-- -->);
281 * give_me_next_number (void)
283 * static int current_number = 0;
286 * g_mutex_lock (give_me_next_number_mutex);
287 * ret_val = current_number = calc_next_number (current_number);
288 * g_mutex_unlock (give_me_next_number_mutex);
295 * A statically initialized #GMutex provides an even simpler and safer
299 * <title>Using a statically allocated mutex</title>
302 * give_me_next_number (void)
304 * static GMutex mutex = G_MUTEX_INIT;
305 * static int current_number = 0;
308 * g_mutex_lock (&mutex);
309 * ret_val = current_number = calc_next_number (current_number);
310 * g_mutex_unlock (&mutex);
317 * A #GMutex should only be accessed via <function>g_mutex_</function>
324 * Initializer for statically allocated #GMutexes.
325 * Alternatively, g_mutex_init() can be used.
328 * GMutex mutex = G_MUTEX_INIT;
334 /* GRecMutex Documentation {{{1 -------------------------------------- */
339 * The GRecMutex struct is an opaque data structure to represent a
340 * recursive mutex. It is similar to a #GMutex with the difference
341 * that it is possible to lock a GRecMutex multiple times in the same
342 * thread without deadlock. When doing so, care has to be taken to
343 * unlock the recursive mutex as often as it has been locked.
345 * A GRecMutex should only be accessed with the
346 * <function>g_rec_mutex_</function> functions. Before a GRecMutex
347 * can be used, it has to be initialized with #G_REC_MUTEX_INIT or
348 * g_rec_mutex_init().
356 * Initializer for statically allocated #GRecMutexes.
357 * Alternatively, g_rec_mutex_init() can be used.
360 * GRecMutex mutex = G_REC_MUTEX_INIT;
366 /* GRWLock Documentation {{{1 ---------------------------------------- */
371 * The GRWLock struct is an opaque data structure to represent a
372 * reader-writer lock. It is similar to a #GMutex in that it allows
373 * multiple threads to coordinate access to a shared resource.
375 * The difference to a mutex is that a reader-writer lock discriminates
376 * between read-only ('reader') and full ('writer') access. While only
377 * one thread at a time is allowed write access (by holding the 'writer'
378 * lock via g_rw_lock_writer_lock()), multiple threads can gain
379 * simultaneous read-only access (by holding the 'reader' lock via
380 * g_rw_lock_reader_lock()).
383 * <title>An array with access functions</title>
385 * GRWLock lock = G_RW_LOCK_INIT;
389 * my_array_get (guint index)
391 * gpointer retval = NULL;
396 * g_rw_lock_reader_lock (&lock);
397 * if (index < array->len)
398 * retval = g_ptr_array_index (array, index);
399 * g_rw_lock_reader_unlock (&lock);
405 * my_array_set (guint index, gpointer data)
407 * g_rw_lock_writer_lock (&lock);
410 * array = g_ptr_array_new (<!-- -->);
412 * if (index >= array->len)
413 * g_ptr_array_set_size (array, index+1);
414 * g_ptr_array_index (array, index) = data;
416 * g_rw_lock_writer_unlock (&lock);
420 * This example shows an array which can be accessed by many readers
421 * (the <function>my_array_get()</function> function) simultaneously,
422 * whereas the writers (the <function>my_array_set()</function>
423 * function) will only be allowed once at a time and only if no readers
424 * currently access the array. This is because of the potentially
425 * dangerous resizing of the array. Using these functions is fully
426 * multi-thread safe now.
430 * A GRWLock should only be accessed with the
431 * <function>g_rw_lock_</function> functions. Before it can be used,
432 * it has to be initialized with #G_RW_LOCK_INIT or g_rw_lock_init().
440 * Initializer for statically allocated #GRWLocks.
441 * Alternatively, g_rw_lock_init_init() can be used.
444 * GRWLock lock = G_RW_LOCK_INIT;
450 /* GCond Documentation {{{1 ------------------------------------------ */
455 * The #GCond struct is an opaque data structure that represents a
456 * condition. Threads can block on a #GCond if they find a certain
457 * condition to be false. If other threads change the state of this
458 * condition they signal the #GCond, and that causes the waiting
459 * threads to be woken up.
463 * Using GCond to block a thread until a condition is satisfied
466 * GCond* data_cond = NULL; /<!-- -->* Must be initialized somewhere *<!-- -->/
467 * GMutex* data_mutex = NULL; /<!-- -->* Must be initialized somewhere *<!-- -->/
468 * gpointer current_data = NULL;
471 * push_data (gpointer data)
473 * g_mutex_lock (data_mutex);
474 * current_data = data;
475 * g_cond_signal (data_cond);
476 * g_mutex_unlock (data_mutex);
484 * g_mutex_lock (data_mutex);
485 * while (!current_data)
486 * g_cond_wait (data_cond, data_mutex);
487 * data = current_data;
488 * current_data = NULL;
489 * g_mutex_unlock (data_mutex);
496 * Whenever a thread calls pop_data() now, it will wait until
497 * current_data is non-%NULL, i.e. until some other thread
498 * has called push_data().
500 * <note><para>It is important to use the g_cond_wait() and
501 * g_cond_timed_wait() functions only inside a loop which checks for the
502 * condition to be true. It is not guaranteed that the waiting thread
503 * will find the condition fulfilled after it wakes up, even if the
504 * signaling thread left the condition in that state: another thread may
505 * have altered the condition before the waiting thread got the chance
506 * to be woken up, even if the condition itself is protected by a
507 * #GMutex, like above.</para></note>
509 * A #GCond should only be accessed via the <function>g_cond_</function>
516 * Initializer for statically allocated #GConds.
517 * Alternatively, g_cond_init() can be used.
520 * GCond cond = G_COND_INIT;
526 /* GThread Documentation {{{1 ---------------------------------------- */
531 * The #GThread struct represents a running thread.
533 * Resources for a joinable thread are not fully released
534 * until g_thread_join() is called for that thread.
539 * @data: data passed to the thread
540 * @Returns: the return value of the thread, which will be returned by
543 * Specifies the type of the @func functions passed to
544 * g_thread_create() or g_thread_create_full().
548 * g_thread_supported:
550 * This macro returns %TRUE if the thread system is initialized,
551 * and %FALSE if it is not.
553 * For language bindings, g_thread_get_initialized() provides
554 * the same functionality as a function.
556 * Returns: %TRUE, if the thread system is initialized
559 /* GThreadError {{{1 ------------------------------------------------------- */
562 * @G_THREAD_ERROR_AGAIN: a thread couldn't be created due to resource
563 * shortage. Try again later.
565 * Possible errors of thread related functions.
571 * The error domain of the GLib thread subsystem.
574 g_thread_error_quark (void)
576 return g_quark_from_static_string ("g_thread_error");
579 /* Miscellaneous Structures {{{1 ------------------------------------------ */
581 typedef struct _GRealThread GRealThread;
585 GArray *private_data;
590 GSystemThread system_thread;
593 /* Local Data {{{1 -------------------------------------------------------- */
595 gboolean g_threads_got_initialized = FALSE;
596 GSystemThread zero_thread; /* This is initialized to all zero */
598 GMutex g_once_mutex = G_MUTEX_INIT;
599 static GCond g_once_cond = G_COND_INIT;
600 static GSList *g_once_init_list = NULL;
602 static void g_thread_cleanup (gpointer data);
603 static GPrivate g_thread_specific_private = G_PRIVATE_INIT (g_thread_cleanup);
604 static GRealThread *g_thread_all_threads = NULL;
605 static GSList *g_thread_free_indices = NULL;
607 /* Protects g_thread_all_threads and g_thread_free_indices */
608 G_LOCK_DEFINE_STATIC (g_thread);
610 /* Initialisation {{{1 ---------------------------------------------------- */
614 * @vtable: a function table of type #GThreadFunctions, that provides
615 * the entry points to the thread system to be used. Since 2.32,
616 * this parameter is ignored and should always be %NULL
618 * If you use GLib from more than one thread, you must initialize the
619 * thread system by calling g_thread_init().
621 * Since version 2.24, calling g_thread_init() multiple times is allowed,
622 * but nothing happens except for the first call.
624 * Since version 2.32, GLib does not support custom thread implementations
625 * anymore and the @vtable parameter is ignored and you should pass %NULL.
627 * <note><para>g_thread_init() must not be called directly or indirectly
628 * in a callback from GLib. Also no mutexes may be currently locked while
629 * calling g_thread_init().</para></note>
631 * <note><para>To use g_thread_init() in your program, you have to link
632 * with the libraries that the command <command>pkg-config --libs
633 * gthread-2.0</command> outputs. This is not the case for all the
634 * other thread-related functions of GLib. Those can be used without
635 * having to link with the thread libraries.</para></note>
639 g_thread_init_glib (void)
641 static gboolean already_done;
642 GRealThread* main_thread;
649 /* We let the main thread (the one that calls g_thread_init) inherit
650 * the static_private data set before calling g_thread_init
652 main_thread = (GRealThread*) g_thread_self ();
654 /* setup the basic threading system */
655 g_threads_got_initialized = TRUE;
656 g_private_set (&g_thread_specific_private, main_thread);
657 g_system_thread_self (&main_thread->system_thread);
659 /* accomplish log system initialization to enable messaging */
660 _g_messages_thread_init_nomessage ();
664 * g_thread_get_initialized:
666 * Indicates if g_thread_init() has been called.
668 * Returns: %TRUE if threads have been initialized.
673 g_thread_get_initialized (void)
675 return g_thread_supported ();
678 /* GOnce {{{1 ------------------------------------------------------------- */
682 * @status: the status of the #GOnce
683 * @retval: the value returned by the call to the function, if @status
684 * is %G_ONCE_STATUS_READY
686 * A #GOnce struct controls a one-time initialization function. Any
687 * one-time initialization function must have its own unique #GOnce
696 * A #GOnce must be initialized with this macro before it can be used.
699 * GOnce my_once = G_ONCE_INIT;
707 * @G_ONCE_STATUS_NOTCALLED: the function has not been called yet.
708 * @G_ONCE_STATUS_PROGRESS: the function call is currently in progress.
709 * @G_ONCE_STATUS_READY: the function has been called.
711 * The possible statuses of a one-time initialization function
712 * controlled by a #GOnce struct.
719 * @once: a #GOnce structure
720 * @func: the #GThreadFunc function associated to @once. This function
721 * is called only once, regardless of the number of times it and
722 * its associated #GOnce struct are passed to g_once().
723 * @arg: data to be passed to @func
725 * The first call to this routine by a process with a given #GOnce
726 * struct calls @func with the given argument. Thereafter, subsequent
727 * calls to g_once() with the same #GOnce struct do not call @func
728 * again, but return the stored result of the first call. On return
729 * from g_once(), the status of @once will be %G_ONCE_STATUS_READY.
731 * For example, a mutex or a thread-specific data key must be created
732 * exactly once. In a threaded environment, calling g_once() ensures
733 * that the initialization is serialized across multiple threads.
735 * Calling g_once() recursively on the same #GOnce struct in
736 * @func will lead to a deadlock.
740 * get_debug_flags (void)
742 * static GOnce my_once = G_ONCE_INIT;
744 * g_once (&my_once, parse_debug_flags, NULL);
746 * return my_once.retval;
753 g_once_impl (GOnce *once,
757 g_mutex_lock (&g_once_mutex);
759 while (once->status == G_ONCE_STATUS_PROGRESS)
760 g_cond_wait (&g_once_cond, &g_once_mutex);
762 if (once->status != G_ONCE_STATUS_READY)
764 once->status = G_ONCE_STATUS_PROGRESS;
765 g_mutex_unlock (&g_once_mutex);
767 once->retval = func (arg);
769 g_mutex_lock (&g_once_mutex);
770 once->status = G_ONCE_STATUS_READY;
771 g_cond_broadcast (&g_once_cond);
774 g_mutex_unlock (&g_once_mutex);
781 * @value_location: location of a static initializable variable
784 * Function to be called when starting a critical initialization
785 * section. The argument @value_location must point to a static
786 * 0-initialized variable that will be set to a value other than 0 at
787 * the end of the initialization section. In combination with
788 * g_once_init_leave() and the unique address @value_location, it can
789 * be ensured that an initialization section will be executed only once
790 * during a program's life time, and that concurrent threads are
791 * blocked until initialization completed. To be used in constructs
795 * static gsize initialization_value = 0;
797 * if (g_once_init_enter (&initialization_value))
799 * gsize setup_value = 42; /** initialization code here **/
801 * g_once_init_leave (&initialization_value, setup_value);
804 * /** use initialization_value here **/
807 * Returns: %TRUE if the initialization section should be entered,
808 * %FALSE and blocks otherwise
813 g_once_init_enter_impl (volatile gsize *value_location)
815 gboolean need_init = FALSE;
816 g_mutex_lock (&g_once_mutex);
817 if (g_atomic_pointer_get (value_location) == NULL)
819 if (!g_slist_find (g_once_init_list, (void*) value_location))
822 g_once_init_list = g_slist_prepend (g_once_init_list, (void*) value_location);
826 g_cond_wait (&g_once_cond, &g_once_mutex);
827 while (g_slist_find (g_once_init_list, (void*) value_location));
829 g_mutex_unlock (&g_once_mutex);
835 * @value_location: location of a static initializable variable
837 * @initialization_value: new non-0 value for *@value_location
839 * Counterpart to g_once_init_enter(). Expects a location of a static
840 * 0-initialized initialization variable, and an initialization value
841 * other than 0. Sets the variable to the initialization value, and
842 * releases concurrent threads blocking in g_once_init_enter() on this
843 * initialization variable.
848 g_once_init_leave (volatile gsize *value_location,
849 gsize initialization_value)
851 g_return_if_fail (g_atomic_pointer_get (value_location) == NULL);
852 g_return_if_fail (initialization_value != 0);
853 g_return_if_fail (g_once_init_list != NULL);
855 g_atomic_pointer_set (value_location, initialization_value);
856 g_mutex_lock (&g_once_mutex);
857 g_once_init_list = g_slist_remove (g_once_init_list, (void*) value_location);
858 g_cond_broadcast (&g_once_cond);
859 g_mutex_unlock (&g_once_mutex);
862 /* GStaticPrivate {{{1 ---------------------------------------------------- */
864 typedef struct _GStaticPrivateNode GStaticPrivateNode;
865 struct _GStaticPrivateNode
868 GDestroyNotify destroy;
869 GStaticPrivate *owner;
875 * A #GStaticPrivate works almost like a #GPrivate, but it has one
876 * significant advantage. It doesn't need to be created at run-time
877 * like a #GPrivate, but can be defined at compile-time. This is
878 * similar to the difference between #GMutex and #GStaticMutex. Now
879 * look at our <function>give_me_next_number()</function> example with
883 * <title>Using GStaticPrivate for per-thread data</title>
886 * give_me_next_number (<!-- -->)
888 * static GStaticPrivate current_number_key = G_STATIC_PRIVATE_INIT;
889 * int *current_number = g_static_private_get (&current_number_key);
891 * if (!current_number)
893 * current_number = g_new (int,1);
894 * *current_number = 0;
895 * g_static_private_set (&current_number_key, current_number, g_free);
898 * *current_number = calc_next_number (*current_number);
900 * return *current_number;
907 * G_STATIC_PRIVATE_INIT:
909 * Every #GStaticPrivate must be initialized with this macro, before it
913 * GStaticPrivate my_private = G_STATIC_PRIVATE_INIT;
918 * g_static_private_init:
919 * @private_key: a #GStaticPrivate to be initialized
921 * Initializes @private_key. Alternatively you can initialize it with
922 * #G_STATIC_PRIVATE_INIT.
925 g_static_private_init (GStaticPrivate *private_key)
927 private_key->index = 0;
931 * g_static_private_get:
932 * @private_key: a #GStaticPrivate
934 * Works like g_private_get() only for a #GStaticPrivate.
936 * This function works even if g_thread_init() has not yet been called.
938 * Returns: the corresponding pointer
941 g_static_private_get (GStaticPrivate *private_key)
943 GRealThread *self = (GRealThread*) g_thread_self ();
947 array = self->private_data;
949 if (array && private_key->index != 0 && private_key->index <= array->len)
951 GStaticPrivateNode *node;
953 node = &g_array_index (array, GStaticPrivateNode, private_key->index - 1);
955 /* Deal with the possibility that the GStaticPrivate which used
956 * to have this index got freed and the index got allocated to
957 * a new one. In this case, the data in the node is stale, so
958 * free it and return NULL.
960 if (G_UNLIKELY (node->owner != private_key))
963 node->destroy (node->data);
964 node->destroy = NULL;
976 * g_static_private_set:
977 * @private_key: a #GStaticPrivate
978 * @data: the new pointer
979 * @notify: a function to be called with the pointer whenever the
980 * current thread ends or sets this pointer again
982 * Sets the pointer keyed to @private_key for the current thread and
983 * the function @notify to be called with that pointer (%NULL or
984 * non-%NULL), whenever the pointer is set again or whenever the
985 * current thread ends.
987 * This function works even if g_thread_init() has not yet been called.
988 * If g_thread_init() is called later, the @data keyed to @private_key
989 * will be inherited only by the main thread, i.e. the one that called
992 * <note><para>@notify is used quite differently from @destructor in
993 * g_private_new().</para></note>
996 g_static_private_set (GStaticPrivate *private_key,
998 GDestroyNotify notify)
1000 GRealThread *self = (GRealThread*) g_thread_self ();
1002 static guint next_index = 0;
1003 GStaticPrivateNode *node;
1005 if (!private_key->index)
1009 if (!private_key->index)
1011 if (g_thread_free_indices)
1013 private_key->index = GPOINTER_TO_UINT (g_thread_free_indices->data);
1014 g_thread_free_indices = g_slist_delete_link (g_thread_free_indices,
1015 g_thread_free_indices);
1018 private_key->index = ++next_index;
1021 G_UNLOCK (g_thread);
1024 array = self->private_data;
1027 array = g_array_new (FALSE, TRUE, sizeof (GStaticPrivateNode));
1028 self->private_data = array;
1031 if (private_key->index > array->len)
1032 g_array_set_size (array, private_key->index);
1034 node = &g_array_index (array, GStaticPrivateNode, private_key->index - 1);
1037 node->destroy (node->data);
1040 node->destroy = notify;
1041 node->owner = private_key;
1045 * g_static_private_free:
1046 * @private_key: a #GStaticPrivate to be freed
1048 * Releases all resources allocated to @private_key.
1050 * You don't have to call this functions for a #GStaticPrivate with an
1051 * unbounded lifetime, i.e. objects declared 'static', but if you have
1052 * a #GStaticPrivate as a member of a structure and the structure is
1053 * freed, you should also free the #GStaticPrivate.
1056 g_static_private_free (GStaticPrivate *private_key)
1058 guint idx = private_key->index;
1063 private_key->index = 0;
1065 /* Freeing the per-thread data is deferred to either the
1066 * thread end or the next g_static_private_get() call for
1070 g_thread_free_indices = g_slist_prepend (g_thread_free_indices,
1071 GUINT_TO_POINTER (idx));
1072 G_UNLOCK (g_thread);
1075 /* GThread {{{1 -------------------------------------------------------- */
1078 g_thread_cleanup (gpointer data)
1082 GRealThread* thread = data;
1085 array = thread->private_data;
1086 thread->private_data = NULL;
1092 for (i = 0; i < array->len; i++ )
1094 GStaticPrivateNode *node = &g_array_index (array, GStaticPrivateNode, i);
1096 node->destroy (node->data);
1098 g_array_free (array, TRUE);
1101 /* We only free the thread structure if it isn't joinable.
1102 * If it is, the structure is freed in g_thread_join()
1104 if (!thread->thread.joinable)
1106 if (thread->enumerable)
1111 for (t = g_thread_all_threads, p = NULL; t; p = t, t = t->next)
1118 g_thread_all_threads = t->next;
1122 G_UNLOCK (g_thread);
1124 /* Just to make sure, this isn't used any more */
1125 g_system_thread_assign (thread->system_thread, zero_thread);
1132 g_thread_create_proxy (gpointer data)
1134 GRealThread* thread = data;
1139 g_system_thread_set_name (thread->name);
1141 /* This has to happen before G_LOCK, as that might call g_thread_self */
1142 g_private_set (&g_thread_specific_private, data);
1144 /* The lock makes sure that thread->system_thread is written,
1145 * before thread->thread.func is called. See g_thread_create().
1148 G_UNLOCK (g_thread);
1150 thread->retval = thread->thread.func (thread->thread.data);
1157 * @name: a name for the new thread
1158 * @func: a function to execute in the new thread
1159 * @data: an argument to supply to the new thread
1160 * @joinable: should this thread be joinable?
1161 * @error: return location for error
1163 * This function creates a new thread.
1165 * The @name can be useful for discriminating threads in
1166 * a debugger. Some systems restrict the length of @name to
1169 * If @joinable is %TRUE, you can wait for this threads termination
1170 * calling g_thread_join(). Otherwise the thread will just disappear
1171 * when it terminates.
1173 * The new thread executes the function @func with the argument @data.
1174 * If the thread was created successfully, it is returned.
1176 * @error can be %NULL to ignore errors, or non-%NULL to report errors.
1177 * The error is set, if and only if the function returns %NULL.
1179 * Returns: the new #GThread on success
1184 g_thread_new (const gchar *name,
1190 return g_thread_new_internal (name, func, data, joinable, 0, FALSE, error);
1194 * g_thread_new_full:
1195 * @name: a name for the new thread
1196 * @func: a function to execute in the new thread
1197 * @data: an argument to supply to the new thread
1198 * @joinable: should this thread be joinable?
1199 * @stack_size: a stack size for the new thread
1200 * @error: return location for error
1202 * This function creates a new thread.
1204 * The @name can be useful for discriminating threads in
1205 * a debugger. Some systems restrict the length of @name to
1208 * If the underlying thread implementation supports it, the thread
1209 * gets a stack size of @stack_size or the default value for the
1210 * current platform, if @stack_size is 0.
1212 * If @joinable is %TRUE, you can wait for this threads termination
1213 * calling g_thread_join(). Otherwise the thread will just disappear
1214 * when it terminates.
1216 * The new thread executes the function @func with the argument @data.
1217 * If the thread was created successfully, it is returned.
1219 * @error can be %NULL to ignore errors, or non-%NULL to report errors.
1220 * The error is set, if and only if the function returns %NULL.
1222 * <note><para>Only use a non-zero @stack_size if you
1223 * really can't use the default instead. g_thread_new()
1224 * does not take @stack_size, as it should only be used in cases
1225 * in which it is unavoidable.</para></note>
1227 * Returns: the new #GThread on success
1232 g_thread_new_full (const gchar *name,
1239 return g_thread_new_internal (name, func, data, joinable, stack_size, FALSE, error);
1243 g_thread_new_internal (const gchar *name,
1248 gboolean enumerable,
1251 GRealThread *result;
1252 GError *local_error = NULL;
1253 g_return_val_if_fail (func, NULL);
1255 result = g_new0 (GRealThread, 1);
1257 result->thread.joinable = joinable;
1258 result->thread.func = func;
1259 result->thread.data = data;
1260 result->private_data = NULL;
1261 result->enumerable = enumerable;
1262 result->name = name;
1264 g_system_thread_create (g_thread_create_proxy, result,
1265 stack_size, joinable,
1266 &result->system_thread, &local_error);
1267 if (enumerable && !local_error)
1269 result->next = g_thread_all_threads;
1270 g_thread_all_threads = result;
1272 G_UNLOCK (g_thread);
1276 g_propagate_error (error, local_error);
1281 return (GThread*) result;
1286 * @retval: the return value of this thread
1288 * Exits the current thread. If another thread is waiting for that
1289 * thread using g_thread_join() and the current thread is joinable, the
1290 * waiting thread will be woken up and get @retval as the return value
1291 * of g_thread_join(). If the current thread is not joinable, @retval
1292 * is ignored. Calling
1295 * g_thread_exit (retval);
1298 * is equivalent to returning @retval from the function @func, as given
1299 * to g_thread_create().
1301 * <note><para>Never call g_thread_exit() from within a thread of a
1302 * #GThreadPool, as that will mess up the bookkeeping and lead to funny
1303 * and unwanted results.</para></note>
1306 g_thread_exit (gpointer retval)
1308 GRealThread* real = (GRealThread*) g_thread_self ();
1309 real->retval = retval;
1311 g_system_thread_exit ();
1316 * @thread: a #GThread to be waited for
1318 * Waits until @thread finishes, i.e. the function @func, as given to
1319 * g_thread_create(), returns or g_thread_exit() is called by @thread.
1320 * All resources of @thread including the #GThread struct are released.
1321 * @thread must have been created with @joinable=%TRUE in
1322 * g_thread_create(). The value returned by @func or given to
1323 * g_thread_exit() by @thread is returned by this function.
1325 * Returns: the return value of the thread
1328 g_thread_join (GThread *thread)
1330 GRealThread *real = (GRealThread*) thread;
1334 g_return_val_if_fail (thread, NULL);
1335 g_return_val_if_fail (thread->joinable, NULL);
1336 g_return_val_if_fail (!g_system_thread_equal (&real->system_thread, &zero_thread), NULL);
1338 g_system_thread_join (&real->system_thread);
1340 retval = real->retval;
1342 if (real->enumerable)
1345 for (t = g_thread_all_threads, p = NULL; t; p = t, t = t->next)
1352 g_thread_all_threads = t->next;
1356 G_UNLOCK (g_thread);
1358 /* Just to make sure, this isn't used any more */
1359 thread->joinable = 0;
1360 g_system_thread_assign (real->system_thread, zero_thread);
1362 /* the thread structure for non-joinable threads is freed upon
1363 * thread end. We free the memory here. This will leave a loose end,
1364 * if a joinable thread is not joined.
1374 * This functions returns the #GThread corresponding to the calling
1377 * Returns: the current thread
1380 g_thread_self (void)
1382 GRealThread* thread = g_private_get (&g_thread_specific_private);
1386 /* If no thread data is available, provide and set one.
1387 * This can happen for the main thread and for threads
1388 * that are not created by GLib.
1390 thread = g_new0 (GRealThread, 1);
1391 thread->thread.joinable = FALSE; /* This is a safe guess */
1392 thread->thread.func = NULL;
1393 thread->thread.data = NULL;
1394 thread->private_data = NULL;
1395 thread->enumerable = FALSE;
1397 g_system_thread_self (&thread->system_thread);
1399 g_private_set (&g_thread_specific_private, thread);
1402 return (GThread*)thread;
1407 * @thread_func: function to call for all #GThread structures
1408 * @user_data: second argument to @thread_func
1410 * Call @thread_func on all existing #GThread structures.
1411 * Note that threads may decide to exit while @thread_func is
1412 * running, so without intimate knowledge about the lifetime of
1413 * foreign threads, @thread_func shouldn't access the GThread*
1414 * pointer passed in as first argument. However, @thread_func will
1415 * not be called for threads which are known to have exited already.
1417 * Due to thread lifetime checks, this function has an execution complexity
1418 * which is quadratic in the number of existing threads.
1423 g_thread_foreach (GFunc thread_func,
1426 GSList *slist = NULL;
1427 GRealThread *thread;
1428 g_return_if_fail (thread_func != NULL);
1429 /* snapshot the list of threads for iteration */
1431 for (thread = g_thread_all_threads; thread; thread = thread->next)
1432 slist = g_slist_prepend (slist, thread);
1433 G_UNLOCK (g_thread);
1434 /* walk the list, skipping non-existent threads */
1437 GSList *node = slist;
1439 /* check whether the current thread still exists */
1441 for (thread = g_thread_all_threads; thread; thread = thread->next)
1442 if (thread == node->data)
1444 G_UNLOCK (g_thread);
1446 thread_func (thread, user_data);
1447 g_slist_free_1 (node);
1451 /* GMutex {{{1 ------------------------------------------------------ */
1456 * Allocated and initializes a new #GMutex.
1458 * Returns: a newly allocated #GMutex. Use g_mutex_free() to free
1465 mutex = g_slice_new (GMutex);
1466 g_mutex_init (mutex);
1475 * Destroys a @mutex that has been created with g_mutex_new().
1477 * Calling g_mutex_free() on a locked mutex may result
1478 * in undefined behaviour.
1481 g_mutex_free (GMutex *mutex)
1483 g_mutex_clear (mutex);
1484 g_slice_free (GMutex, mutex);
1487 /* GCond {{{1 ------------------------------------------------------ */
1492 * Allocates and initializes a new #GCond.
1494 * Returns: a newly allocated #GCond. Free with g_cond_free()
1501 cond = g_slice_new (GCond);
1511 * Destroys a #GCond that has been created with g_cond_new().
1514 g_cond_free (GCond *cond)
1516 g_cond_clear (cond);
1517 g_slice_free (GCond, cond);
1521 /* vim: set foldmethod=marker: */