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 */
64 * @short_description: thread abstraction; including threads, different
65 * mutexes, conditions and thread private data
66 * @see_also: #GThreadPool, #GAsyncQueue
68 * Threads act almost like processes, but unlike processes all threads
69 * of one process share the same memory. This is good, as it provides
70 * easy communication between the involved threads via this shared
71 * memory, and it is bad, because strange things (so called
72 * "Heisenbugs") might happen if the program is not carefully designed.
73 * In particular, due to the concurrent nature of threads, no
74 * assumptions on the order of execution of code running in different
75 * threads can be made, unless order is explicitly forced by the
76 * programmer through synchronization primitives.
78 * The aim of the thread related functions in GLib is to provide a
79 * portable means for writing multi-threaded software. There are
80 * primitives for mutexes to protect the access to portions of memory
81 * (#GMutex, #GStaticMutex, #G_LOCK_DEFINE, #GStaticRecMutex and
82 * #GStaticRWLock). There are primitives for condition variables to
83 * allow synchronization of threads (#GCond). There are primitives for
84 * thread-private data - data that every thread has a private instance
85 * of (#GPrivate, #GStaticPrivate). Last but definitely not least there
86 * are primitives to portably create and manage threads (#GThread).
88 * The threading system is initialized with g_thread_init(), which
89 * takes an optional custom thread implementation or %NULL for the
90 * default implementation. If you want to call g_thread_init() with a
91 * non-%NULL argument this must be done before executing any other GLib
92 * functions (except g_mem_set_vtable()). This is a requirement even if
93 * no threads are in fact ever created by the process.
95 * Calling g_thread_init() with a %NULL argument is somewhat more
96 * relaxed. You may call any other glib functions in the main thread
97 * before g_thread_init() as long as g_thread_init() is not called from
98 * a glib callback, or with any locks held. However, many libraries
99 * above glib does not support late initialization of threads, so doing
100 * this should be avoided if possible.
102 * Please note that since version 2.24 the GObject initialization
103 * function g_type_init() initializes threads (with a %NULL argument),
104 * so most applications, including those using Gtk+ will run with
105 * threads enabled. If you want a special thread implementation, make
106 * sure you call g_thread_init() before g_type_init() is called.
108 * After calling g_thread_init(), GLib is completely thread safe (all
109 * global data is automatically locked), but individual data structure
110 * instances are not automatically locked for performance reasons. So,
111 * for example you must coordinate accesses to the same #GHashTable
112 * from multiple threads. The two notable exceptions from this rule
113 * are #GMainLoop and #GAsyncQueue, which <emphasis>are</emphasis>
114 * threadsafe and needs no further application-level locking to be
115 * accessed from multiple threads.
117 * To help debugging problems in multithreaded applications, GLib
118 * supports error-checking mutexes that will give you helpful error
119 * messages on common problems. To use error-checking mutexes, define
120 * the symbol #G_ERRORCHECK_MUTEXES when compiling the application.
124 * G_THREADS_IMPL_POSIX:
126 * This macro is defined if POSIX style threads are used.
132 * This macro is defined if GLib was compiled with thread support. This
133 * does not necessarily mean that there is a thread implementation
134 * available, but it does mean that the infrastructure is in place and
135 * that once you provide a thread implementation to g_thread_init(),
136 * GLib will be multi-thread safe. If #G_THREADS_ENABLED is not
137 * defined, then Glib is not, and cannot be, multi-thread safe.
141 * G_THREADS_IMPL_NONE:
143 * This macro is defined if no thread implementation is used. You can,
144 * however, provide one to g_thread_init() to make GLib multi-thread
148 /* G_LOCK Documentation {{{1 ---------------------------------------------- */
150 /* IMPLEMENTATION NOTE:
152 * G_LOCK_DEFINE and friends are convenience macros defined in
153 * gthread.h. Their documentation lives here.
158 * @name: the name of the lock.
160 * The %G_LOCK_* macros provide a convenient interface to #GStaticMutex
161 * with the advantage that they will expand to nothing in programs
162 * compiled against a thread-disabled GLib, saving code and memory
163 * there. #G_LOCK_DEFINE defines a lock. It can appear anywhere
164 * variable definitions may appear in programs, i.e. in the first block
165 * of a function or outside of functions. The @name parameter will be
166 * mangled to get the name of the #GStaticMutex. This means that you
167 * can use names of existing variables as the parameter - e.g. the name
168 * of the variable you intent to protect with the lock. Look at our
169 * <function>give_me_next_number()</function> example using the
172 * <example> <title>Using the %G_LOCK_* convenience macros</title>
173 * <programlisting> G_LOCK_DEFINE (current_number); int
174 * give_me_next_number (<!-- -->) { static int current_number = 0; int
175 * ret_val; G_LOCK (current_number); ret_val = current_number =
176 * calc_next_number (current_number); G_UNLOCK (current_number); return
177 * ret_val; } </programlisting> </example>
181 * G_LOCK_DEFINE_STATIC:
182 * @name: the name of the lock.
184 * This works like #G_LOCK_DEFINE, but it creates a static object.
189 * @name: the name of the lock.
191 * This declares a lock, that is defined with #G_LOCK_DEFINE in another
197 * @name: the name of the lock.
199 * Works like g_mutex_lock(), but for a lock defined with
205 * @name: the name of the lock.
206 * @Returns: %TRUE, if the lock could be locked.
208 * Works like g_mutex_trylock(), but for a lock defined with
214 * @name: the name of the lock.
216 * Works like g_mutex_unlock(), but for a lock defined with
220 /* GThreadError {{{1 ------------------------------------------------------- */
223 * @G_THREAD_ERROR_AGAIN: a thread couldn't be created due to resource
224 * shortage. Try again later.
226 * Possible errors of thread related functions.
232 * The error domain of the GLib thread subsystem.
235 g_thread_error_quark (void)
237 return g_quark_from_static_string ("g_thread_error");
240 /* Miscellaneous Structures {{{1 ------------------------------------------ */
241 /* Keep this in sync with GRealThread in gmain.c! */
242 typedef struct _GRealThread GRealThread;
246 gpointer private_data;
249 GSystemThread system_thread;
252 typedef struct _GStaticPrivateNode GStaticPrivateNode;
253 struct _GStaticPrivateNode
256 GDestroyNotify destroy;
259 static void g_thread_cleanup (gpointer data);
260 static void g_thread_fail (void);
261 static guint64 gettime (void);
263 guint64 (*g_thread_gettime) (void) = gettime;
265 /* Global Variables {{{1 -------------------------------------------------- */
267 static GSystemThread zero_thread; /* This is initialized to all zero */
268 gboolean g_thread_use_default_impl = TRUE;
271 * g_thread_supported:
272 * @Returns: %TRUE, if the thread system is initialized.
274 * This function returns %TRUE if the thread system is initialized, and
275 * %FALSE if it is not.
277 * <note><para>This function is actually a macro. Apart from taking the
278 * address of it you can however use it as if it was a
279 * function.</para></note>
282 /* IMPLEMENTATION NOTE:
284 * g_thread_supported() is just returns g_threads_got_initialized
286 gboolean g_threads_got_initialized = FALSE;
289 /* Thread Implementation Virtual Function Table {{{1 ---------------------- */
290 /* Virtual Function Table Documentation {{{2 ------------------------------ */
293 * @mutex_new: virtual function pointer for g_mutex_new()
294 * @mutex_lock: virtual function pointer for g_mutex_lock()
295 * @mutex_trylock: virtual function pointer for g_mutex_trylock()
296 * @mutex_unlock: virtual function pointer for g_mutex_unlock()
297 * @mutex_free: virtual function pointer for g_mutex_free()
298 * @cond_new: virtual function pointer for g_cond_new()
299 * @cond_signal: virtual function pointer for g_cond_signal()
300 * @cond_broadcast: virtual function pointer for g_cond_broadcast()
301 * @cond_wait: virtual function pointer for g_cond_wait()
302 * @cond_timed_wait: virtual function pointer for g_cond_timed_wait()
303 * @cond_free: virtual function pointer for g_cond_free()
304 * @private_new: virtual function pointer for g_private_new()
305 * @private_get: virtual function pointer for g_private_get()
306 * @private_set: virtual function pointer for g_private_set()
307 * @thread_create: virtual function pointer for g_thread_create()
308 * @thread_yield: virtual function pointer for g_thread_yield()
309 * @thread_join: virtual function pointer for g_thread_join()
310 * @thread_exit: virtual function pointer for g_thread_exit()
311 * @thread_set_priority: virtual function pointer for
312 * g_thread_set_priority()
313 * @thread_self: virtual function pointer for g_thread_self()
314 * @thread_equal: used internally by recursive mutex locks and by some
317 * This function table is used by g_thread_init() to initialize the
318 * thread system. The functions in the table are directly used by their
319 * g_* prepended counterparts (described in this document). For
320 * example, if you call g_mutex_new() then mutex_new() from the table
321 * provided to g_thread_init() will be called.
323 * <note><para>Do not use this struct unless you know what you are
324 * doing.</para></note>
327 /* IMPLEMENTATION NOTE:
329 * g_thread_functions_for_glib_use is a global symbol that gets used by
330 * most of the "primative" threading calls. g_mutex_lock(), for
331 * example, is just a macro that calls the appropriate virtual function
334 * For that reason, all of those macros are documented here.
336 GThreadFunctions g_thread_functions_for_glib_use = {
337 /* GMutex Virtual Functions {{{2 ------------------------------------------ */
342 * The #GMutex struct is an opaque data structure to represent a mutex
343 * (mutual exclusion). It can be used to protect data against shared
344 * access. Take for example the following function:
347 * <title>A function which will not work in a threaded environment</title>
350 * give_me_next_number (void)
352 * static int current_number = 0;
354 * /* now do a very complicated calculation to calculate the new
355 * * number, this might for example be a random number generator
357 * current_number = calc_next_number (current_number);
359 * return current_number;
364 * It is easy to see that this won't work in a multi-threaded
365 * application. There current_number must be protected against shared
366 * access. A first naive implementation would be:
369 * <title>The wrong way to write a thread-safe function</title>
372 * give_me_next_number (void)
374 * static int current_number = 0;
376 * static GMutex * mutex = NULL;
378 * if (!mutex) mutex = g_mutex_new (<!-- -->);
380 * g_mutex_lock (mutex);
381 * ret_val = current_number = calc_next_number (current_number);
382 * g_mutex_unlock (mutex);
389 * This looks like it would work, but there is a race condition while
390 * constructing the mutex and this code cannot work reliable. Please do
391 * not use such constructs in your own programs! One working solution
395 * <title>A correct thread-safe function</title>
397 * static GMutex *give_me_next_number_mutex = NULL;
399 * /* this function must be called before any call to
400 * * give_me_next_number(<!-- -->)
402 * * it must be called exactly once.
405 * init_give_me_next_number (void)
407 * g_assert (give_me_next_number_mutex == NULL);
408 * give_me_next_number_mutex = g_mutex_new (<!-- -->);
412 * give_me_next_number (void)
414 * static int current_number = 0;
417 * g_mutex_lock (give_me_next_number_mutex);
418 * ret_val = current_number = calc_next_number (current_number);
419 * g_mutex_unlock (give_me_next_number_mutex);
426 * #GStaticMutex provides a simpler and safer way of doing this.
428 * If you want to use a mutex, and your code should also work without
429 * calling g_thread_init() first, then you can not use a #GMutex, as
430 * g_mutex_new() requires that the thread system be initialized. Use a
431 * #GStaticMutex instead.
433 * A #GMutex should only be accessed via the following functions.
435 * <note><para>All of the <function>g_mutex_*</function> functions are
436 * actually macros. Apart from taking their addresses, you can however
437 * use them as if they were functions.</para></note>
442 * @Returns: a new #GMutex.
444 * Creates a new #GMutex.
446 * <note><para>This function will abort if g_thread_init() has not been
447 * called yet.</para></note>
449 (GMutex*(*)())g_thread_fail,
455 * Locks @mutex. If @mutex is already locked by another thread, the
456 * current thread will block until @mutex is unlocked by the other
459 * This function can be used even if g_thread_init() has not yet been
460 * called, and, in that case, will do nothing.
462 * <note><para>#GMutex is neither guaranteed to be recursive nor to be
463 * non-recursive, i.e. a thread could deadlock while calling
464 * g_mutex_lock(), if it already has locked @mutex. Use
465 * #GStaticRecMutex, if you need recursive mutexes.</para></note>
472 * @Returns: %TRUE, if @mutex could be locked.
474 * Tries to lock @mutex. If @mutex is already locked by another thread,
475 * it immediately returns %FALSE. Otherwise it locks @mutex and returns
478 * This function can be used even if g_thread_init() has not yet been
479 * called, and, in that case, will immediately return %TRUE.
481 * <note><para>#GMutex is neither guaranteed to be recursive nor to be
482 * non-recursive, i.e. the return value of g_mutex_trylock() could be
483 * both %FALSE or %TRUE, if the current thread already has locked
484 * @mutex. Use #GStaticRecMutex, if you need recursive
485 * mutexes.</para></note>
493 * Unlocks @mutex. If another thread is blocked in a g_mutex_lock()
494 * call for @mutex, it will be woken and can lock @mutex itself.
496 * This function can be used even if g_thread_init() has not yet been
497 * called, and, in that case, will do nothing.
507 * <note><para>Calling g_mutex_free() on a locked mutex may result in
508 * undefined behaviour.</para></note>
512 /* GCond Virtual Functions {{{2 ------------------------------------------ */
517 * The #GCond struct is an opaque data structure that represents a
518 * condition. Threads can block on a #GCond if they find a certain
519 * condition to be false. If other threads change the state of this
520 * condition they signal the #GCond, and that causes the waiting
521 * threads to be woken up.
525 * Using GCond to block a thread until a condition is satisfied
528 * GCond* data_cond = NULL; /* Must be initialized somewhere */
529 * GMutex* data_mutex = NULL; /* Must be initialized somewhere */
530 * gpointer current_data = NULL;
533 * push_data (gpointer data)
535 * g_mutex_lock (data_mutex);
536 * current_data = data;
537 * g_cond_signal (data_cond);
538 * g_mutex_unlock (data_mutex);
546 * g_mutex_lock (data_mutex);
547 * while (!current_data)
548 * g_cond_wait (data_cond, data_mutex);
549 * data = current_data;
550 * current_data = NULL;
551 * g_mutex_unlock (data_mutex);
558 * Whenever a thread calls <function>pop_data()</function> now, it will
559 * wait until current_data is non-%NULL, i.e. until some other thread
560 * has called <function>push_data()</function>.
562 * <note><para>It is important to use the g_cond_wait() and
563 * g_cond_timed_wait() functions only inside a loop which checks for the
564 * condition to be true. It is not guaranteed that the waiting thread
565 * will find the condition fulfilled after it wakes up, even if the
566 * signaling thread left the condition in that state: another thread may
567 * have altered the condition before the waiting thread got the chance
568 * to be woken up, even if the condition itself is protected by a
569 * #GMutex, like above.</para></note>
571 * A #GCond should only be accessed via the following functions.
573 * <note><para>All of the <function>g_cond_*</function> functions are
574 * actually macros. Apart from taking their addresses, you can however
575 * use them as if they were functions.</para></note>
580 * @Returns: a new #GCond.
582 * Creates a new #GCond. This function will abort, if g_thread_init()
583 * has not been called yet.
585 (GCond*(*)())g_thread_fail,
591 * If threads are waiting for @cond, exactly one of them is woken up.
592 * It is good practice to hold the same lock as the waiting thread
593 * while calling this function, though not required.
595 * This function can be used even if g_thread_init() has not yet been
596 * called, and, in that case, will do nothing.
604 * If threads are waiting for @cond, all of them are woken up. It is
605 * good practice to lock the same mutex as the waiting threads, while
606 * calling this function, though not required.
608 * This function can be used even if g_thread_init() has not yet been
609 * called, and, in that case, will do nothing.
616 * @mutex: a #GMutex, that is currently locked.
618 * Waits until this thread is woken up on @cond. The @mutex is unlocked
619 * before falling asleep and locked again before resuming.
621 * This function can be used even if g_thread_init() has not yet been
622 * called, and, in that case, will immediately return.
629 * @mutex: a #GMutex that is currently locked.
630 * @abs_time: a #GTimeVal, determining the final time.
631 * @Returns: %TRUE if @cond was signalled, or %FALSE on timeout.
633 * Waits until this thread is woken up on @cond, but not longer than
634 * until the time specified by @abs_time. The @mutex is unlocked before
635 * falling asleep and locked again before resuming.
637 * If @abs_time is %NULL, g_cond_timed_wait() acts like g_cond_wait().
639 * This function can be used even if g_thread_init() has not yet been
640 * called, and, in that case, will immediately return %TRUE.
642 * To easily calculate @abs_time a combination of g_get_current_time()
643 * and g_time_val_add() can be used.
651 * Destroys the #GCond.
655 /* GPrivate Virtual Functions {{{2 --------------------------------------- */
660 * The #GPrivate struct is an opaque data structure to represent a
661 * thread private data key. Threads can thereby obtain and set a
662 * pointer which is private to the current thread. Take our
663 * <function>give_me_next_number(<!-- -->)</function> example from
664 * above. Suppose we don't want <literal>current_number</literal> to be
665 * shared between the threads, but instead to be private to each thread.
666 * This can be done as follows:
669 * <title>Using GPrivate for per-thread data</title>
671 * GPrivate* current_number_key = NULL; /* Must be initialized somewhere
672 * with g_private_new (g_free); a;/
675 * give_me_next_number (void)
677 * int *current_number = g_private_get (current_number_key);
679 * if (!current_number)
681 * current_number = g_new (int, 1);
682 * *current_number = 0;
683 * g_private_set (current_number_key, current_number);
686 * *current_number = calc_next_number (*current_number);
688 * return *current_number;
693 * Here the pointer belonging to the key
694 * <literal>current_number_key</literal> is read. If it is %NULL, it has
695 * not been set yet. Then get memory for an integer value, assign this
696 * memory to the pointer and write the pointer back. Now we have an
697 * integer value that is private to the current thread.
699 * The #GPrivate struct should only be accessed via the following
702 * <note><para>All of the <function>g_private_*</function> functions are
703 * actually macros. Apart from taking their addresses, you can however
704 * use them as if they were functions.</para></note>
709 * @destructor: a function to destroy the data keyed to #GPrivate when
711 * @Returns: a new #GPrivate.
713 * Creates a new #GPrivate. If @destructor is non-%NULL, it is a
714 * pointer to a destructor function. Whenever a thread ends and the
715 * corresponding pointer keyed to this instance of #GPrivate is
716 * non-%NULL, the destructor is called with this pointer as the
719 * <note><para>@destructor is used quite differently from @notify in
720 * g_static_private_set().</para></note>
722 * <note><para>A #GPrivate can not be freed. Reuse it instead, if you
723 * can, to avoid shortage, or use #GStaticPrivate.</para></note>
725 * <note><para>This function will abort if g_thread_init() has not been
726 * called yet.</para></note>
728 (GPrivate*(*)(GDestroyNotify))g_thread_fail,
732 * @private_key: a #GPrivate.
733 * @Returns: the corresponding pointer.
735 * Returns the pointer keyed to @private_key for the current thread. If
736 * g_private_set() hasn't been called for the current @private_key and
737 * thread yet, this pointer will be %NULL.
739 * This function can be used even if g_thread_init() has not yet been
740 * called, and, in that case, will return the value of @private_key
741 * casted to #gpointer. Note however, that private data set
742 * <emphasis>before</emphasis> g_thread_init() will
743 * <emphasis>not</emphasis> be retained <emphasis>after</emphasis> the
744 * call. Instead, %NULL will be returned in all threads directly after
745 * g_thread_init(), regardless of any g_private_set() calls issued
746 * before threading system intialization.
752 * @private_key: a #GPrivate.
753 * @data: the new pointer.
755 * Sets the pointer keyed to @private_key for the current thread.
757 * This function can be used even if g_thread_init() has not yet been
758 * called, and, in that case, will set @private_key to @data casted to
759 * #GPrivate*. See g_private_get() for resulting caveats.
763 /* GThread Virtual Functions {{{2 ---------------------------------------- */
767 * The #GThread struct represents a running thread. It has three public
768 * read-only members, but the underlying struct is bigger, so you must
769 * not copy this struct.
771 * <note><para>Resources for a joinable thread are not fully released
772 * until g_thread_join() is called for that thread.</para></note>
777 * @data: data passed to the thread.
778 * @Returns: the return value of the thread, which will be returned by
781 * Specifies the type of the @func functions passed to
782 * g_thread_create() or g_thread_create_full().
787 * @G_THREAD_PRIORITY_LOW: a priority lower than normal
788 * @G_THREAD_PRIORITY_NORMAL: the default priority
789 * @G_THREAD_PRIORITY_HIGH: a priority higher than normal
790 * @G_THREAD_PRIORITY_URGENT: the highest priority
792 * Specifies the priority of a thread.
794 * <note><para>It is not guaranteed that threads with different priorities
795 * really behave accordingly. On some systems (e.g. Linux) there are no
796 * thread priorities. On other systems (e.g. Solaris) there doesn't
797 * seem to be different scheduling for different priorities. All in all
798 * try to avoid being dependent on priorities.</para></note>
803 * @func: a function to execute in the new thread.
804 * @data: an argument to supply to the new thread.
805 * @joinable: should this thread be joinable?
806 * @error: return location for error.
807 * @Returns: the new #GThread on success.
809 * This function creates a new thread with the default priority.
811 * If @joinable is %TRUE, you can wait for this threads termination
812 * calling g_thread_join(). Otherwise the thread will just disappear
813 * when it terminates.
815 * The new thread executes the function @func with the argument @data.
816 * If the thread was created successfully, it is returned.
818 * @error can be %NULL to ignore errors, or non-%NULL to report errors.
819 * The error is set, if and only if the function returns %NULL.
821 (void(*)(GThreadFunc, gpointer, gulong,
822 gboolean, gboolean, GThreadPriority,
823 gpointer, GError**))g_thread_fail,
828 * Gives way to other threads waiting to be scheduled.
830 * This function is often used as a method to make busy wait less evil.
831 * But in most cases you will encounter, there are better methods to do
832 * that. So in general you shouldn't use this function.
836 NULL, /* thread_join */
837 NULL, /* thread_exit */
838 NULL, /* thread_set_priority */
839 NULL, /* thread_self */
840 NULL /* thread_equal */
843 /* Local Data {{{1 -------------------------------------------------------- */
845 static GMutex *g_once_mutex = NULL;
846 static GCond *g_once_cond = NULL;
847 static GPrivate *g_thread_specific_private = NULL;
848 static GRealThread *g_thread_all_threads = NULL;
849 static GSList *g_thread_free_indeces = NULL;
850 static GSList* g_once_init_list = NULL;
852 G_LOCK_DEFINE_STATIC (g_thread);
854 /* Initialisation {{{1 ---------------------------------------------------- */
856 #ifdef G_THREADS_ENABLED
859 * @vtable: a function table of type #GThreadFunctions, that provides
860 * the entry points to the thread system to be used.
862 * If you use GLib from more than one thread, you must initialize the
863 * thread system by calling g_thread_init(). Most of the time you will
864 * only have to call <literal>g_thread_init (NULL)</literal>.
866 * <note><para>Do not call g_thread_init() with a non-%NULL parameter unless
867 * you really know what you are doing.</para></note>
869 * <note><para>g_thread_init() must not be called directly or indirectly as a
870 * callback from GLib. Also no mutexes may be currently locked while
871 * calling g_thread_init().</para></note>
873 * <note><para>g_thread_init() changes the way in which #GTimer measures
874 * elapsed time. As a consequence, timers that are running while
875 * g_thread_init() is called may report unreliable times.</para></note>
877 * Calling g_thread_init() multiple times is allowed (since version
878 * 2.24), but nothing happens except for the first call. If the
879 * argument is non-%NULL on such a call a warning will be printed, but
880 * otherwise the argument is ignored.
882 * If no thread system is available and @vtable is %NULL or if not all
883 * elements of @vtable are non-%NULL, then g_thread_init() will abort.
885 * <note><para>To use g_thread_init() in your program, you have to link with
886 * the libraries that the command <command>pkg-config --libs
887 * gthread-2.0</command> outputs. This is not the case for all the
888 * other thread related functions of GLib. Those can be used without
889 * having to link with the thread libraries.</para></note>
892 /* This must be called only once, before any threads are created.
893 * It will only be called from g_thread_init() in -lgthread.
896 g_thread_init_glib (void)
898 /* We let the main thread (the one that calls g_thread_init) inherit
899 * the static_private data set before calling g_thread_init
901 GRealThread* main_thread = (GRealThread*) g_thread_self ();
903 /* mutex and cond creation works without g_threads_got_initialized */
904 g_once_mutex = g_mutex_new ();
905 g_once_cond = g_cond_new ();
907 /* we may only create mutex and cond in here */
908 _g_mem_thread_init_noprivate_nomessage ();
910 /* setup the basic threading system */
911 g_threads_got_initialized = TRUE;
912 g_thread_specific_private = g_private_new (g_thread_cleanup);
913 g_private_set (g_thread_specific_private, main_thread);
914 G_THREAD_UF (thread_self, (&main_thread->system_thread));
916 /* complete memory system initialization, g_private_*() works now */
917 _g_slice_thread_init_nomessage ();
919 /* accomplish log system initialization to enable messaging */
920 _g_messages_thread_init_nomessage ();
922 /* we may run full-fledged initializers from here */
923 _g_atomic_thread_init ();
924 _g_convert_thread_init ();
925 _g_rand_thread_init ();
926 _g_main_thread_init ();
927 _g_utils_thread_init ();
928 _g_futex_thread_init ();
930 _g_win32_thread_init ();
933 #endif /* G_THREADS_ENABLED */
935 /* The following sections implement: GOnce, GStaticMutex, GStaticRecMutex,
939 /* GOnce {{{1 ------------------------------------------------------------- */
943 * @status: the status of the #GOnce
944 * @retval: the value returned by the call to the function, if @status
945 * is %G_ONCE_STATUS_READY
947 * A #GOnce struct controls a one-time initialization function. Any
948 * one-time initialization function must have its own unique #GOnce
957 * A #GOnce must be initialized with this macro before it can be used.
959 * <informalexample><programlisting>
960 * GOnce my_once = G_ONCE_INIT;
961 * </programlisting></informalexample>
968 * @G_ONCE_STATUS_NOTCALLED: the function has not been called yet.
969 * @G_ONCE_STATUS_PROGRESS: the function call is currently in progress.
970 * @G_ONCE_STATUS_READY: the function has been called.
972 * The possible statuses of a one-time initialization function
973 * controlled by a #GOnce struct.
980 * @once: a #GOnce structure
981 * @func: the #GThreadFunc function associated to @once. This function
982 * is called only once, regardless of the number of times it and
983 * its associated #GOnce struct are passed to g_once().
984 * @arg: data to be passed to @func
986 * The first call to this routine by a process with a given #GOnce
987 * struct calls @func with the given argument. Thereafter, subsequent
988 * calls to g_once() with the same #GOnce struct do not call @func
989 * again, but return the stored result of the first call. On return
990 * from g_once(), the status of @once will be %G_ONCE_STATUS_READY.
992 * For example, a mutex or a thread-specific data key must be created
993 * exactly once. In a threaded environment, calling g_once() ensures
994 * that the initialization is serialized across multiple threads.
996 * <note><para>Calling g_once() recursively on the same #GOnce struct in
997 * @func will lead to a deadlock.</para></note>
999 * <informalexample><programlisting>
1000 * gpointer get_debug_flags () {
1001 * static GOnce my_once = G_ONCE_INIT;
1002 * g_once (&my_once, parse_debug_flags, NULL);
1003 * return my_once.retval;
1005 * </programlisting></informalexample>
1010 g_once_impl (GOnce *once,
1014 g_mutex_lock (g_once_mutex);
1016 while (once->status == G_ONCE_STATUS_PROGRESS)
1017 g_cond_wait (g_once_cond, g_once_mutex);
1019 if (once->status != G_ONCE_STATUS_READY)
1021 once->status = G_ONCE_STATUS_PROGRESS;
1022 g_mutex_unlock (g_once_mutex);
1024 once->retval = func (arg);
1026 g_mutex_lock (g_once_mutex);
1027 once->status = G_ONCE_STATUS_READY;
1028 g_cond_broadcast (g_once_cond);
1031 g_mutex_unlock (g_once_mutex);
1033 return once->retval;
1037 * g_once_init_enter:
1038 * @value_location: location of a static initializable variable
1040 * @Returns: %TRUE if the initialization section should be entered,
1041 * %FALSE and blocks otherwise
1043 * Function to be called when starting a critical initialization
1044 * section. The argument @value_location must point to a static
1045 * 0-initialized variable that will be set to a value other than 0 at
1046 * the end of the initialization section. In combination with
1047 * g_once_init_leave() and the unique address @value_location, it can
1048 * be ensured that an initialization section will be executed only once
1049 * during a program's life time, and that concurrent threads are
1050 * blocked until initialization completed. To be used in constructs
1055 * static gsize initialization_value = 0;
1057 * if (g_once_init_enter (&initialization_value))
1059 * gsize setup_value = 42; /* initialization code here */
1061 * g_once_init_leave (&initialization_value, setup_value);
1064 * /* use initialization_value here */
1066 * </informalexample>
1071 g_once_init_enter_impl (volatile gsize *value_location)
1073 gboolean need_init = FALSE;
1074 g_mutex_lock (g_once_mutex);
1075 if (g_atomic_pointer_get (value_location) == NULL)
1077 if (!g_slist_find (g_once_init_list, (void*) value_location))
1080 g_once_init_list = g_slist_prepend (g_once_init_list, (void*) value_location);
1084 g_cond_wait (g_once_cond, g_once_mutex);
1085 while (g_slist_find (g_once_init_list, (void*) value_location));
1087 g_mutex_unlock (g_once_mutex);
1092 * g_once_init_leave:
1093 * @value_location: location of a static initializable variable
1095 * @initialization_value: new non-0 value for *@value_location.
1097 * Counterpart to g_once_init_enter(). Expects a location of a static
1098 * 0-initialized initialization variable, and an initialization value
1099 * other than 0. Sets the variable to the initialization value, and
1100 * releases concurrent threads blocking in g_once_init_enter() on this
1101 * initialization variable.
1106 g_once_init_leave (volatile gsize *value_location,
1107 gsize initialization_value)
1109 g_return_if_fail (g_atomic_pointer_get (value_location) == NULL);
1110 g_return_if_fail (initialization_value != 0);
1111 g_return_if_fail (g_once_init_list != NULL);
1113 g_atomic_pointer_set ((void**)value_location, (void*) initialization_value);
1114 g_mutex_lock (g_once_mutex);
1115 g_once_init_list = g_slist_remove (g_once_init_list, (void*) value_location);
1116 g_cond_broadcast (g_once_cond);
1117 g_mutex_unlock (g_once_mutex);
1120 /* GStaticMutex {{{1 ------------------------------------------------------ */
1125 * A #GStaticMutex works like a #GMutex, but it has one significant
1126 * advantage. It doesn't need to be created at run-time like a #GMutex,
1127 * but can be defined at compile-time. Here is a shorter, easier and
1128 * safer version of our <function>give_me_next_number()</function>
1131 * <example> <title>Using <structname>GStaticMutex</structname> to
1132 * simplify thread-safe programming</title> <programlisting> int
1133 * give_me_next_number (<!-- -->) { static int current_number = 0; int
1134 * ret_val; static GStaticMutex mutex = G_STATIC_MUTEX_INIT;
1135 * g_static_mutex_lock (&mutex); ret_val = current_number =
1136 * calc_next_number (current_number); g_static_mutex_unlock
1137 * (&mutex); return ret_val; } </programlisting> </example>
1139 * Sometimes you would like to dynamically create a mutex. If you don't
1140 * want to require prior calling to g_thread_init(), because your code
1141 * should also be usable in non-threaded programs, you are not able to
1142 * use g_mutex_new() and thus #GMutex, as that requires a prior call to
1143 * g_thread_init(). In theses cases you can also use a #GStaticMutex.
1144 * It must be initialized with g_static_mutex_init() before using it
1145 * and freed with with g_static_mutex_free() when not needed anymore to
1146 * free up any allocated resources.
1148 * Even though #GStaticMutex is not opaque, it should only be used with
1149 * the following functions, as it is defined differently on different
1152 * All of the <function>g_static_mutex_*</function> functions apart
1153 * from <function>g_static_mutex_get_mutex</function> can also be used
1154 * even if g_thread_init() has not yet been called. Then they do
1155 * nothing, apart from <function>g_static_mutex_trylock</function>,
1156 * which does nothing but returning %TRUE.
1158 * <note><para>All of the <function>g_static_mutex_*</function>
1159 * functions are actually macros. Apart from taking their addresses, you
1160 * can however use them as if they were functions.</para></note>
1164 * G_STATIC_MUTEX_INIT:
1166 * A #GStaticMutex must be initialized with this macro, before it can
1167 * be used. This macro can used be to initialize a variable, but it
1168 * cannot be assigned to a variable. In that case you have to use
1169 * g_static_mutex_init().
1171 * <informalexample> <programlisting> GStaticMutex my_mutex =
1172 * G_STATIC_MUTEX_INIT; </programlisting> </informalexample>
1176 * g_static_mutex_init:
1177 * @mutex: a #GStaticMutex to be initialized.
1179 * Initializes @mutex. Alternatively you can initialize it with
1180 * #G_STATIC_MUTEX_INIT.
1183 g_static_mutex_init (GStaticMutex *mutex)
1185 static const GStaticMutex init_mutex = G_STATIC_MUTEX_INIT;
1187 g_return_if_fail (mutex);
1189 *mutex = init_mutex;
1192 /* IMPLEMENTATION NOTE:
1194 * On some platforms a GStaticMutex is actually a normal GMutex stored
1195 * inside of a structure instead of being allocated dynamically. We can
1196 * only do this for platforms on which we know, in advance, how to
1197 * allocate (size) and initialise (value) that memory.
1199 * On other platforms, a GStaticMutex is nothing more than a pointer to
1200 * a GMutex. In that case, the first access we make to the static mutex
1201 * must first allocate the normal GMutex and store it into the pointer.
1203 * configure.in writes macros into glibconfig.h to determine if
1204 * g_static_mutex_get_mutex() accesses the sturcture in memory directly
1205 * (on platforms where we are able to do that) or if it ends up here,
1206 * where we may have to allocate the GMutex before returning it.
1210 * g_static_mutex_get_mutex:
1211 * @mutex: a #GStaticMutex.
1212 * @Returns: the #GMutex corresponding to @mutex.
1214 * For some operations (like g_cond_wait()) you must have a #GMutex
1215 * instead of a #GStaticMutex. This function will return the
1216 * corresponding #GMutex for @mutex.
1219 g_static_mutex_get_mutex_impl (GMutex** mutex)
1221 if (!g_thread_supported ())
1224 g_assert (g_once_mutex);
1226 g_mutex_lock (g_once_mutex);
1229 g_atomic_pointer_set (mutex, g_mutex_new());
1231 g_mutex_unlock (g_once_mutex);
1236 /* IMPLEMENTATION NOTE:
1238 * g_static_mutex_lock(), g_static_mutex_trylock() and
1239 * g_static_mutex_unlock() are all preprocessor macros that wrap the
1240 * corresponding g_mutex_*() function around a call to
1241 * g_static_mutex_get_mutex().
1245 * g_static_mutex_lock:
1246 * @mutex: a #GStaticMutex.
1248 * Works like g_mutex_lock(), but for a #GStaticMutex.
1252 * g_static_mutex_trylock:
1253 * @mutex: a #GStaticMutex.
1254 * @Returns: %TRUE, if the #GStaticMutex could be locked.
1256 * Works like g_mutex_trylock(), but for a #GStaticMutex.
1260 * g_static_mutex_unlock:
1261 * @mutex: a #GStaticMutex.
1263 * Works like g_mutex_unlock(), but for a #GStaticMutex.
1267 * g_static_mutex_free:
1268 * @mutex: a #GStaticMutex to be freed.
1270 * Releases all resources allocated to @mutex.
1272 * You don't have to call this functions for a #GStaticMutex with an
1273 * unbounded lifetime, i.e. objects declared 'static', but if you have
1274 * a #GStaticMutex as a member of a structure and the structure is
1275 * freed, you should also free the #GStaticMutex.
1277 * <note><para>Calling g_static_mutex_free() on a locked mutex may
1278 * result in undefined behaviour.</para></note>
1281 g_static_mutex_free (GStaticMutex* mutex)
1283 GMutex **runtime_mutex;
1285 g_return_if_fail (mutex);
1287 /* The runtime_mutex is the first (or only) member of GStaticMutex,
1288 * see both versions (of glibconfig.h) in configure.in. Note, that
1289 * this variable is NULL, if g_thread_init() hasn't been called or
1290 * if we're using the default thread implementation and it provides
1291 * static mutexes. */
1292 runtime_mutex = ((GMutex**)mutex);
1295 g_mutex_free (*runtime_mutex);
1297 *runtime_mutex = NULL;
1300 /* ------------------------------------------------------------------------ */
1305 * A #GStaticRecMutex works like a #GStaticMutex, but it can be locked
1306 * multiple times by one thread. If you enter it n times, you have to
1307 * unlock it n times again to let other threads lock it. An exception
1308 * is the function g_static_rec_mutex_unlock_full(): that allows you to
1309 * unlock a #GStaticRecMutex completely returning the depth, (i.e. the
1310 * number of times this mutex was locked). The depth can later be used
1311 * to restore the state of the #GStaticRecMutex by calling
1312 * g_static_rec_mutex_lock_full().
1314 * Even though #GStaticRecMutex is not opaque, it should only be used
1315 * with the following functions.
1317 * All of the <function>g_static_rec_mutex_*</function> functions can
1318 * be used even if g_thread_init() has not been called. Then they do
1319 * nothing, apart from <function>g_static_rec_mutex_trylock</function>,
1320 * which does nothing but returning %TRUE.
1324 * G_STATIC_REC_MUTEX_INIT:
1326 * A #GStaticRecMutex must be initialized with this macro before it can
1327 * be used. This macro can used be to initialize a variable, but it
1328 * cannot be assigned to a variable. In that case you have to use
1329 * g_static_rec_mutex_init().
1331 * <informalexample> <programlisting> GStaticRecMutex my_mutex =
1332 * G_STATIC_REC_MUTEX_INIT; </programlisting> </informalexample>
1336 * g_static_rec_mutex_init:
1337 * @mutex: a #GStaticRecMutex to be initialized.
1339 * A #GStaticRecMutex must be initialized with this function before it
1340 * can be used. Alternatively you can initialize it with
1341 * #G_STATIC_REC_MUTEX_INIT.
1344 g_static_rec_mutex_init (GStaticRecMutex *mutex)
1346 static const GStaticRecMutex init_mutex = G_STATIC_REC_MUTEX_INIT;
1348 g_return_if_fail (mutex);
1350 *mutex = init_mutex;
1354 * g_static_rec_mutex_lock:
1355 * @mutex: a #GStaticRecMutex to lock.
1357 * Locks @mutex. If @mutex is already locked by another thread, the
1358 * current thread will block until @mutex is unlocked by the other
1359 * thread. If @mutex is already locked by the calling thread, this
1360 * functions increases the depth of @mutex and returns immediately.
1363 g_static_rec_mutex_lock (GStaticRecMutex* mutex)
1367 g_return_if_fail (mutex);
1369 if (!g_thread_supported ())
1372 G_THREAD_UF (thread_self, (&self));
1374 if (g_system_thread_equal (self, mutex->owner))
1379 g_static_mutex_lock (&mutex->mutex);
1380 g_system_thread_assign (mutex->owner, self);
1385 * g_static_rec_mutex_trylock:
1386 * @mutex: a #GStaticRecMutex to lock.
1387 * @Returns: %TRUE, if @mutex could be locked.
1389 * Tries to lock @mutex. If @mutex is already locked by another thread,
1390 * it immediately returns %FALSE. Otherwise it locks @mutex and returns
1391 * %TRUE. If @mutex is already locked by the calling thread, this
1392 * functions increases the depth of @mutex and immediately returns
1396 g_static_rec_mutex_trylock (GStaticRecMutex* mutex)
1400 g_return_val_if_fail (mutex, FALSE);
1402 if (!g_thread_supported ())
1405 G_THREAD_UF (thread_self, (&self));
1407 if (g_system_thread_equal (self, mutex->owner))
1413 if (!g_static_mutex_trylock (&mutex->mutex))
1416 g_system_thread_assign (mutex->owner, self);
1422 * g_static_rec_mutex_unlock:
1423 * @mutex: a #GStaticRecMutex to unlock.
1425 * Unlocks @mutex. Another thread will be allowed to lock @mutex only
1426 * when it has been unlocked as many times as it had been locked
1427 * before. If @mutex is completely unlocked and another thread is
1428 * blocked in a g_static_rec_mutex_lock() call for @mutex, it will be
1429 * woken and can lock @mutex itself.
1432 g_static_rec_mutex_unlock (GStaticRecMutex* mutex)
1434 g_return_if_fail (mutex);
1436 if (!g_thread_supported ())
1439 if (mutex->depth > 1)
1444 g_system_thread_assign (mutex->owner, zero_thread);
1445 g_static_mutex_unlock (&mutex->mutex);
1449 * g_static_rec_mutex_lock_full:
1450 * @mutex: a #GStaticRecMutex to lock.
1451 * @depth: number of times this mutex has to be unlocked to be
1452 * completely unlocked.
1454 * Works like calling g_static_rec_mutex_lock() for @mutex @depth times.
1457 g_static_rec_mutex_lock_full (GStaticRecMutex *mutex,
1461 g_return_if_fail (mutex);
1463 if (!g_thread_supported ())
1469 G_THREAD_UF (thread_self, (&self));
1471 if (g_system_thread_equal (self, mutex->owner))
1473 mutex->depth += depth;
1476 g_static_mutex_lock (&mutex->mutex);
1477 g_system_thread_assign (mutex->owner, self);
1478 mutex->depth = depth;
1482 * g_static_rec_mutex_unlock_full:
1483 * @mutex: a #GStaticRecMutex to completely unlock.
1484 * @Returns: number of times @mutex has been locked by the current
1487 * Completely unlocks @mutex. If another thread is blocked in a
1488 * g_static_rec_mutex_lock() call for @mutex, it will be woken and can
1489 * lock @mutex itself. This function returns the number of times that
1490 * @mutex has been locked by the current thread. To restore the state
1491 * before the call to g_static_rec_mutex_unlock_full() you can call
1492 * g_static_rec_mutex_lock_full() with the depth returned by this
1496 g_static_rec_mutex_unlock_full (GStaticRecMutex *mutex)
1500 g_return_val_if_fail (mutex, 0);
1502 if (!g_thread_supported ())
1505 depth = mutex->depth;
1507 g_system_thread_assign (mutex->owner, zero_thread);
1509 g_static_mutex_unlock (&mutex->mutex);
1515 * g_static_rec_mutex_free:
1516 * @mutex: a #GStaticRecMutex to be freed.
1518 * Releases all resources allocated to a #GStaticRecMutex.
1520 * You don't have to call this functions for a #GStaticRecMutex with an
1521 * unbounded lifetime, i.e. objects declared 'static', but if you have
1522 * a #GStaticRecMutex as a member of a structure and the structure is
1523 * freed, you should also free the #GStaticRecMutex.
1526 g_static_rec_mutex_free (GStaticRecMutex *mutex)
1528 g_return_if_fail (mutex);
1530 g_static_mutex_free (&mutex->mutex);
1533 /* GStaticPrivate {{{1 ---------------------------------------------------- */
1538 * A #GStaticPrivate works almost like a #GPrivate, but it has one
1539 * significant advantage. It doesn't need to be created at run-time
1540 * like a #GPrivate, but can be defined at compile-time. This is
1541 * similar to the difference between #GMutex and #GStaticMutex. Now
1542 * look at our <function>give_me_next_number()</function> example with
1545 * <example> <title>Using GStaticPrivate for per-thread data</title>
1546 * <programlisting> int give_me_next_number (<!-- -->) { static
1547 * GStaticPrivate current_number_key = G_STATIC_PRIVATE_INIT; int
1548 * *current_number = g_static_private_get (&current_number_key); if
1549 * (!current_number) { current_number = g_new (int,1); *current_number
1550 * = 0; g_static_private_set (&current_number_key, current_number,
1551 * g_free); } *current_number = calc_next_number (*current_number);
1552 * return *current_number; } </programlisting> </example>
1556 * G_STATIC_PRIVATE_INIT:
1558 * Every #GStaticPrivate must be initialized with this macro, before it
1561 * <informalexample> <programlisting> GStaticPrivate my_private =
1562 * G_STATIC_PRIVATE_INIT; </programlisting> </informalexample>
1566 * g_static_private_init:
1567 * @private_key: a #GStaticPrivate to be initialized.
1569 * Initializes @private_key. Alternatively you can initialize it with
1570 * #G_STATIC_PRIVATE_INIT.
1573 g_static_private_init (GStaticPrivate *private_key)
1575 private_key->index = 0;
1579 * g_static_private_get:
1580 * @private_key: a #GStaticPrivate.
1581 * @Returns: the corresponding pointer.
1583 * Works like g_private_get() only for a #GStaticPrivate.
1585 * This function works even if g_thread_init() has not yet been called.
1588 g_static_private_get (GStaticPrivate *private_key)
1590 GRealThread *self = (GRealThread*) g_thread_self ();
1593 array = self->private_data;
1597 if (!private_key->index)
1599 else if (private_key->index <= array->len)
1600 return g_array_index (array, GStaticPrivateNode,
1601 private_key->index - 1).data;
1607 * g_static_private_set:
1608 * @private_key: a #GStaticPrivate.
1609 * @data: the new pointer.
1610 * @notify: a function to be called with the pointer whenever the
1611 * current thread ends or sets this pointer again.
1613 * Sets the pointer keyed to @private_key for the current thread and
1614 * the function @notify to be called with that pointer (%NULL or
1615 * non-%NULL), whenever the pointer is set again or whenever the
1616 * current thread ends.
1618 * This function works even if g_thread_init() has not yet been called.
1619 * If g_thread_init() is called later, the @data keyed to @private_key
1620 * will be inherited only by the main thread, i.e. the one that called
1623 * <note><para>@notify is used quite differently from @destructor in
1624 * g_private_new().</para></note>
1627 g_static_private_set (GStaticPrivate *private_key,
1629 GDestroyNotify notify)
1631 GRealThread *self = (GRealThread*) g_thread_self ();
1633 static guint next_index = 0;
1634 GStaticPrivateNode *node;
1636 array = self->private_data;
1639 array = g_array_new (FALSE, TRUE, sizeof (GStaticPrivateNode));
1640 self->private_data = array;
1643 if (!private_key->index)
1647 if (!private_key->index)
1649 if (g_thread_free_indeces)
1651 private_key->index =
1652 GPOINTER_TO_UINT (g_thread_free_indeces->data);
1653 g_thread_free_indeces =
1654 g_slist_delete_link (g_thread_free_indeces,
1655 g_thread_free_indeces);
1658 private_key->index = ++next_index;
1661 G_UNLOCK (g_thread);
1664 if (private_key->index > array->len)
1665 g_array_set_size (array, private_key->index);
1667 node = &g_array_index (array, GStaticPrivateNode, private_key->index - 1);
1670 gpointer ddata = node->data;
1671 GDestroyNotify ddestroy = node->destroy;
1674 node->destroy = notify;
1681 node->destroy = notify;
1686 * g_static_private_free:
1687 * @private_key: a #GStaticPrivate to be freed.
1689 * Releases all resources allocated to @private_key.
1691 * You don't have to call this functions for a #GStaticPrivate with an
1692 * unbounded lifetime, i.e. objects declared 'static', but if you have
1693 * a #GStaticPrivate as a member of a structure and the structure is
1694 * freed, you should also free the #GStaticPrivate.
1697 g_static_private_free (GStaticPrivate *private_key)
1699 guint idx = private_key->index;
1700 GRealThread *thread;
1705 private_key->index = 0;
1709 thread = g_thread_all_threads;
1712 GArray *array = thread->private_data;
1713 thread = thread->next;
1715 if (array && idx <= array->len)
1717 GStaticPrivateNode *node = &g_array_index (array,
1720 gpointer ddata = node->data;
1721 GDestroyNotify ddestroy = node->destroy;
1724 node->destroy = NULL;
1728 G_UNLOCK (g_thread);
1734 g_thread_free_indeces = g_slist_prepend (g_thread_free_indeces,
1735 GUINT_TO_POINTER (idx));
1736 G_UNLOCK (g_thread);
1739 /* GThread Extra Functions {{{1 ------------------------------------------- */
1741 g_thread_cleanup (gpointer data)
1745 GRealThread* thread = data;
1746 if (thread->private_data)
1748 GArray* array = thread->private_data;
1751 for (i = 0; i < array->len; i++ )
1753 GStaticPrivateNode *node =
1754 &g_array_index (array, GStaticPrivateNode, i);
1756 node->destroy (node->data);
1758 g_array_free (array, TRUE);
1761 /* We only free the thread structure, if it isn't joinable. If
1762 it is, the structure is freed in g_thread_join */
1763 if (!thread->thread.joinable)
1768 for (t = g_thread_all_threads, p = NULL; t; p = t, t = t->next)
1775 g_thread_all_threads = t->next;
1779 G_UNLOCK (g_thread);
1781 /* Just to make sure, this isn't used any more */
1782 g_system_thread_assign (thread->system_thread, zero_thread);
1789 g_thread_fail (void)
1791 g_error ("The thread system is not yet initialized.");
1794 #define G_NSEC_PER_SEC 1000000000
1802 /* Returns 100s of nanoseconds since start of 1601 */
1803 GetSystemTimeAsFileTime ((FILETIME *)&v);
1805 /* Offset to Unix epoch */
1806 v -= G_GINT64_CONSTANT (116444736000000000);
1807 /* Convert to nanoseconds */
1814 gettimeofday (&tv, NULL);
1816 return (guint64) tv.tv_sec * G_NSEC_PER_SEC + tv.tv_usec * (G_NSEC_PER_SEC / G_USEC_PER_SEC);
1821 g_thread_create_proxy (gpointer data)
1823 GRealThread* thread = data;
1827 /* This has to happen before G_LOCK, as that might call g_thread_self */
1828 g_private_set (g_thread_specific_private, data);
1830 /* the lock makes sure, that thread->system_thread is written,
1831 before thread->thread.func is called. See g_thread_create. */
1833 G_UNLOCK (g_thread);
1835 thread->retval = thread->thread.func (thread->thread.data);
1841 * g_thread_create_full:
1842 * @func: a function to execute in the new thread.
1843 * @data: an argument to supply to the new thread.
1844 * @stack_size: a stack size for the new thread.
1845 * @joinable: should this thread be joinable?
1846 * @bound: should this thread be bound to a system thread?
1847 * @priority: a priority for the thread.
1848 * @error: return location for error.
1849 * @Returns: the new #GThread on success.
1851 * This function creates a new thread with the priority @priority. If
1852 * the underlying thread implementation supports it, the thread gets a
1853 * stack size of @stack_size or the default value for the current
1854 * platform, if @stack_size is 0.
1856 * If @joinable is %TRUE, you can wait for this threads termination
1857 * calling g_thread_join(). Otherwise the thread will just disappear
1858 * when it terminates. If @bound is %TRUE, this thread will be
1859 * scheduled in the system scope, otherwise the implementation is free
1860 * to do scheduling in the process scope. The first variant is more
1861 * expensive resource-wise, but generally faster. On some systems (e.g.
1862 * Linux) all threads are bound.
1864 * The new thread executes the function @func with the argument @data.
1865 * If the thread was created successfully, it is returned.
1867 * @error can be %NULL to ignore errors, or non-%NULL to report errors.
1868 * The error is set, if and only if the function returns %NULL.
1870 * <note><para>It is not guaranteed that threads with different priorities
1871 * really behave accordingly. On some systems (e.g. Linux) there are no
1872 * thread priorities. On other systems (e.g. Solaris) there doesn't
1873 * seem to be different scheduling for different priorities. All in all
1874 * try to avoid being dependent on priorities. Use
1875 * %G_THREAD_PRIORITY_NORMAL here as a default.</para></note>
1877 * <note><para>Only use g_thread_create_full() if you really can't use
1878 * g_thread_create() instead. g_thread_create() does not take
1879 * @stack_size, @bound, and @priority as arguments, as they should only
1880 * be used in cases in which it is unavoidable.</para></note>
1883 g_thread_create_full (GThreadFunc func,
1888 GThreadPriority priority,
1891 GRealThread* result;
1892 GError *local_error = NULL;
1893 g_return_val_if_fail (func, NULL);
1894 g_return_val_if_fail (priority >= G_THREAD_PRIORITY_LOW, NULL);
1895 g_return_val_if_fail (priority <= G_THREAD_PRIORITY_URGENT, NULL);
1897 result = g_new0 (GRealThread, 1);
1899 result->thread.joinable = joinable;
1900 result->thread.priority = priority;
1901 result->thread.func = func;
1902 result->thread.data = data;
1903 result->private_data = NULL;
1905 G_THREAD_UF (thread_create, (g_thread_create_proxy, result,
1906 stack_size, joinable, bound, priority,
1907 &result->system_thread, &local_error));
1910 result->next = g_thread_all_threads;
1911 g_thread_all_threads = result;
1913 G_UNLOCK (g_thread);
1917 g_propagate_error (error, local_error);
1922 return (GThread*) result;
1927 * @retval: the return value of this thread.
1929 * Exits the current thread. If another thread is waiting for that
1930 * thread using g_thread_join() and the current thread is joinable, the
1931 * waiting thread will be woken up and get @retval as the return value
1932 * of g_thread_join(). If the current thread is not joinable, @retval
1933 * is ignored. Calling
1935 * <informalexample> <programlisting> g_thread_exit (retval);
1936 * </programlisting> </informalexample>
1938 * is equivalent to calling
1940 * <informalexample> <programlisting> return retval; </programlisting>
1941 * </informalexample>
1943 * in the function @func, as given to g_thread_create().
1945 * <note><para>Never call g_thread_exit() from within a thread of a
1946 * #GThreadPool, as that will mess up the bookkeeping and lead to funny
1947 * and unwanted results.</para></note>
1950 g_thread_exit (gpointer retval)
1952 GRealThread* real = (GRealThread*) g_thread_self ();
1953 real->retval = retval;
1954 G_THREAD_CF (thread_exit, (void)0, ());
1959 * @thread: a #GThread to be waited for.
1960 * @Returns: the return value of the thread.
1962 * Waits until @thread finishes, i.e. the function @func, as given to
1963 * g_thread_create(), returns or g_thread_exit() is called by @thread.
1964 * All resources of @thread including the #GThread struct are released.
1965 * @thread must have been created with @joinable=%TRUE in
1966 * g_thread_create(). The value returned by @func or given to
1967 * g_thread_exit() by @thread is returned by this function.
1970 g_thread_join (GThread* thread)
1972 GRealThread* real = (GRealThread*) thread;
1976 g_return_val_if_fail (thread, NULL);
1977 g_return_val_if_fail (thread->joinable, NULL);
1978 g_return_val_if_fail (!g_system_thread_equal (real->system_thread,
1979 zero_thread), NULL);
1981 G_THREAD_UF (thread_join, (&real->system_thread));
1983 retval = real->retval;
1986 for (t = g_thread_all_threads, p = NULL; t; p = t, t = t->next)
1988 if (t == (GRealThread*) thread)
1993 g_thread_all_threads = t->next;
1997 G_UNLOCK (g_thread);
1999 /* Just to make sure, this isn't used any more */
2000 thread->joinable = 0;
2001 g_system_thread_assign (real->system_thread, zero_thread);
2003 /* the thread structure for non-joinable threads is freed upon
2004 thread end. We free the memory here. This will leave a loose end,
2005 if a joinable thread is not joined. */
2013 * g_thread_set_priority:
2014 * @thread: a #GThread.
2015 * @priority: a new priority for @thread.
2017 * Changes the priority of @thread to @priority.
2019 * <note><para>It is not guaranteed that threads with different
2020 * priorities really behave accordingly. On some systems (e.g. Linux)
2021 * there are no thread priorities. On other systems (e.g. Solaris) there
2022 * doesn't seem to be different scheduling for different priorities. All
2023 * in all try to avoid being dependent on priorities.</para></note>
2026 g_thread_set_priority (GThread* thread,
2027 GThreadPriority priority)
2029 GRealThread* real = (GRealThread*) thread;
2031 g_return_if_fail (thread);
2032 g_return_if_fail (!g_system_thread_equal (real->system_thread, zero_thread));
2033 g_return_if_fail (priority >= G_THREAD_PRIORITY_LOW);
2034 g_return_if_fail (priority <= G_THREAD_PRIORITY_URGENT);
2036 thread->priority = priority;
2038 G_THREAD_CF (thread_set_priority, (void)0,
2039 (&real->system_thread, priority));
2044 * @Returns: the current thread.
2046 * This functions returns the #GThread corresponding to the calling
2050 g_thread_self (void)
2052 GRealThread* thread = g_private_get (g_thread_specific_private);
2056 /* If no thread data is available, provide and set one. This
2057 can happen for the main thread and for threads, that are not
2059 thread = g_new0 (GRealThread, 1);
2060 thread->thread.joinable = FALSE; /* This is a save guess */
2061 thread->thread.priority = G_THREAD_PRIORITY_NORMAL; /* This is
2063 thread->thread.func = NULL;
2064 thread->thread.data = NULL;
2065 thread->private_data = NULL;
2067 if (g_thread_supported ())
2068 G_THREAD_UF (thread_self, (&thread->system_thread));
2070 g_private_set (g_thread_specific_private, thread);
2073 thread->next = g_thread_all_threads;
2074 g_thread_all_threads = thread;
2075 G_UNLOCK (g_thread);
2078 return (GThread*)thread;
2081 /* GStaticRWLock {{{1 ----------------------------------------------------- */
2086 * The #GStaticRWLock struct represents a read-write lock. A read-write
2087 * lock can be used for protecting data that some portions of code only
2088 * read from, while others also write. In such situations it is
2089 * desirable that several readers can read at once, whereas of course
2090 * only one writer may write at a time. Take a look at the following
2091 * example: <example> <title>An array with access functions</title>
2092 * <programlisting> GStaticRWLock rwlock = G_STATIC_RW_LOCK_INIT;
2093 * GPtrArray *array; gpointer my_array_get (guint index) { gpointer
2094 * retval = NULL; if (!array) return NULL; g_static_rw_lock_reader_lock
2095 * (&rwlock); if (index < array->len) retval = g_ptr_array_index
2096 * (array, index); g_static_rw_lock_reader_unlock (&rwlock); return
2097 * retval; } void my_array_set (guint index, gpointer data) {
2098 * g_static_rw_lock_writer_lock (&rwlock); if (!array) array =
2099 * g_ptr_array_new (<!-- -->); if (index >= array->len)
2100 * g_ptr_array_set_size (array, index+1); g_ptr_array_index (array,
2101 * index) = data; g_static_rw_lock_writer_unlock (&rwlock); }
2102 * </programlisting> </example>
2104 * This example shows an array which can be accessed by many readers
2105 * (the <function>my_array_get()</function> function) simultaneously,
2106 * whereas the writers (the <function>my_array_set()</function>
2107 * function) will only be allowed once at a time and only if no readers
2108 * currently access the array. This is because of the potentially
2109 * dangerous resizing of the array. Using these functions is fully
2110 * multi-thread safe now.
2112 * Most of the time, writers should have precedence over readers. That
2113 * means, for this implementation, that as soon as a writer wants to
2114 * lock the data, no other reader is allowed to lock the data, whereas,
2115 * of course, the readers that already have locked the data are allowed
2116 * to finish their operation. As soon as the last reader unlocks the
2117 * data, the writer will lock it.
2119 * Even though #GStaticRWLock is not opaque, it should only be used
2120 * with the following functions.
2122 * All of the <function>g_static_rw_lock_*</function> functions can be
2123 * used even if g_thread_init() has not been called. Then they do
2124 * nothing, apart from <function>g_static_rw_lock_*_trylock</function>,
2125 * which does nothing but returning %TRUE.
2127 * <note><para>A read-write lock has a higher overhead than a mutex. For
2128 * example, both g_static_rw_lock_reader_lock() and
2129 * g_static_rw_lock_reader_unlock() have to lock and unlock a
2130 * #GStaticMutex, so it takes at least twice the time to lock and unlock
2131 * a #GStaticRWLock that it does to lock and unlock a #GStaticMutex. So
2132 * only data structures that are accessed by multiple readers, and which
2133 * keep the lock for a considerable time justify a #GStaticRWLock. The
2134 * above example most probably would fare better with a
2135 * #GStaticMutex.</para></note>
2139 * G_STATIC_RW_LOCK_INIT:
2141 * A #GStaticRWLock must be initialized with this macro before it can
2142 * be used. This macro can used be to initialize a variable, but it
2143 * cannot be assigned to a variable. In that case you have to use
2144 * g_static_rw_lock_init().
2146 * <informalexample> <programlisting> GStaticRWLock my_lock =
2147 * G_STATIC_RW_LOCK_INIT; </programlisting> </informalexample>
2151 * g_static_rw_lock_init:
2152 * @lock: a #GStaticRWLock to be initialized.
2154 * A #GStaticRWLock must be initialized with this function before it
2155 * can be used. Alternatively you can initialize it with
2156 * #G_STATIC_RW_LOCK_INIT.
2159 g_static_rw_lock_init (GStaticRWLock* lock)
2161 static const GStaticRWLock init_lock = G_STATIC_RW_LOCK_INIT;
2163 g_return_if_fail (lock);
2169 g_static_rw_lock_wait (GCond** cond, GStaticMutex* mutex)
2172 *cond = g_cond_new ();
2173 g_cond_wait (*cond, g_static_mutex_get_mutex (mutex));
2177 g_static_rw_lock_signal (GStaticRWLock* lock)
2179 if (lock->want_to_write && lock->write_cond)
2180 g_cond_signal (lock->write_cond);
2181 else if (lock->want_to_read && lock->read_cond)
2182 g_cond_broadcast (lock->read_cond);
2186 * g_static_rw_lock_reader_lock:
2187 * @lock: a #GStaticRWLock to lock for reading.
2189 * Locks @lock for reading. There may be unlimited concurrent locks for
2190 * reading of a #GStaticRWLock at the same time. If @lock is already
2191 * locked for writing by another thread or if another thread is already
2192 * waiting to lock @lock for writing, this function will block until
2193 * @lock is unlocked by the other writing thread and no other writing
2194 * threads want to lock @lock. This lock has to be unlocked by
2195 * g_static_rw_lock_reader_unlock().
2197 * #GStaticRWLock is not recursive. It might seem to be possible to
2198 * recursively lock for reading, but that can result in a deadlock, due
2199 * to writer preference.
2202 g_static_rw_lock_reader_lock (GStaticRWLock* lock)
2204 g_return_if_fail (lock);
2206 if (!g_threads_got_initialized)
2209 g_static_mutex_lock (&lock->mutex);
2210 lock->want_to_read++;
2211 while (lock->have_writer || lock->want_to_write)
2212 g_static_rw_lock_wait (&lock->read_cond, &lock->mutex);
2213 lock->want_to_read--;
2214 lock->read_counter++;
2215 g_static_mutex_unlock (&lock->mutex);
2219 * g_static_rw_lock_reader_trylock:
2220 * @lock: a #GStaticRWLock to lock for reading.
2221 * @Returns: %TRUE, if @lock could be locked for reading.
2223 * Tries to lock @lock for reading. If @lock is already locked for
2224 * writing by another thread or if another thread is already waiting to
2225 * lock @lock for writing, immediately returns %FALSE. Otherwise locks
2226 * @lock for reading and returns %TRUE. This lock has to be unlocked by
2227 * g_static_rw_lock_reader_unlock().
2230 g_static_rw_lock_reader_trylock (GStaticRWLock* lock)
2232 gboolean ret_val = FALSE;
2234 g_return_val_if_fail (lock, FALSE);
2236 if (!g_threads_got_initialized)
2239 g_static_mutex_lock (&lock->mutex);
2240 if (!lock->have_writer && !lock->want_to_write)
2242 lock->read_counter++;
2245 g_static_mutex_unlock (&lock->mutex);
2250 * g_static_rw_lock_reader_unlock:
2251 * @lock: a #GStaticRWLock to unlock after reading.
2253 * Unlocks @lock. If a thread waits to lock @lock for writing and all
2254 * locks for reading have been unlocked, the waiting thread is woken up
2255 * and can lock @lock for writing.
2258 g_static_rw_lock_reader_unlock (GStaticRWLock* lock)
2260 g_return_if_fail (lock);
2262 if (!g_threads_got_initialized)
2265 g_static_mutex_lock (&lock->mutex);
2266 lock->read_counter--;
2267 if (lock->read_counter == 0)
2268 g_static_rw_lock_signal (lock);
2269 g_static_mutex_unlock (&lock->mutex);
2273 * g_static_rw_lock_writer_lock:
2274 * @lock: a #GStaticRWLock to lock for writing.
2276 * Locks @lock for writing. If @lock is already locked for writing or
2277 * reading by other threads, this function will block until @lock is
2278 * completely unlocked and then lock @lock for writing. While this
2279 * functions waits to lock @lock, no other thread can lock @lock for
2280 * reading. When @lock is locked for writing, no other thread can lock
2281 * @lock (neither for reading nor writing). This lock has to be
2282 * unlocked by g_static_rw_lock_writer_unlock().
2285 g_static_rw_lock_writer_lock (GStaticRWLock* lock)
2287 g_return_if_fail (lock);
2289 if (!g_threads_got_initialized)
2292 g_static_mutex_lock (&lock->mutex);
2293 lock->want_to_write++;
2294 while (lock->have_writer || lock->read_counter)
2295 g_static_rw_lock_wait (&lock->write_cond, &lock->mutex);
2296 lock->want_to_write--;
2297 lock->have_writer = TRUE;
2298 g_static_mutex_unlock (&lock->mutex);
2302 * g_static_rw_lock_writer_trylock:
2303 * @lock: a #GStaticRWLock to lock for writing.
2304 * @Returns: %TRUE, if @lock could be locked for writing.
2306 * Tries to lock @lock for writing. If @lock is already locked (for
2307 * either reading or writing) by another thread, it immediately returns
2308 * %FALSE. Otherwise it locks @lock for writing and returns %TRUE. This
2309 * lock has to be unlocked by g_static_rw_lock_writer_unlock().
2312 g_static_rw_lock_writer_trylock (GStaticRWLock* lock)
2314 gboolean ret_val = FALSE;
2316 g_return_val_if_fail (lock, FALSE);
2318 if (!g_threads_got_initialized)
2321 g_static_mutex_lock (&lock->mutex);
2322 if (!lock->have_writer && !lock->read_counter)
2324 lock->have_writer = TRUE;
2327 g_static_mutex_unlock (&lock->mutex);
2332 * g_static_rw_lock_writer_unlock:
2333 * @lock: a #GStaticRWLock to unlock after writing.
2335 * Unlocks @lock. If a thread is waiting to lock @lock for writing and
2336 * all locks for reading have been unlocked, the waiting thread is
2337 * woken up and can lock @lock for writing. If no thread is waiting to
2338 * lock @lock for writing, and some thread or threads are waiting to
2339 * lock @lock for reading, the waiting threads are woken up and can
2340 * lock @lock for reading.
2343 g_static_rw_lock_writer_unlock (GStaticRWLock* lock)
2345 g_return_if_fail (lock);
2347 if (!g_threads_got_initialized)
2350 g_static_mutex_lock (&lock->mutex);
2351 lock->have_writer = FALSE;
2352 g_static_rw_lock_signal (lock);
2353 g_static_mutex_unlock (&lock->mutex);
2357 * g_static_rw_lock_free:
2358 * @lock: a #GStaticRWLock to be freed.
2360 * Releases all resources allocated to @lock.
2362 * You don't have to call this functions for a #GStaticRWLock with an
2363 * unbounded lifetime, i.e. objects declared 'static', but if you have
2364 * a #GStaticRWLock as a member of a structure, and the structure is
2365 * freed, you should also free the #GStaticRWLock.
2368 g_static_rw_lock_free (GStaticRWLock* lock)
2370 g_return_if_fail (lock);
2372 if (lock->read_cond)
2374 g_cond_free (lock->read_cond);
2375 lock->read_cond = NULL;
2377 if (lock->write_cond)
2379 g_cond_free (lock->write_cond);
2380 lock->write_cond = NULL;
2382 g_static_mutex_free (&lock->mutex);
2385 /* Unsorted {{{1 ---------------------------------------------------------- */
2389 * @thread_func: function to call for all GThread structures
2390 * @user_data: second argument to @thread_func
2392 * Call @thread_func on all existing #GThread structures. Note that
2393 * threads may decide to exit while @thread_func is running, so
2394 * without intimate knowledge about the lifetime of foreign threads,
2395 * @thread_func shouldn't access the GThread* pointer passed in as
2396 * first argument. However, @thread_func will not be called for threads
2397 * which are known to have exited already.
2399 * Due to thread lifetime checks, this function has an execution complexity
2400 * which is quadratic in the number of existing threads.
2405 g_thread_foreach (GFunc thread_func,
2408 GSList *slist = NULL;
2409 GRealThread *thread;
2410 g_return_if_fail (thread_func != NULL);
2411 /* snapshot the list of threads for iteration */
2413 for (thread = g_thread_all_threads; thread; thread = thread->next)
2414 slist = g_slist_prepend (slist, thread);
2415 G_UNLOCK (g_thread);
2416 /* walk the list, skipping non-existant threads */
2419 GSList *node = slist;
2421 /* check whether the current thread still exists */
2423 for (thread = g_thread_all_threads; thread; thread = thread->next)
2424 if (thread == node->data)
2426 G_UNLOCK (g_thread);
2428 thread_func (thread, user_data);
2429 g_slist_free_1 (node);
2434 * g_thread_get_initialized
2436 * Indicates if g_thread_init() has been called.
2438 * Returns: %TRUE if threads have been initialized.
2443 g_thread_get_initialized ()
2445 return g_thread_supported ();
2448 #define __G_THREAD_C__
2449 #include "galiasdef.c"