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"
55 #endif /* G_OS_WIN32 */
61 #include "gtestutils.h"
69 * @short_description: thread abstraction; including threads, different
70 * mutexes, 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, #GStaticMutex, #G_LOCK_DEFINE, #GStaticRecMutex and
87 * #GStaticRWLock). There are primitives for condition variables to
88 * allow synchronization of threads (#GCond). There are primitives for
89 * thread-private data - data that every thread has a private instance
90 * of (#GPrivate, #GStaticPrivate). Last but definitely not least there
91 * are primitives to portably create and manage threads (#GThread).
93 * The threading system is initialized with g_thread_init(), which
94 * takes an optional custom thread implementation or %NULL for the
95 * default implementation. If you want to call g_thread_init() with a
96 * non-%NULL argument this must be done before executing any other GLib
97 * functions (except g_mem_set_vtable()). This is a requirement even if
98 * no threads are in fact ever created by the process.
100 * Calling g_thread_init() with a %NULL argument is somewhat more
101 * relaxed. You may call any other glib functions in the main thread
102 * before g_thread_init() as long as g_thread_init() is not called from
103 * a glib callback, or with any locks held. However, many libraries
104 * above glib does not support late initialization of threads, so doing
105 * this should be avoided if possible.
107 * Please note that since version 2.24 the GObject initialization
108 * function g_type_init() initializes threads (with a %NULL argument),
109 * so most applications, including those using Gtk+ will run with
110 * threads enabled. If you want a special thread implementation, make
111 * sure you call g_thread_init() before g_type_init() is called.
113 * After calling g_thread_init(), GLib is completely thread safe (all
114 * global data is automatically locked), but individual data structure
115 * instances are not automatically locked for performance reasons. So,
116 * for example you must coordinate accesses to the same #GHashTable
117 * from multiple threads. The two notable exceptions from this rule
118 * are #GMainLoop and #GAsyncQueue, which <emphasis>are</emphasis>
119 * threadsafe and need no further application-level locking to be
120 * accessed from multiple threads.
122 * To help debugging problems in multithreaded applications, GLib
123 * supports error-checking mutexes that will give you helpful error
124 * messages on common problems. To use error-checking mutexes, define
125 * the symbol #G_ERRORCHECK_MUTEXES when compiling the application.
129 * G_THREADS_IMPL_POSIX:
131 * This macro is defined if POSIX style threads are used.
137 * This macro is defined if GLib was compiled with thread support. This
138 * does not necessarily mean that there is a thread implementation
139 * available, but it does mean that the infrastructure is in place and
140 * that once you provide a thread implementation to g_thread_init(),
141 * GLib will be multi-thread safe. If #G_THREADS_ENABLED is not
142 * defined, then Glib is not, and cannot be, multi-thread safe.
146 * G_THREADS_IMPL_NONE:
148 * This macro is defined if no thread implementation is used. You can,
149 * however, provide one to g_thread_init() to make GLib multi-thread
153 /* G_LOCK Documentation {{{1 ---------------------------------------------- */
155 /* IMPLEMENTATION NOTE:
157 * G_LOCK_DEFINE and friends are convenience macros defined in
158 * gthread.h. Their documentation lives here.
163 * @name: the name of the lock.
165 * The %G_LOCK_* macros provide a convenient interface to #GStaticMutex
166 * with the advantage that they will expand to nothing in programs
167 * compiled against a thread-disabled GLib, saving code and memory
168 * there. #G_LOCK_DEFINE defines a lock. It can appear anywhere
169 * variable definitions may appear in programs, i.e. in the first block
170 * of a function or outside of functions. The @name parameter will be
171 * mangled to get the name of the #GStaticMutex. This means that you
172 * can use names of existing variables as the parameter - e.g. the name
173 * of the variable you intent to protect with the lock. Look at our
174 * <function>give_me_next_number()</function> example using the
178 * <title>Using the %G_LOCK_* convenience macros</title>
180 * G_LOCK_DEFINE (current_number);
183 * give_me_next_number (void)
185 * static int current_number = 0;
188 * G_LOCK (current_number);
189 * ret_val = current_number = calc_next_number (current_number);
190 * G_UNLOCK (current_number);
199 * G_LOCK_DEFINE_STATIC:
200 * @name: the name of the lock.
202 * This works like #G_LOCK_DEFINE, but it creates a static object.
207 * @name: the name of the lock.
209 * This declares a lock, that is defined with #G_LOCK_DEFINE in another
215 * @name: the name of the lock.
217 * Works like g_mutex_lock(), but for a lock defined with
223 * @name: the name of the lock.
224 * @Returns: %TRUE, if the lock could be locked.
226 * Works like g_mutex_trylock(), but for a lock defined with
232 * @name: the name of the lock.
234 * Works like g_mutex_unlock(), but for a lock defined with
238 /* GThreadError {{{1 ------------------------------------------------------- */
241 * @G_THREAD_ERROR_AGAIN: a thread couldn't be created due to resource
242 * shortage. Try again later.
244 * Possible errors of thread related functions.
250 * The error domain of the GLib thread subsystem.
253 g_thread_error_quark (void)
255 return g_quark_from_static_string ("g_thread_error");
258 /* Miscellaneous Structures {{{1 ------------------------------------------ */
259 /* Keep this in sync with GRealThread in gmain.c! */
260 typedef struct _GRealThread GRealThread;
264 gpointer private_data;
267 GSystemThread system_thread;
270 typedef struct _GStaticPrivateNode GStaticPrivateNode;
271 struct _GStaticPrivateNode
274 GDestroyNotify destroy;
277 static void g_thread_cleanup (gpointer data);
278 static void g_thread_fail (void);
279 static guint64 gettime (void);
281 guint64 (*g_thread_gettime) (void) = gettime;
283 /* Global Variables {{{1 -------------------------------------------------- */
285 static GSystemThread zero_thread; /* This is initialized to all zero */
286 gboolean g_thread_use_default_impl = TRUE;
289 * g_thread_supported:
290 * @Returns: %TRUE, if the thread system is initialized.
292 * This function returns %TRUE if the thread system is initialized, and
293 * %FALSE if it is not.
295 * <note><para>This function is actually a macro. Apart from taking the
296 * address of it you can however use it as if it was a
297 * function.</para></note>
300 /* IMPLEMENTATION NOTE:
302 * g_thread_supported() is just returns g_threads_got_initialized
304 gboolean g_threads_got_initialized = FALSE;
307 /* Thread Implementation Virtual Function Table {{{1 ---------------------- */
308 /* Virtual Function Table Documentation {{{2 ------------------------------ */
311 * @mutex_new: virtual function pointer for g_mutex_new()
312 * @mutex_lock: virtual function pointer for g_mutex_lock()
313 * @mutex_trylock: virtual function pointer for g_mutex_trylock()
314 * @mutex_unlock: virtual function pointer for g_mutex_unlock()
315 * @mutex_free: virtual function pointer for g_mutex_free()
316 * @cond_new: virtual function pointer for g_cond_new()
317 * @cond_signal: virtual function pointer for g_cond_signal()
318 * @cond_broadcast: virtual function pointer for g_cond_broadcast()
319 * @cond_wait: virtual function pointer for g_cond_wait()
320 * @cond_timed_wait: virtual function pointer for g_cond_timed_wait()
321 * @cond_free: virtual function pointer for g_cond_free()
322 * @private_new: virtual function pointer for g_private_new()
323 * @private_get: virtual function pointer for g_private_get()
324 * @private_set: virtual function pointer for g_private_set()
325 * @thread_create: virtual function pointer for g_thread_create()
326 * @thread_yield: virtual function pointer for g_thread_yield()
327 * @thread_join: virtual function pointer for g_thread_join()
328 * @thread_exit: virtual function pointer for g_thread_exit()
329 * @thread_set_priority: virtual function pointer for
330 * g_thread_set_priority()
331 * @thread_self: virtual function pointer for g_thread_self()
332 * @thread_equal: used internally by recursive mutex locks and by some
335 * This function table is used by g_thread_init() to initialize the
336 * thread system. The functions in the table are directly used by their
337 * g_* prepended counterparts (described in this document). For
338 * example, if you call g_mutex_new() then mutex_new() from the table
339 * provided to g_thread_init() will be called.
341 * <note><para>Do not use this struct unless you know what you are
342 * doing.</para></note>
345 /* IMPLEMENTATION NOTE:
347 * g_thread_functions_for_glib_use is a global symbol that gets used by
348 * most of the "primative" threading calls. g_mutex_lock(), for
349 * example, is just a macro that calls the appropriate virtual function
352 * For that reason, all of those macros are documented here.
354 GThreadFunctions g_thread_functions_for_glib_use = {
355 /* GMutex Virtual Functions {{{2 ------------------------------------------ */
360 * The #GMutex struct is an opaque data structure to represent a mutex
361 * (mutual exclusion). It can be used to protect data against shared
362 * access. Take for example the following function:
365 * <title>A function which will not work in a threaded environment</title>
368 * give_me_next_number (void)
370 * static int current_number = 0;
372 * /<!-- -->* now do a very complicated calculation to calculate the new
373 * * number, this might for example be a random number generator
375 * current_number = calc_next_number (current_number);
377 * return current_number;
382 * It is easy to see that this won't work in a multi-threaded
383 * application. There current_number must be protected against shared
384 * access. A first naive implementation would be:
387 * <title>The wrong way to write a thread-safe function</title>
390 * give_me_next_number (void)
392 * static int current_number = 0;
394 * static GMutex * mutex = NULL;
396 * if (!mutex) mutex = g_mutex_new (<!-- -->);
398 * g_mutex_lock (mutex);
399 * ret_val = current_number = calc_next_number (current_number);
400 * g_mutex_unlock (mutex);
407 * This looks like it would work, but there is a race condition while
408 * constructing the mutex and this code cannot work reliable. Please do
409 * not use such constructs in your own programs! One working solution
413 * <title>A correct thread-safe function</title>
415 * static GMutex *give_me_next_number_mutex = NULL;
417 * /<!-- -->* this function must be called before any call to
418 * * give_me_next_number(<!-- -->)
420 * * it must be called exactly once.
423 * init_give_me_next_number (void)
425 * g_assert (give_me_next_number_mutex == NULL);
426 * give_me_next_number_mutex = g_mutex_new (<!-- -->);
430 * give_me_next_number (void)
432 * static int current_number = 0;
435 * g_mutex_lock (give_me_next_number_mutex);
436 * ret_val = current_number = calc_next_number (current_number);
437 * g_mutex_unlock (give_me_next_number_mutex);
444 * #GStaticMutex provides a simpler and safer way of doing this.
446 * If you want to use a mutex, and your code should also work without
447 * calling g_thread_init() first, then you can not use a #GMutex, as
448 * g_mutex_new() requires that the thread system be initialized. Use a
449 * #GStaticMutex instead.
451 * A #GMutex should only be accessed via the following functions.
453 * <note><para>All of the <function>g_mutex_*</function> functions are
454 * actually macros. Apart from taking their addresses, you can however
455 * use them as if they were functions.</para></note>
460 * @Returns: a new #GMutex.
462 * Creates a new #GMutex.
464 * <note><para>This function will abort if g_thread_init() has not been
465 * called yet.</para></note>
467 (GMutex*(*)())g_thread_fail,
473 * Locks @mutex. If @mutex is already locked by another thread, the
474 * current thread will block until @mutex is unlocked by the other
477 * This function can be used even if g_thread_init() has not yet been
478 * called, and, in that case, will do nothing.
480 * <note><para>#GMutex is neither guaranteed to be recursive nor to be
481 * non-recursive, i.e. a thread could deadlock while calling
482 * g_mutex_lock(), if it already has locked @mutex. Use
483 * #GStaticRecMutex, if you need recursive mutexes.</para></note>
490 * @Returns: %TRUE, if @mutex could be locked.
492 * Tries to lock @mutex. If @mutex is already locked by another thread,
493 * it immediately returns %FALSE. Otherwise it locks @mutex and returns
496 * This function can be used even if g_thread_init() has not yet been
497 * called, and, in that case, will immediately return %TRUE.
499 * <note><para>#GMutex is neither guaranteed to be recursive nor to be
500 * non-recursive, i.e. the return value of g_mutex_trylock() could be
501 * both %FALSE or %TRUE, if the current thread already has locked
502 * @mutex. Use #GStaticRecMutex, if you need recursive
503 * mutexes.</para></note>
511 * Unlocks @mutex. If another thread is blocked in a g_mutex_lock()
512 * call for @mutex, it will be woken and can lock @mutex itself.
514 * This function can be used even if g_thread_init() has not yet been
515 * called, and, in that case, will do nothing.
525 * <note><para>Calling g_mutex_free() on a locked mutex may result in
526 * undefined behaviour.</para></note>
530 /* GCond Virtual Functions {{{2 ------------------------------------------ */
535 * The #GCond struct is an opaque data structure that represents a
536 * condition. Threads can block on a #GCond if they find a certain
537 * condition to be false. If other threads change the state of this
538 * condition they signal the #GCond, and that causes the waiting
539 * threads to be woken up.
543 * Using GCond to block a thread until a condition is satisfied
546 * GCond* data_cond = NULL; /<!-- -->* Must be initialized somewhere *<!-- -->/
547 * GMutex* data_mutex = NULL; /<!-- -->* Must be initialized somewhere *<!-- -->/
548 * gpointer current_data = NULL;
551 * push_data (gpointer data)
553 * g_mutex_lock (data_mutex);
554 * current_data = data;
555 * g_cond_signal (data_cond);
556 * g_mutex_unlock (data_mutex);
564 * g_mutex_lock (data_mutex);
565 * while (!current_data)
566 * g_cond_wait (data_cond, data_mutex);
567 * data = current_data;
568 * current_data = NULL;
569 * g_mutex_unlock (data_mutex);
576 * Whenever a thread calls <function>pop_data()</function> now, it will
577 * wait until current_data is non-%NULL, i.e. until some other thread
578 * has called <function>push_data()</function>.
580 * <note><para>It is important to use the g_cond_wait() and
581 * g_cond_timed_wait() functions only inside a loop which checks for the
582 * condition to be true. It is not guaranteed that the waiting thread
583 * will find the condition fulfilled after it wakes up, even if the
584 * signaling thread left the condition in that state: another thread may
585 * have altered the condition before the waiting thread got the chance
586 * to be woken up, even if the condition itself is protected by a
587 * #GMutex, like above.</para></note>
589 * A #GCond should only be accessed via the following functions.
591 * <note><para>All of the <function>g_cond_*</function> functions are
592 * actually macros. Apart from taking their addresses, you can however
593 * use them as if they were functions.</para></note>
598 * @Returns: a new #GCond.
600 * Creates a new #GCond. This function will abort, if g_thread_init()
601 * has not been called yet.
603 (GCond*(*)())g_thread_fail,
609 * If threads are waiting for @cond, exactly one of them is woken up.
610 * It is good practice to hold the same lock as the waiting thread
611 * while calling this function, though not required.
613 * This function can be used even if g_thread_init() has not yet been
614 * called, and, in that case, will do nothing.
622 * If threads are waiting for @cond, all of them are woken up. It is
623 * good practice to lock the same mutex as the waiting threads, while
624 * calling this function, though not required.
626 * This function can be used even if g_thread_init() has not yet been
627 * called, and, in that case, will do nothing.
634 * @mutex: a #GMutex, that is currently locked.
636 * Waits until this thread is woken up on @cond. The @mutex is unlocked
637 * before falling asleep and locked again before resuming.
639 * This function can be used even if g_thread_init() has not yet been
640 * called, and, in that case, will immediately return.
647 * @mutex: a #GMutex that is currently locked.
648 * @abs_time: a #GTimeVal, determining the final time.
649 * @Returns: %TRUE if @cond was signalled, or %FALSE on timeout.
651 * Waits until this thread is woken up on @cond, but not longer than
652 * until the time specified by @abs_time. The @mutex is unlocked before
653 * falling asleep and locked again before resuming.
655 * If @abs_time is %NULL, g_cond_timed_wait() acts like g_cond_wait().
657 * This function can be used even if g_thread_init() has not yet been
658 * called, and, in that case, will immediately return %TRUE.
660 * To easily calculate @abs_time a combination of g_get_current_time()
661 * and g_time_val_add() can be used.
669 * Destroys the #GCond.
673 /* GPrivate Virtual Functions {{{2 --------------------------------------- */
678 * The #GPrivate struct is an opaque data structure to represent a
679 * thread private data key. Threads can thereby obtain and set a
680 * pointer which is private to the current thread. Take our
681 * <function>give_me_next_number(<!-- -->)</function> example from
682 * above. Suppose we don't want <literal>current_number</literal> to be
683 * shared between the threads, but instead to be private to each thread.
684 * This can be done as follows:
687 * <title>Using GPrivate for per-thread data</title>
689 * GPrivate* current_number_key = NULL; /<!-- -->* Must be initialized somewhere
690 * with g_private_new (g_free); *<!-- -->/
693 * give_me_next_number (void)
695 * int *current_number = g_private_get (current_number_key);
697 * if (!current_number)
699 * current_number = g_new (int, 1);
700 * *current_number = 0;
701 * g_private_set (current_number_key, current_number);
704 * *current_number = calc_next_number (*current_number);
706 * return *current_number;
711 * Here the pointer belonging to the key
712 * <literal>current_number_key</literal> is read. If it is %NULL, it has
713 * not been set yet. Then get memory for an integer value, assign this
714 * memory to the pointer and write the pointer back. Now we have an
715 * integer value that is private to the current thread.
717 * The #GPrivate struct should only be accessed via the following
720 * <note><para>All of the <function>g_private_*</function> functions are
721 * actually macros. Apart from taking their addresses, you can however
722 * use them as if they were functions.</para></note>
727 * @destructor: a function to destroy the data keyed to #GPrivate when
729 * @Returns: a new #GPrivate.
731 * Creates a new #GPrivate. If @destructor is non-%NULL, it is a
732 * pointer to a destructor function. Whenever a thread ends and the
733 * corresponding pointer keyed to this instance of #GPrivate is
734 * non-%NULL, the destructor is called with this pointer as the
737 * <note><para>@destructor is used quite differently from @notify in
738 * g_static_private_set().</para></note>
740 * <note><para>A #GPrivate can not be freed. Reuse it instead, if you
741 * can, to avoid shortage, or use #GStaticPrivate.</para></note>
743 * <note><para>This function will abort if g_thread_init() has not been
744 * called yet.</para></note>
746 (GPrivate*(*)(GDestroyNotify))g_thread_fail,
750 * @private_key: a #GPrivate.
751 * @Returns: the corresponding pointer.
753 * Returns the pointer keyed to @private_key for the current thread. If
754 * g_private_set() hasn't been called for the current @private_key and
755 * thread yet, this pointer will be %NULL.
757 * This function can be used even if g_thread_init() has not yet been
758 * called, and, in that case, will return the value of @private_key
759 * casted to #gpointer. Note however, that private data set
760 * <emphasis>before</emphasis> g_thread_init() will
761 * <emphasis>not</emphasis> be retained <emphasis>after</emphasis> the
762 * call. Instead, %NULL will be returned in all threads directly after
763 * g_thread_init(), regardless of any g_private_set() calls issued
764 * before threading system intialization.
770 * @private_key: a #GPrivate.
771 * @data: the new pointer.
773 * Sets the pointer keyed to @private_key for the current thread.
775 * This function can be used even if g_thread_init() has not yet been
776 * called, and, in that case, will set @private_key to @data casted to
777 * #GPrivate*. See g_private_get() for resulting caveats.
781 /* GThread Virtual Functions {{{2 ---------------------------------------- */
785 * The #GThread struct represents a running thread. It has three public
786 * read-only members, but the underlying struct is bigger, so you must
787 * not copy this struct.
789 * <note><para>Resources for a joinable thread are not fully released
790 * until g_thread_join() is called for that thread.</para></note>
795 * @data: data passed to the thread.
796 * @Returns: the return value of the thread, which will be returned by
799 * Specifies the type of the @func functions passed to
800 * g_thread_create() or g_thread_create_full().
805 * @G_THREAD_PRIORITY_LOW: a priority lower than normal
806 * @G_THREAD_PRIORITY_NORMAL: the default priority
807 * @G_THREAD_PRIORITY_HIGH: a priority higher than normal
808 * @G_THREAD_PRIORITY_URGENT: the highest priority
810 * Specifies the priority of a thread.
812 * <note><para>It is not guaranteed that threads with different priorities
813 * really behave accordingly. On some systems (e.g. Linux) there are no
814 * thread priorities. On other systems (e.g. Solaris) there doesn't
815 * seem to be different scheduling for different priorities. All in all
816 * try to avoid being dependent on priorities.</para></note>
821 * @func: a function to execute in the new thread.
822 * @data: an argument to supply to the new thread.
823 * @joinable: should this thread be joinable?
824 * @error: return location for error.
825 * @Returns: the new #GThread on success.
827 * This function creates a new thread with the default priority.
829 * If @joinable is %TRUE, you can wait for this threads termination
830 * calling g_thread_join(). Otherwise the thread will just disappear
831 * when it terminates.
833 * The new thread executes the function @func with the argument @data.
834 * If the thread was created successfully, it is returned.
836 * @error can be %NULL to ignore errors, or non-%NULL to report errors.
837 * The error is set, if and only if the function returns %NULL.
839 (void(*)(GThreadFunc, gpointer, gulong,
840 gboolean, gboolean, GThreadPriority,
841 gpointer, GError**))g_thread_fail,
846 * Gives way to other threads waiting to be scheduled.
848 * This function is often used as a method to make busy wait less evil.
849 * But in most cases you will encounter, there are better methods to do
850 * that. So in general you shouldn't use this function.
854 NULL, /* thread_join */
855 NULL, /* thread_exit */
856 NULL, /* thread_set_priority */
857 NULL, /* thread_self */
858 NULL /* thread_equal */
861 /* Local Data {{{1 -------------------------------------------------------- */
863 static GMutex *g_once_mutex = NULL;
864 static GCond *g_once_cond = NULL;
865 static GPrivate *g_thread_specific_private = NULL;
866 static GRealThread *g_thread_all_threads = NULL;
867 static GSList *g_thread_free_indeces = NULL;
868 static GSList* g_once_init_list = NULL;
870 G_LOCK_DEFINE_STATIC (g_thread);
872 /* Initialisation {{{1 ---------------------------------------------------- */
874 #ifdef G_THREADS_ENABLED
877 * @vtable: a function table of type #GThreadFunctions, that provides
878 * the entry points to the thread system to be used.
880 * If you use GLib from more than one thread, you must initialize the
881 * thread system by calling g_thread_init(). Most of the time you will
882 * only have to call <literal>g_thread_init (NULL)</literal>.
884 * <note><para>Do not call g_thread_init() with a non-%NULL parameter unless
885 * you really know what you are doing.</para></note>
887 * <note><para>g_thread_init() must not be called directly or indirectly as a
888 * callback from GLib. Also no mutexes may be currently locked while
889 * calling g_thread_init().</para></note>
891 * <note><para>g_thread_init() changes the way in which #GTimer measures
892 * elapsed time. As a consequence, timers that are running while
893 * g_thread_init() is called may report unreliable times.</para></note>
895 * Calling g_thread_init() multiple times is allowed (since version
896 * 2.24), but nothing happens except for the first call. If the
897 * argument is non-%NULL on such a call a warning will be printed, but
898 * otherwise the argument is ignored.
900 * If no thread system is available and @vtable is %NULL or if not all
901 * elements of @vtable are non-%NULL, then g_thread_init() will abort.
903 * <note><para>To use g_thread_init() in your program, you have to link with
904 * the libraries that the command <command>pkg-config --libs
905 * gthread-2.0</command> outputs. This is not the case for all the
906 * other thread related functions of GLib. Those can be used without
907 * having to link with the thread libraries.</para></note>
910 /* This must be called only once, before any threads are created.
911 * It will only be called from g_thread_init() in -lgthread.
914 g_thread_init_glib (void)
916 /* We let the main thread (the one that calls g_thread_init) inherit
917 * the static_private data set before calling g_thread_init
919 GRealThread* main_thread = (GRealThread*) g_thread_self ();
921 /* mutex and cond creation works without g_threads_got_initialized */
922 g_once_mutex = g_mutex_new ();
923 g_once_cond = g_cond_new ();
925 /* we may only create mutex and cond in here */
926 _g_mem_thread_init_noprivate_nomessage ();
928 /* setup the basic threading system */
929 g_threads_got_initialized = TRUE;
930 g_thread_specific_private = g_private_new (g_thread_cleanup);
931 g_private_set (g_thread_specific_private, main_thread);
932 G_THREAD_UF (thread_self, (&main_thread->system_thread));
934 /* complete memory system initialization, g_private_*() works now */
935 _g_slice_thread_init_nomessage ();
937 /* accomplish log system initialization to enable messaging */
938 _g_messages_thread_init_nomessage ();
940 /* we may run full-fledged initializers from here */
941 _g_atomic_thread_init ();
942 _g_convert_thread_init ();
943 _g_rand_thread_init ();
944 _g_main_thread_init ();
945 _g_utils_thread_init ();
946 _g_futex_thread_init ();
948 _g_win32_thread_init ();
951 #endif /* G_THREADS_ENABLED */
953 /* The following sections implement: GOnce, GStaticMutex, GStaticRecMutex,
957 /* GOnce {{{1 ------------------------------------------------------------- */
961 * @status: the status of the #GOnce
962 * @retval: the value returned by the call to the function, if @status
963 * is %G_ONCE_STATUS_READY
965 * A #GOnce struct controls a one-time initialization function. Any
966 * one-time initialization function must have its own unique #GOnce
975 * A #GOnce must be initialized with this macro before it can be used.
979 * GOnce my_once = G_ONCE_INIT;
988 * @G_ONCE_STATUS_NOTCALLED: the function has not been called yet.
989 * @G_ONCE_STATUS_PROGRESS: the function call is currently in progress.
990 * @G_ONCE_STATUS_READY: the function has been called.
992 * The possible statuses of a one-time initialization function
993 * controlled by a #GOnce struct.
1000 * @once: a #GOnce structure
1001 * @func: the #GThreadFunc function associated to @once. This function
1002 * is called only once, regardless of the number of times it and
1003 * its associated #GOnce struct are passed to g_once().
1004 * @arg: data to be passed to @func
1006 * The first call to this routine by a process with a given #GOnce
1007 * struct calls @func with the given argument. Thereafter, subsequent
1008 * calls to g_once() with the same #GOnce struct do not call @func
1009 * again, but return the stored result of the first call. On return
1010 * from g_once(), the status of @once will be %G_ONCE_STATUS_READY.
1012 * For example, a mutex or a thread-specific data key must be created
1013 * exactly once. In a threaded environment, calling g_once() ensures
1014 * that the initialization is serialized across multiple threads.
1016 * <note><para>Calling g_once() recursively on the same #GOnce struct in
1017 * @func will lead to a deadlock.</para></note>
1022 * get_debug_flags (void)
1024 * static GOnce my_once = G_ONCE_INIT;
1026 * g_once (&my_once, parse_debug_flags, NULL);
1028 * return my_once.retval;
1031 * </informalexample>
1036 g_once_impl (GOnce *once,
1040 g_mutex_lock (g_once_mutex);
1042 while (once->status == G_ONCE_STATUS_PROGRESS)
1043 g_cond_wait (g_once_cond, g_once_mutex);
1045 if (once->status != G_ONCE_STATUS_READY)
1047 once->status = G_ONCE_STATUS_PROGRESS;
1048 g_mutex_unlock (g_once_mutex);
1050 once->retval = func (arg);
1052 g_mutex_lock (g_once_mutex);
1053 once->status = G_ONCE_STATUS_READY;
1054 g_cond_broadcast (g_once_cond);
1057 g_mutex_unlock (g_once_mutex);
1059 return once->retval;
1063 * g_once_init_enter:
1064 * @value_location: location of a static initializable variable
1066 * @Returns: %TRUE if the initialization section should be entered,
1067 * %FALSE and blocks otherwise
1069 * Function to be called when starting a critical initialization
1070 * section. The argument @value_location must point to a static
1071 * 0-initialized variable that will be set to a value other than 0 at
1072 * the end of the initialization section. In combination with
1073 * g_once_init_leave() and the unique address @value_location, it can
1074 * be ensured that an initialization section will be executed only once
1075 * during a program's life time, and that concurrent threads are
1076 * blocked until initialization completed. To be used in constructs
1081 * static gsize initialization_value = 0;
1083 * if (g_once_init_enter (&initialization_value))
1085 * gsize setup_value = 42; /<!-- -->* initialization code here *<!-- -->/
1087 * g_once_init_leave (&initialization_value, setup_value);
1090 * /<!-- -->* use initialization_value here *<!-- -->/
1092 * </informalexample>
1097 g_once_init_enter_impl (volatile gsize *value_location)
1099 gboolean need_init = FALSE;
1100 g_mutex_lock (g_once_mutex);
1101 if (g_atomic_pointer_get (value_location) == NULL)
1103 if (!g_slist_find (g_once_init_list, (void*) value_location))
1106 g_once_init_list = g_slist_prepend (g_once_init_list, (void*) value_location);
1110 g_cond_wait (g_once_cond, g_once_mutex);
1111 while (g_slist_find (g_once_init_list, (void*) value_location));
1113 g_mutex_unlock (g_once_mutex);
1118 * g_once_init_leave:
1119 * @value_location: location of a static initializable variable
1121 * @initialization_value: new non-0 value for *@value_location.
1123 * Counterpart to g_once_init_enter(). Expects a location of a static
1124 * 0-initialized initialization variable, and an initialization value
1125 * other than 0. Sets the variable to the initialization value, and
1126 * releases concurrent threads blocking in g_once_init_enter() on this
1127 * initialization variable.
1132 g_once_init_leave (volatile gsize *value_location,
1133 gsize initialization_value)
1135 g_return_if_fail (g_atomic_pointer_get (value_location) == NULL);
1136 g_return_if_fail (initialization_value != 0);
1137 g_return_if_fail (g_once_init_list != NULL);
1139 g_atomic_pointer_set ((void**)value_location, (void*) initialization_value);
1140 g_mutex_lock (g_once_mutex);
1141 g_once_init_list = g_slist_remove (g_once_init_list, (void*) value_location);
1142 g_cond_broadcast (g_once_cond);
1143 g_mutex_unlock (g_once_mutex);
1146 /* GStaticMutex {{{1 ------------------------------------------------------ */
1151 * A #GStaticMutex works like a #GMutex, but it has one significant
1152 * advantage. It doesn't need to be created at run-time like a #GMutex,
1153 * but can be defined at compile-time. Here is a shorter, easier and
1154 * safer version of our <function>give_me_next_number()</function>
1159 * Using <structname>GStaticMutex</structname>
1160 * to simplify thread-safe programming
1164 * give_me_next_number (void)
1166 * static int current_number = 0;
1168 * static GStaticMutex mutex = G_STATIC_MUTEX_INIT;
1170 * g_static_mutex_lock (&mutex);
1171 * ret_val = current_number = calc_next_number (current_number);
1172 * g_static_mutex_unlock (&mutex);
1179 * Sometimes you would like to dynamically create a mutex. If you don't
1180 * want to require prior calling to g_thread_init(), because your code
1181 * should also be usable in non-threaded programs, you are not able to
1182 * use g_mutex_new() and thus #GMutex, as that requires a prior call to
1183 * g_thread_init(). In theses cases you can also use a #GStaticMutex.
1184 * It must be initialized with g_static_mutex_init() before using it
1185 * and freed with with g_static_mutex_free() when not needed anymore to
1186 * free up any allocated resources.
1188 * Even though #GStaticMutex is not opaque, it should only be used with
1189 * the following functions, as it is defined differently on different
1192 * All of the <function>g_static_mutex_*</function> functions apart
1193 * from <function>g_static_mutex_get_mutex</function> can also be used
1194 * even if g_thread_init() has not yet been called. Then they do
1195 * nothing, apart from <function>g_static_mutex_trylock</function>,
1196 * which does nothing but returning %TRUE.
1198 * <note><para>All of the <function>g_static_mutex_*</function>
1199 * functions are actually macros. Apart from taking their addresses, you
1200 * can however use them as if they were functions.</para></note>
1204 * G_STATIC_MUTEX_INIT:
1206 * A #GStaticMutex must be initialized with this macro, before it can
1207 * be used. This macro can used be to initialize a variable, but it
1208 * cannot be assigned to a variable. In that case you have to use
1209 * g_static_mutex_init().
1213 * GStaticMutex my_mutex = G_STATIC_MUTEX_INIT;
1215 * </informalexample>
1219 * g_static_mutex_init:
1220 * @mutex: a #GStaticMutex to be initialized.
1222 * Initializes @mutex. Alternatively you can initialize it with
1223 * #G_STATIC_MUTEX_INIT.
1226 g_static_mutex_init (GStaticMutex *mutex)
1228 static const GStaticMutex init_mutex = G_STATIC_MUTEX_INIT;
1230 g_return_if_fail (mutex);
1232 *mutex = init_mutex;
1235 /* IMPLEMENTATION NOTE:
1237 * On some platforms a GStaticMutex is actually a normal GMutex stored
1238 * inside of a structure instead of being allocated dynamically. We can
1239 * only do this for platforms on which we know, in advance, how to
1240 * allocate (size) and initialise (value) that memory.
1242 * On other platforms, a GStaticMutex is nothing more than a pointer to
1243 * a GMutex. In that case, the first access we make to the static mutex
1244 * must first allocate the normal GMutex and store it into the pointer.
1246 * configure.in writes macros into glibconfig.h to determine if
1247 * g_static_mutex_get_mutex() accesses the sturcture in memory directly
1248 * (on platforms where we are able to do that) or if it ends up here,
1249 * where we may have to allocate the GMutex before returning it.
1253 * g_static_mutex_get_mutex:
1254 * @mutex: a #GStaticMutex.
1255 * @Returns: the #GMutex corresponding to @mutex.
1257 * For some operations (like g_cond_wait()) you must have a #GMutex
1258 * instead of a #GStaticMutex. This function will return the
1259 * corresponding #GMutex for @mutex.
1262 g_static_mutex_get_mutex_impl (GMutex** mutex)
1264 if (!g_thread_supported ())
1267 g_assert (g_once_mutex);
1269 g_mutex_lock (g_once_mutex);
1272 g_atomic_pointer_set (mutex, g_mutex_new());
1274 g_mutex_unlock (g_once_mutex);
1279 /* IMPLEMENTATION NOTE:
1281 * g_static_mutex_lock(), g_static_mutex_trylock() and
1282 * g_static_mutex_unlock() are all preprocessor macros that wrap the
1283 * corresponding g_mutex_*() function around a call to
1284 * g_static_mutex_get_mutex().
1288 * g_static_mutex_lock:
1289 * @mutex: a #GStaticMutex.
1291 * Works like g_mutex_lock(), but for a #GStaticMutex.
1295 * g_static_mutex_trylock:
1296 * @mutex: a #GStaticMutex.
1297 * @Returns: %TRUE, if the #GStaticMutex could be locked.
1299 * Works like g_mutex_trylock(), but for a #GStaticMutex.
1303 * g_static_mutex_unlock:
1304 * @mutex: a #GStaticMutex.
1306 * Works like g_mutex_unlock(), but for a #GStaticMutex.
1310 * g_static_mutex_free:
1311 * @mutex: a #GStaticMutex to be freed.
1313 * Releases all resources allocated to @mutex.
1315 * You don't have to call this functions for a #GStaticMutex with an
1316 * unbounded lifetime, i.e. objects declared 'static', but if you have
1317 * a #GStaticMutex as a member of a structure and the structure is
1318 * freed, you should also free the #GStaticMutex.
1320 * <note><para>Calling g_static_mutex_free() on a locked mutex may
1321 * result in undefined behaviour.</para></note>
1324 g_static_mutex_free (GStaticMutex* mutex)
1326 GMutex **runtime_mutex;
1328 g_return_if_fail (mutex);
1330 /* The runtime_mutex is the first (or only) member of GStaticMutex,
1331 * see both versions (of glibconfig.h) in configure.in. Note, that
1332 * this variable is NULL, if g_thread_init() hasn't been called or
1333 * if we're using the default thread implementation and it provides
1334 * static mutexes. */
1335 runtime_mutex = ((GMutex**)mutex);
1338 g_mutex_free (*runtime_mutex);
1340 *runtime_mutex = NULL;
1343 /* ------------------------------------------------------------------------ */
1348 * A #GStaticRecMutex works like a #GStaticMutex, but it can be locked
1349 * multiple times by one thread. If you enter it n times, you have to
1350 * unlock it n times again to let other threads lock it. An exception
1351 * is the function g_static_rec_mutex_unlock_full(): that allows you to
1352 * unlock a #GStaticRecMutex completely returning the depth, (i.e. the
1353 * number of times this mutex was locked). The depth can later be used
1354 * to restore the state of the #GStaticRecMutex by calling
1355 * g_static_rec_mutex_lock_full().
1357 * Even though #GStaticRecMutex is not opaque, it should only be used
1358 * with the following functions.
1360 * All of the <function>g_static_rec_mutex_*</function> functions can
1361 * be used even if g_thread_init() has not been called. Then they do
1362 * nothing, apart from <function>g_static_rec_mutex_trylock</function>,
1363 * which does nothing but returning %TRUE.
1367 * G_STATIC_REC_MUTEX_INIT:
1369 * A #GStaticRecMutex must be initialized with this macro before it can
1370 * be used. This macro can used be to initialize a variable, but it
1371 * cannot be assigned to a variable. In that case you have to use
1372 * g_static_rec_mutex_init().
1376 * GStaticRecMutex my_mutex = G_STATIC_REC_MUTEX_INIT;
1382 * g_static_rec_mutex_init:
1383 * @mutex: a #GStaticRecMutex to be initialized.
1385 * A #GStaticRecMutex must be initialized with this function before it
1386 * can be used. Alternatively you can initialize it with
1387 * #G_STATIC_REC_MUTEX_INIT.
1390 g_static_rec_mutex_init (GStaticRecMutex *mutex)
1392 static const GStaticRecMutex init_mutex = G_STATIC_REC_MUTEX_INIT;
1394 g_return_if_fail (mutex);
1396 *mutex = init_mutex;
1400 * g_static_rec_mutex_lock:
1401 * @mutex: a #GStaticRecMutex to lock.
1403 * Locks @mutex. If @mutex is already locked by another thread, the
1404 * current thread will block until @mutex is unlocked by the other
1405 * thread. If @mutex is already locked by the calling thread, this
1406 * functions increases the depth of @mutex and returns immediately.
1409 g_static_rec_mutex_lock (GStaticRecMutex* mutex)
1413 g_return_if_fail (mutex);
1415 if (!g_thread_supported ())
1418 G_THREAD_UF (thread_self, (&self));
1420 if (g_system_thread_equal (self, mutex->owner))
1425 g_static_mutex_lock (&mutex->mutex);
1426 g_system_thread_assign (mutex->owner, self);
1431 * g_static_rec_mutex_trylock:
1432 * @mutex: a #GStaticRecMutex to lock.
1433 * @Returns: %TRUE, if @mutex could be locked.
1435 * Tries to lock @mutex. If @mutex is already locked by another thread,
1436 * it immediately returns %FALSE. Otherwise it locks @mutex and returns
1437 * %TRUE. If @mutex is already locked by the calling thread, this
1438 * functions increases the depth of @mutex and immediately returns
1442 g_static_rec_mutex_trylock (GStaticRecMutex* mutex)
1446 g_return_val_if_fail (mutex, FALSE);
1448 if (!g_thread_supported ())
1451 G_THREAD_UF (thread_self, (&self));
1453 if (g_system_thread_equal (self, mutex->owner))
1459 if (!g_static_mutex_trylock (&mutex->mutex))
1462 g_system_thread_assign (mutex->owner, self);
1468 * g_static_rec_mutex_unlock:
1469 * @mutex: a #GStaticRecMutex to unlock.
1471 * Unlocks @mutex. Another thread will be allowed to lock @mutex only
1472 * when it has been unlocked as many times as it had been locked
1473 * before. If @mutex is completely unlocked and another thread is
1474 * blocked in a g_static_rec_mutex_lock() call for @mutex, it will be
1475 * woken and can lock @mutex itself.
1478 g_static_rec_mutex_unlock (GStaticRecMutex* mutex)
1480 g_return_if_fail (mutex);
1482 if (!g_thread_supported ())
1485 if (mutex->depth > 1)
1490 g_system_thread_assign (mutex->owner, zero_thread);
1491 g_static_mutex_unlock (&mutex->mutex);
1495 * g_static_rec_mutex_lock_full:
1496 * @mutex: a #GStaticRecMutex to lock.
1497 * @depth: number of times this mutex has to be unlocked to be
1498 * completely unlocked.
1500 * Works like calling g_static_rec_mutex_lock() for @mutex @depth times.
1503 g_static_rec_mutex_lock_full (GStaticRecMutex *mutex,
1507 g_return_if_fail (mutex);
1509 if (!g_thread_supported ())
1515 G_THREAD_UF (thread_self, (&self));
1517 if (g_system_thread_equal (self, mutex->owner))
1519 mutex->depth += depth;
1522 g_static_mutex_lock (&mutex->mutex);
1523 g_system_thread_assign (mutex->owner, self);
1524 mutex->depth = depth;
1528 * g_static_rec_mutex_unlock_full:
1529 * @mutex: a #GStaticRecMutex to completely unlock.
1530 * @Returns: number of times @mutex has been locked by the current
1533 * Completely unlocks @mutex. If another thread is blocked in a
1534 * g_static_rec_mutex_lock() call for @mutex, it will be woken and can
1535 * lock @mutex itself. This function returns the number of times that
1536 * @mutex has been locked by the current thread. To restore the state
1537 * before the call to g_static_rec_mutex_unlock_full() you can call
1538 * g_static_rec_mutex_lock_full() with the depth returned by this
1542 g_static_rec_mutex_unlock_full (GStaticRecMutex *mutex)
1546 g_return_val_if_fail (mutex, 0);
1548 if (!g_thread_supported ())
1551 depth = mutex->depth;
1553 g_system_thread_assign (mutex->owner, zero_thread);
1555 g_static_mutex_unlock (&mutex->mutex);
1561 * g_static_rec_mutex_free:
1562 * @mutex: a #GStaticRecMutex to be freed.
1564 * Releases all resources allocated to a #GStaticRecMutex.
1566 * You don't have to call this functions for a #GStaticRecMutex with an
1567 * unbounded lifetime, i.e. objects declared 'static', but if you have
1568 * a #GStaticRecMutex as a member of a structure and the structure is
1569 * freed, you should also free the #GStaticRecMutex.
1572 g_static_rec_mutex_free (GStaticRecMutex *mutex)
1574 g_return_if_fail (mutex);
1576 g_static_mutex_free (&mutex->mutex);
1579 /* GStaticPrivate {{{1 ---------------------------------------------------- */
1584 * A #GStaticPrivate works almost like a #GPrivate, but it has one
1585 * significant advantage. It doesn't need to be created at run-time
1586 * like a #GPrivate, but can be defined at compile-time. This is
1587 * similar to the difference between #GMutex and #GStaticMutex. Now
1588 * look at our <function>give_me_next_number()</function> example with
1592 * <title>Using GStaticPrivate for per-thread data</title>
1595 * give_me_next_number (<!-- -->)
1597 * static GStaticPrivate current_number_key = G_STATIC_PRIVATE_INIT;
1598 * int *current_number = g_static_private_get (&current_number_key);
1600 * if (!current_number)
1602 * current_number = g_new (int,1);
1603 * *current_number = 0;
1604 * g_static_private_set (&current_number_key, current_number, g_free);
1607 * *current_number = calc_next_number (*current_number);
1609 * return *current_number;
1616 * G_STATIC_PRIVATE_INIT:
1618 * Every #GStaticPrivate must be initialized with this macro, before it
1623 * GStaticPrivate my_private = G_STATIC_PRIVATE_INIT;
1625 * </informalexample>
1629 * g_static_private_init:
1630 * @private_key: a #GStaticPrivate to be initialized.
1632 * Initializes @private_key. Alternatively you can initialize it with
1633 * #G_STATIC_PRIVATE_INIT.
1636 g_static_private_init (GStaticPrivate *private_key)
1638 private_key->index = 0;
1642 * g_static_private_get:
1643 * @private_key: a #GStaticPrivate.
1644 * @Returns: the corresponding pointer.
1646 * Works like g_private_get() only for a #GStaticPrivate.
1648 * This function works even if g_thread_init() has not yet been called.
1651 g_static_private_get (GStaticPrivate *private_key)
1653 GRealThread *self = (GRealThread*) g_thread_self ();
1656 array = self->private_data;
1660 if (!private_key->index)
1662 else if (private_key->index <= array->len)
1663 return g_array_index (array, GStaticPrivateNode,
1664 private_key->index - 1).data;
1670 * g_static_private_set:
1671 * @private_key: a #GStaticPrivate.
1672 * @data: the new pointer.
1673 * @notify: a function to be called with the pointer whenever the
1674 * current thread ends or sets this pointer again.
1676 * Sets the pointer keyed to @private_key for the current thread and
1677 * the function @notify to be called with that pointer (%NULL or
1678 * non-%NULL), whenever the pointer is set again or whenever the
1679 * current thread ends.
1681 * This function works even if g_thread_init() has not yet been called.
1682 * If g_thread_init() is called later, the @data keyed to @private_key
1683 * will be inherited only by the main thread, i.e. the one that called
1686 * <note><para>@notify is used quite differently from @destructor in
1687 * g_private_new().</para></note>
1690 g_static_private_set (GStaticPrivate *private_key,
1692 GDestroyNotify notify)
1694 GRealThread *self = (GRealThread*) g_thread_self ();
1696 static guint next_index = 0;
1697 GStaticPrivateNode *node;
1699 array = self->private_data;
1702 array = g_array_new (FALSE, TRUE, sizeof (GStaticPrivateNode));
1703 self->private_data = array;
1706 if (!private_key->index)
1710 if (!private_key->index)
1712 if (g_thread_free_indeces)
1714 private_key->index =
1715 GPOINTER_TO_UINT (g_thread_free_indeces->data);
1716 g_thread_free_indeces =
1717 g_slist_delete_link (g_thread_free_indeces,
1718 g_thread_free_indeces);
1721 private_key->index = ++next_index;
1724 G_UNLOCK (g_thread);
1727 if (private_key->index > array->len)
1728 g_array_set_size (array, private_key->index);
1730 node = &g_array_index (array, GStaticPrivateNode, private_key->index - 1);
1733 gpointer ddata = node->data;
1734 GDestroyNotify ddestroy = node->destroy;
1737 node->destroy = notify;
1744 node->destroy = notify;
1749 * g_static_private_free:
1750 * @private_key: a #GStaticPrivate to be freed.
1752 * Releases all resources allocated to @private_key.
1754 * You don't have to call this functions for a #GStaticPrivate with an
1755 * unbounded lifetime, i.e. objects declared 'static', but if you have
1756 * a #GStaticPrivate as a member of a structure and the structure is
1757 * freed, you should also free the #GStaticPrivate.
1760 g_static_private_free (GStaticPrivate *private_key)
1762 guint idx = private_key->index;
1763 GRealThread *thread;
1768 private_key->index = 0;
1772 thread = g_thread_all_threads;
1775 GArray *array = thread->private_data;
1776 thread = thread->next;
1778 if (array && idx <= array->len)
1780 GStaticPrivateNode *node = &g_array_index (array,
1783 gpointer ddata = node->data;
1784 GDestroyNotify ddestroy = node->destroy;
1787 node->destroy = NULL;
1791 G_UNLOCK (g_thread);
1797 g_thread_free_indeces = g_slist_prepend (g_thread_free_indeces,
1798 GUINT_TO_POINTER (idx));
1799 G_UNLOCK (g_thread);
1802 /* GThread Extra Functions {{{1 ------------------------------------------- */
1804 g_thread_cleanup (gpointer data)
1808 GRealThread* thread = data;
1809 if (thread->private_data)
1811 GArray* array = thread->private_data;
1814 for (i = 0; i < array->len; i++ )
1816 GStaticPrivateNode *node =
1817 &g_array_index (array, GStaticPrivateNode, i);
1819 node->destroy (node->data);
1821 g_array_free (array, TRUE);
1824 /* We only free the thread structure, if it isn't joinable. If
1825 it is, the structure is freed in g_thread_join */
1826 if (!thread->thread.joinable)
1831 for (t = g_thread_all_threads, p = NULL; t; p = t, t = t->next)
1838 g_thread_all_threads = t->next;
1842 G_UNLOCK (g_thread);
1844 /* Just to make sure, this isn't used any more */
1845 g_system_thread_assign (thread->system_thread, zero_thread);
1852 g_thread_fail (void)
1854 g_error ("The thread system is not yet initialized.");
1857 #define G_NSEC_PER_SEC 1000000000
1865 /* Returns 100s of nanoseconds since start of 1601 */
1866 GetSystemTimeAsFileTime ((FILETIME *)&v);
1868 /* Offset to Unix epoch */
1869 v -= G_GINT64_CONSTANT (116444736000000000);
1870 /* Convert to nanoseconds */
1877 gettimeofday (&tv, NULL);
1879 return (guint64) tv.tv_sec * G_NSEC_PER_SEC + tv.tv_usec * (G_NSEC_PER_SEC / G_USEC_PER_SEC);
1884 g_thread_create_proxy (gpointer data)
1886 GRealThread* thread = data;
1890 /* This has to happen before G_LOCK, as that might call g_thread_self */
1891 g_private_set (g_thread_specific_private, data);
1893 /* the lock makes sure, that thread->system_thread is written,
1894 before thread->thread.func is called. See g_thread_create. */
1896 G_UNLOCK (g_thread);
1898 thread->retval = thread->thread.func (thread->thread.data);
1904 * g_thread_create_full:
1905 * @func: a function to execute in the new thread.
1906 * @data: an argument to supply to the new thread.
1907 * @stack_size: a stack size for the new thread.
1908 * @joinable: should this thread be joinable?
1909 * @bound: should this thread be bound to a system thread?
1910 * @priority: a priority for the thread.
1911 * @error: return location for error.
1912 * @Returns: the new #GThread on success.
1914 * This function creates a new thread with the priority @priority. If
1915 * the underlying thread implementation supports it, the thread gets a
1916 * stack size of @stack_size or the default value for the current
1917 * platform, if @stack_size is 0.
1919 * If @joinable is %TRUE, you can wait for this threads termination
1920 * calling g_thread_join(). Otherwise the thread will just disappear
1921 * when it terminates. If @bound is %TRUE, this thread will be
1922 * scheduled in the system scope, otherwise the implementation is free
1923 * to do scheduling in the process scope. The first variant is more
1924 * expensive resource-wise, but generally faster. On some systems (e.g.
1925 * Linux) all threads are bound.
1927 * The new thread executes the function @func with the argument @data.
1928 * If the thread was created successfully, it is returned.
1930 * @error can be %NULL to ignore errors, or non-%NULL to report errors.
1931 * The error is set, if and only if the function returns %NULL.
1933 * <note><para>It is not guaranteed that threads with different priorities
1934 * really behave accordingly. On some systems (e.g. Linux) there are no
1935 * thread priorities. On other systems (e.g. Solaris) there doesn't
1936 * seem to be different scheduling for different priorities. All in all
1937 * try to avoid being dependent on priorities. Use
1938 * %G_THREAD_PRIORITY_NORMAL here as a default.</para></note>
1940 * <note><para>Only use g_thread_create_full() if you really can't use
1941 * g_thread_create() instead. g_thread_create() does not take
1942 * @stack_size, @bound, and @priority as arguments, as they should only
1943 * be used in cases in which it is unavoidable.</para></note>
1946 g_thread_create_full (GThreadFunc func,
1951 GThreadPriority priority,
1954 GRealThread* result;
1955 GError *local_error = NULL;
1956 g_return_val_if_fail (func, NULL);
1957 g_return_val_if_fail (priority >= G_THREAD_PRIORITY_LOW, NULL);
1958 g_return_val_if_fail (priority <= G_THREAD_PRIORITY_URGENT, NULL);
1960 result = g_new0 (GRealThread, 1);
1962 result->thread.joinable = joinable;
1963 result->thread.priority = priority;
1964 result->thread.func = func;
1965 result->thread.data = data;
1966 result->private_data = NULL;
1968 G_THREAD_UF (thread_create, (g_thread_create_proxy, result,
1969 stack_size, joinable, bound, priority,
1970 &result->system_thread, &local_error));
1973 result->next = g_thread_all_threads;
1974 g_thread_all_threads = result;
1976 G_UNLOCK (g_thread);
1980 g_propagate_error (error, local_error);
1985 return (GThread*) result;
1990 * @retval: the return value of this thread.
1992 * Exits the current thread. If another thread is waiting for that
1993 * thread using g_thread_join() and the current thread is joinable, the
1994 * waiting thread will be woken up and get @retval as the return value
1995 * of g_thread_join(). If the current thread is not joinable, @retval
1996 * is ignored. Calling
2000 * g_thread_exit (retval);
2002 * </informalexample>
2004 * is equivalent to returning @retval from the function @func, as given
2005 * to g_thread_create().
2007 * <note><para>Never call g_thread_exit() from within a thread of a
2008 * #GThreadPool, as that will mess up the bookkeeping and lead to funny
2009 * and unwanted results.</para></note>
2012 g_thread_exit (gpointer retval)
2014 GRealThread* real = (GRealThread*) g_thread_self ();
2015 real->retval = retval;
2016 G_THREAD_CF (thread_exit, (void)0, ());
2021 * @thread: a #GThread to be waited for.
2022 * @Returns: the return value of the thread.
2024 * Waits until @thread finishes, i.e. the function @func, as given to
2025 * g_thread_create(), returns or g_thread_exit() is called by @thread.
2026 * All resources of @thread including the #GThread struct are released.
2027 * @thread must have been created with @joinable=%TRUE in
2028 * g_thread_create(). The value returned by @func or given to
2029 * g_thread_exit() by @thread is returned by this function.
2032 g_thread_join (GThread* thread)
2034 GRealThread* real = (GRealThread*) thread;
2038 g_return_val_if_fail (thread, NULL);
2039 g_return_val_if_fail (thread->joinable, NULL);
2040 g_return_val_if_fail (!g_system_thread_equal (real->system_thread,
2041 zero_thread), NULL);
2043 G_THREAD_UF (thread_join, (&real->system_thread));
2045 retval = real->retval;
2048 for (t = g_thread_all_threads, p = NULL; t; p = t, t = t->next)
2050 if (t == (GRealThread*) thread)
2055 g_thread_all_threads = t->next;
2059 G_UNLOCK (g_thread);
2061 /* Just to make sure, this isn't used any more */
2062 thread->joinable = 0;
2063 g_system_thread_assign (real->system_thread, zero_thread);
2065 /* the thread structure for non-joinable threads is freed upon
2066 thread end. We free the memory here. This will leave a loose end,
2067 if a joinable thread is not joined. */
2075 * g_thread_set_priority:
2076 * @thread: a #GThread.
2077 * @priority: a new priority for @thread.
2079 * Changes the priority of @thread to @priority.
2081 * <note><para>It is not guaranteed that threads with different
2082 * priorities really behave accordingly. On some systems (e.g. Linux)
2083 * there are no thread priorities. On other systems (e.g. Solaris) there
2084 * doesn't seem to be different scheduling for different priorities. All
2085 * in all try to avoid being dependent on priorities.</para></note>
2088 g_thread_set_priority (GThread* thread,
2089 GThreadPriority priority)
2091 GRealThread* real = (GRealThread*) thread;
2093 g_return_if_fail (thread);
2094 g_return_if_fail (!g_system_thread_equal (real->system_thread, zero_thread));
2095 g_return_if_fail (priority >= G_THREAD_PRIORITY_LOW);
2096 g_return_if_fail (priority <= G_THREAD_PRIORITY_URGENT);
2098 thread->priority = priority;
2100 G_THREAD_CF (thread_set_priority, (void)0,
2101 (&real->system_thread, priority));
2106 * @Returns: the current thread.
2108 * This functions returns the #GThread corresponding to the calling
2112 g_thread_self (void)
2114 GRealThread* thread = g_private_get (g_thread_specific_private);
2118 /* If no thread data is available, provide and set one. This
2119 can happen for the main thread and for threads, that are not
2121 thread = g_new0 (GRealThread, 1);
2122 thread->thread.joinable = FALSE; /* This is a save guess */
2123 thread->thread.priority = G_THREAD_PRIORITY_NORMAL; /* This is
2125 thread->thread.func = NULL;
2126 thread->thread.data = NULL;
2127 thread->private_data = NULL;
2129 if (g_thread_supported ())
2130 G_THREAD_UF (thread_self, (&thread->system_thread));
2132 g_private_set (g_thread_specific_private, thread);
2135 thread->next = g_thread_all_threads;
2136 g_thread_all_threads = thread;
2137 G_UNLOCK (g_thread);
2140 return (GThread*)thread;
2143 /* GStaticRWLock {{{1 ----------------------------------------------------- */
2148 * The #GStaticRWLock struct represents a read-write lock. A read-write
2149 * lock can be used for protecting data that some portions of code only
2150 * read from, while others also write. In such situations it is
2151 * desirable that several readers can read at once, whereas of course
2152 * only one writer may write at a time. Take a look at the following
2156 * <title>An array with access functions</title>
2158 * GStaticRWLock rwlock = G_STATIC_RW_LOCK_INIT;
2162 * my_array_get (guint index)
2164 * gpointer retval = NULL;
2169 * g_static_rw_lock_reader_lock (&rwlock);
2170 * if (index < array->len)
2171 * retval = g_ptr_array_index (array, index);
2172 * g_static_rw_lock_reader_unlock (&rwlock);
2178 * my_array_set (guint index, gpointer data)
2180 * g_static_rw_lock_writer_lock (&rwlock);
2183 * array = g_ptr_array_new (<!-- -->);
2185 * if (index >= array->len)
2186 * g_ptr_array_set_size (array, index+1);
2187 * g_ptr_array_index (array, index) = data;
2189 * g_static_rw_lock_writer_unlock (&rwlock);
2194 * This example shows an array which can be accessed by many readers
2195 * (the <function>my_array_get()</function> function) simultaneously,
2196 * whereas the writers (the <function>my_array_set()</function>
2197 * function) will only be allowed once at a time and only if no readers
2198 * currently access the array. This is because of the potentially
2199 * dangerous resizing of the array. Using these functions is fully
2200 * multi-thread safe now.
2202 * Most of the time, writers should have precedence over readers. That
2203 * means, for this implementation, that as soon as a writer wants to
2204 * lock the data, no other reader is allowed to lock the data, whereas,
2205 * of course, the readers that already have locked the data are allowed
2206 * to finish their operation. As soon as the last reader unlocks the
2207 * data, the writer will lock it.
2209 * Even though #GStaticRWLock is not opaque, it should only be used
2210 * with the following functions.
2212 * All of the <function>g_static_rw_lock_*</function> functions can be
2213 * used even if g_thread_init() has not been called. Then they do
2214 * nothing, apart from <function>g_static_rw_lock_*_trylock</function>,
2215 * which does nothing but returning %TRUE.
2217 * <note><para>A read-write lock has a higher overhead than a mutex. For
2218 * example, both g_static_rw_lock_reader_lock() and
2219 * g_static_rw_lock_reader_unlock() have to lock and unlock a
2220 * #GStaticMutex, so it takes at least twice the time to lock and unlock
2221 * a #GStaticRWLock that it does to lock and unlock a #GStaticMutex. So
2222 * only data structures that are accessed by multiple readers, and which
2223 * keep the lock for a considerable time justify a #GStaticRWLock. The
2224 * above example most probably would fare better with a
2225 * #GStaticMutex.</para></note>
2229 * G_STATIC_RW_LOCK_INIT:
2231 * A #GStaticRWLock must be initialized with this macro before it can
2232 * be used. This macro can used be to initialize a variable, but it
2233 * cannot be assigned to a variable. In that case you have to use
2234 * g_static_rw_lock_init().
2238 * GStaticRWLock my_lock = G_STATIC_RW_LOCK_INIT;
2240 * </informalexample>
2244 * g_static_rw_lock_init:
2245 * @lock: a #GStaticRWLock to be initialized.
2247 * A #GStaticRWLock must be initialized with this function before it
2248 * can be used. Alternatively you can initialize it with
2249 * #G_STATIC_RW_LOCK_INIT.
2252 g_static_rw_lock_init (GStaticRWLock* lock)
2254 static const GStaticRWLock init_lock = G_STATIC_RW_LOCK_INIT;
2256 g_return_if_fail (lock);
2262 g_static_rw_lock_wait (GCond** cond, GStaticMutex* mutex)
2265 *cond = g_cond_new ();
2266 g_cond_wait (*cond, g_static_mutex_get_mutex (mutex));
2270 g_static_rw_lock_signal (GStaticRWLock* lock)
2272 if (lock->want_to_write && lock->write_cond)
2273 g_cond_signal (lock->write_cond);
2274 else if (lock->want_to_read && lock->read_cond)
2275 g_cond_broadcast (lock->read_cond);
2279 * g_static_rw_lock_reader_lock:
2280 * @lock: a #GStaticRWLock to lock for reading.
2282 * Locks @lock for reading. There may be unlimited concurrent locks for
2283 * reading of a #GStaticRWLock at the same time. If @lock is already
2284 * locked for writing by another thread or if another thread is already
2285 * waiting to lock @lock for writing, this function will block until
2286 * @lock is unlocked by the other writing thread and no other writing
2287 * threads want to lock @lock. This lock has to be unlocked by
2288 * g_static_rw_lock_reader_unlock().
2290 * #GStaticRWLock is not recursive. It might seem to be possible to
2291 * recursively lock for reading, but that can result in a deadlock, due
2292 * to writer preference.
2295 g_static_rw_lock_reader_lock (GStaticRWLock* lock)
2297 g_return_if_fail (lock);
2299 if (!g_threads_got_initialized)
2302 g_static_mutex_lock (&lock->mutex);
2303 lock->want_to_read++;
2304 while (lock->have_writer || lock->want_to_write)
2305 g_static_rw_lock_wait (&lock->read_cond, &lock->mutex);
2306 lock->want_to_read--;
2307 lock->read_counter++;
2308 g_static_mutex_unlock (&lock->mutex);
2312 * g_static_rw_lock_reader_trylock:
2313 * @lock: a #GStaticRWLock to lock for reading.
2314 * @Returns: %TRUE, if @lock could be locked for reading.
2316 * Tries to lock @lock for reading. If @lock is already locked for
2317 * writing by another thread or if another thread is already waiting to
2318 * lock @lock for writing, immediately returns %FALSE. Otherwise locks
2319 * @lock for reading and returns %TRUE. This lock has to be unlocked by
2320 * g_static_rw_lock_reader_unlock().
2323 g_static_rw_lock_reader_trylock (GStaticRWLock* lock)
2325 gboolean ret_val = FALSE;
2327 g_return_val_if_fail (lock, FALSE);
2329 if (!g_threads_got_initialized)
2332 g_static_mutex_lock (&lock->mutex);
2333 if (!lock->have_writer && !lock->want_to_write)
2335 lock->read_counter++;
2338 g_static_mutex_unlock (&lock->mutex);
2343 * g_static_rw_lock_reader_unlock:
2344 * @lock: a #GStaticRWLock to unlock after reading.
2346 * Unlocks @lock. If a thread waits to lock @lock for writing and all
2347 * locks for reading have been unlocked, the waiting thread is woken up
2348 * and can lock @lock for writing.
2351 g_static_rw_lock_reader_unlock (GStaticRWLock* lock)
2353 g_return_if_fail (lock);
2355 if (!g_threads_got_initialized)
2358 g_static_mutex_lock (&lock->mutex);
2359 lock->read_counter--;
2360 if (lock->read_counter == 0)
2361 g_static_rw_lock_signal (lock);
2362 g_static_mutex_unlock (&lock->mutex);
2366 * g_static_rw_lock_writer_lock:
2367 * @lock: a #GStaticRWLock to lock for writing.
2369 * Locks @lock for writing. If @lock is already locked for writing or
2370 * reading by other threads, this function will block until @lock is
2371 * completely unlocked and then lock @lock for writing. While this
2372 * functions waits to lock @lock, no other thread can lock @lock for
2373 * reading. When @lock is locked for writing, no other thread can lock
2374 * @lock (neither for reading nor writing). This lock has to be
2375 * unlocked by g_static_rw_lock_writer_unlock().
2378 g_static_rw_lock_writer_lock (GStaticRWLock* lock)
2380 g_return_if_fail (lock);
2382 if (!g_threads_got_initialized)
2385 g_static_mutex_lock (&lock->mutex);
2386 lock->want_to_write++;
2387 while (lock->have_writer || lock->read_counter)
2388 g_static_rw_lock_wait (&lock->write_cond, &lock->mutex);
2389 lock->want_to_write--;
2390 lock->have_writer = TRUE;
2391 g_static_mutex_unlock (&lock->mutex);
2395 * g_static_rw_lock_writer_trylock:
2396 * @lock: a #GStaticRWLock to lock for writing.
2397 * @Returns: %TRUE, if @lock could be locked for writing.
2399 * Tries to lock @lock for writing. If @lock is already locked (for
2400 * either reading or writing) by another thread, it immediately returns
2401 * %FALSE. Otherwise it locks @lock for writing and returns %TRUE. This
2402 * lock has to be unlocked by g_static_rw_lock_writer_unlock().
2405 g_static_rw_lock_writer_trylock (GStaticRWLock* lock)
2407 gboolean ret_val = FALSE;
2409 g_return_val_if_fail (lock, FALSE);
2411 if (!g_threads_got_initialized)
2414 g_static_mutex_lock (&lock->mutex);
2415 if (!lock->have_writer && !lock->read_counter)
2417 lock->have_writer = TRUE;
2420 g_static_mutex_unlock (&lock->mutex);
2425 * g_static_rw_lock_writer_unlock:
2426 * @lock: a #GStaticRWLock to unlock after writing.
2428 * Unlocks @lock. If a thread is waiting to lock @lock for writing and
2429 * all locks for reading have been unlocked, the waiting thread is
2430 * woken up and can lock @lock for writing. If no thread is waiting to
2431 * lock @lock for writing, and some thread or threads are waiting to
2432 * lock @lock for reading, the waiting threads are woken up and can
2433 * lock @lock for reading.
2436 g_static_rw_lock_writer_unlock (GStaticRWLock* lock)
2438 g_return_if_fail (lock);
2440 if (!g_threads_got_initialized)
2443 g_static_mutex_lock (&lock->mutex);
2444 lock->have_writer = FALSE;
2445 g_static_rw_lock_signal (lock);
2446 g_static_mutex_unlock (&lock->mutex);
2450 * g_static_rw_lock_free:
2451 * @lock: a #GStaticRWLock to be freed.
2453 * Releases all resources allocated to @lock.
2455 * You don't have to call this functions for a #GStaticRWLock with an
2456 * unbounded lifetime, i.e. objects declared 'static', but if you have
2457 * a #GStaticRWLock as a member of a structure, and the structure is
2458 * freed, you should also free the #GStaticRWLock.
2461 g_static_rw_lock_free (GStaticRWLock* lock)
2463 g_return_if_fail (lock);
2465 if (lock->read_cond)
2467 g_cond_free (lock->read_cond);
2468 lock->read_cond = NULL;
2470 if (lock->write_cond)
2472 g_cond_free (lock->write_cond);
2473 lock->write_cond = NULL;
2475 g_static_mutex_free (&lock->mutex);
2478 /* Unsorted {{{1 ---------------------------------------------------------- */
2482 * @thread_func: function to call for all GThread structures
2483 * @user_data: second argument to @thread_func
2485 * Call @thread_func on all existing #GThread structures. Note that
2486 * threads may decide to exit while @thread_func is running, so
2487 * without intimate knowledge about the lifetime of foreign threads,
2488 * @thread_func shouldn't access the GThread* pointer passed in as
2489 * first argument. However, @thread_func will not be called for threads
2490 * which are known to have exited already.
2492 * Due to thread lifetime checks, this function has an execution complexity
2493 * which is quadratic in the number of existing threads.
2498 g_thread_foreach (GFunc thread_func,
2501 GSList *slist = NULL;
2502 GRealThread *thread;
2503 g_return_if_fail (thread_func != NULL);
2504 /* snapshot the list of threads for iteration */
2506 for (thread = g_thread_all_threads; thread; thread = thread->next)
2507 slist = g_slist_prepend (slist, thread);
2508 G_UNLOCK (g_thread);
2509 /* walk the list, skipping non-existant threads */
2512 GSList *node = slist;
2514 /* check whether the current thread still exists */
2516 for (thread = g_thread_all_threads; thread; thread = thread->next)
2517 if (thread == node->data)
2519 G_UNLOCK (g_thread);
2521 thread_func (thread, user_data);
2522 g_slist_free_1 (node);
2527 * g_thread_get_initialized
2529 * Indicates if g_thread_init() has been called.
2531 * Returns: %TRUE if threads have been initialized.
2536 g_thread_get_initialized ()
2538 return g_thread_supported ();
2541 #define __G_THREAD_C__
2542 #include "galiasdef.c"