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: thread abstraction; including threads, different
71 * mutexes, 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, #GStaticMutex, #G_LOCK_DEFINE, #GStaticRecMutex and
88 * #GStaticRWLock). There is a facility to use individual bits for
89 * locks (g_bit_lock()). There are primitives for condition variables to
90 * allow synchronization of threads (#GCond). There are primitives for
91 * thread-private data - data that every thread has a private instance
92 * of (#GPrivate, #GStaticPrivate). There are facilities for one-time
93 * initialization (#GOnce, g_once_init_enter()). Last but definitely
94 * not least there are primitives to portably create and manage
97 * The threading system is initialized with g_thread_init(), which
98 * takes an optional custom thread implementation or %NULL for the
99 * default implementation. If you want to call g_thread_init() with a
100 * non-%NULL argument this must be done before executing any other GLib
101 * functions (except g_mem_set_vtable()). This is a requirement even if
102 * no threads are in fact ever created by the process.
104 * Calling g_thread_init() with a %NULL argument is somewhat more
105 * relaxed. You may call any other glib functions in the main thread
106 * before g_thread_init() as long as g_thread_init() is not called from
107 * a glib callback, or with any locks held. However, many libraries
108 * above glib does not support late initialization of threads, so doing
109 * this should be avoided if possible.
111 * Please note that since version 2.24 the GObject initialization
112 * function g_type_init() initializes threads (with a %NULL argument),
113 * so most applications, including those using Gtk+ will run with
114 * threads enabled. If you want a special thread implementation, make
115 * sure you call g_thread_init() before g_type_init() is called.
117 * After calling g_thread_init(), GLib is completely thread safe (all
118 * global data is automatically locked), but individual data structure
119 * instances are not automatically locked for performance reasons. So,
120 * for example you must coordinate accesses to the same #GHashTable
121 * from multiple threads. The two notable exceptions from this rule
122 * are #GMainLoop and #GAsyncQueue, which <emphasis>are</emphasis>
123 * threadsafe and need no further application-level locking to be
124 * accessed from multiple threads.
126 * To help debugging problems in multithreaded applications, GLib
127 * supports error-checking mutexes that will give you helpful error
128 * messages on common problems. To use error-checking mutexes, define
129 * the symbol #G_ERRORCHECK_MUTEXES when compiling the application.
133 * G_THREADS_IMPL_POSIX:
135 * This macro is defined if POSIX style threads are used.
141 * This macro is defined, for backward compatibility, to indicate that
142 * GLib has been compiled with thread support. As of glib 2.28, it is
147 * G_THREADS_IMPL_NONE:
149 * This macro is defined if no thread implementation is used. You can,
150 * however, provide one to g_thread_init() to make GLib multi-thread
154 /* G_LOCK Documentation {{{1 ---------------------------------------------- */
156 /* IMPLEMENTATION NOTE:
158 * G_LOCK_DEFINE and friends are convenience macros defined in
159 * gthread.h. Their documentation lives here.
164 * @name: the name of the lock.
166 * The %G_LOCK_* macros provide a convenient interface to #GStaticMutex
167 * with the advantage that they will expand to nothing in programs
168 * compiled against a thread-disabled GLib, saving code and memory
169 * there. #G_LOCK_DEFINE defines a lock. It can appear anywhere
170 * variable definitions may appear in programs, i.e. in the first block
171 * of a function or outside of functions. The @name parameter will be
172 * mangled to get the name of the #GStaticMutex. This means that you
173 * can use names of existing variables as the parameter - e.g. the name
174 * of the variable you intent to protect with the lock. Look at our
175 * <function>give_me_next_number()</function> example using the
179 * <title>Using the %G_LOCK_* convenience macros</title>
181 * G_LOCK_DEFINE (current_number);
184 * give_me_next_number (void)
186 * static int current_number = 0;
189 * G_LOCK (current_number);
190 * ret_val = current_number = calc_next_number (current_number);
191 * G_UNLOCK (current_number);
200 * G_LOCK_DEFINE_STATIC:
201 * @name: the name of the lock.
203 * This works like #G_LOCK_DEFINE, but it creates a static object.
208 * @name: the name of the lock.
210 * This declares a lock, that is defined with #G_LOCK_DEFINE in another
216 * @name: the name of the lock.
218 * Works like g_mutex_lock(), but for a lock defined with
224 * @name: the name of the lock.
225 * @Returns: %TRUE, if the lock could be locked.
227 * Works like g_mutex_trylock(), but for a lock defined with
233 * @name: the name of the lock.
235 * Works like g_mutex_unlock(), but for a lock defined with
239 /* GThreadError {{{1 ------------------------------------------------------- */
242 * @G_THREAD_ERROR_AGAIN: a thread couldn't be created due to resource
243 * shortage. Try again later.
245 * Possible errors of thread related functions.
251 * The error domain of the GLib thread subsystem.
254 g_thread_error_quark (void)
256 return g_quark_from_static_string ("g_thread_error");
259 /* Miscellaneous Structures {{{1 ------------------------------------------ */
260 typedef struct _GRealThread GRealThread;
264 /* Bit 0 protects private_data. To avoid deadlocks, do not block while
265 * holding this (particularly on the g_thread lock). */
266 volatile gint private_data_lock;
267 GArray *private_data;
270 GSystemThread system_thread;
273 #define LOCK_PRIVATE_DATA(self) g_bit_lock (&(self)->private_data_lock, 0)
274 #define UNLOCK_PRIVATE_DATA(self) g_bit_unlock (&(self)->private_data_lock, 0)
276 typedef struct _GStaticPrivateNode GStaticPrivateNode;
277 struct _GStaticPrivateNode
280 GDestroyNotify destroy;
283 static void g_thread_cleanup (gpointer data);
284 static guint64 gettime (void);
286 guint64 (*g_thread_gettime) (void) = gettime;
288 /* Global Variables {{{1 -------------------------------------------------- */
290 static GSystemThread zero_thread; /* This is initialized to all zero */
291 gboolean g_thread_use_default_impl = TRUE;
294 * g_thread_supported:
295 * @Returns: %TRUE, if the thread system is initialized.
297 * This function returns %TRUE if the thread system is initialized, and
298 * %FALSE if it is not.
300 * <note><para>This function is actually a macro. Apart from taking the
301 * address of it you can however use it as if it was a
302 * function.</para></note>
305 /* IMPLEMENTATION NOTE:
307 * g_thread_supported() is just returns g_threads_got_initialized
309 gboolean g_threads_got_initialized = FALSE;
312 /* Thread Implementation Virtual Function Table {{{1 ---------------------- */
313 /* Virtual Function Table Documentation {{{2 ------------------------------ */
316 * @mutex_new: virtual function pointer for g_mutex_new()
317 * @mutex_lock: virtual function pointer for g_mutex_lock()
318 * @mutex_trylock: virtual function pointer for g_mutex_trylock()
319 * @mutex_unlock: virtual function pointer for g_mutex_unlock()
320 * @mutex_free: virtual function pointer for g_mutex_free()
321 * @cond_new: virtual function pointer for g_cond_new()
322 * @cond_signal: virtual function pointer for g_cond_signal()
323 * @cond_broadcast: virtual function pointer for g_cond_broadcast()
324 * @cond_wait: virtual function pointer for g_cond_wait()
325 * @cond_timed_wait: virtual function pointer for g_cond_timed_wait()
326 * @cond_free: virtual function pointer for g_cond_free()
327 * @private_new: virtual function pointer for g_private_new()
328 * @private_get: virtual function pointer for g_private_get()
329 * @private_set: virtual function pointer for g_private_set()
330 * @thread_create: virtual function pointer for g_thread_create()
331 * @thread_yield: virtual function pointer for g_thread_yield()
332 * @thread_join: virtual function pointer for g_thread_join()
333 * @thread_exit: virtual function pointer for g_thread_exit()
334 * @thread_set_priority: virtual function pointer for
335 * g_thread_set_priority()
336 * @thread_self: virtual function pointer for g_thread_self()
337 * @thread_equal: used internally by recursive mutex locks and by some
340 * This function table is used by g_thread_init() to initialize the
341 * thread system. The functions in the table are directly used by their
342 * g_* prepended counterparts (described in this document). For
343 * example, if you call g_mutex_new() then mutex_new() from the table
344 * provided to g_thread_init() will be called.
346 * <note><para>Do not use this struct unless you know what you are
347 * doing.</para></note>
350 /* GMutex Virtual Functions {{{2 ------------------------------------------ */
355 * The #GMutex struct is an opaque data structure to represent a mutex
356 * (mutual exclusion). It can be used to protect data against shared
357 * access. Take for example the following function:
360 * <title>A function which will not work in a threaded environment</title>
363 * give_me_next_number (void)
365 * static int current_number = 0;
367 * /<!-- -->* now do a very complicated calculation to calculate the new
368 * * number, this might for example be a random number generator
370 * current_number = calc_next_number (current_number);
372 * return current_number;
377 * It is easy to see that this won't work in a multi-threaded
378 * application. There current_number must be protected against shared
379 * access. A first naive implementation would be:
382 * <title>The wrong way to write a thread-safe function</title>
385 * give_me_next_number (void)
387 * static int current_number = 0;
389 * static GMutex * mutex = NULL;
391 * if (!mutex) mutex = g_mutex_new (<!-- -->);
393 * g_mutex_lock (mutex);
394 * ret_val = current_number = calc_next_number (current_number);
395 * g_mutex_unlock (mutex);
402 * This looks like it would work, but there is a race condition while
403 * constructing the mutex and this code cannot work reliable. Please do
404 * not use such constructs in your own programs! One working solution
408 * <title>A correct thread-safe function</title>
410 * static GMutex *give_me_next_number_mutex = NULL;
412 * /<!-- -->* this function must be called before any call to
413 * * give_me_next_number(<!-- -->)
415 * * it must be called exactly once.
418 * init_give_me_next_number (void)
420 * g_assert (give_me_next_number_mutex == NULL);
421 * give_me_next_number_mutex = g_mutex_new (<!-- -->);
425 * give_me_next_number (void)
427 * static int current_number = 0;
430 * g_mutex_lock (give_me_next_number_mutex);
431 * ret_val = current_number = calc_next_number (current_number);
432 * g_mutex_unlock (give_me_next_number_mutex);
439 * #GStaticMutex provides a simpler and safer way of doing this.
441 * If you want to use a mutex, and your code should also work without
442 * calling g_thread_init() first, then you cannot use a #GMutex, as
443 * g_mutex_new() requires that the thread system be initialized. Use a
444 * #GStaticMutex instead.
446 * A #GMutex should only be accessed via the following functions.
449 /* GCond Virtual Functions {{{2 ------------------------------------------ */
454 * The #GCond struct is an opaque data structure that represents a
455 * condition. Threads can block on a #GCond if they find a certain
456 * condition to be false. If other threads change the state of this
457 * condition they signal the #GCond, and that causes the waiting
458 * threads to be woken up.
462 * Using GCond to block a thread until a condition is satisfied
465 * GCond* data_cond = NULL; /<!-- -->* Must be initialized somewhere *<!-- -->/
466 * GMutex* data_mutex = NULL; /<!-- -->* Must be initialized somewhere *<!-- -->/
467 * gpointer current_data = NULL;
470 * push_data (gpointer data)
472 * g_mutex_lock (data_mutex);
473 * current_data = data;
474 * g_cond_signal (data_cond);
475 * g_mutex_unlock (data_mutex);
483 * g_mutex_lock (data_mutex);
484 * while (!current_data)
485 * g_cond_wait (data_cond, data_mutex);
486 * data = current_data;
487 * current_data = NULL;
488 * g_mutex_unlock (data_mutex);
495 * Whenever a thread calls <function>pop_data()</function> now, it will
496 * wait until current_data is non-%NULL, i.e. until some other thread
497 * has called <function>push_data()</function>.
499 * <note><para>It is important to use the g_cond_wait() and
500 * g_cond_timed_wait() functions only inside a loop which checks for the
501 * condition to be true. It is not guaranteed that the waiting thread
502 * will find the condition fulfilled after it wakes up, even if the
503 * signaling thread left the condition in that state: another thread may
504 * have altered the condition before the waiting thread got the chance
505 * to be woken up, even if the condition itself is protected by a
506 * #GMutex, like above.</para></note>
508 * A #GCond should only be accessed via the following functions.
511 /* GPrivate Virtual Functions {{{2 --------------------------------------- */
517 * #GStaticPrivate is a better choice for most uses.
520 * The #GPrivate struct is an opaque data structure to represent a
521 * thread private data key. Threads can thereby obtain and set a
522 * pointer which is private to the current thread. Take our
523 * <function>give_me_next_number(<!-- -->)</function> example from
524 * above. Suppose we don't want <literal>current_number</literal> to be
525 * shared between the threads, but instead to be private to each thread.
526 * This can be done as follows:
529 * <title>Using GPrivate for per-thread data</title>
531 * GPrivate* current_number_key = NULL; /<!-- -->* Must be initialized somewhere
532 * with g_private_new (g_free); *<!-- -->/
535 * give_me_next_number (void)
537 * int *current_number = g_private_get (current_number_key);
539 * if (!current_number)
541 * current_number = g_new (int, 1);
542 * *current_number = 0;
543 * g_private_set (current_number_key, current_number);
546 * *current_number = calc_next_number (*current_number);
548 * return *current_number;
553 * Here the pointer belonging to the key
554 * <literal>current_number_key</literal> is read. If it is %NULL, it has
555 * not been set yet. Then get memory for an integer value, assign this
556 * memory to the pointer and write the pointer back. Now we have an
557 * integer value that is private to the current thread.
559 * The #GPrivate struct should only be accessed via the following
562 * <note><para>All of the <function>g_private_*</function> functions are
563 * actually macros. Apart from taking their addresses, you can however
564 * use them as if they were functions.</para></note>
567 /* GThread Virtual Functions {{{2 ---------------------------------------- */
571 * The #GThread struct represents a running thread. It has three public
572 * read-only members, but the underlying struct is bigger, so you must
573 * not copy this struct.
575 * <note><para>Resources for a joinable thread are not fully released
576 * until g_thread_join() is called for that thread.</para></note>
581 * @data: data passed to the thread.
582 * @Returns: the return value of the thread, which will be returned by
585 * Specifies the type of the @func functions passed to
586 * g_thread_create() or g_thread_create_full().
591 * @G_THREAD_PRIORITY_LOW: a priority lower than normal
592 * @G_THREAD_PRIORITY_NORMAL: the default priority
593 * @G_THREAD_PRIORITY_HIGH: a priority higher than normal
594 * @G_THREAD_PRIORITY_URGENT: the highest priority
596 * Deprecated:2.32: thread priorities no longer have any effect.
599 /* Local Data {{{1 -------------------------------------------------------- */
601 static GMutex g_once_mutex = G_MUTEX_INIT;
602 static GCond g_once_cond = G_COND_INIT;
603 static GPrivate g_thread_specific_private;
604 static GRealThread *g_thread_all_threads = NULL;
605 static GSList *g_thread_free_indices = NULL;
606 static GSList* g_once_init_list = NULL;
608 G_LOCK_DEFINE_STATIC (g_thread);
610 /* Initialisation {{{1 ---------------------------------------------------- */
614 * @vtable: a function table of type #GThreadFunctions, that provides
615 * the entry points to the thread system to be used.
617 * If you use GLib from more than one thread, you must initialize the
618 * thread system by calling g_thread_init(). Most of the time you will
619 * only have to call <literal>g_thread_init (NULL)</literal>.
621 * <note><para>Do not call g_thread_init() with a non-%NULL parameter unless
622 * you really know what you are doing.</para></note>
624 * <note><para>g_thread_init() must not be called directly or indirectly as a
625 * callback from GLib. Also no mutexes may be currently locked while
626 * calling g_thread_init().</para></note>
628 * <note><para>g_thread_init() changes the way in which #GTimer measures
629 * elapsed time. As a consequence, timers that are running while
630 * g_thread_init() is called may report unreliable times.</para></note>
632 * Calling g_thread_init() multiple times is allowed (since version
633 * 2.24), but nothing happens except for the first call. If the
634 * argument is non-%NULL on such a call a warning will be printed, but
635 * otherwise the argument is ignored.
637 * If no thread system is available and @vtable is %NULL or if not all
638 * elements of @vtable are non-%NULL, then g_thread_init() will abort.
640 * <note><para>To use g_thread_init() in your program, you have to link with
641 * the libraries that the command <command>pkg-config --libs
642 * gthread-2.0</command> outputs. This is not the case for all the
643 * other thread related functions of GLib. Those can be used without
644 * having to link with the thread libraries.</para></note>
647 /* This must be called only once, before any threads are created.
648 * It will only be called from g_thread_init() in -lgthread.
651 g_thread_init_glib (void)
653 static gboolean already_done;
660 _g_thread_impl_init ();
662 /* We let the main thread (the one that calls g_thread_init) inherit
663 * the static_private data set before calling g_thread_init
665 GRealThread* main_thread = (GRealThread*) g_thread_self ();
667 /* setup the basic threading system */
668 g_threads_got_initialized = TRUE;
669 g_private_init (&g_thread_specific_private, g_thread_cleanup);
670 g_private_set (&g_thread_specific_private, main_thread);
671 g_system_thread_self (&main_thread->system_thread);
673 /* accomplish log system initialization to enable messaging */
674 _g_messages_thread_init_nomessage ();
677 /* The following sections implement: GOnce, GStaticMutex, GStaticRecMutex,
681 /* GOnce {{{1 ------------------------------------------------------------- */
685 * @status: the status of the #GOnce
686 * @retval: the value returned by the call to the function, if @status
687 * is %G_ONCE_STATUS_READY
689 * A #GOnce struct controls a one-time initialization function. Any
690 * one-time initialization function must have its own unique #GOnce
699 * A #GOnce must be initialized with this macro before it can be used.
703 * GOnce my_once = G_ONCE_INIT;
712 * @G_ONCE_STATUS_NOTCALLED: the function has not been called yet.
713 * @G_ONCE_STATUS_PROGRESS: the function call is currently in progress.
714 * @G_ONCE_STATUS_READY: the function has been called.
716 * The possible statuses of a one-time initialization function
717 * controlled by a #GOnce struct.
724 * @once: a #GOnce structure
725 * @func: the #GThreadFunc function associated to @once. This function
726 * is called only once, regardless of the number of times it and
727 * its associated #GOnce struct are passed to g_once().
728 * @arg: data to be passed to @func
730 * The first call to this routine by a process with a given #GOnce
731 * struct calls @func with the given argument. Thereafter, subsequent
732 * calls to g_once() with the same #GOnce struct do not call @func
733 * again, but return the stored result of the first call. On return
734 * from g_once(), the status of @once will be %G_ONCE_STATUS_READY.
736 * For example, a mutex or a thread-specific data key must be created
737 * exactly once. In a threaded environment, calling g_once() ensures
738 * that the initialization is serialized across multiple threads.
740 * <note><para>Calling g_once() recursively on the same #GOnce struct in
741 * @func will lead to a deadlock.</para></note>
746 * get_debug_flags (void)
748 * static GOnce my_once = G_ONCE_INIT;
750 * g_once (&my_once, parse_debug_flags, NULL);
752 * return my_once.retval;
760 g_once_impl (GOnce *once,
764 g_mutex_lock (&g_once_mutex);
766 while (once->status == G_ONCE_STATUS_PROGRESS)
767 g_cond_wait (&g_once_cond, &g_once_mutex);
769 if (once->status != G_ONCE_STATUS_READY)
771 once->status = G_ONCE_STATUS_PROGRESS;
772 g_mutex_unlock (&g_once_mutex);
774 once->retval = func (arg);
776 g_mutex_lock (&g_once_mutex);
777 once->status = G_ONCE_STATUS_READY;
778 g_cond_broadcast (&g_once_cond);
781 g_mutex_unlock (&g_once_mutex);
788 * @value_location: location of a static initializable variable
790 * @Returns: %TRUE if the initialization section should be entered,
791 * %FALSE and blocks otherwise
793 * Function to be called when starting a critical initialization
794 * section. The argument @value_location must point to a static
795 * 0-initialized variable that will be set to a value other than 0 at
796 * the end of the initialization section. In combination with
797 * g_once_init_leave() and the unique address @value_location, it can
798 * be ensured that an initialization section will be executed only once
799 * during a program's life time, and that concurrent threads are
800 * blocked until initialization completed. To be used in constructs
805 * static gsize initialization_value = 0;
807 * if (g_once_init_enter (&initialization_value))
809 * gsize setup_value = 42; /<!-- -->* initialization code here *<!-- -->/
811 * g_once_init_leave (&initialization_value, setup_value);
814 * /<!-- -->* use initialization_value here *<!-- -->/
821 g_once_init_enter_impl (volatile gsize *value_location)
823 gboolean need_init = FALSE;
824 g_mutex_lock (&g_once_mutex);
825 if (g_atomic_pointer_get (value_location) == NULL)
827 if (!g_slist_find (g_once_init_list, (void*) value_location))
830 g_once_init_list = g_slist_prepend (g_once_init_list, (void*) value_location);
834 g_cond_wait (&g_once_cond, &g_once_mutex);
835 while (g_slist_find (g_once_init_list, (void*) value_location));
837 g_mutex_unlock (&g_once_mutex);
843 * @value_location: location of a static initializable variable
845 * @initialization_value: new non-0 value for *@value_location.
847 * Counterpart to g_once_init_enter(). Expects a location of a static
848 * 0-initialized initialization variable, and an initialization value
849 * other than 0. Sets the variable to the initialization value, and
850 * releases concurrent threads blocking in g_once_init_enter() on this
851 * initialization variable.
856 g_once_init_leave (volatile gsize *value_location,
857 gsize initialization_value)
859 g_return_if_fail (g_atomic_pointer_get (value_location) == NULL);
860 g_return_if_fail (initialization_value != 0);
861 g_return_if_fail (g_once_init_list != NULL);
863 g_atomic_pointer_set (value_location, initialization_value);
864 g_mutex_lock (&g_once_mutex);
865 g_once_init_list = g_slist_remove (g_once_init_list, (void*) value_location);
866 g_cond_broadcast (&g_once_cond);
867 g_mutex_unlock (&g_once_mutex);
870 /* GStaticMutex {{{1 ------------------------------------------------------ */
875 * A #GStaticMutex works like a #GMutex, but it has one significant
876 * advantage. It doesn't need to be created at run-time like a #GMutex,
877 * but can be defined at compile-time. Here is a shorter, easier and
878 * safer version of our <function>give_me_next_number()</function>
883 * Using <structname>GStaticMutex</structname>
884 * to simplify thread-safe programming
888 * give_me_next_number (void)
890 * static int current_number = 0;
892 * static GStaticMutex mutex = G_STATIC_MUTEX_INIT;
894 * g_static_mutex_lock (&mutex);
895 * ret_val = current_number = calc_next_number (current_number);
896 * g_static_mutex_unlock (&mutex);
903 * Sometimes you would like to dynamically create a mutex. If you don't
904 * want to require prior calling to g_thread_init(), because your code
905 * should also be usable in non-threaded programs, you are not able to
906 * use g_mutex_new() and thus #GMutex, as that requires a prior call to
907 * g_thread_init(). In theses cases you can also use a #GStaticMutex.
908 * It must be initialized with g_static_mutex_init() before using it
909 * and freed with with g_static_mutex_free() when not needed anymore to
910 * free up any allocated resources.
912 * Even though #GStaticMutex is not opaque, it should only be used with
913 * the following functions, as it is defined differently on different
916 * All of the <function>g_static_mutex_*</function> functions apart
917 * from <function>g_static_mutex_get_mutex</function> can also be used
918 * even if g_thread_init() has not yet been called. Then they do
919 * nothing, apart from <function>g_static_mutex_trylock</function>,
920 * which does nothing but returning %TRUE.
922 * <note><para>All of the <function>g_static_mutex_*</function>
923 * functions are actually macros. Apart from taking their addresses, you
924 * can however use them as if they were functions.</para></note>
928 * G_STATIC_MUTEX_INIT:
930 * A #GStaticMutex must be initialized with this macro, before it can
931 * be used. This macro can used be to initialize a variable, but it
932 * cannot be assigned to a variable. In that case you have to use
933 * g_static_mutex_init().
937 * GStaticMutex my_mutex = G_STATIC_MUTEX_INIT;
943 * g_static_mutex_init:
944 * @mutex: a #GStaticMutex to be initialized.
946 * Initializes @mutex. Alternatively you can initialize it with
947 * #G_STATIC_MUTEX_INIT.
950 g_static_mutex_init (GStaticMutex *mutex)
952 static const GStaticMutex init_mutex = G_STATIC_MUTEX_INIT;
954 g_return_if_fail (mutex);
959 /* IMPLEMENTATION NOTE:
961 * On some platforms a GStaticMutex is actually a normal GMutex stored
962 * inside of a structure instead of being allocated dynamically. We can
963 * only do this for platforms on which we know, in advance, how to
964 * allocate (size) and initialise (value) that memory.
966 * On other platforms, a GStaticMutex is nothing more than a pointer to
967 * a GMutex. In that case, the first access we make to the static mutex
968 * must first allocate the normal GMutex and store it into the pointer.
970 * configure.ac writes macros into glibconfig.h to determine if
971 * g_static_mutex_get_mutex() accesses the structure in memory directly
972 * (on platforms where we are able to do that) or if it ends up here,
973 * where we may have to allocate the GMutex before returning it.
977 * g_static_mutex_get_mutex:
978 * @mutex: a #GStaticMutex.
979 * @Returns: the #GMutex corresponding to @mutex.
981 * For some operations (like g_cond_wait()) you must have a #GMutex
982 * instead of a #GStaticMutex. This function will return the
983 * corresponding #GMutex for @mutex.
986 g_static_mutex_get_mutex_impl (GMutex** mutex)
990 if (!g_thread_supported ())
993 result = g_atomic_pointer_get (mutex);
997 g_mutex_lock (&g_once_mutex);
1002 result = g_mutex_new ();
1003 g_atomic_pointer_set (mutex, result);
1006 g_mutex_unlock (&g_once_mutex);
1012 /* IMPLEMENTATION NOTE:
1014 * g_static_mutex_lock(), g_static_mutex_trylock() and
1015 * g_static_mutex_unlock() are all preprocessor macros that wrap the
1016 * corresponding g_mutex_*() function around a call to
1017 * g_static_mutex_get_mutex().
1021 * g_static_mutex_lock:
1022 * @mutex: a #GStaticMutex.
1024 * Works like g_mutex_lock(), but for a #GStaticMutex.
1028 * g_static_mutex_trylock:
1029 * @mutex: a #GStaticMutex.
1030 * @Returns: %TRUE, if the #GStaticMutex could be locked.
1032 * Works like g_mutex_trylock(), but for a #GStaticMutex.
1036 * g_static_mutex_unlock:
1037 * @mutex: a #GStaticMutex.
1039 * Works like g_mutex_unlock(), but for a #GStaticMutex.
1043 * g_static_mutex_free:
1044 * @mutex: a #GStaticMutex to be freed.
1046 * Releases all resources allocated to @mutex.
1048 * You don't have to call this functions for a #GStaticMutex with an
1049 * unbounded lifetime, i.e. objects declared 'static', but if you have
1050 * a #GStaticMutex as a member of a structure and the structure is
1051 * freed, you should also free the #GStaticMutex.
1053 * <note><para>Calling g_static_mutex_free() on a locked mutex may
1054 * result in undefined behaviour.</para></note>
1057 g_static_mutex_free (GStaticMutex* mutex)
1059 GMutex **runtime_mutex;
1061 g_return_if_fail (mutex);
1063 /* The runtime_mutex is the first (or only) member of GStaticMutex,
1064 * see both versions (of glibconfig.h) in configure.ac. Note, that
1065 * this variable is NULL, if g_thread_init() hasn't been called or
1066 * if we're using the default thread implementation and it provides
1067 * static mutexes. */
1068 runtime_mutex = ((GMutex**)mutex);
1071 g_mutex_free (*runtime_mutex);
1073 *runtime_mutex = NULL;
1076 /* ------------------------------------------------------------------------ */
1081 * A #GStaticRecMutex works like a #GStaticMutex, but it can be locked
1082 * multiple times by one thread. If you enter it n times, you have to
1083 * unlock it n times again to let other threads lock it. An exception
1084 * is the function g_static_rec_mutex_unlock_full(): that allows you to
1085 * unlock a #GStaticRecMutex completely returning the depth, (i.e. the
1086 * number of times this mutex was locked). The depth can later be used
1087 * to restore the state of the #GStaticRecMutex by calling
1088 * g_static_rec_mutex_lock_full().
1090 * Even though #GStaticRecMutex is not opaque, it should only be used
1091 * with the following functions.
1093 * All of the <function>g_static_rec_mutex_*</function> functions can
1094 * be used even if g_thread_init() has not been called. Then they do
1095 * nothing, apart from <function>g_static_rec_mutex_trylock</function>,
1096 * which does nothing but returning %TRUE.
1100 * G_STATIC_REC_MUTEX_INIT:
1102 * A #GStaticRecMutex must be initialized with this macro before it can
1103 * be used. This macro can used be to initialize a variable, but it
1104 * cannot be assigned to a variable. In that case you have to use
1105 * g_static_rec_mutex_init().
1109 * GStaticRecMutex my_mutex = G_STATIC_REC_MUTEX_INIT;
1115 * g_static_rec_mutex_init:
1116 * @mutex: a #GStaticRecMutex to be initialized.
1118 * A #GStaticRecMutex must be initialized with this function before it
1119 * can be used. Alternatively you can initialize it with
1120 * #G_STATIC_REC_MUTEX_INIT.
1123 g_static_rec_mutex_init (GStaticRecMutex *mutex)
1125 static const GStaticRecMutex init_mutex = G_STATIC_REC_MUTEX_INIT;
1127 g_return_if_fail (mutex);
1129 *mutex = init_mutex;
1133 * g_static_rec_mutex_lock:
1134 * @mutex: a #GStaticRecMutex to lock.
1136 * Locks @mutex. If @mutex is already locked by another thread, the
1137 * current thread will block until @mutex is unlocked by the other
1138 * thread. If @mutex is already locked by the calling thread, this
1139 * functions increases the depth of @mutex and returns immediately.
1142 g_static_rec_mutex_lock (GStaticRecMutex* mutex)
1146 g_return_if_fail (mutex);
1148 if (!g_thread_supported ())
1151 g_system_thread_self (&self);
1153 if (g_system_thread_equal (&self, &mutex->owner))
1158 g_static_mutex_lock (&mutex->mutex);
1159 g_system_thread_assign (mutex->owner, self);
1164 * g_static_rec_mutex_trylock:
1165 * @mutex: a #GStaticRecMutex to lock.
1166 * @Returns: %TRUE, if @mutex could be locked.
1168 * Tries to lock @mutex. If @mutex is already locked by another thread,
1169 * it immediately returns %FALSE. Otherwise it locks @mutex and returns
1170 * %TRUE. If @mutex is already locked by the calling thread, this
1171 * functions increases the depth of @mutex and immediately returns
1175 g_static_rec_mutex_trylock (GStaticRecMutex* mutex)
1179 g_return_val_if_fail (mutex, FALSE);
1181 if (!g_thread_supported ())
1184 g_system_thread_self (&self);
1186 if (g_system_thread_equal (&self, &mutex->owner))
1192 if (!g_static_mutex_trylock (&mutex->mutex))
1195 g_system_thread_assign (mutex->owner, self);
1201 * g_static_rec_mutex_unlock:
1202 * @mutex: a #GStaticRecMutex to unlock.
1204 * Unlocks @mutex. Another thread will be allowed to lock @mutex only
1205 * when it has been unlocked as many times as it had been locked
1206 * before. If @mutex is completely unlocked and another thread is
1207 * blocked in a g_static_rec_mutex_lock() call for @mutex, it will be
1208 * woken and can lock @mutex itself.
1211 g_static_rec_mutex_unlock (GStaticRecMutex* mutex)
1213 g_return_if_fail (mutex);
1215 if (!g_thread_supported ())
1218 if (mutex->depth > 1)
1223 g_system_thread_assign (mutex->owner, zero_thread);
1224 g_static_mutex_unlock (&mutex->mutex);
1228 * g_static_rec_mutex_lock_full:
1229 * @mutex: a #GStaticRecMutex to lock.
1230 * @depth: number of times this mutex has to be unlocked to be
1231 * completely unlocked.
1233 * Works like calling g_static_rec_mutex_lock() for @mutex @depth times.
1236 g_static_rec_mutex_lock_full (GStaticRecMutex *mutex,
1240 g_return_if_fail (mutex);
1242 if (!g_thread_supported ())
1248 g_system_thread_self (&self);
1250 if (g_system_thread_equal (&self, &mutex->owner))
1252 mutex->depth += depth;
1255 g_static_mutex_lock (&mutex->mutex);
1256 g_system_thread_assign (mutex->owner, self);
1257 mutex->depth = depth;
1261 * g_static_rec_mutex_unlock_full:
1262 * @mutex: a #GStaticRecMutex to completely unlock.
1263 * @Returns: number of times @mutex has been locked by the current
1266 * Completely unlocks @mutex. If another thread is blocked in a
1267 * g_static_rec_mutex_lock() call for @mutex, it will be woken and can
1268 * lock @mutex itself. This function returns the number of times that
1269 * @mutex has been locked by the current thread. To restore the state
1270 * before the call to g_static_rec_mutex_unlock_full() you can call
1271 * g_static_rec_mutex_lock_full() with the depth returned by this
1275 g_static_rec_mutex_unlock_full (GStaticRecMutex *mutex)
1279 g_return_val_if_fail (mutex, 0);
1281 if (!g_thread_supported ())
1284 depth = mutex->depth;
1286 g_system_thread_assign (mutex->owner, zero_thread);
1288 g_static_mutex_unlock (&mutex->mutex);
1294 * g_static_rec_mutex_free:
1295 * @mutex: a #GStaticRecMutex to be freed.
1297 * Releases all resources allocated to a #GStaticRecMutex.
1299 * You don't have to call this functions for a #GStaticRecMutex with an
1300 * unbounded lifetime, i.e. objects declared 'static', but if you have
1301 * a #GStaticRecMutex as a member of a structure and the structure is
1302 * freed, you should also free the #GStaticRecMutex.
1305 g_static_rec_mutex_free (GStaticRecMutex *mutex)
1307 g_return_if_fail (mutex);
1309 g_static_mutex_free (&mutex->mutex);
1312 /* GStaticPrivate {{{1 ---------------------------------------------------- */
1317 * A #GStaticPrivate works almost like a #GPrivate, but it has one
1318 * significant advantage. It doesn't need to be created at run-time
1319 * like a #GPrivate, but can be defined at compile-time. This is
1320 * similar to the difference between #GMutex and #GStaticMutex. Now
1321 * look at our <function>give_me_next_number()</function> example with
1325 * <title>Using GStaticPrivate for per-thread data</title>
1328 * give_me_next_number (<!-- -->)
1330 * static GStaticPrivate current_number_key = G_STATIC_PRIVATE_INIT;
1331 * int *current_number = g_static_private_get (&current_number_key);
1333 * if (!current_number)
1335 * current_number = g_new (int,1);
1336 * *current_number = 0;
1337 * g_static_private_set (&current_number_key, current_number, g_free);
1340 * *current_number = calc_next_number (*current_number);
1342 * return *current_number;
1349 * G_STATIC_PRIVATE_INIT:
1351 * Every #GStaticPrivate must be initialized with this macro, before it
1356 * GStaticPrivate my_private = G_STATIC_PRIVATE_INIT;
1358 * </informalexample>
1362 * g_static_private_init:
1363 * @private_key: a #GStaticPrivate to be initialized.
1365 * Initializes @private_key. Alternatively you can initialize it with
1366 * #G_STATIC_PRIVATE_INIT.
1369 g_static_private_init (GStaticPrivate *private_key)
1371 private_key->index = 0;
1375 * g_static_private_get:
1376 * @private_key: a #GStaticPrivate.
1377 * @Returns: the corresponding pointer.
1379 * Works like g_private_get() only for a #GStaticPrivate.
1381 * This function works even if g_thread_init() has not yet been called.
1384 g_static_private_get (GStaticPrivate *private_key)
1386 GRealThread *self = (GRealThread*) g_thread_self ();
1388 gpointer ret = NULL;
1390 LOCK_PRIVATE_DATA (self);
1392 array = self->private_data;
1394 if (array && private_key->index != 0 && private_key->index <= array->len)
1395 ret = g_array_index (array, GStaticPrivateNode,
1396 private_key->index - 1).data;
1398 UNLOCK_PRIVATE_DATA (self);
1403 * g_static_private_set:
1404 * @private_key: a #GStaticPrivate.
1405 * @data: the new pointer.
1406 * @notify: a function to be called with the pointer whenever the
1407 * current thread ends or sets this pointer again.
1409 * Sets the pointer keyed to @private_key for the current thread and
1410 * the function @notify to be called with that pointer (%NULL or
1411 * non-%NULL), whenever the pointer is set again or whenever the
1412 * current thread ends.
1414 * This function works even if g_thread_init() has not yet been called.
1415 * If g_thread_init() is called later, the @data keyed to @private_key
1416 * will be inherited only by the main thread, i.e. the one that called
1419 * <note><para>@notify is used quite differently from @destructor in
1420 * g_private_new().</para></note>
1423 g_static_private_set (GStaticPrivate *private_key,
1425 GDestroyNotify notify)
1427 GRealThread *self = (GRealThread*) g_thread_self ();
1429 static guint next_index = 0;
1430 GStaticPrivateNode *node;
1431 gpointer ddata = NULL;
1432 GDestroyNotify ddestroy = NULL;
1434 if (!private_key->index)
1438 if (!private_key->index)
1440 if (g_thread_free_indices)
1442 private_key->index =
1443 GPOINTER_TO_UINT (g_thread_free_indices->data);
1444 g_thread_free_indices =
1445 g_slist_delete_link (g_thread_free_indices,
1446 g_thread_free_indices);
1449 private_key->index = ++next_index;
1452 G_UNLOCK (g_thread);
1455 LOCK_PRIVATE_DATA (self);
1457 array = self->private_data;
1460 array = g_array_new (FALSE, TRUE, sizeof (GStaticPrivateNode));
1461 self->private_data = array;
1464 if (private_key->index > array->len)
1465 g_array_set_size (array, private_key->index);
1467 node = &g_array_index (array, GStaticPrivateNode, private_key->index - 1);
1470 ddestroy = node->destroy;
1473 node->destroy = notify;
1475 UNLOCK_PRIVATE_DATA (self);
1482 * g_static_private_free:
1483 * @private_key: a #GStaticPrivate to be freed.
1485 * Releases all resources allocated to @private_key.
1487 * You don't have to call this functions for a #GStaticPrivate with an
1488 * unbounded lifetime, i.e. objects declared 'static', but if you have
1489 * a #GStaticPrivate as a member of a structure and the structure is
1490 * freed, you should also free the #GStaticPrivate.
1493 g_static_private_free (GStaticPrivate *private_key)
1495 guint idx = private_key->index;
1496 GRealThread *thread, *next;
1497 GArray *garbage = NULL;
1502 private_key->index = 0;
1506 thread = g_thread_all_threads;
1508 for (thread = g_thread_all_threads; thread; thread = next)
1512 next = thread->next;
1514 LOCK_PRIVATE_DATA (thread);
1516 array = thread->private_data;
1518 if (array && idx <= array->len)
1520 GStaticPrivateNode *node = &g_array_index (array,
1523 gpointer ddata = node->data;
1524 GDestroyNotify ddestroy = node->destroy;
1527 node->destroy = NULL;
1531 /* defer non-trivial destruction til after we've finished
1532 * iterating, since we must continue to hold the lock */
1533 if (garbage == NULL)
1534 garbage = g_array_new (FALSE, TRUE,
1535 sizeof (GStaticPrivateNode));
1537 g_array_set_size (garbage, garbage->len + 1);
1539 node = &g_array_index (garbage, GStaticPrivateNode,
1542 node->destroy = ddestroy;
1546 UNLOCK_PRIVATE_DATA (thread);
1548 g_thread_free_indices = g_slist_prepend (g_thread_free_indices,
1549 GUINT_TO_POINTER (idx));
1550 G_UNLOCK (g_thread);
1556 for (i = 0; i < garbage->len; i++)
1558 GStaticPrivateNode *node;
1560 node = &g_array_index (garbage, GStaticPrivateNode, i);
1561 node->destroy (node->data);
1564 g_array_free (garbage, TRUE);
1568 /* GThread Extra Functions {{{1 ------------------------------------------- */
1570 g_thread_cleanup (gpointer data)
1574 GRealThread* thread = data;
1577 LOCK_PRIVATE_DATA (thread);
1578 array = thread->private_data;
1579 thread->private_data = NULL;
1580 UNLOCK_PRIVATE_DATA (thread);
1586 for (i = 0; i < array->len; i++ )
1588 GStaticPrivateNode *node =
1589 &g_array_index (array, GStaticPrivateNode, i);
1591 node->destroy (node->data);
1593 g_array_free (array, TRUE);
1596 /* We only free the thread structure, if it isn't joinable. If
1597 it is, the structure is freed in g_thread_join */
1598 if (!thread->thread.joinable)
1603 for (t = g_thread_all_threads, p = NULL; t; p = t, t = t->next)
1610 g_thread_all_threads = t->next;
1614 G_UNLOCK (g_thread);
1616 /* Just to make sure, this isn't used any more */
1617 g_system_thread_assign (thread->system_thread, zero_thread);
1623 #define G_NSEC_PER_SEC 1000000000
1628 return g_get_monotonic_time () * 1000;
1632 g_thread_create_proxy (gpointer data)
1634 GRealThread* thread = data;
1638 /* This has to happen before G_LOCK, as that might call g_thread_self */
1639 g_private_set (&g_thread_specific_private, data);
1641 /* the lock makes sure, that thread->system_thread is written,
1642 before thread->thread.func is called. See g_thread_create. */
1644 G_UNLOCK (g_thread);
1646 thread->retval = thread->thread.func (thread->thread.data);
1653 * @func: a function to execute in the new thread
1654 * @data: an argument to supply to the new thread
1655 * @joinable: should this thread be joinable?
1656 * @error: return location for error, or %NULL
1658 * This function creates a new thread.
1660 * If @joinable is %TRUE, you can wait for this threads termination
1661 * calling g_thread_join(). Otherwise the thread will just disappear
1662 * when it terminates.
1664 * The new thread executes the function @func with the argument @data.
1665 * If the thread was created successfully, it is returned.
1667 * @error can be %NULL to ignore errors, or non-%NULL to report errors.
1668 * The error is set, if and only if the function returns %NULL.
1670 * Returns: the new #GThread on success
1673 g_thread_create (GThreadFunc func,
1678 return g_thread_create_with_stack_size (func, data, joinable, 0, error);
1682 * g_thread_create_with_stack_size:
1683 * @func: a function to execute in the new thread.
1684 * @data: an argument to supply to the new thread.
1685 * @joinable: should this thread be joinable?
1686 * @stack_size: a stack size for the new thread.
1687 * @error: return location for error.
1688 * @Returns: the new #GThread on success.
1690 * This function creates a new thread. If the underlying thread
1691 * implementation supports it, the thread gets a stack size of
1692 * @stack_size or the default value for the current platform, if
1695 * If @joinable is %TRUE, you can wait for this threads termination
1696 * calling g_thread_join(). Otherwise the thread will just disappear
1697 * when it terminates.
1699 * The new thread executes the function @func with the argument @data.
1700 * If the thread was created successfully, it is returned.
1702 * @error can be %NULL to ignore errors, or non-%NULL to report errors.
1703 * The error is set, if and only if the function returns %NULL.
1706 * Only use g_thread_create_with_stack_size() if you really can't use
1707 * g_thread_create() instead. g_thread_create() does not take
1708 * @stack_size, as it should only be used in cases in which it is
1713 g_thread_create_with_stack_size (GThreadFunc func,
1719 GRealThread* result;
1720 GError *local_error = NULL;
1721 g_return_val_if_fail (func, NULL);
1723 result = g_new0 (GRealThread, 1);
1725 result->thread.joinable = joinable;
1726 result->thread.func = func;
1727 result->thread.data = data;
1728 result->private_data = NULL;
1730 g_system_thread_create (g_thread_create_proxy, result,
1731 stack_size, joinable,
1732 &result->system_thread, &local_error);
1735 result->next = g_thread_all_threads;
1736 g_thread_all_threads = result;
1738 G_UNLOCK (g_thread);
1742 g_propagate_error (error, local_error);
1747 return (GThread*) result;
1751 * g_thread_create_full:
1752 * @func: a function to execute in the new thread.
1753 * @data: an argument to supply to the new thread.
1754 * @stack_size: a stack size for the new thread.
1755 * @joinable: should this thread be joinable?
1757 * @priority: ignored
1758 * @error: return location for error.
1759 * @Returns: the new #GThread on success.
1761 * This function creates a new thread.
1763 * Deprecated:2.32: The @bound and @priority arguments are now ignored.
1764 * Use g_thread_create() or g_thread_create_with_stack_size() instead.
1767 g_thread_create_full (GThreadFunc func,
1772 GThreadPriority priority,
1775 return g_thread_create_with_stack_size (func, data, joinable, stack_size, error);
1780 * @retval: the return value of this thread.
1782 * Exits the current thread. If another thread is waiting for that
1783 * thread using g_thread_join() and the current thread is joinable, the
1784 * waiting thread will be woken up and get @retval as the return value
1785 * of g_thread_join(). If the current thread is not joinable, @retval
1786 * is ignored. Calling
1789 * g_thread_exit (retval);
1792 * is equivalent to returning @retval from the function @func, as given
1793 * to g_thread_create().
1795 * <note><para>Never call g_thread_exit() from within a thread of a
1796 * #GThreadPool, as that will mess up the bookkeeping and lead to funny
1797 * and unwanted results.</para></note>
1800 g_thread_exit (gpointer retval)
1802 GRealThread* real = (GRealThread*) g_thread_self ();
1803 real->retval = retval;
1805 g_system_thread_exit ();
1810 * @thread: a #GThread to be waited for.
1811 * @Returns: the return value of the thread.
1813 * Waits until @thread finishes, i.e. the function @func, as given to
1814 * g_thread_create(), returns or g_thread_exit() is called by @thread.
1815 * All resources of @thread including the #GThread struct are released.
1816 * @thread must have been created with @joinable=%TRUE in
1817 * g_thread_create(). The value returned by @func or given to
1818 * g_thread_exit() by @thread is returned by this function.
1821 g_thread_join (GThread* thread)
1823 GRealThread* real = (GRealThread*) thread;
1827 g_return_val_if_fail (thread, NULL);
1828 g_return_val_if_fail (thread->joinable, NULL);
1829 g_return_val_if_fail (!g_system_thread_equal (&real->system_thread, &zero_thread), NULL);
1831 g_system_thread_join (&real->system_thread);
1833 retval = real->retval;
1836 for (t = g_thread_all_threads, p = NULL; t; p = t, t = t->next)
1838 if (t == (GRealThread*) thread)
1843 g_thread_all_threads = t->next;
1847 G_UNLOCK (g_thread);
1849 /* Just to make sure, this isn't used any more */
1850 thread->joinable = 0;
1851 g_system_thread_assign (real->system_thread, zero_thread);
1853 /* the thread structure for non-joinable threads is freed upon
1854 thread end. We free the memory here. This will leave a loose end,
1855 if a joinable thread is not joined. */
1863 * g_thread_set_priority:
1864 * @thread: a #GThread.
1865 * @priority: ignored
1867 * This function does nothing.
1869 * Deprecated:2.32: Thread priorities no longer have any effect.
1872 g_thread_set_priority (GThread *thread,
1873 GThreadPriority priority)
1879 * @Returns: the current thread.
1881 * This functions returns the #GThread corresponding to the calling
1885 g_thread_self (void)
1887 GRealThread* thread = g_private_get (&g_thread_specific_private);
1891 /* If no thread data is available, provide and set one. This
1892 can happen for the main thread and for threads, that are not
1894 thread = g_new0 (GRealThread, 1);
1895 thread->thread.joinable = FALSE; /* This is a save guess */
1896 thread->thread.func = NULL;
1897 thread->thread.data = NULL;
1898 thread->private_data = NULL;
1900 g_system_thread_self (&thread->system_thread);
1902 g_private_set (&g_thread_specific_private, thread);
1905 thread->next = g_thread_all_threads;
1906 g_thread_all_threads = thread;
1907 G_UNLOCK (g_thread);
1910 return (GThread*)thread;
1913 /* GStaticRWLock {{{1 ----------------------------------------------------- */
1918 * The #GStaticRWLock struct represents a read-write lock. A read-write
1919 * lock can be used for protecting data that some portions of code only
1920 * read from, while others also write. In such situations it is
1921 * desirable that several readers can read at once, whereas of course
1922 * only one writer may write at a time. Take a look at the following
1926 * <title>An array with access functions</title>
1928 * GStaticRWLock rwlock = G_STATIC_RW_LOCK_INIT;
1932 * my_array_get (guint index)
1934 * gpointer retval = NULL;
1939 * g_static_rw_lock_reader_lock (&rwlock);
1940 * if (index < array->len)
1941 * retval = g_ptr_array_index (array, index);
1942 * g_static_rw_lock_reader_unlock (&rwlock);
1948 * my_array_set (guint index, gpointer data)
1950 * g_static_rw_lock_writer_lock (&rwlock);
1953 * array = g_ptr_array_new (<!-- -->);
1955 * if (index >= array->len)
1956 * g_ptr_array_set_size (array, index+1);
1957 * g_ptr_array_index (array, index) = data;
1959 * g_static_rw_lock_writer_unlock (&rwlock);
1964 * This example shows an array which can be accessed by many readers
1965 * (the <function>my_array_get()</function> function) simultaneously,
1966 * whereas the writers (the <function>my_array_set()</function>
1967 * function) will only be allowed once at a time and only if no readers
1968 * currently access the array. This is because of the potentially
1969 * dangerous resizing of the array. Using these functions is fully
1970 * multi-thread safe now.
1972 * Most of the time, writers should have precedence over readers. That
1973 * means, for this implementation, that as soon as a writer wants to
1974 * lock the data, no other reader is allowed to lock the data, whereas,
1975 * of course, the readers that already have locked the data are allowed
1976 * to finish their operation. As soon as the last reader unlocks the
1977 * data, the writer will lock it.
1979 * Even though #GStaticRWLock is not opaque, it should only be used
1980 * with the following functions.
1982 * All of the <function>g_static_rw_lock_*</function> functions can be
1983 * used even if g_thread_init() has not been called. Then they do
1984 * nothing, apart from <function>g_static_rw_lock_*_trylock</function>,
1985 * which does nothing but returning %TRUE.
1987 * <note><para>A read-write lock has a higher overhead than a mutex. For
1988 * example, both g_static_rw_lock_reader_lock() and
1989 * g_static_rw_lock_reader_unlock() have to lock and unlock a
1990 * #GStaticMutex, so it takes at least twice the time to lock and unlock
1991 * a #GStaticRWLock that it does to lock and unlock a #GStaticMutex. So
1992 * only data structures that are accessed by multiple readers, and which
1993 * keep the lock for a considerable time justify a #GStaticRWLock. The
1994 * above example most probably would fare better with a
1995 * #GStaticMutex.</para></note>
1999 * G_STATIC_RW_LOCK_INIT:
2001 * A #GStaticRWLock must be initialized with this macro before it can
2002 * be used. This macro can used be to initialize a variable, but it
2003 * cannot be assigned to a variable. In that case you have to use
2004 * g_static_rw_lock_init().
2008 * GStaticRWLock my_lock = G_STATIC_RW_LOCK_INIT;
2010 * </informalexample>
2014 * g_static_rw_lock_init:
2015 * @lock: a #GStaticRWLock to be initialized.
2017 * A #GStaticRWLock must be initialized with this function before it
2018 * can be used. Alternatively you can initialize it with
2019 * #G_STATIC_RW_LOCK_INIT.
2022 g_static_rw_lock_init (GStaticRWLock* lock)
2024 static const GStaticRWLock init_lock = G_STATIC_RW_LOCK_INIT;
2026 g_return_if_fail (lock);
2032 g_static_rw_lock_wait (GCond** cond, GStaticMutex* mutex)
2035 *cond = g_cond_new ();
2036 g_cond_wait (*cond, g_static_mutex_get_mutex (mutex));
2040 g_static_rw_lock_signal (GStaticRWLock* lock)
2042 if (lock->want_to_write && lock->write_cond)
2043 g_cond_signal (lock->write_cond);
2044 else if (lock->want_to_read && lock->read_cond)
2045 g_cond_broadcast (lock->read_cond);
2049 * g_static_rw_lock_reader_lock:
2050 * @lock: a #GStaticRWLock to lock for reading.
2052 * Locks @lock for reading. There may be unlimited concurrent locks for
2053 * reading of a #GStaticRWLock at the same time. If @lock is already
2054 * locked for writing by another thread or if another thread is already
2055 * waiting to lock @lock for writing, this function will block until
2056 * @lock is unlocked by the other writing thread and no other writing
2057 * threads want to lock @lock. This lock has to be unlocked by
2058 * g_static_rw_lock_reader_unlock().
2060 * #GStaticRWLock is not recursive. It might seem to be possible to
2061 * recursively lock for reading, but that can result in a deadlock, due
2062 * to writer preference.
2065 g_static_rw_lock_reader_lock (GStaticRWLock* lock)
2067 g_return_if_fail (lock);
2069 if (!g_threads_got_initialized)
2072 g_static_mutex_lock (&lock->mutex);
2073 lock->want_to_read++;
2074 while (lock->have_writer || lock->want_to_write)
2075 g_static_rw_lock_wait (&lock->read_cond, &lock->mutex);
2076 lock->want_to_read--;
2077 lock->read_counter++;
2078 g_static_mutex_unlock (&lock->mutex);
2082 * g_static_rw_lock_reader_trylock:
2083 * @lock: a #GStaticRWLock to lock for reading.
2084 * @Returns: %TRUE, if @lock could be locked for reading.
2086 * Tries to lock @lock for reading. If @lock is already locked for
2087 * writing by another thread or if another thread is already waiting to
2088 * lock @lock for writing, immediately returns %FALSE. Otherwise locks
2089 * @lock for reading and returns %TRUE. This lock has to be unlocked by
2090 * g_static_rw_lock_reader_unlock().
2093 g_static_rw_lock_reader_trylock (GStaticRWLock* lock)
2095 gboolean ret_val = FALSE;
2097 g_return_val_if_fail (lock, FALSE);
2099 if (!g_threads_got_initialized)
2102 g_static_mutex_lock (&lock->mutex);
2103 if (!lock->have_writer && !lock->want_to_write)
2105 lock->read_counter++;
2108 g_static_mutex_unlock (&lock->mutex);
2113 * g_static_rw_lock_reader_unlock:
2114 * @lock: a #GStaticRWLock to unlock after reading.
2116 * Unlocks @lock. If a thread waits to lock @lock for writing and all
2117 * locks for reading have been unlocked, the waiting thread is woken up
2118 * and can lock @lock for writing.
2121 g_static_rw_lock_reader_unlock (GStaticRWLock* lock)
2123 g_return_if_fail (lock);
2125 if (!g_threads_got_initialized)
2128 g_static_mutex_lock (&lock->mutex);
2129 lock->read_counter--;
2130 if (lock->read_counter == 0)
2131 g_static_rw_lock_signal (lock);
2132 g_static_mutex_unlock (&lock->mutex);
2136 * g_static_rw_lock_writer_lock:
2137 * @lock: a #GStaticRWLock to lock for writing.
2139 * Locks @lock for writing. If @lock is already locked for writing or
2140 * reading by other threads, this function will block until @lock is
2141 * completely unlocked and then lock @lock for writing. While this
2142 * functions waits to lock @lock, no other thread can lock @lock for
2143 * reading. When @lock is locked for writing, no other thread can lock
2144 * @lock (neither for reading nor writing). This lock has to be
2145 * unlocked by g_static_rw_lock_writer_unlock().
2148 g_static_rw_lock_writer_lock (GStaticRWLock* lock)
2150 g_return_if_fail (lock);
2152 if (!g_threads_got_initialized)
2155 g_static_mutex_lock (&lock->mutex);
2156 lock->want_to_write++;
2157 while (lock->have_writer || lock->read_counter)
2158 g_static_rw_lock_wait (&lock->write_cond, &lock->mutex);
2159 lock->want_to_write--;
2160 lock->have_writer = TRUE;
2161 g_static_mutex_unlock (&lock->mutex);
2165 * g_static_rw_lock_writer_trylock:
2166 * @lock: a #GStaticRWLock to lock for writing.
2167 * @Returns: %TRUE, if @lock could be locked for writing.
2169 * Tries to lock @lock for writing. If @lock is already locked (for
2170 * either reading or writing) by another thread, it immediately returns
2171 * %FALSE. Otherwise it locks @lock for writing and returns %TRUE. This
2172 * lock has to be unlocked by g_static_rw_lock_writer_unlock().
2175 g_static_rw_lock_writer_trylock (GStaticRWLock* lock)
2177 gboolean ret_val = FALSE;
2179 g_return_val_if_fail (lock, FALSE);
2181 if (!g_threads_got_initialized)
2184 g_static_mutex_lock (&lock->mutex);
2185 if (!lock->have_writer && !lock->read_counter)
2187 lock->have_writer = TRUE;
2190 g_static_mutex_unlock (&lock->mutex);
2195 * g_static_rw_lock_writer_unlock:
2196 * @lock: a #GStaticRWLock to unlock after writing.
2198 * Unlocks @lock. If a thread is waiting to lock @lock for writing and
2199 * all locks for reading have been unlocked, the waiting thread is
2200 * woken up and can lock @lock for writing. If no thread is waiting to
2201 * lock @lock for writing, and some thread or threads are waiting to
2202 * lock @lock for reading, the waiting threads are woken up and can
2203 * lock @lock for reading.
2206 g_static_rw_lock_writer_unlock (GStaticRWLock* lock)
2208 g_return_if_fail (lock);
2210 if (!g_threads_got_initialized)
2213 g_static_mutex_lock (&lock->mutex);
2214 lock->have_writer = FALSE;
2215 g_static_rw_lock_signal (lock);
2216 g_static_mutex_unlock (&lock->mutex);
2220 * g_static_rw_lock_free:
2221 * @lock: a #GStaticRWLock to be freed.
2223 * Releases all resources allocated to @lock.
2225 * You don't have to call this functions for a #GStaticRWLock with an
2226 * unbounded lifetime, i.e. objects declared 'static', but if you have
2227 * a #GStaticRWLock as a member of a structure, and the structure is
2228 * freed, you should also free the #GStaticRWLock.
2231 g_static_rw_lock_free (GStaticRWLock* lock)
2233 g_return_if_fail (lock);
2235 if (lock->read_cond)
2237 g_cond_free (lock->read_cond);
2238 lock->read_cond = NULL;
2240 if (lock->write_cond)
2242 g_cond_free (lock->write_cond);
2243 lock->write_cond = NULL;
2245 g_static_mutex_free (&lock->mutex);
2248 /* Unsorted {{{1 ---------------------------------------------------------- */
2252 * @thread_func: function to call for all GThread structures
2253 * @user_data: second argument to @thread_func
2255 * Call @thread_func on all existing #GThread structures. Note that
2256 * threads may decide to exit while @thread_func is running, so
2257 * without intimate knowledge about the lifetime of foreign threads,
2258 * @thread_func shouldn't access the GThread* pointer passed in as
2259 * first argument. However, @thread_func will not be called for threads
2260 * which are known to have exited already.
2262 * Due to thread lifetime checks, this function has an execution complexity
2263 * which is quadratic in the number of existing threads.
2268 g_thread_foreach (GFunc thread_func,
2271 GSList *slist = NULL;
2272 GRealThread *thread;
2273 g_return_if_fail (thread_func != NULL);
2274 /* snapshot the list of threads for iteration */
2276 for (thread = g_thread_all_threads; thread; thread = thread->next)
2277 slist = g_slist_prepend (slist, thread);
2278 G_UNLOCK (g_thread);
2279 /* walk the list, skipping non-existent threads */
2282 GSList *node = slist;
2284 /* check whether the current thread still exists */
2286 for (thread = g_thread_all_threads; thread; thread = thread->next)
2287 if (thread == node->data)
2289 G_UNLOCK (g_thread);
2291 thread_func (thread, user_data);
2292 g_slist_free_1 (node);
2297 * g_thread_get_initialized:
2299 * Indicates if g_thread_init() has been called.
2301 * Returns: %TRUE if threads have been initialized.
2306 g_thread_get_initialized ()
2308 return g_thread_supported ();
2314 * Creates a new #GMutex.
2316 * Returns: a newly allocated #GMutex. Use g_mutex_free() to free
2323 mutex = g_slice_new (GMutex);
2324 g_mutex_init (mutex);
2333 * Destroys a @mutex that has been created with g_mutex_new().
2335 * <note>Calling g_mutex_free() on a locked mutex may result
2336 * in undefined behaviour.</note>
2339 g_mutex_free (GMutex *mutex)
2341 g_mutex_clear (mutex);
2342 g_slice_free (GMutex, mutex);
2348 * Creates a new #GCond.
2350 * Returns: a newly allocated #GCond. Free with g_cond_free()
2357 cond = g_slice_new (GCond);
2367 * Destroys a #GCond that has been created with g_cond_new().
2370 g_cond_free (GCond *cond)
2372 g_cond_clear (cond);
2373 g_slice_free (GCond, cond);
2378 * @destructor: a function to destroy the data keyed to
2379 * the #GPrivate when a thread ends
2381 * Creates a new #GPrivate. If @destructor is non-%NULL, it is a
2382 * pointer to a destructor function. Whenever a thread ends and the
2383 * corresponding pointer keyed to this instance of #GPrivate is
2384 * non-%NULL, the destructor is called with this pointer as the
2388 * #GStaticPrivate is a better choice for most uses.
2391 * <note><para>@destructor is used quite differently from @notify in
2392 * g_static_private_set().</para></note>
2394 * <note><para>A #GPrivate cannot be freed. Reuse it instead, if you
2395 * can, to avoid shortage, or use #GStaticPrivate.</para></note>
2397 * <note><para>This function will abort if g_thread_init() has not been
2398 * called yet.</para></note>
2400 * Returns: a newly allocated #GPrivate
2403 g_private_new (GDestroyNotify notify)
2407 key = g_slice_new (GPrivate);
2408 g_private_init (key, notify);
2413 GThreadFunctions g_thread_functions_for_glib_use =