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 need 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
173 * <title>Using the %G_LOCK_* convenience macros</title>
175 * G_LOCK_DEFINE (current_number);
178 * give_me_next_number (void)
180 * static int current_number = 0;
183 * G_LOCK (current_number);
184 * ret_val = current_number = calc_next_number (current_number);
185 * G_UNLOCK (current_number);
194 * G_LOCK_DEFINE_STATIC:
195 * @name: the name of the lock.
197 * This works like #G_LOCK_DEFINE, but it creates a static object.
202 * @name: the name of the lock.
204 * This declares a lock, that is defined with #G_LOCK_DEFINE in another
210 * @name: the name of the lock.
212 * Works like g_mutex_lock(), but for a lock defined with
218 * @name: the name of the lock.
219 * @Returns: %TRUE, if the lock could be locked.
221 * Works like g_mutex_trylock(), but for a lock defined with
227 * @name: the name of the lock.
229 * Works like g_mutex_unlock(), but for a lock defined with
233 /* GThreadError {{{1 ------------------------------------------------------- */
236 * @G_THREAD_ERROR_AGAIN: a thread couldn't be created due to resource
237 * shortage. Try again later.
239 * Possible errors of thread related functions.
245 * The error domain of the GLib thread subsystem.
248 g_thread_error_quark (void)
250 return g_quark_from_static_string ("g_thread_error");
253 /* Miscellaneous Structures {{{1 ------------------------------------------ */
254 /* Keep this in sync with GRealThread in gmain.c! */
255 typedef struct _GRealThread GRealThread
;
259 gpointer private_data
;
262 GSystemThread system_thread
;
265 typedef struct _GStaticPrivateNode GStaticPrivateNode
;
266 struct _GStaticPrivateNode
269 GDestroyNotify destroy
;
272 static void g_thread_cleanup (gpointer data
);
273 static void g_thread_fail (void);
274 static guint64
gettime (void);
276 guint64 (*g_thread_gettime
) (void) = gettime
;
278 /* Global Variables {{{1 -------------------------------------------------- */
280 static GSystemThread zero_thread
; /* This is initialized to all zero */
281 gboolean g_thread_use_default_impl
= TRUE
;
284 * g_thread_supported:
285 * @Returns: %TRUE, if the thread system is initialized.
287 * This function returns %TRUE if the thread system is initialized, and
288 * %FALSE if it is not.
290 * <note><para>This function is actually a macro. Apart from taking the
291 * address of it you can however use it as if it was a
292 * function.</para></note>
295 /* IMPLEMENTATION NOTE:
297 * g_thread_supported() is just returns g_threads_got_initialized
299 gboolean g_threads_got_initialized
= FALSE
;
302 /* Thread Implementation Virtual Function Table {{{1 ---------------------- */
303 /* Virtual Function Table Documentation {{{2 ------------------------------ */
306 * @mutex_new: virtual function pointer for g_mutex_new()
307 * @mutex_lock: virtual function pointer for g_mutex_lock()
308 * @mutex_trylock: virtual function pointer for g_mutex_trylock()
309 * @mutex_unlock: virtual function pointer for g_mutex_unlock()
310 * @mutex_free: virtual function pointer for g_mutex_free()
311 * @cond_new: virtual function pointer for g_cond_new()
312 * @cond_signal: virtual function pointer for g_cond_signal()
313 * @cond_broadcast: virtual function pointer for g_cond_broadcast()
314 * @cond_wait: virtual function pointer for g_cond_wait()
315 * @cond_timed_wait: virtual function pointer for g_cond_timed_wait()
316 * @cond_free: virtual function pointer for g_cond_free()
317 * @private_new: virtual function pointer for g_private_new()
318 * @private_get: virtual function pointer for g_private_get()
319 * @private_set: virtual function pointer for g_private_set()
320 * @thread_create: virtual function pointer for g_thread_create()
321 * @thread_yield: virtual function pointer for g_thread_yield()
322 * @thread_join: virtual function pointer for g_thread_join()
323 * @thread_exit: virtual function pointer for g_thread_exit()
324 * @thread_set_priority: virtual function pointer for
325 * g_thread_set_priority()
326 * @thread_self: virtual function pointer for g_thread_self()
327 * @thread_equal: used internally by recursive mutex locks and by some
330 * This function table is used by g_thread_init() to initialize the
331 * thread system. The functions in the table are directly used by their
332 * g_* prepended counterparts (described in this document). For
333 * example, if you call g_mutex_new() then mutex_new() from the table
334 * provided to g_thread_init() will be called.
336 * <note><para>Do not use this struct unless you know what you are
337 * doing.</para></note>
340 /* IMPLEMENTATION NOTE:
342 * g_thread_functions_for_glib_use is a global symbol that gets used by
343 * most of the "primative" threading calls. g_mutex_lock(), for
344 * example, is just a macro that calls the appropriate virtual function
347 * For that reason, all of those macros are documented here.
349 GThreadFunctions g_thread_functions_for_glib_use
= {
350 /* GMutex Virtual Functions {{{2 ------------------------------------------ */
355 * The #GMutex struct is an opaque data structure to represent a mutex
356 * (mutual exclusion). It can be used to protect data against shared
357 * access. Take for example the following function:
360 * <title>A function which will not work in a threaded environment</title>
363 * give_me_next_number (void)
365 * static int current_number = 0;
367 * /<!-- -->* now do a very complicated calculation to calculate the new
368 * * number, this might for example be a random number generator
370 * current_number = calc_next_number (current_number);
372 * return current_number;
377 * It is easy to see that this won't work in a multi-threaded
378 * application. There current_number must be protected against shared
379 * access. A first naive implementation would be:
382 * <title>The wrong way to write a thread-safe function</title>
385 * give_me_next_number (void)
387 * static int current_number = 0;
389 * static GMutex * mutex = NULL;
391 * if (!mutex) mutex = g_mutex_new (<!-- -->);
393 * g_mutex_lock (mutex);
394 * ret_val = current_number = calc_next_number (current_number);
395 * g_mutex_unlock (mutex);
402 * This looks like it would work, but there is a race condition while
403 * constructing the mutex and this code cannot work reliable. Please do
404 * not use such constructs in your own programs! One working solution
408 * <title>A correct thread-safe function</title>
410 * static GMutex *give_me_next_number_mutex = NULL;
412 * /<!-- -->* this function must be called before any call to
413 * * give_me_next_number(<!-- -->)
415 * * it must be called exactly once.
418 * init_give_me_next_number (void)
420 * g_assert (give_me_next_number_mutex == NULL);
421 * give_me_next_number_mutex = g_mutex_new (<!-- -->);
425 * give_me_next_number (void)
427 * static int current_number = 0;
430 * g_mutex_lock (give_me_next_number_mutex);
431 * ret_val = current_number = calc_next_number (current_number);
432 * g_mutex_unlock (give_me_next_number_mutex);
439 * #GStaticMutex provides a simpler and safer way of doing this.
441 * If you want to use a mutex, and your code should also work without
442 * calling g_thread_init() first, then you can not use a #GMutex, as
443 * g_mutex_new() requires that the thread system be initialized. Use a
444 * #GStaticMutex instead.
446 * A #GMutex should only be accessed via the following functions.
448 * <note><para>All of the <function>g_mutex_*</function> functions are
449 * actually macros. Apart from taking their addresses, you can however
450 * use them as if they were functions.</para></note>
455 * @Returns: a new #GMutex.
457 * Creates a new #GMutex.
459 * <note><para>This function will abort if g_thread_init() has not been
460 * called yet.</para></note>
462 (GMutex
*(*)())g_thread_fail
,
468 * Locks @mutex. If @mutex is already locked by another thread, the
469 * current thread will block until @mutex is unlocked by the other
472 * This function can be used even if g_thread_init() has not yet been
473 * called, and, in that case, will do nothing.
475 * <note><para>#GMutex is neither guaranteed to be recursive nor to be
476 * non-recursive, i.e. a thread could deadlock while calling
477 * g_mutex_lock(), if it already has locked @mutex. Use
478 * #GStaticRecMutex, if you need recursive mutexes.</para></note>
485 * @Returns: %TRUE, if @mutex could be locked.
487 * Tries to lock @mutex. If @mutex is already locked by another thread,
488 * it immediately returns %FALSE. Otherwise it locks @mutex and returns
491 * This function can be used even if g_thread_init() has not yet been
492 * called, and, in that case, will immediately return %TRUE.
494 * <note><para>#GMutex is neither guaranteed to be recursive nor to be
495 * non-recursive, i.e. the return value of g_mutex_trylock() could be
496 * both %FALSE or %TRUE, if the current thread already has locked
497 * @mutex. Use #GStaticRecMutex, if you need recursive
498 * mutexes.</para></note>
506 * Unlocks @mutex. If another thread is blocked in a g_mutex_lock()
507 * call for @mutex, it will be woken and can lock @mutex itself.
509 * This function can be used even if g_thread_init() has not yet been
510 * called, and, in that case, will do nothing.
520 * <note><para>Calling g_mutex_free() on a locked mutex may result in
521 * undefined behaviour.</para></note>
525 /* GCond Virtual Functions {{{2 ------------------------------------------ */
530 * The #GCond struct is an opaque data structure that represents a
531 * condition. Threads can block on a #GCond if they find a certain
532 * condition to be false. If other threads change the state of this
533 * condition they signal the #GCond, and that causes the waiting
534 * threads to be woken up.
538 * Using GCond to block a thread until a condition is satisfied
541 * GCond* data_cond = NULL; /<!-- -->* Must be initialized somewhere *<!-- -->/
542 * GMutex* data_mutex = NULL; /<!-- -->* Must be initialized somewhere *<!-- -->/
543 * gpointer current_data = NULL;
546 * push_data (gpointer data)
548 * g_mutex_lock (data_mutex);
549 * current_data = data;
550 * g_cond_signal (data_cond);
551 * g_mutex_unlock (data_mutex);
559 * g_mutex_lock (data_mutex);
560 * while (!current_data)
561 * g_cond_wait (data_cond, data_mutex);
562 * data = current_data;
563 * current_data = NULL;
564 * g_mutex_unlock (data_mutex);
571 * Whenever a thread calls <function>pop_data()</function> now, it will
572 * wait until current_data is non-%NULL, i.e. until some other thread
573 * has called <function>push_data()</function>.
575 * <note><para>It is important to use the g_cond_wait() and
576 * g_cond_timed_wait() functions only inside a loop which checks for the
577 * condition to be true. It is not guaranteed that the waiting thread
578 * will find the condition fulfilled after it wakes up, even if the
579 * signaling thread left the condition in that state: another thread may
580 * have altered the condition before the waiting thread got the chance
581 * to be woken up, even if the condition itself is protected by a
582 * #GMutex, like above.</para></note>
584 * A #GCond should only be accessed via the following functions.
586 * <note><para>All of the <function>g_cond_*</function> functions are
587 * actually macros. Apart from taking their addresses, you can however
588 * use them as if they were functions.</para></note>
593 * @Returns: a new #GCond.
595 * Creates a new #GCond. This function will abort, if g_thread_init()
596 * has not been called yet.
598 (GCond
*(*)())g_thread_fail
,
604 * If threads are waiting for @cond, exactly one of them is woken up.
605 * It is good practice to hold the same lock as the waiting thread
606 * while 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.
617 * If threads are waiting for @cond, all of them are woken up. It is
618 * good practice to lock the same mutex as the waiting threads, while
619 * calling this function, though not required.
621 * This function can be used even if g_thread_init() has not yet been
622 * called, and, in that case, will do nothing.
629 * @mutex: a #GMutex, that is currently locked.
631 * Waits until this thread is woken up on @cond. The @mutex is unlocked
632 * before falling asleep and locked again before resuming.
634 * This function can be used even if g_thread_init() has not yet been
635 * called, and, in that case, will immediately return.
642 * @mutex: a #GMutex that is currently locked.
643 * @abs_time: a #GTimeVal, determining the final time.
644 * @Returns: %TRUE if @cond was signalled, or %FALSE on timeout.
646 * Waits until this thread is woken up on @cond, but not longer than
647 * until the time specified by @abs_time. The @mutex is unlocked before
648 * falling asleep and locked again before resuming.
650 * If @abs_time is %NULL, g_cond_timed_wait() acts like g_cond_wait().
652 * This function can be used even if g_thread_init() has not yet been
653 * called, and, in that case, will immediately return %TRUE.
655 * To easily calculate @abs_time a combination of g_get_current_time()
656 * and g_time_val_add() can be used.
664 * Destroys the #GCond.
668 /* GPrivate Virtual Functions {{{2 --------------------------------------- */
673 * The #GPrivate struct is an opaque data structure to represent a
674 * thread private data key. Threads can thereby obtain and set a
675 * pointer which is private to the current thread. Take our
676 * <function>give_me_next_number(<!-- -->)</function> example from
677 * above. Suppose we don't want <literal>current_number</literal> to be
678 * shared between the threads, but instead to be private to each thread.
679 * This can be done as follows:
682 * <title>Using GPrivate for per-thread data</title>
684 * GPrivate* current_number_key = NULL; /<!-- -->* Must be initialized somewhere
685 * with g_private_new (g_free); *<!-- -->/
688 * give_me_next_number (void)
690 * int *current_number = g_private_get (current_number_key);
692 * if (!current_number)
694 * current_number = g_new (int, 1);
695 * *current_number = 0;
696 * g_private_set (current_number_key, current_number);
699 * *current_number = calc_next_number (*current_number);
701 * return *current_number;
706 * Here the pointer belonging to the key
707 * <literal>current_number_key</literal> is read. If it is %NULL, it has
708 * not been set yet. Then get memory for an integer value, assign this
709 * memory to the pointer and write the pointer back. Now we have an
710 * integer value that is private to the current thread.
712 * The #GPrivate struct should only be accessed via the following
715 * <note><para>All of the <function>g_private_*</function> functions are
716 * actually macros. Apart from taking their addresses, you can however
717 * use them as if they were functions.</para></note>
722 * @destructor: a function to destroy the data keyed to #GPrivate when
724 * @Returns: a new #GPrivate.
726 * Creates a new #GPrivate. If @destructor is non-%NULL, it is a
727 * pointer to a destructor function. Whenever a thread ends and the
728 * corresponding pointer keyed to this instance of #GPrivate is
729 * non-%NULL, the destructor is called with this pointer as the
732 * <note><para>@destructor is used quite differently from @notify in
733 * g_static_private_set().</para></note>
735 * <note><para>A #GPrivate can not be freed. Reuse it instead, if you
736 * can, to avoid shortage, or use #GStaticPrivate.</para></note>
738 * <note><para>This function will abort if g_thread_init() has not been
739 * called yet.</para></note>
741 (GPrivate
*(*)(GDestroyNotify
))g_thread_fail
,
745 * @private_key: a #GPrivate.
746 * @Returns: the corresponding pointer.
748 * Returns the pointer keyed to @private_key for the current thread. If
749 * g_private_set() hasn't been called for the current @private_key and
750 * thread yet, this pointer will be %NULL.
752 * This function can be used even if g_thread_init() has not yet been
753 * called, and, in that case, will return the value of @private_key
754 * casted to #gpointer. Note however, that private data set
755 * <emphasis>before</emphasis> g_thread_init() will
756 * <emphasis>not</emphasis> be retained <emphasis>after</emphasis> the
757 * call. Instead, %NULL will be returned in all threads directly after
758 * g_thread_init(), regardless of any g_private_set() calls issued
759 * before threading system intialization.
765 * @private_key: a #GPrivate.
766 * @data: the new pointer.
768 * Sets the pointer keyed to @private_key for the current thread.
770 * This function can be used even if g_thread_init() has not yet been
771 * called, and, in that case, will set @private_key to @data casted to
772 * #GPrivate*. See g_private_get() for resulting caveats.
776 /* GThread Virtual Functions {{{2 ---------------------------------------- */
780 * The #GThread struct represents a running thread. It has three public
781 * read-only members, but the underlying struct is bigger, so you must
782 * not copy this struct.
784 * <note><para>Resources for a joinable thread are not fully released
785 * until g_thread_join() is called for that thread.</para></note>
790 * @data: data passed to the thread.
791 * @Returns: the return value of the thread, which will be returned by
794 * Specifies the type of the @func functions passed to
795 * g_thread_create() or g_thread_create_full().
800 * @G_THREAD_PRIORITY_LOW: a priority lower than normal
801 * @G_THREAD_PRIORITY_NORMAL: the default priority
802 * @G_THREAD_PRIORITY_HIGH: a priority higher than normal
803 * @G_THREAD_PRIORITY_URGENT: the highest priority
805 * Specifies the priority of a thread.
807 * <note><para>It is not guaranteed that threads with different priorities
808 * really behave accordingly. On some systems (e.g. Linux) there are no
809 * thread priorities. On other systems (e.g. Solaris) there doesn't
810 * seem to be different scheduling for different priorities. All in all
811 * try to avoid being dependent on priorities.</para></note>
816 * @func: a function to execute in the new thread.
817 * @data: an argument to supply to the new thread.
818 * @joinable: should this thread be joinable?
819 * @error: return location for error.
820 * @Returns: the new #GThread on success.
822 * This function creates a new thread with the default priority.
824 * If @joinable is %TRUE, you can wait for this threads termination
825 * calling g_thread_join(). Otherwise the thread will just disappear
826 * when it terminates.
828 * The new thread executes the function @func with the argument @data.
829 * If the thread was created successfully, it is returned.
831 * @error can be %NULL to ignore errors, or non-%NULL to report errors.
832 * The error is set, if and only if the function returns %NULL.
834 (void(*)(GThreadFunc
, gpointer
, gulong
,
835 gboolean
, gboolean
, GThreadPriority
,
836 gpointer
, GError
**))g_thread_fail
,
841 * Gives way to other threads waiting to be scheduled.
843 * This function is often used as a method to make busy wait less evil.
844 * But in most cases you will encounter, there are better methods to do
845 * that. So in general you shouldn't use this function.
849 NULL
, /* thread_join */
850 NULL
, /* thread_exit */
851 NULL
, /* thread_set_priority */
852 NULL
, /* thread_self */
853 NULL
/* thread_equal */
856 /* Local Data {{{1 -------------------------------------------------------- */
858 static GMutex
*g_once_mutex
= NULL
;
859 static GCond
*g_once_cond
= NULL
;
860 static GPrivate
*g_thread_specific_private
= NULL
;
861 static GRealThread
*g_thread_all_threads
= NULL
;
862 static GSList
*g_thread_free_indeces
= NULL
;
863 static GSList
* g_once_init_list
= NULL
;
865 G_LOCK_DEFINE_STATIC (g_thread
);
867 /* Initialisation {{{1 ---------------------------------------------------- */
869 #ifdef G_THREADS_ENABLED
872 * @vtable: a function table of type #GThreadFunctions, that provides
873 * the entry points to the thread system to be used.
875 * If you use GLib from more than one thread, you must initialize the
876 * thread system by calling g_thread_init(). Most of the time you will
877 * only have to call <literal>g_thread_init (NULL)</literal>.
879 * <note><para>Do not call g_thread_init() with a non-%NULL parameter unless
880 * you really know what you are doing.</para></note>
882 * <note><para>g_thread_init() must not be called directly or indirectly as a
883 * callback from GLib. Also no mutexes may be currently locked while
884 * calling g_thread_init().</para></note>
886 * <note><para>g_thread_init() changes the way in which #GTimer measures
887 * elapsed time. As a consequence, timers that are running while
888 * g_thread_init() is called may report unreliable times.</para></note>
890 * Calling g_thread_init() multiple times is allowed (since version
891 * 2.24), but nothing happens except for the first call. If the
892 * argument is non-%NULL on such a call a warning will be printed, but
893 * otherwise the argument is ignored.
895 * If no thread system is available and @vtable is %NULL or if not all
896 * elements of @vtable are non-%NULL, then g_thread_init() will abort.
898 * <note><para>To use g_thread_init() in your program, you have to link with
899 * the libraries that the command <command>pkg-config --libs
900 * gthread-2.0</command> outputs. This is not the case for all the
901 * other thread related functions of GLib. Those can be used without
902 * having to link with the thread libraries.</para></note>
905 /* This must be called only once, before any threads are created.
906 * It will only be called from g_thread_init() in -lgthread.
909 g_thread_init_glib (void)
911 /* We let the main thread (the one that calls g_thread_init) inherit
912 * the static_private data set before calling g_thread_init
914 GRealThread
* main_thread
= (GRealThread
*) g_thread_self ();
916 /* mutex and cond creation works without g_threads_got_initialized */
917 g_once_mutex
= g_mutex_new ();
918 g_once_cond
= g_cond_new ();
920 /* we may only create mutex and cond in here */
921 _g_mem_thread_init_noprivate_nomessage ();
923 /* setup the basic threading system */
924 g_threads_got_initialized
= TRUE
;
925 g_thread_specific_private
= g_private_new (g_thread_cleanup
);
926 g_private_set (g_thread_specific_private
, main_thread
);
927 G_THREAD_UF (thread_self
, (&main_thread
->system_thread
));
929 /* complete memory system initialization, g_private_*() works now */
930 _g_slice_thread_init_nomessage ();
932 /* accomplish log system initialization to enable messaging */
933 _g_messages_thread_init_nomessage ();
935 /* we may run full-fledged initializers from here */
936 _g_atomic_thread_init ();
937 _g_convert_thread_init ();
938 _g_rand_thread_init ();
939 _g_main_thread_init ();
940 _g_utils_thread_init ();
941 _g_futex_thread_init ();
943 _g_win32_thread_init ();
946 #endif /* G_THREADS_ENABLED */
948 /* The following sections implement: GOnce, GStaticMutex, GStaticRecMutex,
952 /* GOnce {{{1 ------------------------------------------------------------- */
956 * @status: the status of the #GOnce
957 * @retval: the value returned by the call to the function, if @status
958 * is %G_ONCE_STATUS_READY
960 * A #GOnce struct controls a one-time initialization function. Any
961 * one-time initialization function must have its own unique #GOnce
970 * A #GOnce must be initialized with this macro before it can be used.
974 * GOnce my_once = G_ONCE_INIT;
983 * @G_ONCE_STATUS_NOTCALLED: the function has not been called yet.
984 * @G_ONCE_STATUS_PROGRESS: the function call is currently in progress.
985 * @G_ONCE_STATUS_READY: the function has been called.
987 * The possible statuses of a one-time initialization function
988 * controlled by a #GOnce struct.
995 * @once: a #GOnce structure
996 * @func: the #GThreadFunc function associated to @once. This function
997 * is called only once, regardless of the number of times it and
998 * its associated #GOnce struct are passed to g_once().
999 * @arg: data to be passed to @func
1001 * The first call to this routine by a process with a given #GOnce
1002 * struct calls @func with the given argument. Thereafter, subsequent
1003 * calls to g_once() with the same #GOnce struct do not call @func
1004 * again, but return the stored result of the first call. On return
1005 * from g_once(), the status of @once will be %G_ONCE_STATUS_READY.
1007 * For example, a mutex or a thread-specific data key must be created
1008 * exactly once. In a threaded environment, calling g_once() ensures
1009 * that the initialization is serialized across multiple threads.
1011 * <note><para>Calling g_once() recursively on the same #GOnce struct in
1012 * @func will lead to a deadlock.</para></note>
1017 * get_debug_flags (void)
1019 * static GOnce my_once = G_ONCE_INIT;
1021 * g_once (&my_once, parse_debug_flags, NULL);
1023 * return my_once.retval;
1026 * </informalexample>
1031 g_once_impl (GOnce
*once
,
1035 g_mutex_lock (g_once_mutex
);
1037 while (once
->status
== G_ONCE_STATUS_PROGRESS
)
1038 g_cond_wait (g_once_cond
, g_once_mutex
);
1040 if (once
->status
!= G_ONCE_STATUS_READY
)
1042 once
->status
= G_ONCE_STATUS_PROGRESS
;
1043 g_mutex_unlock (g_once_mutex
);
1045 once
->retval
= func (arg
);
1047 g_mutex_lock (g_once_mutex
);
1048 once
->status
= G_ONCE_STATUS_READY
;
1049 g_cond_broadcast (g_once_cond
);
1052 g_mutex_unlock (g_once_mutex
);
1054 return once
->retval
;
1058 * g_once_init_enter:
1059 * @value_location: location of a static initializable variable
1061 * @Returns: %TRUE if the initialization section should be entered,
1062 * %FALSE and blocks otherwise
1064 * Function to be called when starting a critical initialization
1065 * section. The argument @value_location must point to a static
1066 * 0-initialized variable that will be set to a value other than 0 at
1067 * the end of the initialization section. In combination with
1068 * g_once_init_leave() and the unique address @value_location, it can
1069 * be ensured that an initialization section will be executed only once
1070 * during a program's life time, and that concurrent threads are
1071 * blocked until initialization completed. To be used in constructs
1076 * static gsize initialization_value = 0;
1078 * if (g_once_init_enter (&initialization_value))
1080 * gsize setup_value = 42; /<!-- -->* initialization code here *<!-- -->/
1082 * g_once_init_leave (&initialization_value, setup_value);
1085 * /<!-- -->* use initialization_value here *<!-- -->/
1087 * </informalexample>
1092 g_once_init_enter_impl (volatile gsize
*value_location
)
1094 gboolean need_init
= FALSE
;
1095 g_mutex_lock (g_once_mutex
);
1096 if (g_atomic_pointer_get (value_location
) == NULL
)
1098 if (!g_slist_find (g_once_init_list
, (void*) value_location
))
1101 g_once_init_list
= g_slist_prepend (g_once_init_list
, (void*) value_location
);
1105 g_cond_wait (g_once_cond
, g_once_mutex
);
1106 while (g_slist_find (g_once_init_list
, (void*) value_location
));
1108 g_mutex_unlock (g_once_mutex
);
1113 * g_once_init_leave:
1114 * @value_location: location of a static initializable variable
1116 * @initialization_value: new non-0 value for *@value_location.
1118 * Counterpart to g_once_init_enter(). Expects a location of a static
1119 * 0-initialized initialization variable, and an initialization value
1120 * other than 0. Sets the variable to the initialization value, and
1121 * releases concurrent threads blocking in g_once_init_enter() on this
1122 * initialization variable.
1127 g_once_init_leave (volatile gsize
*value_location
,
1128 gsize initialization_value
)
1130 g_return_if_fail (g_atomic_pointer_get (value_location
) == NULL
);
1131 g_return_if_fail (initialization_value
!= 0);
1132 g_return_if_fail (g_once_init_list
!= NULL
);
1134 g_atomic_pointer_set ((void**)value_location
, (void*) initialization_value
);
1135 g_mutex_lock (g_once_mutex
);
1136 g_once_init_list
= g_slist_remove (g_once_init_list
, (void*) value_location
);
1137 g_cond_broadcast (g_once_cond
);
1138 g_mutex_unlock (g_once_mutex
);
1141 /* GStaticMutex {{{1 ------------------------------------------------------ */
1146 * A #GStaticMutex works like a #GMutex, but it has one significant
1147 * advantage. It doesn't need to be created at run-time like a #GMutex,
1148 * but can be defined at compile-time. Here is a shorter, easier and
1149 * safer version of our <function>give_me_next_number()</function>
1154 * Using <structname>GStaticMutex</structname>
1155 * to simplify thread-safe programming
1159 * give_me_next_number (void)
1161 * static int current_number = 0;
1163 * static GStaticMutex mutex = G_STATIC_MUTEX_INIT;
1165 * g_static_mutex_lock (&mutex);
1166 * ret_val = current_number = calc_next_number (current_number);
1167 * g_static_mutex_unlock (&mutex);
1174 * Sometimes you would like to dynamically create a mutex. If you don't
1175 * want to require prior calling to g_thread_init(), because your code
1176 * should also be usable in non-threaded programs, you are not able to
1177 * use g_mutex_new() and thus #GMutex, as that requires a prior call to
1178 * g_thread_init(). In theses cases you can also use a #GStaticMutex.
1179 * It must be initialized with g_static_mutex_init() before using it
1180 * and freed with with g_static_mutex_free() when not needed anymore to
1181 * free up any allocated resources.
1183 * Even though #GStaticMutex is not opaque, it should only be used with
1184 * the following functions, as it is defined differently on different
1187 * All of the <function>g_static_mutex_*</function> functions apart
1188 * from <function>g_static_mutex_get_mutex</function> can also be used
1189 * even if g_thread_init() has not yet been called. Then they do
1190 * nothing, apart from <function>g_static_mutex_trylock</function>,
1191 * which does nothing but returning %TRUE.
1193 * <note><para>All of the <function>g_static_mutex_*</function>
1194 * functions are actually macros. Apart from taking their addresses, you
1195 * can however use them as if they were functions.</para></note>
1199 * G_STATIC_MUTEX_INIT:
1201 * A #GStaticMutex must be initialized with this macro, before it can
1202 * be used. This macro can used be to initialize a variable, but it
1203 * cannot be assigned to a variable. In that case you have to use
1204 * g_static_mutex_init().
1208 * GStaticMutex my_mutex = G_STATIC_MUTEX_INIT;
1210 * </informalexample>
1214 * g_static_mutex_init:
1215 * @mutex: a #GStaticMutex to be initialized.
1217 * Initializes @mutex. Alternatively you can initialize it with
1218 * #G_STATIC_MUTEX_INIT.
1221 g_static_mutex_init (GStaticMutex
*mutex
)
1223 static const GStaticMutex init_mutex
= G_STATIC_MUTEX_INIT
;
1225 g_return_if_fail (mutex
);
1227 *mutex
= init_mutex
;
1230 /* IMPLEMENTATION NOTE:
1232 * On some platforms a GStaticMutex is actually a normal GMutex stored
1233 * inside of a structure instead of being allocated dynamically. We can
1234 * only do this for platforms on which we know, in advance, how to
1235 * allocate (size) and initialise (value) that memory.
1237 * On other platforms, a GStaticMutex is nothing more than a pointer to
1238 * a GMutex. In that case, the first access we make to the static mutex
1239 * must first allocate the normal GMutex and store it into the pointer.
1241 * configure.in writes macros into glibconfig.h to determine if
1242 * g_static_mutex_get_mutex() accesses the sturcture in memory directly
1243 * (on platforms where we are able to do that) or if it ends up here,
1244 * where we may have to allocate the GMutex before returning it.
1248 * g_static_mutex_get_mutex:
1249 * @mutex: a #GStaticMutex.
1250 * @Returns: the #GMutex corresponding to @mutex.
1252 * For some operations (like g_cond_wait()) you must have a #GMutex
1253 * instead of a #GStaticMutex. This function will return the
1254 * corresponding #GMutex for @mutex.
1257 g_static_mutex_get_mutex_impl (GMutex
** mutex
)
1259 if (!g_thread_supported ())
1262 g_assert (g_once_mutex
);
1264 g_mutex_lock (g_once_mutex
);
1267 g_atomic_pointer_set (mutex
, g_mutex_new());
1269 g_mutex_unlock (g_once_mutex
);
1274 /* IMPLEMENTATION NOTE:
1276 * g_static_mutex_lock(), g_static_mutex_trylock() and
1277 * g_static_mutex_unlock() are all preprocessor macros that wrap the
1278 * corresponding g_mutex_*() function around a call to
1279 * g_static_mutex_get_mutex().
1283 * g_static_mutex_lock:
1284 * @mutex: a #GStaticMutex.
1286 * Works like g_mutex_lock(), but for a #GStaticMutex.
1290 * g_static_mutex_trylock:
1291 * @mutex: a #GStaticMutex.
1292 * @Returns: %TRUE, if the #GStaticMutex could be locked.
1294 * Works like g_mutex_trylock(), but for a #GStaticMutex.
1298 * g_static_mutex_unlock:
1299 * @mutex: a #GStaticMutex.
1301 * Works like g_mutex_unlock(), but for a #GStaticMutex.
1305 * g_static_mutex_free:
1306 * @mutex: a #GStaticMutex to be freed.
1308 * Releases all resources allocated to @mutex.
1310 * You don't have to call this functions for a #GStaticMutex with an
1311 * unbounded lifetime, i.e. objects declared 'static', but if you have
1312 * a #GStaticMutex as a member of a structure and the structure is
1313 * freed, you should also free the #GStaticMutex.
1315 * <note><para>Calling g_static_mutex_free() on a locked mutex may
1316 * result in undefined behaviour.</para></note>
1319 g_static_mutex_free (GStaticMutex
* mutex
)
1321 GMutex
**runtime_mutex
;
1323 g_return_if_fail (mutex
);
1325 /* The runtime_mutex is the first (or only) member of GStaticMutex,
1326 * see both versions (of glibconfig.h) in configure.in. Note, that
1327 * this variable is NULL, if g_thread_init() hasn't been called or
1328 * if we're using the default thread implementation and it provides
1329 * static mutexes. */
1330 runtime_mutex
= ((GMutex
**)mutex
);
1333 g_mutex_free (*runtime_mutex
);
1335 *runtime_mutex
= NULL
;
1338 /* ------------------------------------------------------------------------ */
1343 * A #GStaticRecMutex works like a #GStaticMutex, but it can be locked
1344 * multiple times by one thread. If you enter it n times, you have to
1345 * unlock it n times again to let other threads lock it. An exception
1346 * is the function g_static_rec_mutex_unlock_full(): that allows you to
1347 * unlock a #GStaticRecMutex completely returning the depth, (i.e. the
1348 * number of times this mutex was locked). The depth can later be used
1349 * to restore the state of the #GStaticRecMutex by calling
1350 * g_static_rec_mutex_lock_full().
1352 * Even though #GStaticRecMutex is not opaque, it should only be used
1353 * with the following functions.
1355 * All of the <function>g_static_rec_mutex_*</function> functions can
1356 * be used even if g_thread_init() has not been called. Then they do
1357 * nothing, apart from <function>g_static_rec_mutex_trylock</function>,
1358 * which does nothing but returning %TRUE.
1362 * G_STATIC_REC_MUTEX_INIT:
1364 * A #GStaticRecMutex must be initialized with this macro before it can
1365 * be used. This macro can used be to initialize a variable, but it
1366 * cannot be assigned to a variable. In that case you have to use
1367 * g_static_rec_mutex_init().
1371 * GStaticRecMutex my_mutex = G_STATIC_REC_MUTEX_INIT;
1377 * g_static_rec_mutex_init:
1378 * @mutex: a #GStaticRecMutex to be initialized.
1380 * A #GStaticRecMutex must be initialized with this function before it
1381 * can be used. Alternatively you can initialize it with
1382 * #G_STATIC_REC_MUTEX_INIT.
1385 g_static_rec_mutex_init (GStaticRecMutex
*mutex
)
1387 static const GStaticRecMutex init_mutex
= G_STATIC_REC_MUTEX_INIT
;
1389 g_return_if_fail (mutex
);
1391 *mutex
= init_mutex
;
1395 * g_static_rec_mutex_lock:
1396 * @mutex: a #GStaticRecMutex to lock.
1398 * Locks @mutex. If @mutex is already locked by another thread, the
1399 * current thread will block until @mutex is unlocked by the other
1400 * thread. If @mutex is already locked by the calling thread, this
1401 * functions increases the depth of @mutex and returns immediately.
1404 g_static_rec_mutex_lock (GStaticRecMutex
* mutex
)
1408 g_return_if_fail (mutex
);
1410 if (!g_thread_supported ())
1413 G_THREAD_UF (thread_self
, (&self
));
1415 if (g_system_thread_equal (self
, mutex
->owner
))
1420 g_static_mutex_lock (&mutex
->mutex
);
1421 g_system_thread_assign (mutex
->owner
, self
);
1426 * g_static_rec_mutex_trylock:
1427 * @mutex: a #GStaticRecMutex to lock.
1428 * @Returns: %TRUE, if @mutex could be locked.
1430 * Tries to lock @mutex. If @mutex is already locked by another thread,
1431 * it immediately returns %FALSE. Otherwise it locks @mutex and returns
1432 * %TRUE. If @mutex is already locked by the calling thread, this
1433 * functions increases the depth of @mutex and immediately returns
1437 g_static_rec_mutex_trylock (GStaticRecMutex
* mutex
)
1441 g_return_val_if_fail (mutex
, FALSE
);
1443 if (!g_thread_supported ())
1446 G_THREAD_UF (thread_self
, (&self
));
1448 if (g_system_thread_equal (self
, mutex
->owner
))
1454 if (!g_static_mutex_trylock (&mutex
->mutex
))
1457 g_system_thread_assign (mutex
->owner
, self
);
1463 * g_static_rec_mutex_unlock:
1464 * @mutex: a #GStaticRecMutex to unlock.
1466 * Unlocks @mutex. Another thread will be allowed to lock @mutex only
1467 * when it has been unlocked as many times as it had been locked
1468 * before. If @mutex is completely unlocked and another thread is
1469 * blocked in a g_static_rec_mutex_lock() call for @mutex, it will be
1470 * woken and can lock @mutex itself.
1473 g_static_rec_mutex_unlock (GStaticRecMutex
* mutex
)
1475 g_return_if_fail (mutex
);
1477 if (!g_thread_supported ())
1480 if (mutex
->depth
> 1)
1485 g_system_thread_assign (mutex
->owner
, zero_thread
);
1486 g_static_mutex_unlock (&mutex
->mutex
);
1490 * g_static_rec_mutex_lock_full:
1491 * @mutex: a #GStaticRecMutex to lock.
1492 * @depth: number of times this mutex has to be unlocked to be
1493 * completely unlocked.
1495 * Works like calling g_static_rec_mutex_lock() for @mutex @depth times.
1498 g_static_rec_mutex_lock_full (GStaticRecMutex
*mutex
,
1502 g_return_if_fail (mutex
);
1504 if (!g_thread_supported ())
1510 G_THREAD_UF (thread_self
, (&self
));
1512 if (g_system_thread_equal (self
, mutex
->owner
))
1514 mutex
->depth
+= depth
;
1517 g_static_mutex_lock (&mutex
->mutex
);
1518 g_system_thread_assign (mutex
->owner
, self
);
1519 mutex
->depth
= depth
;
1523 * g_static_rec_mutex_unlock_full:
1524 * @mutex: a #GStaticRecMutex to completely unlock.
1525 * @Returns: number of times @mutex has been locked by the current
1528 * Completely unlocks @mutex. If another thread is blocked in a
1529 * g_static_rec_mutex_lock() call for @mutex, it will be woken and can
1530 * lock @mutex itself. This function returns the number of times that
1531 * @mutex has been locked by the current thread. To restore the state
1532 * before the call to g_static_rec_mutex_unlock_full() you can call
1533 * g_static_rec_mutex_lock_full() with the depth returned by this
1537 g_static_rec_mutex_unlock_full (GStaticRecMutex
*mutex
)
1541 g_return_val_if_fail (mutex
, 0);
1543 if (!g_thread_supported ())
1546 depth
= mutex
->depth
;
1548 g_system_thread_assign (mutex
->owner
, zero_thread
);
1550 g_static_mutex_unlock (&mutex
->mutex
);
1556 * g_static_rec_mutex_free:
1557 * @mutex: a #GStaticRecMutex to be freed.
1559 * Releases all resources allocated to a #GStaticRecMutex.
1561 * You don't have to call this functions for a #GStaticRecMutex with an
1562 * unbounded lifetime, i.e. objects declared 'static', but if you have
1563 * a #GStaticRecMutex as a member of a structure and the structure is
1564 * freed, you should also free the #GStaticRecMutex.
1567 g_static_rec_mutex_free (GStaticRecMutex
*mutex
)
1569 g_return_if_fail (mutex
);
1571 g_static_mutex_free (&mutex
->mutex
);
1574 /* GStaticPrivate {{{1 ---------------------------------------------------- */
1579 * A #GStaticPrivate works almost like a #GPrivate, but it has one
1580 * significant advantage. It doesn't need to be created at run-time
1581 * like a #GPrivate, but can be defined at compile-time. This is
1582 * similar to the difference between #GMutex and #GStaticMutex. Now
1583 * look at our <function>give_me_next_number()</function> example with
1587 * <title>Using GStaticPrivate for per-thread data</title>
1590 * give_me_next_number (<!-- -->)
1592 * static GStaticPrivate current_number_key = G_STATIC_PRIVATE_INIT;
1593 * int *current_number = g_static_private_get (&current_number_key);
1595 * if (!current_number)
1597 * current_number = g_new (int,1);
1598 * *current_number = 0;
1599 * g_static_private_set (&current_number_key, current_number, g_free);
1602 * *current_number = calc_next_number (*current_number);
1604 * return *current_number;
1611 * G_STATIC_PRIVATE_INIT:
1613 * Every #GStaticPrivate must be initialized with this macro, before it
1618 * GStaticPrivate my_private = G_STATIC_PRIVATE_INIT;
1620 * </informalexample>
1624 * g_static_private_init:
1625 * @private_key: a #GStaticPrivate to be initialized.
1627 * Initializes @private_key. Alternatively you can initialize it with
1628 * #G_STATIC_PRIVATE_INIT.
1631 g_static_private_init (GStaticPrivate
*private_key
)
1633 private_key
->index
= 0;
1637 * g_static_private_get:
1638 * @private_key: a #GStaticPrivate.
1639 * @Returns: the corresponding pointer.
1641 * Works like g_private_get() only for a #GStaticPrivate.
1643 * This function works even if g_thread_init() has not yet been called.
1646 g_static_private_get (GStaticPrivate
*private_key
)
1648 GRealThread
*self
= (GRealThread
*) g_thread_self ();
1651 array
= self
->private_data
;
1655 if (!private_key
->index
)
1657 else if (private_key
->index
<= array
->len
)
1658 return g_array_index (array
, GStaticPrivateNode
,
1659 private_key
->index
- 1).data
;
1665 * g_static_private_set:
1666 * @private_key: a #GStaticPrivate.
1667 * @data: the new pointer.
1668 * @notify: a function to be called with the pointer whenever the
1669 * current thread ends or sets this pointer again.
1671 * Sets the pointer keyed to @private_key for the current thread and
1672 * the function @notify to be called with that pointer (%NULL or
1673 * non-%NULL), whenever the pointer is set again or whenever the
1674 * current thread ends.
1676 * This function works even if g_thread_init() has not yet been called.
1677 * If g_thread_init() is called later, the @data keyed to @private_key
1678 * will be inherited only by the main thread, i.e. the one that called
1681 * <note><para>@notify is used quite differently from @destructor in
1682 * g_private_new().</para></note>
1685 g_static_private_set (GStaticPrivate
*private_key
,
1687 GDestroyNotify notify
)
1689 GRealThread
*self
= (GRealThread
*) g_thread_self ();
1691 static guint next_index
= 0;
1692 GStaticPrivateNode
*node
;
1694 array
= self
->private_data
;
1697 array
= g_array_new (FALSE
, TRUE
, sizeof (GStaticPrivateNode
));
1698 self
->private_data
= array
;
1701 if (!private_key
->index
)
1705 if (!private_key
->index
)
1707 if (g_thread_free_indeces
)
1709 private_key
->index
=
1710 GPOINTER_TO_UINT (g_thread_free_indeces
->data
);
1711 g_thread_free_indeces
=
1712 g_slist_delete_link (g_thread_free_indeces
,
1713 g_thread_free_indeces
);
1716 private_key
->index
= ++next_index
;
1719 G_UNLOCK (g_thread
);
1722 if (private_key
->index
> array
->len
)
1723 g_array_set_size (array
, private_key
->index
);
1725 node
= &g_array_index (array
, GStaticPrivateNode
, private_key
->index
- 1);
1728 gpointer ddata
= node
->data
;
1729 GDestroyNotify ddestroy
= node
->destroy
;
1732 node
->destroy
= notify
;
1739 node
->destroy
= notify
;
1744 * g_static_private_free:
1745 * @private_key: a #GStaticPrivate to be freed.
1747 * Releases all resources allocated to @private_key.
1749 * You don't have to call this functions for a #GStaticPrivate with an
1750 * unbounded lifetime, i.e. objects declared 'static', but if you have
1751 * a #GStaticPrivate as a member of a structure and the structure is
1752 * freed, you should also free the #GStaticPrivate.
1755 g_static_private_free (GStaticPrivate
*private_key
)
1757 guint idx
= private_key
->index
;
1758 GRealThread
*thread
;
1763 private_key
->index
= 0;
1767 thread
= g_thread_all_threads
;
1770 GArray
*array
= thread
->private_data
;
1771 thread
= thread
->next
;
1773 if (array
&& idx
<= array
->len
)
1775 GStaticPrivateNode
*node
= &g_array_index (array
,
1778 gpointer ddata
= node
->data
;
1779 GDestroyNotify ddestroy
= node
->destroy
;
1782 node
->destroy
= NULL
;
1786 G_UNLOCK (g_thread
);
1792 g_thread_free_indeces
= g_slist_prepend (g_thread_free_indeces
,
1793 GUINT_TO_POINTER (idx
));
1794 G_UNLOCK (g_thread
);
1797 /* GThread Extra Functions {{{1 ------------------------------------------- */
1799 g_thread_cleanup (gpointer data
)
1803 GRealThread
* thread
= data
;
1804 if (thread
->private_data
)
1806 GArray
* array
= thread
->private_data
;
1809 for (i
= 0; i
< array
->len
; i
++ )
1811 GStaticPrivateNode
*node
=
1812 &g_array_index (array
, GStaticPrivateNode
, i
);
1814 node
->destroy (node
->data
);
1816 g_array_free (array
, TRUE
);
1819 /* We only free the thread structure, if it isn't joinable. If
1820 it is, the structure is freed in g_thread_join */
1821 if (!thread
->thread
.joinable
)
1826 for (t
= g_thread_all_threads
, p
= NULL
; t
; p
= t
, t
= t
->next
)
1833 g_thread_all_threads
= t
->next
;
1837 G_UNLOCK (g_thread
);
1839 /* Just to make sure, this isn't used any more */
1840 g_system_thread_assign (thread
->system_thread
, zero_thread
);
1847 g_thread_fail (void)
1849 g_error ("The thread system is not yet initialized.");
1852 #define G_NSEC_PER_SEC 1000000000
1860 /* Returns 100s of nanoseconds since start of 1601 */
1861 GetSystemTimeAsFileTime ((FILETIME
*)&v
);
1863 /* Offset to Unix epoch */
1864 v
-= G_GINT64_CONSTANT (116444736000000000);
1865 /* Convert to nanoseconds */
1872 gettimeofday (&tv
, NULL
);
1874 return (guint64
) tv
.tv_sec
* G_NSEC_PER_SEC
+ tv
.tv_usec
* (G_NSEC_PER_SEC
/ G_USEC_PER_SEC
);
1879 g_thread_create_proxy (gpointer data
)
1881 GRealThread
* thread
= data
;
1885 /* This has to happen before G_LOCK, as that might call g_thread_self */
1886 g_private_set (g_thread_specific_private
, data
);
1888 /* the lock makes sure, that thread->system_thread is written,
1889 before thread->thread.func is called. See g_thread_create. */
1891 G_UNLOCK (g_thread
);
1893 thread
->retval
= thread
->thread
.func (thread
->thread
.data
);
1899 * g_thread_create_full:
1900 * @func: a function to execute in the new thread.
1901 * @data: an argument to supply to the new thread.
1902 * @stack_size: a stack size for the new thread.
1903 * @joinable: should this thread be joinable?
1904 * @bound: should this thread be bound to a system thread?
1905 * @priority: a priority for the thread.
1906 * @error: return location for error.
1907 * @Returns: the new #GThread on success.
1909 * This function creates a new thread with the priority @priority. If
1910 * the underlying thread implementation supports it, the thread gets a
1911 * stack size of @stack_size or the default value for the current
1912 * platform, if @stack_size is 0.
1914 * If @joinable is %TRUE, you can wait for this threads termination
1915 * calling g_thread_join(). Otherwise the thread will just disappear
1916 * when it terminates. If @bound is %TRUE, this thread will be
1917 * scheduled in the system scope, otherwise the implementation is free
1918 * to do scheduling in the process scope. The first variant is more
1919 * expensive resource-wise, but generally faster. On some systems (e.g.
1920 * Linux) all threads are bound.
1922 * The new thread executes the function @func with the argument @data.
1923 * If the thread was created successfully, it is returned.
1925 * @error can be %NULL to ignore errors, or non-%NULL to report errors.
1926 * The error is set, if and only if the function returns %NULL.
1928 * <note><para>It is not guaranteed that threads with different priorities
1929 * really behave accordingly. On some systems (e.g. Linux) there are no
1930 * thread priorities. On other systems (e.g. Solaris) there doesn't
1931 * seem to be different scheduling for different priorities. All in all
1932 * try to avoid being dependent on priorities. Use
1933 * %G_THREAD_PRIORITY_NORMAL here as a default.</para></note>
1935 * <note><para>Only use g_thread_create_full() if you really can't use
1936 * g_thread_create() instead. g_thread_create() does not take
1937 * @stack_size, @bound, and @priority as arguments, as they should only
1938 * be used in cases in which it is unavoidable.</para></note>
1941 g_thread_create_full (GThreadFunc func
,
1946 GThreadPriority priority
,
1949 GRealThread
* result
;
1950 GError
*local_error
= NULL
;
1951 g_return_val_if_fail (func
, NULL
);
1952 g_return_val_if_fail (priority
>= G_THREAD_PRIORITY_LOW
, NULL
);
1953 g_return_val_if_fail (priority
<= G_THREAD_PRIORITY_URGENT
, NULL
);
1955 result
= g_new0 (GRealThread
, 1);
1957 result
->thread
.joinable
= joinable
;
1958 result
->thread
.priority
= priority
;
1959 result
->thread
.func
= func
;
1960 result
->thread
.data
= data
;
1961 result
->private_data
= NULL
;
1963 G_THREAD_UF (thread_create
, (g_thread_create_proxy
, result
,
1964 stack_size
, joinable
, bound
, priority
,
1965 &result
->system_thread
, &local_error
));
1968 result
->next
= g_thread_all_threads
;
1969 g_thread_all_threads
= result
;
1971 G_UNLOCK (g_thread
);
1975 g_propagate_error (error
, local_error
);
1980 return (GThread
*) result
;
1985 * @retval: the return value of this thread.
1987 * Exits the current thread. If another thread is waiting for that
1988 * thread using g_thread_join() and the current thread is joinable, the
1989 * waiting thread will be woken up and get @retval as the return value
1990 * of g_thread_join(). If the current thread is not joinable, @retval
1991 * is ignored. Calling
1995 * g_thread_exit (retval);
1997 * </informalexample>
1999 * is equivalent to returning @retval from the function @func, as given
2000 * to g_thread_create().
2002 * <note><para>Never call g_thread_exit() from within a thread of a
2003 * #GThreadPool, as that will mess up the bookkeeping and lead to funny
2004 * and unwanted results.</para></note>
2007 g_thread_exit (gpointer retval
)
2009 GRealThread
* real
= (GRealThread
*) g_thread_self ();
2010 real
->retval
= retval
;
2011 G_THREAD_CF (thread_exit
, (void)0, ());
2016 * @thread: a #GThread to be waited for.
2017 * @Returns: the return value of the thread.
2019 * Waits until @thread finishes, i.e. the function @func, as given to
2020 * g_thread_create(), returns or g_thread_exit() is called by @thread.
2021 * All resources of @thread including the #GThread struct are released.
2022 * @thread must have been created with @joinable=%TRUE in
2023 * g_thread_create(). The value returned by @func or given to
2024 * g_thread_exit() by @thread is returned by this function.
2027 g_thread_join (GThread
* thread
)
2029 GRealThread
* real
= (GRealThread
*) thread
;
2033 g_return_val_if_fail (thread
, NULL
);
2034 g_return_val_if_fail (thread
->joinable
, NULL
);
2035 g_return_val_if_fail (!g_system_thread_equal (real
->system_thread
,
2036 zero_thread
), NULL
);
2038 G_THREAD_UF (thread_join
, (&real
->system_thread
));
2040 retval
= real
->retval
;
2043 for (t
= g_thread_all_threads
, p
= NULL
; t
; p
= t
, t
= t
->next
)
2045 if (t
== (GRealThread
*) thread
)
2050 g_thread_all_threads
= t
->next
;
2054 G_UNLOCK (g_thread
);
2056 /* Just to make sure, this isn't used any more */
2057 thread
->joinable
= 0;
2058 g_system_thread_assign (real
->system_thread
, zero_thread
);
2060 /* the thread structure for non-joinable threads is freed upon
2061 thread end. We free the memory here. This will leave a loose end,
2062 if a joinable thread is not joined. */
2070 * g_thread_set_priority:
2071 * @thread: a #GThread.
2072 * @priority: a new priority for @thread.
2074 * Changes the priority of @thread to @priority.
2076 * <note><para>It is not guaranteed that threads with different
2077 * priorities really behave accordingly. On some systems (e.g. Linux)
2078 * there are no thread priorities. On other systems (e.g. Solaris) there
2079 * doesn't seem to be different scheduling for different priorities. All
2080 * in all try to avoid being dependent on priorities.</para></note>
2083 g_thread_set_priority (GThread
* thread
,
2084 GThreadPriority priority
)
2086 GRealThread
* real
= (GRealThread
*) thread
;
2088 g_return_if_fail (thread
);
2089 g_return_if_fail (!g_system_thread_equal (real
->system_thread
, zero_thread
));
2090 g_return_if_fail (priority
>= G_THREAD_PRIORITY_LOW
);
2091 g_return_if_fail (priority
<= G_THREAD_PRIORITY_URGENT
);
2093 thread
->priority
= priority
;
2095 G_THREAD_CF (thread_set_priority
, (void)0,
2096 (&real
->system_thread
, priority
));
2101 * @Returns: the current thread.
2103 * This functions returns the #GThread corresponding to the calling
2107 g_thread_self (void)
2109 GRealThread
* thread
= g_private_get (g_thread_specific_private
);
2113 /* If no thread data is available, provide and set one. This
2114 can happen for the main thread and for threads, that are not
2116 thread
= g_new0 (GRealThread
, 1);
2117 thread
->thread
.joinable
= FALSE
; /* This is a save guess */
2118 thread
->thread
.priority
= G_THREAD_PRIORITY_NORMAL
; /* This is
2120 thread
->thread
.func
= NULL
;
2121 thread
->thread
.data
= NULL
;
2122 thread
->private_data
= NULL
;
2124 if (g_thread_supported ())
2125 G_THREAD_UF (thread_self
, (&thread
->system_thread
));
2127 g_private_set (g_thread_specific_private
, thread
);
2130 thread
->next
= g_thread_all_threads
;
2131 g_thread_all_threads
= thread
;
2132 G_UNLOCK (g_thread
);
2135 return (GThread
*)thread
;
2138 /* GStaticRWLock {{{1 ----------------------------------------------------- */
2143 * The #GStaticRWLock struct represents a read-write lock. A read-write
2144 * lock can be used for protecting data that some portions of code only
2145 * read from, while others also write. In such situations it is
2146 * desirable that several readers can read at once, whereas of course
2147 * only one writer may write at a time. Take a look at the following
2151 * <title>An array with access functions</title>
2153 * GStaticRWLock rwlock = G_STATIC_RW_LOCK_INIT;
2157 * my_array_get (guint index)
2159 * gpointer retval = NULL;
2164 * g_static_rw_lock_reader_lock (&rwlock);
2165 * if (index < array->len)
2166 * retval = g_ptr_array_index (array, index);
2167 * g_static_rw_lock_reader_unlock (&rwlock);
2173 * my_array_set (guint index, gpointer data)
2175 * g_static_rw_lock_writer_lock (&rwlock);
2178 * array = g_ptr_array_new (<!-- -->);
2180 * if (index >= array->len)
2181 * g_ptr_array_set_size (array, index+1);
2182 * g_ptr_array_index (array, index) = data;
2184 * g_static_rw_lock_writer_unlock (&rwlock);
2189 * This example shows an array which can be accessed by many readers
2190 * (the <function>my_array_get()</function> function) simultaneously,
2191 * whereas the writers (the <function>my_array_set()</function>
2192 * function) will only be allowed once at a time and only if no readers
2193 * currently access the array. This is because of the potentially
2194 * dangerous resizing of the array. Using these functions is fully
2195 * multi-thread safe now.
2197 * Most of the time, writers should have precedence over readers. That
2198 * means, for this implementation, that as soon as a writer wants to
2199 * lock the data, no other reader is allowed to lock the data, whereas,
2200 * of course, the readers that already have locked the data are allowed
2201 * to finish their operation. As soon as the last reader unlocks the
2202 * data, the writer will lock it.
2204 * Even though #GStaticRWLock is not opaque, it should only be used
2205 * with the following functions.
2207 * All of the <function>g_static_rw_lock_*</function> functions can be
2208 * used even if g_thread_init() has not been called. Then they do
2209 * nothing, apart from <function>g_static_rw_lock_*_trylock</function>,
2210 * which does nothing but returning %TRUE.
2212 * <note><para>A read-write lock has a higher overhead than a mutex. For
2213 * example, both g_static_rw_lock_reader_lock() and
2214 * g_static_rw_lock_reader_unlock() have to lock and unlock a
2215 * #GStaticMutex, so it takes at least twice the time to lock and unlock
2216 * a #GStaticRWLock that it does to lock and unlock a #GStaticMutex. So
2217 * only data structures that are accessed by multiple readers, and which
2218 * keep the lock for a considerable time justify a #GStaticRWLock. The
2219 * above example most probably would fare better with a
2220 * #GStaticMutex.</para></note>
2224 * G_STATIC_RW_LOCK_INIT:
2226 * A #GStaticRWLock must be initialized with this macro before it can
2227 * be used. This macro can used be to initialize a variable, but it
2228 * cannot be assigned to a variable. In that case you have to use
2229 * g_static_rw_lock_init().
2233 * GStaticRWLock my_lock = G_STATIC_RW_LOCK_INIT;
2235 * </informalexample>
2239 * g_static_rw_lock_init:
2240 * @lock: a #GStaticRWLock to be initialized.
2242 * A #GStaticRWLock must be initialized with this function before it
2243 * can be used. Alternatively you can initialize it with
2244 * #G_STATIC_RW_LOCK_INIT.
2247 g_static_rw_lock_init (GStaticRWLock
* lock
)
2249 static const GStaticRWLock init_lock
= G_STATIC_RW_LOCK_INIT
;
2251 g_return_if_fail (lock
);
2257 g_static_rw_lock_wait (GCond
** cond
, GStaticMutex
* mutex
)
2260 *cond
= g_cond_new ();
2261 g_cond_wait (*cond
, g_static_mutex_get_mutex (mutex
));
2265 g_static_rw_lock_signal (GStaticRWLock
* lock
)
2267 if (lock
->want_to_write
&& lock
->write_cond
)
2268 g_cond_signal (lock
->write_cond
);
2269 else if (lock
->want_to_read
&& lock
->read_cond
)
2270 g_cond_broadcast (lock
->read_cond
);
2274 * g_static_rw_lock_reader_lock:
2275 * @lock: a #GStaticRWLock to lock for reading.
2277 * Locks @lock for reading. There may be unlimited concurrent locks for
2278 * reading of a #GStaticRWLock at the same time. If @lock is already
2279 * locked for writing by another thread or if another thread is already
2280 * waiting to lock @lock for writing, this function will block until
2281 * @lock is unlocked by the other writing thread and no other writing
2282 * threads want to lock @lock. This lock has to be unlocked by
2283 * g_static_rw_lock_reader_unlock().
2285 * #GStaticRWLock is not recursive. It might seem to be possible to
2286 * recursively lock for reading, but that can result in a deadlock, due
2287 * to writer preference.
2290 g_static_rw_lock_reader_lock (GStaticRWLock
* lock
)
2292 g_return_if_fail (lock
);
2294 if (!g_threads_got_initialized
)
2297 g_static_mutex_lock (&lock
->mutex
);
2298 lock
->want_to_read
++;
2299 while (lock
->have_writer
|| lock
->want_to_write
)
2300 g_static_rw_lock_wait (&lock
->read_cond
, &lock
->mutex
);
2301 lock
->want_to_read
--;
2302 lock
->read_counter
++;
2303 g_static_mutex_unlock (&lock
->mutex
);
2307 * g_static_rw_lock_reader_trylock:
2308 * @lock: a #GStaticRWLock to lock for reading.
2309 * @Returns: %TRUE, if @lock could be locked for reading.
2311 * Tries to lock @lock for reading. If @lock is already locked for
2312 * writing by another thread or if another thread is already waiting to
2313 * lock @lock for writing, immediately returns %FALSE. Otherwise locks
2314 * @lock for reading and returns %TRUE. This lock has to be unlocked by
2315 * g_static_rw_lock_reader_unlock().
2318 g_static_rw_lock_reader_trylock (GStaticRWLock
* lock
)
2320 gboolean ret_val
= FALSE
;
2322 g_return_val_if_fail (lock
, FALSE
);
2324 if (!g_threads_got_initialized
)
2327 g_static_mutex_lock (&lock
->mutex
);
2328 if (!lock
->have_writer
&& !lock
->want_to_write
)
2330 lock
->read_counter
++;
2333 g_static_mutex_unlock (&lock
->mutex
);
2338 * g_static_rw_lock_reader_unlock:
2339 * @lock: a #GStaticRWLock to unlock after reading.
2341 * Unlocks @lock. If a thread waits to lock @lock for writing and all
2342 * locks for reading have been unlocked, the waiting thread is woken up
2343 * and can lock @lock for writing.
2346 g_static_rw_lock_reader_unlock (GStaticRWLock
* lock
)
2348 g_return_if_fail (lock
);
2350 if (!g_threads_got_initialized
)
2353 g_static_mutex_lock (&lock
->mutex
);
2354 lock
->read_counter
--;
2355 if (lock
->read_counter
== 0)
2356 g_static_rw_lock_signal (lock
);
2357 g_static_mutex_unlock (&lock
->mutex
);
2361 * g_static_rw_lock_writer_lock:
2362 * @lock: a #GStaticRWLock to lock for writing.
2364 * Locks @lock for writing. If @lock is already locked for writing or
2365 * reading by other threads, this function will block until @lock is
2366 * completely unlocked and then lock @lock for writing. While this
2367 * functions waits to lock @lock, no other thread can lock @lock for
2368 * reading. When @lock is locked for writing, no other thread can lock
2369 * @lock (neither for reading nor writing). This lock has to be
2370 * unlocked by g_static_rw_lock_writer_unlock().
2373 g_static_rw_lock_writer_lock (GStaticRWLock
* lock
)
2375 g_return_if_fail (lock
);
2377 if (!g_threads_got_initialized
)
2380 g_static_mutex_lock (&lock
->mutex
);
2381 lock
->want_to_write
++;
2382 while (lock
->have_writer
|| lock
->read_counter
)
2383 g_static_rw_lock_wait (&lock
->write_cond
, &lock
->mutex
);
2384 lock
->want_to_write
--;
2385 lock
->have_writer
= TRUE
;
2386 g_static_mutex_unlock (&lock
->mutex
);
2390 * g_static_rw_lock_writer_trylock:
2391 * @lock: a #GStaticRWLock to lock for writing.
2392 * @Returns: %TRUE, if @lock could be locked for writing.
2394 * Tries to lock @lock for writing. If @lock is already locked (for
2395 * either reading or writing) by another thread, it immediately returns
2396 * %FALSE. Otherwise it locks @lock for writing and returns %TRUE. This
2397 * lock has to be unlocked by g_static_rw_lock_writer_unlock().
2400 g_static_rw_lock_writer_trylock (GStaticRWLock
* lock
)
2402 gboolean ret_val
= FALSE
;
2404 g_return_val_if_fail (lock
, FALSE
);
2406 if (!g_threads_got_initialized
)
2409 g_static_mutex_lock (&lock
->mutex
);
2410 if (!lock
->have_writer
&& !lock
->read_counter
)
2412 lock
->have_writer
= TRUE
;
2415 g_static_mutex_unlock (&lock
->mutex
);
2420 * g_static_rw_lock_writer_unlock:
2421 * @lock: a #GStaticRWLock to unlock after writing.
2423 * Unlocks @lock. If a thread is waiting to lock @lock for writing and
2424 * all locks for reading have been unlocked, the waiting thread is
2425 * woken up and can lock @lock for writing. If no thread is waiting to
2426 * lock @lock for writing, and some thread or threads are waiting to
2427 * lock @lock for reading, the waiting threads are woken up and can
2428 * lock @lock for reading.
2431 g_static_rw_lock_writer_unlock (GStaticRWLock
* lock
)
2433 g_return_if_fail (lock
);
2435 if (!g_threads_got_initialized
)
2438 g_static_mutex_lock (&lock
->mutex
);
2439 lock
->have_writer
= FALSE
;
2440 g_static_rw_lock_signal (lock
);
2441 g_static_mutex_unlock (&lock
->mutex
);
2445 * g_static_rw_lock_free:
2446 * @lock: a #GStaticRWLock to be freed.
2448 * Releases all resources allocated to @lock.
2450 * You don't have to call this functions for a #GStaticRWLock with an
2451 * unbounded lifetime, i.e. objects declared 'static', but if you have
2452 * a #GStaticRWLock as a member of a structure, and the structure is
2453 * freed, you should also free the #GStaticRWLock.
2456 g_static_rw_lock_free (GStaticRWLock
* lock
)
2458 g_return_if_fail (lock
);
2460 if (lock
->read_cond
)
2462 g_cond_free (lock
->read_cond
);
2463 lock
->read_cond
= NULL
;
2465 if (lock
->write_cond
)
2467 g_cond_free (lock
->write_cond
);
2468 lock
->write_cond
= NULL
;
2470 g_static_mutex_free (&lock
->mutex
);
2473 /* Unsorted {{{1 ---------------------------------------------------------- */
2477 * @thread_func: function to call for all GThread structures
2478 * @user_data: second argument to @thread_func
2480 * Call @thread_func on all existing #GThread structures. Note that
2481 * threads may decide to exit while @thread_func is running, so
2482 * without intimate knowledge about the lifetime of foreign threads,
2483 * @thread_func shouldn't access the GThread* pointer passed in as
2484 * first argument. However, @thread_func will not be called for threads
2485 * which are known to have exited already.
2487 * Due to thread lifetime checks, this function has an execution complexity
2488 * which is quadratic in the number of existing threads.
2493 g_thread_foreach (GFunc thread_func
,
2496 GSList
*slist
= NULL
;
2497 GRealThread
*thread
;
2498 g_return_if_fail (thread_func
!= NULL
);
2499 /* snapshot the list of threads for iteration */
2501 for (thread
= g_thread_all_threads
; thread
; thread
= thread
->next
)
2502 slist
= g_slist_prepend (slist
, thread
);
2503 G_UNLOCK (g_thread
);
2504 /* walk the list, skipping non-existant threads */
2507 GSList
*node
= slist
;
2509 /* check whether the current thread still exists */
2511 for (thread
= g_thread_all_threads
; thread
; thread
= thread
->next
)
2512 if (thread
== node
->data
)
2514 G_UNLOCK (g_thread
);
2516 thread_func (thread
, user_data
);
2517 g_slist_free_1 (node
);
2522 * g_thread_get_initialized
2524 * Indicates if g_thread_init() has been called.
2526 * Returns: %TRUE if threads have been initialized.
2531 g_thread_get_initialized ()
2533 return g_thread_supported ();
2536 #define __G_THREAD_C__
2537 #include "galiasdef.c"