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 #GMutex
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 #GMutex. 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 ();
724 * g_thread_get_initialized:
726 * Indicates if g_thread_init() has been called.
728 * Returns: %TRUE if threads have been initialized.
733 g_thread_get_initialized (void)
735 return g_thread_supported ();
738 /* GOnce {{{1 ------------------------------------------------------------- */
742 * @status: the status of the #GOnce
743 * @retval: the value returned by the call to the function, if @status
744 * is %G_ONCE_STATUS_READY
746 * A #GOnce struct controls a one-time initialization function. Any
747 * one-time initialization function must have its own unique #GOnce
756 * A #GOnce must be initialized with this macro before it can be used.
759 * GOnce my_once = G_ONCE_INIT;
767 * @G_ONCE_STATUS_NOTCALLED: the function has not been called yet.
768 * @G_ONCE_STATUS_PROGRESS: the function call is currently in progress.
769 * @G_ONCE_STATUS_READY: the function has been called.
771 * The possible statuses of a one-time initialization function
772 * controlled by a #GOnce struct.
779 * @once: a #GOnce structure
780 * @func: the #GThreadFunc function associated to @once. This function
781 * is called only once, regardless of the number of times it and
782 * its associated #GOnce struct are passed to g_once().
783 * @arg: data to be passed to @func
785 * The first call to this routine by a process with a given #GOnce
786 * struct calls @func with the given argument. Thereafter, subsequent
787 * calls to g_once() with the same #GOnce struct do not call @func
788 * again, but return the stored result of the first call. On return
789 * from g_once(), the status of @once will be %G_ONCE_STATUS_READY.
791 * For example, a mutex or a thread-specific data key must be created
792 * exactly once. In a threaded environment, calling g_once() ensures
793 * that the initialization is serialized across multiple threads.
795 * Calling g_once() recursively on the same #GOnce struct in
796 * @func will lead to a deadlock.
800 * get_debug_flags (void)
802 * static GOnce my_once = G_ONCE_INIT;
804 * g_once (&my_once, parse_debug_flags, NULL);
806 * return my_once.retval;
813 g_once_impl (GOnce *once,
817 g_mutex_lock (&g_once_mutex);
819 while (once->status == G_ONCE_STATUS_PROGRESS)
820 g_cond_wait (&g_once_cond, &g_once_mutex);
822 if (once->status != G_ONCE_STATUS_READY)
824 once->status = G_ONCE_STATUS_PROGRESS;
825 g_mutex_unlock (&g_once_mutex);
827 once->retval = func (arg);
829 g_mutex_lock (&g_once_mutex);
830 once->status = G_ONCE_STATUS_READY;
831 g_cond_broadcast (&g_once_cond);
834 g_mutex_unlock (&g_once_mutex);
841 * @value_location: location of a static initializable variable
844 * Function to be called when starting a critical initialization
845 * section. The argument @value_location must point to a static
846 * 0-initialized variable that will be set to a value other than 0 at
847 * the end of the initialization section. In combination with
848 * g_once_init_leave() and the unique address @value_location, it can
849 * be ensured that an initialization section will be executed only once
850 * during a program's life time, and that concurrent threads are
851 * blocked until initialization completed. To be used in constructs
855 * static gsize initialization_value = 0;
857 * if (g_once_init_enter (&initialization_value))
859 * gsize setup_value = 42; /** initialization code here **/
861 * g_once_init_leave (&initialization_value, setup_value);
864 * /** use initialization_value here **/
867 * Returns: %TRUE if the initialization section should be entered,
868 * %FALSE and blocks otherwise
873 g_once_init_enter_impl (volatile gsize *value_location)
875 gboolean need_init = FALSE;
876 g_mutex_lock (&g_once_mutex);
877 if (g_atomic_pointer_get (value_location) == NULL)
879 if (!g_slist_find (g_once_init_list, (void*) value_location))
882 g_once_init_list = g_slist_prepend (g_once_init_list, (void*) value_location);
886 g_cond_wait (&g_once_cond, &g_once_mutex);
887 while (g_slist_find (g_once_init_list, (void*) value_location));
889 g_mutex_unlock (&g_once_mutex);
895 * @value_location: location of a static initializable variable
897 * @initialization_value: new non-0 value for *@value_location
899 * Counterpart to g_once_init_enter(). Expects a location of a static
900 * 0-initialized initialization variable, and an initialization value
901 * other than 0. Sets the variable to the initialization value, and
902 * releases concurrent threads blocking in g_once_init_enter() on this
903 * initialization variable.
908 g_once_init_leave (volatile gsize *value_location,
909 gsize initialization_value)
911 g_return_if_fail (g_atomic_pointer_get (value_location) == NULL);
912 g_return_if_fail (initialization_value != 0);
913 g_return_if_fail (g_once_init_list != NULL);
915 g_atomic_pointer_set (value_location, initialization_value);
916 g_mutex_lock (&g_once_mutex);
917 g_once_init_list = g_slist_remove (g_once_init_list, (void*) value_location);
918 g_cond_broadcast (&g_once_cond);
919 g_mutex_unlock (&g_once_mutex);
922 /* GStaticPrivate {{{1 ---------------------------------------------------- */
924 typedef struct _GStaticPrivateNode GStaticPrivateNode;
925 struct _GStaticPrivateNode
928 GDestroyNotify destroy;
934 * A #GStaticPrivate works almost like a #GPrivate, but it has one
935 * significant advantage. It doesn't need to be created at run-time
936 * like a #GPrivate, but can be defined at compile-time. This is
937 * similar to the difference between #GMutex and #GStaticMutex. Now
938 * look at our <function>give_me_next_number()</function> example with
942 * <title>Using GStaticPrivate for per-thread data</title>
945 * give_me_next_number (<!-- -->)
947 * static GStaticPrivate current_number_key = G_STATIC_PRIVATE_INIT;
948 * int *current_number = g_static_private_get (&current_number_key);
950 * if (!current_number)
952 * current_number = g_new (int,1);
953 * *current_number = 0;
954 * g_static_private_set (&current_number_key, current_number, g_free);
957 * *current_number = calc_next_number (*current_number);
959 * return *current_number;
966 * G_STATIC_PRIVATE_INIT:
968 * Every #GStaticPrivate must be initialized with this macro, before it
972 * GStaticPrivate my_private = G_STATIC_PRIVATE_INIT;
977 * g_static_private_init:
978 * @private_key: a #GStaticPrivate to be initialized
980 * Initializes @private_key. Alternatively you can initialize it with
981 * #G_STATIC_PRIVATE_INIT.
984 g_static_private_init (GStaticPrivate *private_key)
986 private_key->index = 0;
990 * g_static_private_get:
991 * @private_key: a #GStaticPrivate
993 * Works like g_private_get() only for a #GStaticPrivate.
995 * This function works even if g_thread_init() has not yet been called.
997 * Returns: the corresponding pointer
1000 g_static_private_get (GStaticPrivate *private_key)
1002 GRealThread *self = (GRealThread*) g_thread_self ();
1004 gpointer ret = NULL;
1006 LOCK_PRIVATE_DATA (self);
1008 array = self->private_data;
1010 if (array && private_key->index != 0 && private_key->index <= array->len)
1011 ret = g_array_index (array, GStaticPrivateNode,
1012 private_key->index - 1).data;
1014 UNLOCK_PRIVATE_DATA (self);
1019 * g_static_private_set:
1020 * @private_key: a #GStaticPrivate
1021 * @data: the new pointer
1022 * @notify: a function to be called with the pointer whenever the
1023 * current thread ends or sets this pointer again
1025 * Sets the pointer keyed to @private_key for the current thread and
1026 * the function @notify to be called with that pointer (%NULL or
1027 * non-%NULL), whenever the pointer is set again or whenever the
1028 * current thread ends.
1030 * This function works even if g_thread_init() has not yet been called.
1031 * If g_thread_init() is called later, the @data keyed to @private_key
1032 * will be inherited only by the main thread, i.e. the one that called
1035 * <note><para>@notify is used quite differently from @destructor in
1036 * g_private_new().</para></note>
1039 g_static_private_set (GStaticPrivate *private_key,
1041 GDestroyNotify notify)
1043 GRealThread *self = (GRealThread*) g_thread_self ();
1045 static guint next_index = 0;
1046 GStaticPrivateNode *node;
1047 gpointer ddata = NULL;
1048 GDestroyNotify ddestroy = NULL;
1050 if (!private_key->index)
1054 if (!private_key->index)
1056 if (g_thread_free_indices)
1058 private_key->index =
1059 GPOINTER_TO_UINT (g_thread_free_indices->data);
1060 g_thread_free_indices =
1061 g_slist_delete_link (g_thread_free_indices,
1062 g_thread_free_indices);
1065 private_key->index = ++next_index;
1068 G_UNLOCK (g_thread);
1071 LOCK_PRIVATE_DATA (self);
1073 array = self->private_data;
1076 array = g_array_new (FALSE, TRUE, sizeof (GStaticPrivateNode));
1077 self->private_data = array;
1080 if (private_key->index > array->len)
1081 g_array_set_size (array, private_key->index);
1083 node = &g_array_index (array, GStaticPrivateNode, private_key->index - 1);
1086 ddestroy = node->destroy;
1089 node->destroy = notify;
1091 UNLOCK_PRIVATE_DATA (self);
1098 * g_static_private_free:
1099 * @private_key: a #GStaticPrivate to be freed
1101 * Releases all resources allocated to @private_key.
1103 * You don't have to call this functions for a #GStaticPrivate with an
1104 * unbounded lifetime, i.e. objects declared 'static', but if you have
1105 * a #GStaticPrivate as a member of a structure and the structure is
1106 * freed, you should also free the #GStaticPrivate.
1109 g_static_private_free (GStaticPrivate *private_key)
1111 guint idx = private_key->index;
1112 GRealThread *thread, *next;
1113 GArray *garbage = NULL;
1118 private_key->index = 0;
1122 thread = g_thread_all_threads;
1124 for (thread = g_thread_all_threads; thread; thread = next)
1128 next = thread->next;
1130 LOCK_PRIVATE_DATA (thread);
1132 array = thread->private_data;
1134 if (array && idx <= array->len)
1136 GStaticPrivateNode *node = &g_array_index (array,
1139 gpointer ddata = node->data;
1140 GDestroyNotify ddestroy = node->destroy;
1143 node->destroy = NULL;
1147 /* defer non-trivial destruction til after we've finished
1148 * iterating, since we must continue to hold the lock */
1149 if (garbage == NULL)
1150 garbage = g_array_new (FALSE, TRUE,
1151 sizeof (GStaticPrivateNode));
1153 g_array_set_size (garbage, garbage->len + 1);
1155 node = &g_array_index (garbage, GStaticPrivateNode,
1158 node->destroy = ddestroy;
1162 UNLOCK_PRIVATE_DATA (thread);
1164 g_thread_free_indices = g_slist_prepend (g_thread_free_indices,
1165 GUINT_TO_POINTER (idx));
1166 G_UNLOCK (g_thread);
1172 for (i = 0; i < garbage->len; i++)
1174 GStaticPrivateNode *node;
1176 node = &g_array_index (garbage, GStaticPrivateNode, i);
1177 node->destroy (node->data);
1180 g_array_free (garbage, TRUE);
1184 /* GThread {{{1 -------------------------------------------------------- */
1187 g_thread_cleanup (gpointer data)
1191 GRealThread* thread = data;
1194 LOCK_PRIVATE_DATA (thread);
1195 array = thread->private_data;
1196 thread->private_data = NULL;
1197 UNLOCK_PRIVATE_DATA (thread);
1203 for (i = 0; i < array->len; i++ )
1205 GStaticPrivateNode *node =
1206 &g_array_index (array, GStaticPrivateNode, i);
1208 node->destroy (node->data);
1210 g_array_free (array, TRUE);
1213 /* We only free the thread structure if it isn't joinable.
1214 * If it is, the structure is freed in g_thread_join()
1216 if (!thread->thread.joinable)
1221 for (t = g_thread_all_threads, p = NULL; t; p = t, t = t->next)
1228 g_thread_all_threads = t->next;
1232 G_UNLOCK (g_thread);
1234 /* Just to make sure, this isn't used any more */
1235 g_system_thread_assign (thread->system_thread, zero_thread);
1242 g_thread_create_proxy (gpointer data)
1244 GRealThread* thread = data;
1248 /* This has to happen before G_LOCK, as that might call g_thread_self */
1249 g_private_set (&g_thread_specific_private, data);
1251 /* The lock makes sure that thread->system_thread is written,
1252 * before thread->thread.func is called. See g_thread_create().
1255 G_UNLOCK (g_thread);
1257 thread->retval = thread->thread.func (thread->thread.data);
1264 * @func: a function to execute in the new thread
1265 * @data: an argument to supply to the new thread
1266 * @joinable: should this thread be joinable?
1267 * @error: return location for error, or %NULL
1269 * This function creates a new thread.
1271 * If @joinable is %TRUE, you can wait for this threads termination
1272 * calling g_thread_join(). Otherwise the thread will just disappear
1273 * when it terminates.
1275 * The new thread executes the function @func with the argument @data.
1276 * If the thread was created successfully, it is returned.
1278 * @error can be %NULL to ignore errors, or non-%NULL to report errors.
1279 * The error is set, if and only if the function returns %NULL.
1281 * Returns: the new #GThread on success
1284 g_thread_create (GThreadFunc func,
1289 return g_thread_create_with_stack_size (func, data, joinable, 0, error);
1293 * g_thread_create_with_stack_size:
1294 * @func: a function to execute in the new thread
1295 * @data: an argument to supply to the new thread
1296 * @joinable: should this thread be joinable?
1297 * @stack_size: a stack size for the new thread
1298 * @error: return location for error
1300 * This function creates a new thread. If the underlying thread
1301 * implementation supports it, the thread gets a stack size of
1302 * @stack_size or the default value for the current platform, if
1305 * If @joinable is %TRUE, you can wait for this threads termination
1306 * calling g_thread_join(). Otherwise the thread will just disappear
1307 * when it terminates.
1309 * The new thread executes the function @func with the argument @data.
1310 * If the thread was created successfully, it is returned.
1312 * @error can be %NULL to ignore errors, or non-%NULL to report errors.
1313 * The error is set, if and only if the function returns %NULL.
1315 * <note><para>Only use g_thread_create_with_stack_size() if you
1316 * really can't use g_thread_create() instead. g_thread_create()
1317 * does not take @stack_size, as it should only be used in cases
1318 * in which it is unavoidable.</para></note>
1320 * Returns: the new #GThread on success
1325 g_thread_create_with_stack_size (GThreadFunc func,
1331 GRealThread* result;
1332 GError *local_error = NULL;
1333 g_return_val_if_fail (func, NULL);
1335 result = g_new0 (GRealThread, 1);
1337 result->thread.joinable = joinable;
1338 result->thread.func = func;
1339 result->thread.data = data;
1340 result->private_data = NULL;
1342 g_system_thread_create (g_thread_create_proxy, result,
1343 stack_size, joinable,
1344 &result->system_thread, &local_error);
1347 result->next = g_thread_all_threads;
1348 g_thread_all_threads = result;
1350 G_UNLOCK (g_thread);
1354 g_propagate_error (error, local_error);
1359 return (GThread*) result;
1364 * @retval: the return value of this thread
1366 * Exits the current thread. If another thread is waiting for that
1367 * thread using g_thread_join() and the current thread is joinable, the
1368 * waiting thread will be woken up and get @retval as the return value
1369 * of g_thread_join(). If the current thread is not joinable, @retval
1370 * is ignored. Calling
1373 * g_thread_exit (retval);
1376 * is equivalent to returning @retval from the function @func, as given
1377 * to g_thread_create().
1379 * <note><para>Never call g_thread_exit() from within a thread of a
1380 * #GThreadPool, as that will mess up the bookkeeping and lead to funny
1381 * and unwanted results.</para></note>
1384 g_thread_exit (gpointer retval)
1386 GRealThread* real = (GRealThread*) g_thread_self ();
1387 real->retval = retval;
1389 g_system_thread_exit ();
1394 * @thread: a #GThread to be waited for
1396 * Waits until @thread finishes, i.e. the function @func, as given to
1397 * g_thread_create(), returns or g_thread_exit() is called by @thread.
1398 * All resources of @thread including the #GThread struct are released.
1399 * @thread must have been created with @joinable=%TRUE in
1400 * g_thread_create(). The value returned by @func or given to
1401 * g_thread_exit() by @thread is returned by this function.
1403 * Returns: the return value of the thread
1406 g_thread_join (GThread* thread)
1408 GRealThread* real = (GRealThread*) thread;
1412 g_return_val_if_fail (thread, NULL);
1413 g_return_val_if_fail (thread->joinable, NULL);
1414 g_return_val_if_fail (!g_system_thread_equal (&real->system_thread, &zero_thread), NULL);
1416 g_system_thread_join (&real->system_thread);
1418 retval = real->retval;
1421 for (t = g_thread_all_threads, p = NULL; t; p = t, t = t->next)
1423 if (t == (GRealThread*) thread)
1428 g_thread_all_threads = t->next;
1432 G_UNLOCK (g_thread);
1434 /* Just to make sure, this isn't used any more */
1435 thread->joinable = 0;
1436 g_system_thread_assign (real->system_thread, zero_thread);
1438 /* the thread structure for non-joinable threads is freed upon
1439 * thread end. We free the memory here. This will leave a loose end,
1440 * if a joinable thread is not joined.
1450 * This functions returns the #GThread corresponding to the calling
1453 * Returns: the current thread
1456 g_thread_self (void)
1458 GRealThread* thread = g_private_get (&g_thread_specific_private);
1462 /* If no thread data is available, provide and set one.
1463 * This can happen for the main thread and for threads
1464 * that are not created by GLib.
1466 thread = g_new0 (GRealThread, 1);
1467 thread->thread.joinable = FALSE; /* This is a safe guess */
1468 thread->thread.func = NULL;
1469 thread->thread.data = NULL;
1470 thread->private_data = NULL;
1472 g_system_thread_self (&thread->system_thread);
1474 g_private_set (&g_thread_specific_private, thread);
1477 thread->next = g_thread_all_threads;
1478 g_thread_all_threads = thread;
1479 G_UNLOCK (g_thread);
1482 return (GThread*)thread;
1487 * @thread_func: function to call for all #GThread structures
1488 * @user_data: second argument to @thread_func
1490 * Call @thread_func on all existing #GThread structures.
1491 * Note that threads may decide to exit while @thread_func is
1492 * running, so without intimate knowledge about the lifetime of
1493 * foreign threads, @thread_func shouldn't access the GThread*
1494 * pointer passed in as first argument. However, @thread_func will
1495 * not be called for threads which are known to have exited already.
1497 * Due to thread lifetime checks, this function has an execution complexity
1498 * which is quadratic in the number of existing threads.
1503 g_thread_foreach (GFunc thread_func,
1506 GSList *slist = NULL;
1507 GRealThread *thread;
1508 g_return_if_fail (thread_func != NULL);
1509 /* snapshot the list of threads for iteration */
1511 for (thread = g_thread_all_threads; thread; thread = thread->next)
1512 slist = g_slist_prepend (slist, thread);
1513 G_UNLOCK (g_thread);
1514 /* walk the list, skipping non-existent threads */
1517 GSList *node = slist;
1519 /* check whether the current thread still exists */
1521 for (thread = g_thread_all_threads; thread; thread = thread->next)
1522 if (thread == node->data)
1524 G_UNLOCK (g_thread);
1526 thread_func (thread, user_data);
1527 g_slist_free_1 (node);
1531 /* GMutex {{{1 ------------------------------------------------------ */
1536 * Allocated and initializes a new #GMutex.
1538 * Returns: a newly allocated #GMutex. Use g_mutex_free() to free
1545 mutex = g_slice_new (GMutex);
1546 g_mutex_init (mutex);
1555 * Destroys a @mutex that has been created with g_mutex_new().
1557 * Calling g_mutex_free() on a locked mutex may result
1558 * in undefined behaviour.
1561 g_mutex_free (GMutex *mutex)
1563 g_mutex_clear (mutex);
1564 g_slice_free (GMutex, mutex);
1567 /* GCond {{{1 ------------------------------------------------------ */
1572 * Allocates and initializes a new #GCond.
1574 * Returns: a newly allocated #GCond. Free with g_cond_free()
1581 cond = g_slice_new (GCond);
1591 * Destroys a #GCond that has been created with g_cond_new().
1594 g_cond_free (GCond *cond)
1596 g_cond_clear (cond);
1597 g_slice_free (GCond, cond);
1600 /* GPrivate {{{1 ------------------------------------------------------ */
1604 * @destructor: a function to destroy the data keyed to
1605 * the #GPrivate when a thread ends
1607 * Creates a new #GPrivate. If @destructor is non-%NULL, it is a
1608 * pointer to a destructor function. Whenever a thread ends and the
1609 * corresponding pointer keyed to this instance of #GPrivate is
1610 * non-%NULL, the destructor is called with this pointer as the
1614 * #GStaticPrivate is a better choice for most uses.
1617 * <note><para>@destructor is used quite differently from @notify in
1618 * g_static_private_set().</para></note>
1620 * <note><para>A #GPrivate cannot be freed. Reuse it instead, if you
1621 * can, to avoid shortage, or use #GStaticPrivate.</para></note>
1623 * <note><para>This function will abort if g_thread_init() has not been
1624 * called yet.</para></note>
1626 * Returns: a newly allocated #GPrivate
1629 g_private_new (GDestroyNotify notify)
1633 key = g_slice_new (GPrivate);
1634 g_private_init (key, notify);
1639 /* vim: set foldmethod=marker: */