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"
57 #endif /* G_OS_WIN32 */
60 #include "gtestutils.h"
65 * @short_description: portable support for threads, mutexes, locks,
66 * conditions and thread private data
67 * @see_also: #GThreadPool, #GAsyncQueue
69 * Threads act almost like processes, but unlike processes all threads
70 * of one process share the same memory. This is good, as it provides
71 * easy communication between the involved threads via this shared
72 * memory, and it is bad, because strange things (so called
73 * "Heisenbugs") might happen if the program is not carefully designed.
74 * In particular, due to the concurrent nature of threads, no
75 * assumptions on the order of execution of code running in different
76 * threads can be made, unless order is explicitly forced by the
77 * programmer through synchronization primitives.
79 * The aim of the thread-related functions in GLib is to provide a
80 * portable means for writing multi-threaded software. There are
81 * primitives for mutexes to protect the access to portions of memory
82 * (#GMutex, #GRecMutex and #GRWLock). There is a facility to use
83 * individual bits for locks (g_bit_lock()). There are primitives
84 * for condition variables to allow synchronization of threads (#GCond).
85 * There are primitives for thread-private data - data that every thread
86 * has a private instance of (#GPrivate). There are
87 * facilities for one-time initialization (#GOnce, g_once_init_enter()).
88 * Finally there are primitives to create and manage threads (#GThread).
90 * The GLib threading system used to be initialized with g_thread_init().
91 * This is no longer necessary. Since version 2.32, the GLib threading
92 * system is automatically initialized at the start of your program,
93 * and all thread-creation functions and synchronization primitives
94 * are available right away. It is still possible to do thread-unsafe
95 * initialization and setup at the beginning of your program, before
96 * creating the first threads.
98 * GLib is internally completely thread-safe (all global data is
99 * automatically locked), but individual data structure instances are
100 * not automatically locked for performance reasons. For example,
101 * you must coordinate accesses to the same #GHashTable from multiple
102 * threads. The two notable exceptions from this rule are #GMainLoop
103 * and #GAsyncQueue, which <emphasis>are</emphasis> thread-safe and
104 * need no further application-level locking to be accessed from
105 * multiple threads. Most refcounting functions such as g_object_ref()
106 * are also thread-safe.
109 /* G_LOCK Documentation {{{1 ---------------------------------------------- */
113 * @name: the name of the lock
115 * The %G_LOCK_* macros provide a convenient interface to #GMutex.
116 * #G_LOCK_DEFINE defines a lock. It can appear in any place where
117 * variable definitions may appear in programs, i.e. in the first block
118 * of a function or outside of functions. The @name parameter will be
119 * mangled to get the name of the #GMutex. This means that you
120 * can use names of existing variables as the parameter - e.g. the name
121 * of the variable you intend to protect with the lock. Look at our
122 * <function>give_me_next_number()</function> example using the
126 * <title>Using the %G_LOCK_* convenience macros</title>
128 * G_LOCK_DEFINE (current_number);
131 * give_me_next_number (void)
133 * static int current_number = 0;
136 * G_LOCK (current_number);
137 * ret_val = current_number = calc_next_number (current_number);
138 * G_UNLOCK (current_number);
147 * G_LOCK_DEFINE_STATIC:
148 * @name: the name of the lock
150 * This works like #G_LOCK_DEFINE, but it creates a static object.
155 * @name: the name of the lock
157 * This declares a lock, that is defined with #G_LOCK_DEFINE in another
163 * @name: the name of the lock
165 * Works like g_mutex_lock(), but for a lock defined with
171 * @name: the name of the lock
172 * @Returns: %TRUE, if the lock could be locked.
174 * Works like g_mutex_trylock(), but for a lock defined with
180 * @name: the name of the lock
182 * Works like g_mutex_unlock(), but for a lock defined with
186 /* GMutex Documentation {{{1 ------------------------------------------ */
191 * The #GMutex struct is an opaque data structure to represent a mutex
192 * (mutual exclusion). It can be used to protect data against shared
193 * access. Take for example the following function:
196 * <title>A function which will not work in a threaded environment</title>
199 * give_me_next_number (void)
201 * static int current_number = 0;
203 * /<!-- -->* now do a very complicated calculation to calculate the new
204 * * number, this might for example be a random number generator
206 * current_number = calc_next_number (current_number);
208 * return current_number;
213 * It is easy to see that this won't work in a multi-threaded
214 * application. There current_number must be protected against shared
215 * access. A #GMutex can be used as a solution to this problem:
218 * <title>Using GMutex to protected a shared variable</title>
221 * give_me_next_number (void)
223 * static GMutex mutex;
224 * static int current_number = 0;
227 * g_mutex_lock (&mutex);
228 * ret_val = current_number = calc_next_number (current_number);
229 * g_mutex_unlock (&mutex);
236 * Notice that the #GMutex is not initialised to any particular value.
237 * Its placement in static storage ensures that it will be initialised
238 * to all-zeros, which is appropriate.
240 * If a #GMutex is placed in other contexts (eg: embedded in a struct)
241 * then it must be explicitly initialised using g_mutex_init().
243 * A #GMutex should only be accessed via <function>g_mutex_</function>
247 /* GRecMutex Documentation {{{1 -------------------------------------- */
252 * The GRecMutex struct is an opaque data structure to represent a
253 * recursive mutex. It is similar to a #GMutex with the difference
254 * that it is possible to lock a GRecMutex multiple times in the same
255 * thread without deadlock. When doing so, care has to be taken to
256 * unlock the recursive mutex as often as it has been locked.
258 * If a #GRecMutex is allocated in static storage then it can be used
259 * without initialisation. Otherwise, you should call
260 * g_rec_mutex_init() on it and g_rec_mutex_clear() when done.
262 * A GRecMutex should only be accessed with the
263 * <function>g_rec_mutex_</function> functions.
268 /* GRWLock Documentation {{{1 ---------------------------------------- */
273 * The GRWLock struct is an opaque data structure to represent a
274 * reader-writer lock. It is similar to a #GMutex in that it allows
275 * multiple threads to coordinate access to a shared resource.
277 * The difference to a mutex is that a reader-writer lock discriminates
278 * between read-only ('reader') and full ('writer') access. While only
279 * one thread at a time is allowed write access (by holding the 'writer'
280 * lock via g_rw_lock_writer_lock()), multiple threads can gain
281 * simultaneous read-only access (by holding the 'reader' lock via
282 * g_rw_lock_reader_lock()).
285 * <title>An array with access functions</title>
291 * my_array_get (guint index)
293 * gpointer retval = NULL;
298 * g_rw_lock_reader_lock (&lock);
299 * if (index < array->len)
300 * retval = g_ptr_array_index (array, index);
301 * g_rw_lock_reader_unlock (&lock);
307 * my_array_set (guint index, gpointer data)
309 * g_rw_lock_writer_lock (&lock);
312 * array = g_ptr_array_new (<!-- -->);
314 * if (index >= array->len)
315 * g_ptr_array_set_size (array, index+1);
316 * g_ptr_array_index (array, index) = data;
318 * g_rw_lock_writer_unlock (&lock);
322 * This example shows an array which can be accessed by many readers
323 * (the <function>my_array_get()</function> function) simultaneously,
324 * whereas the writers (the <function>my_array_set()</function>
325 * function) will only be allowed once at a time and only if no readers
326 * currently access the array. This is because of the potentially
327 * dangerous resizing of the array. Using these functions is fully
328 * multi-thread safe now.
332 * If a #GRWLock is allocated in static storage then it can be used
333 * without initialisation. Otherwise, you should call
334 * g_rw_lock_init() on it and g_rw_lock_clear() when done.
336 * A GRWLock should only be accessed with the
337 * <function>g_rw_lock_</function> functions.
342 /* GCond Documentation {{{1 ------------------------------------------ */
347 * The #GCond struct is an opaque data structure that represents a
348 * condition. Threads can block on a #GCond if they find a certain
349 * condition to be false. If other threads change the state of this
350 * condition they signal the #GCond, and that causes the waiting
351 * threads to be woken up.
355 * Using GCond to block a thread until a condition is satisfied
358 * GCond* data_cond = NULL; /<!-- -->* Must be initialized somewhere *<!-- -->/
359 * GMutex* data_mutex = NULL; /<!-- -->* Must be initialized somewhere *<!-- -->/
360 * gpointer current_data = NULL;
363 * push_data (gpointer data)
365 * g_mutex_lock (data_mutex);
366 * current_data = data;
367 * g_cond_signal (data_cond);
368 * g_mutex_unlock (data_mutex);
376 * g_mutex_lock (data_mutex);
377 * while (!current_data)
378 * g_cond_wait (data_cond, data_mutex);
379 * data = current_data;
380 * current_data = NULL;
381 * g_mutex_unlock (data_mutex);
388 * Whenever a thread calls pop_data() now, it will wait until
389 * current_data is non-%NULL, i.e. until some other thread
390 * has called push_data().
392 * <note><para>It is important to use the g_cond_wait() and
393 * g_cond_timed_wait() functions only inside a loop which checks for the
394 * condition to be true. It is not guaranteed that the waiting thread
395 * will find the condition fulfilled after it wakes up, even if the
396 * signaling thread left the condition in that state: another thread may
397 * have altered the condition before the waiting thread got the chance
398 * to be woken up, even if the condition itself is protected by a
399 * #GMutex, like above.</para></note>
401 * If a #GCond is allocated in static storage then it can be used
402 * without initialisation. Otherwise, you should call g_cond_init() on
403 * it and g_cond_clear() when done.
405 * A #GCond should only be accessed via the <function>g_cond_</function>
409 /* GThread Documentation {{{1 ---------------------------------------- */
414 * The #GThread struct represents a running thread. This struct
415 * is returned by g_thread_new() or g_thread_new_full(). You can
416 * obtain the #GThread struct representing the current thead by
417 * calling g_thread_self().
419 * The structure is opaque -- none of its fields may be directly
425 * @data: data passed to the thread
427 * Specifies the type of the @func functions passed to
428 * g_thread_new() or g_thread_new_full().
430 * If the thread is joinable, the return value of this function
431 * is returned by a g_thread_join() call waiting for the thread.
432 * If the thread is not joinable, the return value is ignored.
434 * Returns: the return value of the thread
438 * g_thread_supported:
440 * This macro returns %TRUE if the thread system is initialized,
441 * and %FALSE if it is not.
443 * For language bindings, g_thread_get_initialized() provides
444 * the same functionality as a function.
446 * Returns: %TRUE, if the thread system is initialized
449 /* GThreadError {{{1 ------------------------------------------------------- */
452 * @G_THREAD_ERROR_AGAIN: a thread couldn't be created due to resource
453 * shortage. Try again later.
455 * Possible errors of thread related functions.
461 * The error domain of the GLib thread subsystem.
464 g_thread_error_quark (void)
466 return g_quark_from_static_string ("g_thread_error");
469 /* Local Data {{{1 -------------------------------------------------------- */
472 static GCond g_once_cond;
473 static GSList *g_once_init_list = NULL;
475 static void g_thread_cleanup (gpointer data);
476 static GPrivate g_thread_specific_private = G_PRIVATE_INIT (g_thread_cleanup);
478 G_LOCK_DEFINE_STATIC (g_thread_new);
480 /* GOnce {{{1 ------------------------------------------------------------- */
484 * @status: the status of the #GOnce
485 * @retval: the value returned by the call to the function, if @status
486 * is %G_ONCE_STATUS_READY
488 * A #GOnce struct controls a one-time initialization function. Any
489 * one-time initialization function must have its own unique #GOnce
498 * A #GOnce must be initialized with this macro before it can be used.
501 * GOnce my_once = G_ONCE_INIT;
509 * @G_ONCE_STATUS_NOTCALLED: the function has not been called yet.
510 * @G_ONCE_STATUS_PROGRESS: the function call is currently in progress.
511 * @G_ONCE_STATUS_READY: the function has been called.
513 * The possible statuses of a one-time initialization function
514 * controlled by a #GOnce struct.
521 * @once: a #GOnce structure
522 * @func: the #GThreadFunc function associated to @once. This function
523 * is called only once, regardless of the number of times it and
524 * its associated #GOnce struct are passed to g_once().
525 * @arg: data to be passed to @func
527 * The first call to this routine by a process with a given #GOnce
528 * struct calls @func with the given argument. Thereafter, subsequent
529 * calls to g_once() with the same #GOnce struct do not call @func
530 * again, but return the stored result of the first call. On return
531 * from g_once(), the status of @once will be %G_ONCE_STATUS_READY.
533 * For example, a mutex or a thread-specific data key must be created
534 * exactly once. In a threaded environment, calling g_once() ensures
535 * that the initialization is serialized across multiple threads.
537 * Calling g_once() recursively on the same #GOnce struct in
538 * @func will lead to a deadlock.
542 * get_debug_flags (void)
544 * static GOnce my_once = G_ONCE_INIT;
546 * g_once (&my_once, parse_debug_flags, NULL);
548 * return my_once.retval;
555 g_once_impl (GOnce *once,
559 g_mutex_lock (&g_once_mutex);
561 while (once->status == G_ONCE_STATUS_PROGRESS)
562 g_cond_wait (&g_once_cond, &g_once_mutex);
564 if (once->status != G_ONCE_STATUS_READY)
566 once->status = G_ONCE_STATUS_PROGRESS;
567 g_mutex_unlock (&g_once_mutex);
569 once->retval = func (arg);
571 g_mutex_lock (&g_once_mutex);
572 once->status = G_ONCE_STATUS_READY;
573 g_cond_broadcast (&g_once_cond);
576 g_mutex_unlock (&g_once_mutex);
583 * @value_location: location of a static initializable variable
586 * Function to be called when starting a critical initialization
587 * section. The argument @value_location must point to a static
588 * 0-initialized variable that will be set to a value other than 0 at
589 * the end of the initialization section. In combination with
590 * g_once_init_leave() and the unique address @value_location, it can
591 * be ensured that an initialization section will be executed only once
592 * during a program's life time, and that concurrent threads are
593 * blocked until initialization completed. To be used in constructs
597 * static gsize initialization_value = 0;
599 * if (g_once_init_enter (&initialization_value))
601 * gsize setup_value = 42; /** initialization code here **/
603 * g_once_init_leave (&initialization_value, setup_value);
606 * /** use initialization_value here **/
609 * Returns: %TRUE if the initialization section should be entered,
610 * %FALSE and blocks otherwise
615 (g_once_init_enter) (volatile void *pointer)
617 volatile gsize *value_location = pointer;
618 gboolean need_init = FALSE;
619 g_mutex_lock (&g_once_mutex);
620 if (g_atomic_pointer_get (value_location) == NULL)
622 if (!g_slist_find (g_once_init_list, (void*) value_location))
625 g_once_init_list = g_slist_prepend (g_once_init_list, (void*) value_location);
629 g_cond_wait (&g_once_cond, &g_once_mutex);
630 while (g_slist_find (g_once_init_list, (void*) value_location));
632 g_mutex_unlock (&g_once_mutex);
638 * @value_location: location of a static initializable variable
640 * @result: new non-0 value for *@value_location
642 * Counterpart to g_once_init_enter(). Expects a location of a static
643 * 0-initialized initialization variable, and an initialization value
644 * other than 0. Sets the variable to the initialization value, and
645 * releases concurrent threads blocking in g_once_init_enter() on this
646 * initialization variable.
651 (g_once_init_leave) (volatile void *pointer,
654 volatile gsize *value_location = pointer;
656 g_return_if_fail (g_atomic_pointer_get (value_location) == NULL);
657 g_return_if_fail (result != 0);
658 g_return_if_fail (g_once_init_list != NULL);
660 g_atomic_pointer_set (value_location, result);
661 g_mutex_lock (&g_once_mutex);
662 g_once_init_list = g_slist_remove (g_once_init_list, (void*) value_location);
663 g_cond_broadcast (&g_once_cond);
664 g_mutex_unlock (&g_once_mutex);
667 /* GThread {{{1 -------------------------------------------------------- */
670 g_thread_cleanup (gpointer data)
674 GRealThread* thread = data;
676 g_static_private_cleanup (thread);
678 /* We only free the thread structure if it isn't joinable.
679 * If it is, the structure is freed in g_thread_join()
681 if (!thread->thread.joinable)
683 if (thread->enumerable)
684 g_enumerable_thread_remove (thread);
686 /* Just to make sure, this isn't used any more */
687 g_system_thread_assign (thread->system_thread, zero_thread);
694 g_thread_create_proxy (gpointer data)
696 GRealThread* thread = data;
701 g_system_thread_set_name (thread->name);
703 /* This has to happen before G_LOCK, as that might call g_thread_self */
704 g_private_set (&g_thread_specific_private, data);
706 /* The lock makes sure that thread->system_thread is written,
707 * before thread->thread.func is called. See g_thread_new_internal().
709 G_LOCK (g_thread_new);
710 G_UNLOCK (g_thread_new);
712 thread->retval = thread->thread.func (thread->thread.data);
719 * @name: a name for the new thread
720 * @func: a function to execute in the new thread
721 * @data: an argument to supply to the new thread
722 * @joinable: should this thread be joinable?
723 * @error: return location for error
725 * This function creates a new thread. The new thread starts by invoking
726 * @func with the argument data. The thread will run until @func returns
727 * or until g_thread_exit() is called from the new thread.
729 * The @name can be useful for discriminating threads in
730 * a debugger. Some systems restrict the length of @name to
733 * If @joinable is %TRUE, you can wait for this thread's termination
734 * calling g_thread_join(). Resources for a joinable thread are not
735 * fully released until g_thread_join() is called for that thread.
736 * Otherwise the thread will just disappear when it terminates.
738 * @error can be %NULL to ignore errors, or non-%NULL to report errors.
739 * The error is set, if and only if the function returns %NULL.
741 * Returns: the new #GThread, or %NULL if an error occurred
746 g_thread_new (const gchar *name,
752 return g_thread_new_internal (name, func, data, joinable, 0, FALSE, error);
757 * @name: a name for the new thread
758 * @func: a function to execute in the new thread
759 * @data: an argument to supply to the new thread
760 * @joinable: should this thread be joinable?
761 * @stack_size: a stack size for the new thread
762 * @error: return location for error
764 * This function creates a new thread. The new thread starts by
765 * invoking @func with the argument data. The thread will run
766 * until @func returns or until g_thread_exit() is called.
768 * The @name can be useful for discriminating threads in
769 * a debugger. Some systems restrict the length of @name to
772 * If the underlying thread implementation supports it, the thread
773 * gets a stack size of @stack_size or the default value for the
774 * current platform, if @stack_size is 0. Note that you should only
775 * use a non-zero @stack_size if you really can't use the default.
776 * In most cases, using g_thread_new() (which doesn't take a
777 * @stack_size) is better.
779 * If @joinable is %TRUE, you can wait for this thread's termination
780 * calling g_thread_join(). Resources for a joinable thread are not
781 * fully released until g_thread_join() is called for that thread.
782 * Otherwise the thread will just disappear when it terminates.
784 * @error can be %NULL to ignore errors, or non-%NULL to report errors.
785 * The error is set, if and only if the function returns %NULL.
787 * Returns: the new #GThread, or %NULL if an error occurred
792 g_thread_new_full (const gchar *name,
799 return g_thread_new_internal (name, func, data, joinable, stack_size, FALSE, error);
803 g_thread_new_internal (const gchar *name,
812 GError *local_error = NULL;
814 g_return_val_if_fail (func != NULL, NULL);
816 result = g_new0 (GRealThread, 1);
818 result->thread.joinable = joinable;
819 result->thread.func = func;
820 result->thread.data = data;
821 result->private_data = NULL;
822 result->enumerable = enumerable;
824 G_LOCK (g_thread_new);
825 g_system_thread_create (g_thread_create_proxy, result,
826 stack_size, joinable,
827 &result->system_thread, &local_error);
828 if (enumerable && !local_error)
829 g_enumerable_thread_add (result);
830 G_UNLOCK (g_thread_new);
834 g_propagate_error (error, local_error);
839 return (GThread*) result;
844 * @retval: the return value of this thread
846 * Terminates the current thread.
848 * If another thread is waiting for that thread using g_thread_join()
849 * and the current thread is joinable, the waiting thread will be woken
850 * up and get @retval as the return value of g_thread_join(). If the
851 * current thread is not joinable, @retval is ignored.
853 * Calling <literal>g_thread_exit (retval)</literal> is equivalent to
854 * returning @retval from the function @func, as given to g_thread_new().
856 * <note><para>Never call g_thread_exit() from within a thread of a
857 * #GThreadPool, as that will mess up the bookkeeping and lead to funny
858 * and unwanted results.</para></note>
861 g_thread_exit (gpointer retval)
863 GRealThread* real = (GRealThread*) g_thread_self ();
864 real->retval = retval;
866 g_system_thread_exit ();
871 * @thread: a joinable #GThread
873 * Waits until @thread finishes, i.e. the function @func, as
874 * given to g_thread_new(), returns or g_thread_exit() is called.
875 * If @thread has already terminated, then g_thread_join()
876 * returns immediately. @thread must be joinable.
878 * Any thread can wait for any other (joinable) thread by calling
879 * g_thread_join(), not just its 'creator'. Calling g_thread_join()
880 * from multiple threads for the same @thread leads to undefined
883 * The value returned by @func or given to g_thread_exit() is
884 * returned by this function.
886 * All resources of @thread including the #GThread struct are
887 * released before g_thread_join() returns.
889 * Returns: the return value of the thread
892 g_thread_join (GThread *thread)
894 GRealThread *real = (GRealThread*) thread;
897 g_return_val_if_fail (thread, NULL);
898 g_return_val_if_fail (thread->joinable, NULL);
899 g_return_val_if_fail (!g_system_thread_equal (&real->system_thread, &zero_thread), NULL);
901 g_system_thread_join (&real->system_thread);
903 retval = real->retval;
905 if (real->enumerable)
906 g_enumerable_thread_remove (real);
908 /* Just to make sure, this isn't used any more */
909 thread->joinable = 0;
910 g_system_thread_assign (real->system_thread, zero_thread);
912 /* the thread structure for non-joinable threads is freed upon
913 * thread end. We free the memory here. This will leave a loose end,
914 * if a joinable thread is not joined.
924 * This functions returns the #GThread corresponding to the
927 * Returns: the #GThread representing the current thread
932 GRealThread* thread = g_private_get (&g_thread_specific_private);
936 /* If no thread data is available, provide and set one.
937 * This can happen for the main thread and for threads
938 * that are not created by GLib.
940 thread = g_new0 (GRealThread, 1);
941 thread->thread.joinable = FALSE; /* This is a safe guess */
942 thread->thread.func = NULL;
943 thread->thread.data = NULL;
944 thread->private_data = NULL;
945 thread->enumerable = FALSE;
947 g_system_thread_self (&thread->system_thread);
949 g_private_set (&g_thread_specific_private, thread);
952 return (GThread*)thread;
956 /* vim: set foldmethod=marker: */