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 */
64 #include "gtestutils.h"
69 * @short_description: portable support for threads, mutexes, locks,
70 * conditions and thread private data
71 * @see_also: #GThreadPool, #GAsyncQueue
73 * Threads act almost like processes, but unlike processes all threads
74 * of one process share the same memory. This is good, as it provides
75 * easy communication between the involved threads via this shared
76 * memory, and it is bad, because strange things (so called
77 * "Heisenbugs") might happen if the program is not carefully designed.
78 * In particular, due to the concurrent nature of threads, no
79 * assumptions on the order of execution of code running in different
80 * threads can be made, unless order is explicitly forced by the
81 * programmer through synchronization primitives.
83 * The aim of the thread-related functions in GLib is to provide a
84 * portable means for writing multi-threaded software. There are
85 * primitives for mutexes to protect the access to portions of memory
86 * (#GMutex, #GRecMutex and #GRWLock). There is a facility to use
87 * individual bits for locks (g_bit_lock()). There are primitives
88 * for condition variables to allow synchronization of threads (#GCond).
89 * There are primitives for thread-private data - data that every thread
90 * has a private instance of (#GPrivate, #GStaticPrivate). There are
91 * facilities for one-time initialization (#GOnce, g_once_init_enter()).
92 * Finally there are primitives to create and manage threads (#GThread).
94 * The threading system is initialized with g_thread_init().
95 * You may call any other glib functions in the main thread before
96 * g_thread_init() as long as g_thread_init() is not called from
97 * a GLib callback, or with any locks held. However, many libraries
98 * above GLib does not support late initialization of threads, so
99 * doing this should be avoided if possible.
101 * Please note that since version 2.24 the GObject initialization
102 * function g_type_init() initializes threads. Since 2.32, creating
103 * a mainloop will do so too. As a consequence, most applications,
104 * including those using GTK+ will run with threads enabled.
106 * After calling g_thread_init(), GLib is completely thread safe
107 * (all global data is automatically locked), but individual data
108 * structure instances are not automatically locked for performance
109 * reasons. So, for example you must coordinate accesses to the same
110 * #GHashTable from multiple threads. The two notable exceptions from
111 * this rule are #GMainLoop and #GAsyncQueue, which <emphasis>are</emphasis>
112 * threadsafe and need no further application-level locking to be
113 * accessed from multiple threads.
117 * G_THREADS_IMPL_POSIX:
119 * This macro is defined if POSIX style threads are used.
123 * G_THREADS_IMPL_WIN32:
125 * This macro is defined if Windows style threads are used.
128 /* G_LOCK Documentation {{{1 ---------------------------------------------- */
132 * @name: the name of the lock.
134 * The %G_LOCK_* macros provide a convenient interface to #GMutex
135 * with the advantage that they will expand to nothing in programs
136 * compiled against a thread-disabled GLib, saving code and memory
137 * there. #G_LOCK_DEFINE defines a lock. It can appear anywhere
138 * variable definitions may appear in programs, i.e. in the first block
139 * of a function or outside of functions. The @name parameter will be
140 * mangled to get the name of the #GMutex. This means that you
141 * can use names of existing variables as the parameter - e.g. the name
142 * of the variable you intent to protect with the lock. Look at our
143 * <function>give_me_next_number()</function> example using the
147 * <title>Using the %G_LOCK_* convenience macros</title>
149 * G_LOCK_DEFINE (current_number);
152 * give_me_next_number (void)
154 * static int current_number = 0;
157 * G_LOCK (current_number);
158 * ret_val = current_number = calc_next_number (current_number);
159 * G_UNLOCK (current_number);
168 * G_LOCK_DEFINE_STATIC:
169 * @name: the name of the lock.
171 * This works like #G_LOCK_DEFINE, but it creates a static object.
176 * @name: the name of the lock.
178 * This declares a lock, that is defined with #G_LOCK_DEFINE in another
184 * @name: the name of the lock.
186 * Works like g_mutex_lock(), but for a lock defined with
192 * @name: the name of the lock.
193 * @Returns: %TRUE, if the lock could be locked.
195 * Works like g_mutex_trylock(), but for a lock defined with
201 * @name: the name of the lock.
203 * Works like g_mutex_unlock(), but for a lock defined with
207 /* GMutex Documentation {{{1 ------------------------------------------ */
212 * The #GMutex struct is an opaque data structure to represent a mutex
213 * (mutual exclusion). It can be used to protect data against shared
214 * access. Take for example the following function:
217 * <title>A function which will not work in a threaded environment</title>
220 * give_me_next_number (void)
222 * static int current_number = 0;
224 * /<!-- -->* now do a very complicated calculation to calculate the new
225 * * number, this might for example be a random number generator
227 * current_number = calc_next_number (current_number);
229 * return current_number;
234 * It is easy to see that this won't work in a multi-threaded
235 * application. There current_number must be protected against shared
236 * access. A first naive implementation would be:
239 * <title>The wrong way to write a thread-safe function</title>
242 * give_me_next_number (void)
244 * static int current_number = 0;
246 * static GMutex * mutex = NULL;
248 * if (!mutex) mutex = g_mutex_new (<!-- -->);
250 * g_mutex_lock (mutex);
251 * ret_val = current_number = calc_next_number (current_number);
252 * g_mutex_unlock (mutex);
259 * This looks like it would work, but there is a race condition while
260 * constructing the mutex and this code cannot work reliable. Please do
261 * not use such constructs in your own programs! One working solution
265 * <title>A correct thread-safe function</title>
267 * static GMutex *give_me_next_number_mutex = NULL;
269 * /<!-- -->* this function must be called before any call to
270 * * give_me_next_number(<!-- -->)
272 * * it must be called exactly once.
275 * init_give_me_next_number (void)
277 * g_assert (give_me_next_number_mutex == NULL);
278 * give_me_next_number_mutex = g_mutex_new (<!-- -->);
282 * give_me_next_number (void)
284 * static int current_number = 0;
287 * g_mutex_lock (give_me_next_number_mutex);
288 * ret_val = current_number = calc_next_number (current_number);
289 * g_mutex_unlock (give_me_next_number_mutex);
296 * A statically initialized #GMutex provides an even simpler and safer
300 * <title>Using a statically allocated mutex</title>
303 * give_me_next_number (void)
305 * static GMutex mutex = G_MUTEX_INIT;
306 * static int current_number = 0;
309 * g_mutex_lock (&mutex);
310 * ret_val = current_number = calc_next_number (current_number);
311 * g_mutex_unlock (&mutex);
318 * A #GMutex should only be accessed via <function>g_mutex_</function>
325 * Initializer for statically allocated #GMutexes.
326 * Alternatively, g_mutex_init() can be used.
329 * GMutex mutex = G_MUTEX_INIT;
335 /* GRecMutex Documentation {{{1 -------------------------------------- */
340 * The GRecMutex struct is an opaque data structure to represent a
341 * recursive mutex. It is similar to a #GMutex with the difference
342 * that it is possible to lock a GRecMutex multiple times in the same
343 * thread without deadlock. When doing so, care has to be taken to
344 * unlock the recursive mutex as often as it has been locked.
346 * A GRecMutex should only be accessed with the
347 * <function>g_rec_mutex_</function> functions. Before a GRecMutex
348 * can be used, it has to be initialized with #G_REC_MUTEX_INIT or
349 * g_rec_mutex_init().
357 * Initializer for statically allocated #GRecMutexes.
358 * Alternatively, g_rec_mutex_init() can be used.
361 * GRecMutex mutex = G_REC_MUTEX_INIT;
367 /* GRWLock Documentation {{{1 ---------------------------------------- */
372 * The GRWLock struct is an opaque data structure to represent a
373 * reader-writer lock. It is similar to a #GMutex in that it allows
374 * multiple threads to coordinate access to a shared resource.
376 * The difference to a mutex is that a reader-writer lock discriminates
377 * between read-only ('reader') and full ('writer') access. While only
378 * one thread at a time is allowed write access (by holding the 'writer'
379 * lock via g_rw_lock_writer_lock()), multiple threads can gain
380 * simultaneous read-only access (by holding the 'reader' lock via
381 * g_rw_lock_reader_lock()).
384 * <title>An array with access functions</title>
386 * GRWLock lock = G_RW_LOCK_INIT;
390 * my_array_get (guint index)
392 * gpointer retval = NULL;
397 * g_rw_lock_reader_lock (&lock);
398 * if (index < array->len)
399 * retval = g_ptr_array_index (array, index);
400 * g_rw_lock_reader_unlock (&lock);
406 * my_array_set (guint index, gpointer data)
408 * g_rw_lock_writer_lock (&lock);
411 * array = g_ptr_array_new (<!-- -->);
413 * if (index >= array->len)
414 * g_ptr_array_set_size (array, index+1);
415 * g_ptr_array_index (array, index) = data;
417 * g_rw_lock_writer_unlock (&lock);
421 * This example shows an array which can be accessed by many readers
422 * (the <function>my_array_get()</function> function) simultaneously,
423 * whereas the writers (the <function>my_array_set()</function>
424 * function) will only be allowed once at a time and only if no readers
425 * currently access the array. This is because of the potentially
426 * dangerous resizing of the array. Using these functions is fully
427 * multi-thread safe now.
431 * A GRWLock should only be accessed with the
432 * <function>g_rw_lock_</function> functions. Before it can be used,
433 * it has to be initialized with #G_RW_LOCK_INIT or g_rw_lock_init().
441 * Initializer for statically allocated #GRWLocks.
442 * Alternatively, g_rw_lock_init_init() can be used.
445 * GRWLock lock = G_RW_LOCK_INIT;
451 /* GCond Documentation {{{1 ------------------------------------------ */
456 * The #GCond struct is an opaque data structure that represents a
457 * condition. Threads can block on a #GCond if they find a certain
458 * condition to be false. If other threads change the state of this
459 * condition they signal the #GCond, and that causes the waiting
460 * threads to be woken up.
464 * Using GCond to block a thread until a condition is satisfied
467 * GCond* data_cond = NULL; /<!-- -->* Must be initialized somewhere *<!-- -->/
468 * GMutex* data_mutex = NULL; /<!-- -->* Must be initialized somewhere *<!-- -->/
469 * gpointer current_data = NULL;
472 * push_data (gpointer data)
474 * g_mutex_lock (data_mutex);
475 * current_data = data;
476 * g_cond_signal (data_cond);
477 * g_mutex_unlock (data_mutex);
485 * g_mutex_lock (data_mutex);
486 * while (!current_data)
487 * g_cond_wait (data_cond, data_mutex);
488 * data = current_data;
489 * current_data = NULL;
490 * g_mutex_unlock (data_mutex);
497 * Whenever a thread calls pop_data() now, it will wait until
498 * current_data is non-%NULL, i.e. until some other thread
499 * has called push_data().
501 * <note><para>It is important to use the g_cond_wait() and
502 * g_cond_timed_wait() functions only inside a loop which checks for the
503 * condition to be true. It is not guaranteed that the waiting thread
504 * will find the condition fulfilled after it wakes up, even if the
505 * signaling thread left the condition in that state: another thread may
506 * have altered the condition before the waiting thread got the chance
507 * to be woken up, even if the condition itself is protected by a
508 * #GMutex, like above.</para></note>
510 * A #GCond should only be accessed via the <function>g_cond_</function>
517 * Initializer for statically allocated #GConds.
518 * Alternatively, g_cond_init() can be used.
521 * GCond cond = G_COND_INIT;
527 /* GPrivate Documentation {{{1 --------------------------------------- */
533 * #GStaticPrivate is a better choice for most uses.
536 * The #GPrivate struct is an opaque data structure to represent a
537 * thread private data key. Threads can thereby obtain and set a
538 * pointer which is private to the current thread. Take our
539 * <function>give_me_next_number(<!-- -->)</function> example from
540 * above. Suppose we don't want <literal>current_number</literal> to be
541 * shared between the threads, but instead to be private to each thread.
542 * This can be done as follows:
545 * <title>Using GPrivate for per-thread data</title>
547 * GPrivate* current_number_key = NULL; /<!-- -->* Must be initialized somewhere
548 * with g_private_new (g_free); *<!-- -->/
551 * give_me_next_number (void)
553 * int *current_number = g_private_get (current_number_key);
555 * if (!current_number)
557 * current_number = g_new (int, 1);
558 * *current_number = 0;
559 * g_private_set (current_number_key, current_number);
562 * *current_number = calc_next_number (*current_number);
564 * return *current_number;
569 * Here the pointer belonging to the key
570 * <literal>current_number_key</literal> is read. If it is %NULL, it has
571 * not been set yet. Then get memory for an integer value, assign this
572 * memory to the pointer and write the pointer back. Now we have an
573 * integer value that is private to the current thread.
575 * The #GPrivate struct should only be accessed via the
576 * <function>g_private_</function> functions.
579 /* GThread Documentation {{{1 ---------------------------------------- */
584 * The #GThread struct represents a running thread.
586 * Resources for a joinable thread are not fully released
587 * until g_thread_join() is called for that thread.
592 * @data: data passed to the thread
593 * @Returns: the return value of the thread, which will be returned by
596 * Specifies the type of the @func functions passed to
597 * g_thread_create() or g_thread_create_full().
601 * g_thread_supported:
603 * This macro returns %TRUE if the thread system is initialized,
604 * and %FALSE if it is not.
606 * For language bindings, g_thread_get_initialized() provides
607 * the same functionality as a function.
609 * Returns: %TRUE, if the thread system is initialized
612 /* GThreadError {{{1 ------------------------------------------------------- */
615 * @G_THREAD_ERROR_AGAIN: a thread couldn't be created due to resource
616 * shortage. Try again later.
618 * Possible errors of thread related functions.
624 * The error domain of the GLib thread subsystem.
627 g_thread_error_quark (void)
629 return g_quark_from_static_string ("g_thread_error");
632 /* Miscellaneous Structures {{{1 ------------------------------------------ */
634 typedef struct _GRealThread GRealThread;
638 /* Bit 0 protects private_data. To avoid deadlocks,
639 * do not block while holding this (particularly on
640 * the g_thread lock).
642 volatile gint private_data_lock;
643 GArray *private_data;
646 GSystemThread system_thread;
649 #define LOCK_PRIVATE_DATA(self) g_bit_lock (&(self)->private_data_lock, 0)
650 #define UNLOCK_PRIVATE_DATA(self) g_bit_unlock (&(self)->private_data_lock, 0)
652 /* Local Data {{{1 -------------------------------------------------------- */
654 gboolean g_threads_got_initialized = FALSE;
655 GSystemThread zero_thread; /* This is initialized to all zero */
656 GMutex g_once_mutex = G_MUTEX_INIT;
658 static GCond g_once_cond = G_COND_INIT;
659 static GPrivate g_thread_specific_private;
660 static GRealThread *g_thread_all_threads = NULL;
661 static GSList *g_thread_free_indices = NULL;
662 static GSList* g_once_init_list = NULL;
664 G_LOCK_DEFINE_STATIC (g_thread);
666 /* Initialisation {{{1 ---------------------------------------------------- */
670 * @vtable: a function table of type #GThreadFunctions, that provides
671 * the entry points to the thread system to be used. Since 2.32,
672 * this parameter is ignored and should always be %NULL
674 * If you use GLib from more than one thread, you must initialize the
675 * thread system by calling g_thread_init().
677 * Since version 2.24, calling g_thread_init() multiple times is allowed,
678 * but nothing happens except for the first call.
680 * Since version 2.32, GLib does not support custom thread implementations
681 * anymore and the @vtable parameter is ignored and you should pass %NULL.
683 * <note><para>g_thread_init() must not be called directly or indirectly
684 * in a callback from GLib. Also no mutexes may be currently locked while
685 * calling g_thread_init().</para></note>
687 * <note><para>To use g_thread_init() in your program, you have to link
688 * with the libraries that the command <command>pkg-config --libs
689 * gthread-2.0</command> outputs. This is not the case for all the
690 * other thread-related functions of GLib. Those can be used without
691 * having to link with the thread libraries.</para></note>
694 static void g_thread_cleanup (gpointer data);
697 g_thread_init_glib (void)
699 static gboolean already_done;
700 GRealThread* main_thread;
707 /* We let the main thread (the one that calls g_thread_init) inherit
708 * the static_private data set before calling g_thread_init
710 main_thread = (GRealThread*) g_thread_self ();
712 /* setup the basic threading system */
713 g_threads_got_initialized = TRUE;
714 g_private_init (&g_thread_specific_private, g_thread_cleanup);
715 g_private_set (&g_thread_specific_private, main_thread);
716 g_system_thread_self (&main_thread->system_thread);
718 /* accomplish log system initialization to enable messaging */
719 _g_messages_thread_init_nomessage ();
723 * g_thread_get_initialized:
725 * Indicates if g_thread_init() has been called.
727 * Returns: %TRUE if threads have been initialized.
732 g_thread_get_initialized (void)
734 return g_thread_supported ();
737 /* GOnce {{{1 ------------------------------------------------------------- */
741 * @status: the status of the #GOnce
742 * @retval: the value returned by the call to the function, if @status
743 * is %G_ONCE_STATUS_READY
745 * A #GOnce struct controls a one-time initialization function. Any
746 * one-time initialization function must have its own unique #GOnce
755 * A #GOnce must be initialized with this macro before it can be used.
758 * GOnce my_once = G_ONCE_INIT;
766 * @G_ONCE_STATUS_NOTCALLED: the function has not been called yet.
767 * @G_ONCE_STATUS_PROGRESS: the function call is currently in progress.
768 * @G_ONCE_STATUS_READY: the function has been called.
770 * The possible statuses of a one-time initialization function
771 * controlled by a #GOnce struct.
778 * @once: a #GOnce structure
779 * @func: the #GThreadFunc function associated to @once. This function
780 * is called only once, regardless of the number of times it and
781 * its associated #GOnce struct are passed to g_once().
782 * @arg: data to be passed to @func
784 * The first call to this routine by a process with a given #GOnce
785 * struct calls @func with the given argument. Thereafter, subsequent
786 * calls to g_once() with the same #GOnce struct do not call @func
787 * again, but return the stored result of the first call. On return
788 * from g_once(), the status of @once will be %G_ONCE_STATUS_READY.
790 * For example, a mutex or a thread-specific data key must be created
791 * exactly once. In a threaded environment, calling g_once() ensures
792 * that the initialization is serialized across multiple threads.
794 * Calling g_once() recursively on the same #GOnce struct in
795 * @func will lead to a deadlock.
799 * get_debug_flags (void)
801 * static GOnce my_once = G_ONCE_INIT;
803 * g_once (&my_once, parse_debug_flags, NULL);
805 * return my_once.retval;
812 g_once_impl (GOnce *once,
816 g_mutex_lock (&g_once_mutex);
818 while (once->status == G_ONCE_STATUS_PROGRESS)
819 g_cond_wait (&g_once_cond, &g_once_mutex);
821 if (once->status != G_ONCE_STATUS_READY)
823 once->status = G_ONCE_STATUS_PROGRESS;
824 g_mutex_unlock (&g_once_mutex);
826 once->retval = func (arg);
828 g_mutex_lock (&g_once_mutex);
829 once->status = G_ONCE_STATUS_READY;
830 g_cond_broadcast (&g_once_cond);
833 g_mutex_unlock (&g_once_mutex);
840 * @value_location: location of a static initializable variable
843 * Function to be called when starting a critical initialization
844 * section. The argument @value_location must point to a static
845 * 0-initialized variable that will be set to a value other than 0 at
846 * the end of the initialization section. In combination with
847 * g_once_init_leave() and the unique address @value_location, it can
848 * be ensured that an initialization section will be executed only once
849 * during a program's life time, and that concurrent threads are
850 * blocked until initialization completed. To be used in constructs
854 * static gsize initialization_value = 0;
856 * if (g_once_init_enter (&initialization_value))
858 * gsize setup_value = 42; /** initialization code here **/
860 * g_once_init_leave (&initialization_value, setup_value);
863 * /** use initialization_value here **/
866 * Returns: %TRUE if the initialization section should be entered,
867 * %FALSE and blocks otherwise
872 g_once_init_enter_impl (volatile gsize *value_location)
874 gboolean need_init = FALSE;
875 g_mutex_lock (&g_once_mutex);
876 if (g_atomic_pointer_get (value_location) == NULL)
878 if (!g_slist_find (g_once_init_list, (void*) value_location))
881 g_once_init_list = g_slist_prepend (g_once_init_list, (void*) value_location);
885 g_cond_wait (&g_once_cond, &g_once_mutex);
886 while (g_slist_find (g_once_init_list, (void*) value_location));
888 g_mutex_unlock (&g_once_mutex);
894 * @value_location: location of a static initializable variable
896 * @initialization_value: new non-0 value for *@value_location
898 * Counterpart to g_once_init_enter(). Expects a location of a static
899 * 0-initialized initialization variable, and an initialization value
900 * other than 0. Sets the variable to the initialization value, and
901 * releases concurrent threads blocking in g_once_init_enter() on this
902 * initialization variable.
907 g_once_init_leave (volatile gsize *value_location,
908 gsize initialization_value)
910 g_return_if_fail (g_atomic_pointer_get (value_location) == NULL);
911 g_return_if_fail (initialization_value != 0);
912 g_return_if_fail (g_once_init_list != NULL);
914 g_atomic_pointer_set (value_location, initialization_value);
915 g_mutex_lock (&g_once_mutex);
916 g_once_init_list = g_slist_remove (g_once_init_list, (void*) value_location);
917 g_cond_broadcast (&g_once_cond);
918 g_mutex_unlock (&g_once_mutex);
921 /* GStaticPrivate {{{1 ---------------------------------------------------- */
923 typedef struct _GStaticPrivateNode GStaticPrivateNode;
924 struct _GStaticPrivateNode
927 GDestroyNotify destroy;
933 * A #GStaticPrivate works almost like a #GPrivate, but it has one
934 * significant advantage. It doesn't need to be created at run-time
935 * like a #GPrivate, but can be defined at compile-time. This is
936 * similar to the difference between #GMutex and #GStaticMutex. Now
937 * look at our <function>give_me_next_number()</function> example with
941 * <title>Using GStaticPrivate for per-thread data</title>
944 * give_me_next_number (<!-- -->)
946 * static GStaticPrivate current_number_key = G_STATIC_PRIVATE_INIT;
947 * int *current_number = g_static_private_get (&current_number_key);
949 * if (!current_number)
951 * current_number = g_new (int,1);
952 * *current_number = 0;
953 * g_static_private_set (&current_number_key, current_number, g_free);
956 * *current_number = calc_next_number (*current_number);
958 * return *current_number;
965 * G_STATIC_PRIVATE_INIT:
967 * Every #GStaticPrivate must be initialized with this macro, before it
971 * GStaticPrivate my_private = G_STATIC_PRIVATE_INIT;
976 * g_static_private_init:
977 * @private_key: a #GStaticPrivate to be initialized
979 * Initializes @private_key. Alternatively you can initialize it with
980 * #G_STATIC_PRIVATE_INIT.
983 g_static_private_init (GStaticPrivate *private_key)
985 private_key->index = 0;
989 * g_static_private_get:
990 * @private_key: a #GStaticPrivate
992 * Works like g_private_get() only for a #GStaticPrivate.
994 * This function works even if g_thread_init() has not yet been called.
996 * Returns: the corresponding pointer
999 g_static_private_get (GStaticPrivate *private_key)
1001 GRealThread *self = (GRealThread*) g_thread_self ();
1003 gpointer ret = NULL;
1005 LOCK_PRIVATE_DATA (self);
1007 array = self->private_data;
1009 if (array && private_key->index != 0 && private_key->index <= array->len)
1010 ret = g_array_index (array, GStaticPrivateNode,
1011 private_key->index - 1).data;
1013 UNLOCK_PRIVATE_DATA (self);
1018 * g_static_private_set:
1019 * @private_key: a #GStaticPrivate
1020 * @data: the new pointer
1021 * @notify: a function to be called with the pointer whenever the
1022 * current thread ends or sets this pointer again
1024 * Sets the pointer keyed to @private_key for the current thread and
1025 * the function @notify to be called with that pointer (%NULL or
1026 * non-%NULL), whenever the pointer is set again or whenever the
1027 * current thread ends.
1029 * This function works even if g_thread_init() has not yet been called.
1030 * If g_thread_init() is called later, the @data keyed to @private_key
1031 * will be inherited only by the main thread, i.e. the one that called
1034 * <note><para>@notify is used quite differently from @destructor in
1035 * g_private_new().</para></note>
1038 g_static_private_set (GStaticPrivate *private_key,
1040 GDestroyNotify notify)
1042 GRealThread *self = (GRealThread*) g_thread_self ();
1044 static guint next_index = 0;
1045 GStaticPrivateNode *node;
1046 gpointer ddata = NULL;
1047 GDestroyNotify ddestroy = NULL;
1049 if (!private_key->index)
1053 if (!private_key->index)
1055 if (g_thread_free_indices)
1057 private_key->index =
1058 GPOINTER_TO_UINT (g_thread_free_indices->data);
1059 g_thread_free_indices =
1060 g_slist_delete_link (g_thread_free_indices,
1061 g_thread_free_indices);
1064 private_key->index = ++next_index;
1067 G_UNLOCK (g_thread);
1070 LOCK_PRIVATE_DATA (self);
1072 array = self->private_data;
1075 array = g_array_new (FALSE, TRUE, sizeof (GStaticPrivateNode));
1076 self->private_data = array;
1079 if (private_key->index > array->len)
1080 g_array_set_size (array, private_key->index);
1082 node = &g_array_index (array, GStaticPrivateNode, private_key->index - 1);
1085 ddestroy = node->destroy;
1088 node->destroy = notify;
1090 UNLOCK_PRIVATE_DATA (self);
1097 * g_static_private_free:
1098 * @private_key: a #GStaticPrivate to be freed
1100 * Releases all resources allocated to @private_key.
1102 * You don't have to call this functions for a #GStaticPrivate with an
1103 * unbounded lifetime, i.e. objects declared 'static', but if you have
1104 * a #GStaticPrivate as a member of a structure and the structure is
1105 * freed, you should also free the #GStaticPrivate.
1108 g_static_private_free (GStaticPrivate *private_key)
1110 guint idx = private_key->index;
1111 GRealThread *thread, *next;
1112 GArray *garbage = NULL;
1117 private_key->index = 0;
1121 thread = g_thread_all_threads;
1123 for (thread = g_thread_all_threads; thread; thread = next)
1127 next = thread->next;
1129 LOCK_PRIVATE_DATA (thread);
1131 array = thread->private_data;
1133 if (array && idx <= array->len)
1135 GStaticPrivateNode *node = &g_array_index (array,
1138 gpointer ddata = node->data;
1139 GDestroyNotify ddestroy = node->destroy;
1142 node->destroy = NULL;
1146 /* defer non-trivial destruction til after we've finished
1147 * iterating, since we must continue to hold the lock */
1148 if (garbage == NULL)
1149 garbage = g_array_new (FALSE, TRUE,
1150 sizeof (GStaticPrivateNode));
1152 g_array_set_size (garbage, garbage->len + 1);
1154 node = &g_array_index (garbage, GStaticPrivateNode,
1157 node->destroy = ddestroy;
1161 UNLOCK_PRIVATE_DATA (thread);
1163 g_thread_free_indices = g_slist_prepend (g_thread_free_indices,
1164 GUINT_TO_POINTER (idx));
1165 G_UNLOCK (g_thread);
1171 for (i = 0; i < garbage->len; i++)
1173 GStaticPrivateNode *node;
1175 node = &g_array_index (garbage, GStaticPrivateNode, i);
1176 node->destroy (node->data);
1179 g_array_free (garbage, TRUE);
1183 /* GThread {{{1 -------------------------------------------------------- */
1186 g_thread_cleanup (gpointer data)
1190 GRealThread* thread = data;
1193 LOCK_PRIVATE_DATA (thread);
1194 array = thread->private_data;
1195 thread->private_data = NULL;
1196 UNLOCK_PRIVATE_DATA (thread);
1202 for (i = 0; i < array->len; i++ )
1204 GStaticPrivateNode *node =
1205 &g_array_index (array, GStaticPrivateNode, i);
1207 node->destroy (node->data);
1209 g_array_free (array, TRUE);
1212 /* We only free the thread structure if it isn't joinable.
1213 * If it is, the structure is freed in g_thread_join()
1215 if (!thread->thread.joinable)
1220 for (t = g_thread_all_threads, p = NULL; t; p = t, t = t->next)
1227 g_thread_all_threads = t->next;
1231 G_UNLOCK (g_thread);
1233 /* Just to make sure, this isn't used any more */
1234 g_system_thread_assign (thread->system_thread, zero_thread);
1241 g_thread_create_proxy (gpointer data)
1243 GRealThread* thread = data;
1247 /* This has to happen before G_LOCK, as that might call g_thread_self */
1248 g_private_set (&g_thread_specific_private, data);
1250 /* The lock makes sure that thread->system_thread is written,
1251 * before thread->thread.func is called. See g_thread_create().
1254 G_UNLOCK (g_thread);
1256 thread->retval = thread->thread.func (thread->thread.data);
1263 * @func: a function to execute in the new thread
1264 * @data: an argument to supply to the new thread
1265 * @joinable: should this thread be joinable?
1266 * @error: return location for error, or %NULL
1268 * This function creates a new thread.
1270 * If @joinable is %TRUE, you can wait for this threads termination
1271 * calling g_thread_join(). Otherwise the thread will just disappear
1272 * when it terminates.
1274 * The new thread executes the function @func with the argument @data.
1275 * If the thread was created successfully, it is returned.
1277 * @error can be %NULL to ignore errors, or non-%NULL to report errors.
1278 * The error is set, if and only if the function returns %NULL.
1280 * Returns: the new #GThread on success
1283 g_thread_create (GThreadFunc func,
1288 return g_thread_create_with_stack_size (func, data, joinable, 0, error);
1292 * g_thread_create_with_stack_size:
1293 * @func: a function to execute in the new thread
1294 * @data: an argument to supply to the new thread
1295 * @joinable: should this thread be joinable?
1296 * @stack_size: a stack size for the new thread
1297 * @error: return location for error
1299 * This function creates a new thread. If the underlying thread
1300 * implementation supports it, the thread gets a stack size of
1301 * @stack_size or the default value for the current platform, if
1304 * If @joinable is %TRUE, you can wait for this threads termination
1305 * calling g_thread_join(). Otherwise the thread will just disappear
1306 * when it terminates.
1308 * The new thread executes the function @func with the argument @data.
1309 * If the thread was created successfully, it is returned.
1311 * @error can be %NULL to ignore errors, or non-%NULL to report errors.
1312 * The error is set, if and only if the function returns %NULL.
1314 * <note><para>Only use g_thread_create_with_stack_size() if you
1315 * really can't use g_thread_create() instead. g_thread_create()
1316 * does not take @stack_size, as it should only be used in cases
1317 * in which it is unavoidable.</para></note>
1319 * Returns: the new #GThread on success
1324 g_thread_create_with_stack_size (GThreadFunc func,
1330 GRealThread* result;
1331 GError *local_error = NULL;
1332 g_return_val_if_fail (func, NULL);
1334 result = g_new0 (GRealThread, 1);
1336 result->thread.joinable = joinable;
1337 result->thread.func = func;
1338 result->thread.data = data;
1339 result->private_data = NULL;
1341 g_system_thread_create (g_thread_create_proxy, result,
1342 stack_size, joinable,
1343 &result->system_thread, &local_error);
1346 result->next = g_thread_all_threads;
1347 g_thread_all_threads = result;
1349 G_UNLOCK (g_thread);
1353 g_propagate_error (error, local_error);
1358 return (GThread*) result;
1363 * @retval: the return value of this thread
1365 * Exits the current thread. If another thread is waiting for that
1366 * thread using g_thread_join() and the current thread is joinable, the
1367 * waiting thread will be woken up and get @retval as the return value
1368 * of g_thread_join(). If the current thread is not joinable, @retval
1369 * is ignored. Calling
1372 * g_thread_exit (retval);
1375 * is equivalent to returning @retval from the function @func, as given
1376 * to g_thread_create().
1378 * <note><para>Never call g_thread_exit() from within a thread of a
1379 * #GThreadPool, as that will mess up the bookkeeping and lead to funny
1380 * and unwanted results.</para></note>
1383 g_thread_exit (gpointer retval)
1385 GRealThread* real = (GRealThread*) g_thread_self ();
1386 real->retval = retval;
1388 g_system_thread_exit ();
1393 * @thread: a #GThread to be waited for
1395 * Waits until @thread finishes, i.e. the function @func, as given to
1396 * g_thread_create(), returns or g_thread_exit() is called by @thread.
1397 * All resources of @thread including the #GThread struct are released.
1398 * @thread must have been created with @joinable=%TRUE in
1399 * g_thread_create(). The value returned by @func or given to
1400 * g_thread_exit() by @thread is returned by this function.
1402 * Returns: the return value of the thread
1405 g_thread_join (GThread* thread)
1407 GRealThread* real = (GRealThread*) thread;
1411 g_return_val_if_fail (thread, NULL);
1412 g_return_val_if_fail (thread->joinable, NULL);
1413 g_return_val_if_fail (!g_system_thread_equal (&real->system_thread, &zero_thread), NULL);
1415 g_system_thread_join (&real->system_thread);
1417 retval = real->retval;
1420 for (t = g_thread_all_threads, p = NULL; t; p = t, t = t->next)
1422 if (t == (GRealThread*) thread)
1427 g_thread_all_threads = t->next;
1431 G_UNLOCK (g_thread);
1433 /* Just to make sure, this isn't used any more */
1434 thread->joinable = 0;
1435 g_system_thread_assign (real->system_thread, zero_thread);
1437 /* the thread structure for non-joinable threads is freed upon
1438 * thread end. We free the memory here. This will leave a loose end,
1439 * if a joinable thread is not joined.
1449 * This functions returns the #GThread corresponding to the calling
1452 * Returns: the current thread
1455 g_thread_self (void)
1457 GRealThread* thread = g_private_get (&g_thread_specific_private);
1461 /* If no thread data is available, provide and set one.
1462 * This can happen for the main thread and for threads
1463 * that are not created by GLib.
1465 thread = g_new0 (GRealThread, 1);
1466 thread->thread.joinable = FALSE; /* This is a safe guess */
1467 thread->thread.func = NULL;
1468 thread->thread.data = NULL;
1469 thread->private_data = NULL;
1471 g_system_thread_self (&thread->system_thread);
1473 g_private_set (&g_thread_specific_private, thread);
1476 thread->next = g_thread_all_threads;
1477 g_thread_all_threads = thread;
1478 G_UNLOCK (g_thread);
1481 return (GThread*)thread;
1486 * @thread_func: function to call for all #GThread structures
1487 * @user_data: second argument to @thread_func
1489 * Call @thread_func on all existing #GThread structures.
1490 * Note that threads may decide to exit while @thread_func is
1491 * running, so without intimate knowledge about the lifetime of
1492 * foreign threads, @thread_func shouldn't access the GThread*
1493 * pointer passed in as first argument. However, @thread_func will
1494 * not be called for threads which are known to have exited already.
1496 * Due to thread lifetime checks, this function has an execution complexity
1497 * which is quadratic in the number of existing threads.
1502 g_thread_foreach (GFunc thread_func,
1505 GSList *slist = NULL;
1506 GRealThread *thread;
1507 g_return_if_fail (thread_func != NULL);
1508 /* snapshot the list of threads for iteration */
1510 for (thread = g_thread_all_threads; thread; thread = thread->next)
1511 slist = g_slist_prepend (slist, thread);
1512 G_UNLOCK (g_thread);
1513 /* walk the list, skipping non-existent threads */
1516 GSList *node = slist;
1518 /* check whether the current thread still exists */
1520 for (thread = g_thread_all_threads; thread; thread = thread->next)
1521 if (thread == node->data)
1523 G_UNLOCK (g_thread);
1525 thread_func (thread, user_data);
1526 g_slist_free_1 (node);
1530 /* GMutex {{{1 ------------------------------------------------------ */
1535 * Allocated and initializes a new #GMutex.
1537 * Returns: a newly allocated #GMutex. Use g_mutex_free() to free
1544 mutex = g_slice_new (GMutex);
1545 g_mutex_init (mutex);
1554 * Destroys a @mutex that has been created with g_mutex_new().
1556 * Calling g_mutex_free() on a locked mutex may result
1557 * in undefined behaviour.
1560 g_mutex_free (GMutex *mutex)
1562 g_mutex_clear (mutex);
1563 g_slice_free (GMutex, mutex);
1566 /* GCond {{{1 ------------------------------------------------------ */
1571 * Allocates and initializes a new #GCond.
1573 * Returns: a newly allocated #GCond. Free with g_cond_free()
1580 cond = g_slice_new (GCond);
1590 * Destroys a #GCond that has been created with g_cond_new().
1593 g_cond_free (GCond *cond)
1595 g_cond_clear (cond);
1596 g_slice_free (GCond, cond);
1599 /* GPrivate {{{1 ------------------------------------------------------ */
1603 * @destructor: a function to destroy the data keyed to
1604 * the #GPrivate when a thread ends
1606 * Creates a new #GPrivate. If @destructor is non-%NULL, it is a
1607 * pointer to a destructor function. Whenever a thread ends and the
1608 * corresponding pointer keyed to this instance of #GPrivate is
1609 * non-%NULL, the destructor is called with this pointer as the
1613 * #GStaticPrivate is a better choice for most uses.
1616 * <note><para>@destructor is used quite differently from @notify in
1617 * g_static_private_set().</para></note>
1619 * <note><para>A #GPrivate cannot be freed. Reuse it instead, if you
1620 * can, to avoid shortage, or use #GStaticPrivate.</para></note>
1622 * <note><para>This function will abort if g_thread_init() has not been
1623 * called yet.</para></note>
1625 * Returns: a newly allocated #GPrivate
1628 g_private_new (GDestroyNotify notify)
1632 key = g_slice_new (GPrivate);
1633 g_private_init (key, notify);
1638 /* vim: set foldmethod=marker: */