Misc doc formatting fixes
[platform/upstream/glib.git] / glib / gthread.c
1 /* GLIB - Library of useful routines for C programming
2  * Copyright (C) 1995-1997  Peter Mattis, Spencer Kimball and Josh MacDonald
3  *
4  * gthread.c: MT safety related functions
5  * Copyright 1998 Sebastian Wilhelmi; University of Karlsruhe
6  *                Owen Taylor
7  *
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.
12  *
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.
17  *
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.
22  */
23
24 /* Prelude {{{1 ----------------------------------------------------------- */
25
26 /*
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/.
31  */
32
33 /*
34  * MT safe
35  */
36
37 /* implement gthread.h's inline functions */
38 #define G_IMPLEMENT_INLINES 1
39 #define __G_THREAD_C__
40
41 #include "config.h"
42
43 #include "gthread.h"
44 #include "gthreadprivate.h"
45
46 #include <string.h>
47
48 #ifdef HAVE_UNISTD_H
49 #include <unistd.h>
50 #endif
51
52 #ifndef G_OS_WIN32
53 #include <sys/time.h>
54 #include <time.h>
55 #else
56 #include <windows.h>
57 #endif /* G_OS_WIN32 */
58
59 #include "gslice.h"
60 #include "gtestutils.h"
61
62 /**
63  * SECTION:threads
64  * @title: Threads
65  * @short_description: portable support for threads, mutexes, locks,
66  *     conditions and thread private data
67  * @see_also: #GThreadPool, #GAsyncQueue
68  *
69  * Threads act almost like processes, but unlike processes all threads
70  * of one process share the same memory. This is good, as it provides
71  * easy communication between the involved threads via this shared
72  * memory, and it is bad, because strange things (so called
73  * "Heisenbugs") might happen if the program is not carefully designed.
74  * In particular, due to the concurrent nature of threads, no
75  * assumptions on the order of execution of code running in different
76  * threads can be made, unless order is explicitly forced by the
77  * programmer through synchronization primitives.
78  *
79  * The aim of the thread-related functions in GLib is to provide a
80  * portable means for writing multi-threaded software. There are
81  * primitives for mutexes to protect the access to portions of memory
82  * (#GMutex, #GRecMutex and #GRWLock). There is a facility to use
83  * individual bits for locks (g_bit_lock()). There are primitives
84  * for condition variables to allow synchronization of threads (#GCond).
85  * There are primitives for thread-private data - data that every
86  * thread has a private instance of (#GPrivate). There are facilities
87  * for one-time initialization (#GOnce, g_once_init_enter()). Finally,
88  * there are primitives to create and manage threads (#GThread).
89  *
90  * The GLib threading system used to be initialized with g_thread_init().
91  * This is no longer necessary. Since version 2.32, the GLib threading
92  * system is automatically initialized at the start of your program,
93  * and all thread-creation functions and synchronization primitives
94  * are available right away.
95  *
96  * Note that it is not safe to assume that your program has no threads
97  * even if you don't call g_thread_new() yourself. GLib and GIO can
98  * and will create threads for their own purposes in some cases, such
99  * as when using g_unix_signal_source_new() or when using #GDBus.
100  *
101  * Originally, UNIX did not have threads, and therefore some traditional
102  * UNIX APIs are problematic in threaded programs. Some notable examples
103  * are
104  * <itemizedlist>
105  *   <listitem>
106  *     C library functions that return data in statically allocated
107  *     buffers, such as strtok() or strerror(). For many of these,
108  *     there are thread-safe variants with a _r suffix, or you can
109  *     look at corresponding GLib APIs (like g_strsplit() or g_strerror()).
110  *   </listitem>
111  *   <listitem>
112  *     setenv() and unsetenv() manipulate the process environment in
113  *     a not thread-safe way, and may interfere with getenv() calls
114  *     in other threads. Note that getenv() calls may be
115  *     <quote>hidden</quote> behind other APIs. For example, GNU gettext()
116  *     calls getenv() under the covers. In general, it is best to treat
117  *     the environment as readonly. If you absolutely have to modify the
118  *     environment, do it early in main(), when no other threads are around yet.
119  *   </listitem>
120  *   <listitem>
121  *     setlocale() changes the locale for the entire process, affecting
122  *     all threads. Temporary changes to the locale are often made to
123  *     change the behavior of string scanning or formatting functions
124  *     like scanf() or printf(). GLib offers a number of string APIs
125  *     (like g_ascii_formatd() or g_ascii_strtod()) that can often be
126  *     used as an alternative. Or you can use the uselocale() function
127  *     to change the locale only for the current thread.
128  *   </listitem>
129  *   <listitem>
130  *     fork() only takes the calling thread into the child's copy of the
131  *     process image.  If other threads were executing in critical
132  *     sections they could have left mutexes locked which could easily
133  *     cause deadlocks in the new child.  For this reason, you should
134  *     call exit() or exec() as soon as possible in the child and only
135  *     make signal-safe library calls before that.
136  *   </listitem>
137  *   <listitem>
138  *     daemon() uses fork() in a way contrary to what is described
139  *     above.  It should not be used with GLib programs.
140  *   </listitem>
141  * </itemizedlist>
142  *
143  * GLib itself is internally completely thread-safe (all global data is
144  * automatically locked), but individual data structure instances are
145  * not automatically locked for performance reasons. For example,
146  * you must coordinate accesses to the same #GHashTable from multiple
147  * threads. The two notable exceptions from this rule are #GMainLoop
148  * and #GAsyncQueue, which <emphasis>are</emphasis> thread-safe and
149  * need no further application-level locking to be accessed from
150  * multiple threads. Most refcounting functions such as g_object_ref()
151  * are also thread-safe.
152  */
153
154 /* G_LOCK Documentation {{{1 ---------------------------------------------- */
155
156 /**
157  * G_LOCK_DEFINE:
158  * @name: the name of the lock
159  *
160  * The %G_LOCK_* macros provide a convenient interface to #GMutex.
161  * #G_LOCK_DEFINE defines a lock. It can appear in any place where
162  * variable definitions may appear in programs, i.e. in the first block
163  * of a function or outside of functions. The @name parameter will be
164  * mangled to get the name of the #GMutex. This means that you
165  * can use names of existing variables as the parameter - e.g. the name
166  * of the variable you intend to protect with the lock. Look at our
167  * <function>give_me_next_number()</function> example using the
168  * %G_LOCK_* macros:
169  *
170  * <example>
171  *  <title>Using the %G_LOCK_* convenience macros</title>
172  *  <programlisting>
173  *   G_LOCK_DEFINE (current_number);
174  *
175  *   int
176  *   give_me_next_number (void)
177  *   {
178  *     static int current_number = 0;
179  *     int ret_val;
180  *
181  *     G_LOCK (current_number);
182  *     ret_val = current_number = calc_next_number (current_number);
183  *     G_UNLOCK (current_number);
184  *
185  *     return ret_val;
186  *   }
187  *  </programlisting>
188  * </example>
189  */
190
191 /**
192  * G_LOCK_DEFINE_STATIC:
193  * @name: the name of the lock
194  *
195  * This works like #G_LOCK_DEFINE, but it creates a static object.
196  */
197
198 /**
199  * G_LOCK_EXTERN:
200  * @name: the name of the lock
201  *
202  * This declares a lock, that is defined with #G_LOCK_DEFINE in another
203  * module.
204  */
205
206 /**
207  * G_LOCK:
208  * @name: the name of the lock
209  *
210  * Works like g_mutex_lock(), but for a lock defined with
211  * #G_LOCK_DEFINE.
212  */
213
214 /**
215  * G_TRYLOCK:
216  * @name: the name of the lock
217  * @Returns: %TRUE, if the lock could be locked.
218  *
219  * Works like g_mutex_trylock(), but for a lock defined with
220  * #G_LOCK_DEFINE.
221  */
222
223 /**
224  * G_UNLOCK:
225  * @name: the name of the lock
226  *
227  * Works like g_mutex_unlock(), but for a lock defined with
228  * #G_LOCK_DEFINE.
229  */
230
231 /* GMutex Documentation {{{1 ------------------------------------------ */
232
233 /**
234  * GMutex:
235  *
236  * The #GMutex struct is an opaque data structure to represent a mutex
237  * (mutual exclusion). It can be used to protect data against shared
238  * access. Take for example the following function:
239  *
240  * <example>
241  *  <title>A function which will not work in a threaded environment</title>
242  *  <programlisting>
243  *   int
244  *   give_me_next_number (void)
245  *   {
246  *     static int current_number = 0;
247  *
248  *     /<!-- -->* now do a very complicated calculation to calculate the new
249  *      * number, this might for example be a random number generator
250  *      *<!-- -->/
251  *     current_number = calc_next_number (current_number);
252  *
253  *     return current_number;
254  *   }
255  *  </programlisting>
256  * </example>
257  *
258  * It is easy to see that this won't work in a multi-threaded
259  * application. There current_number must be protected against shared
260  * access. A #GMutex can be used as a solution to this problem:
261  *
262  * <example>
263  *  <title>Using GMutex to protected a shared variable</title>
264  *  <programlisting>
265  *   int
266  *   give_me_next_number (void)
267  *   {
268  *     static GMutex mutex;
269  *     static int current_number = 0;
270  *     int ret_val;
271  *
272  *     g_mutex_lock (&amp;mutex);
273  *     ret_val = current_number = calc_next_number (current_number);
274  *     g_mutex_unlock (&amp;mutex);
275  *
276  *     return ret_val;
277  *   }
278  *  </programlisting>
279  * </example>
280  *
281  * Notice that the #GMutex is not initialised to any particular value.
282  * Its placement in static storage ensures that it will be initialised
283  * to all-zeros, which is appropriate.
284  *
285  * If a #GMutex is placed in other contexts (eg: embedded in a struct)
286  * then it must be explicitly initialised using g_mutex_init().
287  *
288  * A #GMutex should only be accessed via <function>g_mutex_</function>
289  * functions.
290  */
291
292 /* GRecMutex Documentation {{{1 -------------------------------------- */
293
294 /**
295  * GRecMutex:
296  *
297  * The GRecMutex struct is an opaque data structure to represent a
298  * recursive mutex. It is similar to a #GMutex with the difference
299  * that it is possible to lock a GRecMutex multiple times in the same
300  * thread without deadlock. When doing so, care has to be taken to
301  * unlock the recursive mutex as often as it has been locked.
302  *
303  * If a #GRecMutex is allocated in static storage then it can be used
304  * without initialisation.  Otherwise, you should call
305  * g_rec_mutex_init() on it and g_rec_mutex_clear() when done.
306  *
307  * A GRecMutex should only be accessed with the
308  * <function>g_rec_mutex_</function> functions.
309  *
310  * Since: 2.32
311  */
312
313 /* GRWLock Documentation {{{1 ---------------------------------------- */
314
315 /**
316  * GRWLock:
317  *
318  * The GRWLock struct is an opaque data structure to represent a
319  * reader-writer lock. It is similar to a #GMutex in that it allows
320  * multiple threads to coordinate access to a shared resource.
321  *
322  * The difference to a mutex is that a reader-writer lock discriminates
323  * between read-only ('reader') and full ('writer') access. While only
324  * one thread at a time is allowed write access (by holding the 'writer'
325  * lock via g_rw_lock_writer_lock()), multiple threads can gain
326  * simultaneous read-only access (by holding the 'reader' lock via
327  * g_rw_lock_reader_lock()).
328  *
329  * <example>
330  *  <title>An array with access functions</title>
331  *  <programlisting>
332  *   GRWLock lock;
333  *   GPtrArray *array;
334  *
335  *   gpointer
336  *   my_array_get (guint index)
337  *   {
338  *     gpointer retval = NULL;
339  *
340  *     if (!array)
341  *       return NULL;
342  *
343  *     g_rw_lock_reader_lock (&amp;lock);
344  *     if (index &lt; array->len)
345  *       retval = g_ptr_array_index (array, index);
346  *     g_rw_lock_reader_unlock (&amp;lock);
347  *
348  *     return retval;
349  *   }
350  *
351  *   void
352  *   my_array_set (guint index, gpointer data)
353  *   {
354  *     g_rw_lock_writer_lock (&amp;lock);
355  *
356  *     if (!array)
357  *       array = g_ptr_array_new (<!-- -->);
358  *
359  *     if (index >= array->len)
360  *       g_ptr_array_set_size (array, index+1);
361  *     g_ptr_array_index (array, index) = data;
362  *
363  *     g_rw_lock_writer_unlock (&amp;lock);
364  *   }
365  *  </programlisting>
366  *  <para>
367  *    This example shows an array which can be accessed by many readers
368  *    (the <function>my_array_get()</function> function) simultaneously,
369  *    whereas the writers (the <function>my_array_set()</function>
370  *    function) will only be allowed once at a time and only if no readers
371  *    currently access the array. This is because of the potentially
372  *    dangerous resizing of the array. Using these functions is fully
373  *    multi-thread safe now.
374  *  </para>
375  * </example>
376  *
377  * If a #GRWLock is allocated in static storage then it can be used
378  * without initialisation.  Otherwise, you should call
379  * g_rw_lock_init() on it and g_rw_lock_clear() when done.
380  *
381  * A GRWLock should only be accessed with the
382  * <function>g_rw_lock_</function> functions.
383  *
384  * Since: 2.32
385  */
386
387 /* GCond Documentation {{{1 ------------------------------------------ */
388
389 /**
390  * GCond:
391  *
392  * The #GCond struct is an opaque data structure that represents a
393  * condition. Threads can block on a #GCond if they find a certain
394  * condition to be false. If other threads change the state of this
395  * condition they signal the #GCond, and that causes the waiting
396  * threads to be woken up.
397  *
398  * Consider the following example of a shared variable.  One or more
399  * threads can wait for data to be published to the variable and when
400  * another thread publishes the data, it can signal one of the waiting
401  * threads to wake up to collect the data.
402  *
403  * <example>
404  *  <title>
405  *   Using GCond to block a thread until a condition is satisfied
406  *  </title>
407  *  <programlisting>
408  *   gpointer current_data = NULL;
409  *   GMutex data_mutex;
410  *   GCond data_cond;
411  *
412  *   void
413  *   push_data (gpointer data)
414  *   {
415  *     g_mutex_lock (&data_mutex);
416  *     current_data = data;
417  *     g_cond_signal (&data_cond);
418  *     g_mutex_unlock (&data_mutex);
419  *   }
420  *
421  *   gpointer
422  *   pop_data (void)
423  *   {
424  *     gpointer data;
425  *
426  *     g_mutex_lock (&data_mutex);
427  *     while (!current_data)
428  *       g_cond_wait (&data_cond, &data_mutex);
429  *     data = current_data;
430  *     current_data = NULL;
431  *     g_mutex_unlock (&data_mutex);
432  *
433  *     return data;
434  *   }
435  *  </programlisting>
436  * </example>
437  *
438  * Whenever a thread calls pop_data() now, it will wait until
439  * current_data is non-%NULL, i.e. until some other thread
440  * has called push_data().
441  *
442  * The example shows that use of a condition variable must always be
443  * paired with a mutex.  Without the use of a mutex, there would be a
444  * race between the check of <varname>current_data</varname> by the
445  * while loop in <function>pop_data</function> and waiting.
446  * Specifically, another thread could set <varname>pop_data</varname>
447  * after the check, and signal the cond (with nobody waiting on it)
448  * before the first thread goes to sleep.  #GCond is specifically useful
449  * for its ability to release the mutex and go to sleep atomically.
450  *
451  * It is also important to use the g_cond_wait() and g_cond_wait_until()
452  * functions only inside a loop which checks for the condition to be
453  * true.  See g_cond_wait() for an explanation of why the condition may
454  * not be true even after it returns.
455  *
456  * If a #GCond is allocated in static storage then it can be used
457  * without initialisation.  Otherwise, you should call g_cond_init() on
458  * it and g_cond_clear() when done.
459  *
460  * A #GCond should only be accessed via the <function>g_cond_</function>
461  * functions.
462  */
463
464 /* GThread Documentation {{{1 ---------------------------------------- */
465
466 /**
467  * GThread:
468  *
469  * The #GThread struct represents a running thread. This struct
470  * is returned by g_thread_new() or g_thread_try_new(). You can
471  * obtain the #GThread struct representing the current thead by
472  * calling g_thread_self().
473  *
474  * GThread is refcounted, see g_thread_ref() and g_thread_unref().
475  * The thread represented by it holds a reference while it is running,
476  * and g_thread_join() consumes the reference that it is given, so
477  * it is normally not necessary to manage GThread references
478  * explicitly.
479  *
480  * The structure is opaque -- none of its fields may be directly
481  * accessed.
482  */
483
484 /**
485  * GThreadFunc:
486  * @data: data passed to the thread
487  *
488  * Specifies the type of the @func functions passed to g_thread_new()
489  * or g_thread_try_new().
490  *
491  * Returns: the return value of the thread
492  */
493
494 /**
495  * g_thread_supported:
496  *
497  * This macro returns %TRUE if the thread system is initialized,
498  * and %FALSE if it is not.
499  *
500  * For language bindings, g_thread_get_initialized() provides
501  * the same functionality as a function.
502  *
503  * Returns: %TRUE, if the thread system is initialized
504  */
505
506 /* GThreadError {{{1 ------------------------------------------------------- */
507 /**
508  * GThreadError:
509  * @G_THREAD_ERROR_AGAIN: a thread couldn't be created due to resource
510  *                        shortage. Try again later.
511  *
512  * Possible errors of thread related functions.
513  **/
514
515 /**
516  * G_THREAD_ERROR:
517  *
518  * The error domain of the GLib thread subsystem.
519  **/
520 GQuark
521 g_thread_error_quark (void)
522 {
523   return g_quark_from_static_string ("g_thread_error");
524 }
525
526 /* Local Data {{{1 -------------------------------------------------------- */
527
528 static GMutex    g_once_mutex;
529 static GCond     g_once_cond;
530 static GSList   *g_once_init_list = NULL;
531
532 static void g_thread_cleanup (gpointer data);
533 static GPrivate     g_thread_specific_private = G_PRIVATE_INIT (g_thread_cleanup);
534
535 G_LOCK_DEFINE_STATIC (g_thread_new);
536
537 /* GOnce {{{1 ------------------------------------------------------------- */
538
539 /**
540  * GOnce:
541  * @status: the status of the #GOnce
542  * @retval: the value returned by the call to the function, if @status
543  *          is %G_ONCE_STATUS_READY
544  *
545  * A #GOnce struct controls a one-time initialization function. Any
546  * one-time initialization function must have its own unique #GOnce
547  * struct.
548  *
549  * Since: 2.4
550  */
551
552 /**
553  * G_ONCE_INIT:
554  *
555  * A #GOnce must be initialized with this macro before it can be used.
556  *
557  * |[
558  *   GOnce my_once = G_ONCE_INIT;
559  * ]|
560  *
561  * Since: 2.4
562  */
563
564 /**
565  * GOnceStatus:
566  * @G_ONCE_STATUS_NOTCALLED: the function has not been called yet.
567  * @G_ONCE_STATUS_PROGRESS: the function call is currently in progress.
568  * @G_ONCE_STATUS_READY: the function has been called.
569  *
570  * The possible statuses of a one-time initialization function
571  * controlled by a #GOnce struct.
572  *
573  * Since: 2.4
574  */
575
576 /**
577  * g_once:
578  * @once: a #GOnce structure
579  * @func: the #GThreadFunc function associated to @once. This function
580  *        is called only once, regardless of the number of times it and
581  *        its associated #GOnce struct are passed to g_once().
582  * @arg: data to be passed to @func
583  *
584  * The first call to this routine by a process with a given #GOnce
585  * struct calls @func with the given argument. Thereafter, subsequent
586  * calls to g_once()  with the same #GOnce struct do not call @func
587  * again, but return the stored result of the first call. On return
588  * from g_once(), the status of @once will be %G_ONCE_STATUS_READY.
589  *
590  * For example, a mutex or a thread-specific data key must be created
591  * exactly once. In a threaded environment, calling g_once() ensures
592  * that the initialization is serialized across multiple threads.
593  *
594  * Calling g_once() recursively on the same #GOnce struct in
595  * @func will lead to a deadlock.
596  *
597  * |[
598  *   gpointer
599  *   get_debug_flags (void)
600  *   {
601  *     static GOnce my_once = G_ONCE_INIT;
602  *
603  *     g_once (&my_once, parse_debug_flags, NULL);
604  *
605  *     return my_once.retval;
606  *   }
607  * ]|
608  *
609  * Since: 2.4
610  */
611 gpointer
612 g_once_impl (GOnce       *once,
613              GThreadFunc  func,
614              gpointer     arg)
615 {
616   g_mutex_lock (&g_once_mutex);
617
618   while (once->status == G_ONCE_STATUS_PROGRESS)
619     g_cond_wait (&g_once_cond, &g_once_mutex);
620
621   if (once->status != G_ONCE_STATUS_READY)
622     {
623       once->status = G_ONCE_STATUS_PROGRESS;
624       g_mutex_unlock (&g_once_mutex);
625
626       once->retval = func (arg);
627
628       g_mutex_lock (&g_once_mutex);
629       once->status = G_ONCE_STATUS_READY;
630       g_cond_broadcast (&g_once_cond);
631     }
632
633   g_mutex_unlock (&g_once_mutex);
634
635   return once->retval;
636 }
637
638 /**
639  * g_once_init_enter:
640  * @location: location of a static initializable variable containing 0
641  *
642  * Function to be called when starting a critical initialization
643  * section. The argument @location must point to a static
644  * 0-initialized variable that will be set to a value other than 0 at
645  * the end of the initialization section. In combination with
646  * g_once_init_leave() and the unique address @value_location, it can
647  * be ensured that an initialization section will be executed only once
648  * during a program's life time, and that concurrent threads are
649  * blocked until initialization completed. To be used in constructs
650  * like this:
651  *
652  * |[
653  *   static gsize initialization_value = 0;
654  *
655  *   if (g_once_init_enter (&amp;initialization_value))
656  *     {
657  *       gsize setup_value = 42; /&ast;* initialization code here *&ast;/
658  *
659  *       g_once_init_leave (&amp;initialization_value, setup_value);
660  *     }
661  *
662  *   /&ast;* use initialization_value here *&ast;/
663  * ]|
664  *
665  * Returns: %TRUE if the initialization section should be entered,
666  *     %FALSE and blocks otherwise
667  *
668  * Since: 2.14
669  */
670 gboolean
671 (g_once_init_enter) (volatile void *location)
672 {
673   volatile gsize *value_location = location;
674   gboolean need_init = FALSE;
675   g_mutex_lock (&g_once_mutex);
676   if (g_atomic_pointer_get (value_location) == NULL)
677     {
678       if (!g_slist_find (g_once_init_list, (void*) value_location))
679         {
680           need_init = TRUE;
681           g_once_init_list = g_slist_prepend (g_once_init_list, (void*) value_location);
682         }
683       else
684         do
685           g_cond_wait (&g_once_cond, &g_once_mutex);
686         while (g_slist_find (g_once_init_list, (void*) value_location));
687     }
688   g_mutex_unlock (&g_once_mutex);
689   return need_init;
690 }
691
692 /**
693  * g_once_init_leave:
694  * @location: location of a static initializable variable containing 0
695  * @result: new non-0 value for *@value_location
696  *
697  * Counterpart to g_once_init_enter(). Expects a location of a static
698  * 0-initialized initialization variable, and an initialization value
699  * other than 0. Sets the variable to the initialization value, and
700  * releases concurrent threads blocking in g_once_init_enter() on this
701  * initialization variable.
702  *
703  * Since: 2.14
704  */
705 void
706 (g_once_init_leave) (volatile void *location,
707                      gsize          result)
708 {
709   volatile gsize *value_location = location;
710
711   g_return_if_fail (g_atomic_pointer_get (value_location) == NULL);
712   g_return_if_fail (result != 0);
713   g_return_if_fail (g_once_init_list != NULL);
714
715   g_atomic_pointer_set (value_location, result);
716   g_mutex_lock (&g_once_mutex);
717   g_once_init_list = g_slist_remove (g_once_init_list, (void*) value_location);
718   g_cond_broadcast (&g_once_cond);
719   g_mutex_unlock (&g_once_mutex);
720 }
721
722 /* GThread {{{1 -------------------------------------------------------- */
723
724 /**
725  * g_thread_ref:
726  * @thread: a #GThread
727  *
728  * Increase the reference count on @thread.
729  *
730  * Returns: a new reference to @thread
731  *
732  * Since: 2.32
733  */
734 GThread *
735 g_thread_ref (GThread *thread)
736 {
737   GRealThread *real = (GRealThread *) thread;
738
739   g_atomic_int_inc (&real->ref_count);
740
741   return thread;
742 }
743
744 /**
745  * g_thread_unref:
746  * @thread: a #GThread
747  *
748  * Decrease the reference count on @thread, possibly freeing all
749  * resources associated with it.
750  *
751  * Note that each thread holds a reference to its #GThread while
752  * it is running, so it is safe to drop your own reference to it
753  * if you don't need it anymore.
754  *
755  * Since: 2.32
756  */
757 void
758 g_thread_unref (GThread *thread)
759 {
760   GRealThread *real = (GRealThread *) thread;
761
762   if (g_atomic_int_dec_and_test (&real->ref_count))
763     {
764       if (real->ours)
765         g_system_thread_free (real);
766       else
767         g_slice_free (GRealThread, real);
768     }
769 }
770
771 static void
772 g_thread_cleanup (gpointer data)
773 {
774   g_thread_unref (data);
775 }
776
777 gpointer
778 g_thread_proxy (gpointer data)
779 {
780   GRealThread* thread = data;
781
782   g_assert (data);
783
784   if (thread->name)
785     g_system_thread_set_name (thread->name);
786
787   /* This has to happen before G_LOCK, as that might call g_thread_self */
788   g_private_set (&g_thread_specific_private, data);
789
790   /* The lock makes sure that g_thread_new_internal() has a chance to
791    * setup 'func' and 'data' before we make the call.
792    */
793   G_LOCK (g_thread_new);
794   G_UNLOCK (g_thread_new);
795
796   thread->retval = thread->thread.func (thread->thread.data);
797
798   return NULL;
799 }
800
801 /**
802  * g_thread_new:
803  * @name: a name for the new thread
804  * @func: a function to execute in the new thread
805  * @data: an argument to supply to the new thread
806  *
807  * This function creates a new thread. The new thread starts by invoking
808  * @func with the argument data. The thread will run until @func returns
809  * or until g_thread_exit() is called from the new thread. The return value
810  * of @func becomes the return value of the thread, which can be obtained
811  * with g_thread_join().
812  *
813  * The @name can be useful for discriminating threads in a debugger.
814  * Some systems restrict the length of @name to 16 bytes.
815  *
816  * If the thread can not be created the program aborts. See
817  * g_thread_try_new() if you want to attempt to deal with failures.
818  *
819  * To free the struct returned by this function, use g_thread_unref().
820  * Note that g_thread_join() implicitly unrefs the #GThread as well.
821  *
822  * Returns: the new #GThread
823  *
824  * Since: 2.32
825  */
826 GThread *
827 g_thread_new (const gchar *name,
828               GThreadFunc  func,
829               gpointer     data)
830 {
831   GError *error = NULL;
832   GThread *thread;
833
834   thread = g_thread_new_internal (name, g_thread_proxy, func, data, 0, &error);
835
836   if G_UNLIKELY (thread == NULL)
837     g_error ("creating thread '%s': %s", name ? name : "", error->message);
838
839   return thread;
840 }
841
842 /**
843  * g_thread_try_new:
844  * @name: a name for the new thread
845  * @func: a function to execute in the new thread
846  * @data: an argument to supply to the new thread
847  * @error: return location for error, or %NULL
848  *
849  * This function is the same as g_thread_new() except that
850  * it allows for the possibility of failure.
851  *
852  * If a thread can not be created (due to resource limits),
853  * @error is set and %NULL is returned.
854  *
855  * Returns: the new #GThread, or %NULL if an error occurred
856  *
857  * Since: 2.32
858  */
859 GThread *
860 g_thread_try_new (const gchar  *name,
861                   GThreadFunc   func,
862                   gpointer      data,
863                   GError      **error)
864 {
865   return g_thread_new_internal (name, g_thread_proxy, func, data, 0, error);
866 }
867
868 GThread *
869 g_thread_new_internal (const gchar   *name,
870                        GThreadFunc    proxy,
871                        GThreadFunc    func,
872                        gpointer       data,
873                        gsize          stack_size,
874                        GError       **error)
875 {
876   GRealThread *thread;
877
878   g_return_val_if_fail (func != NULL, NULL);
879
880   G_LOCK (g_thread_new);
881   thread = g_system_thread_new (proxy, stack_size, error);
882   if (thread)
883     {
884       thread->ref_count = 2;
885       thread->ours = TRUE;
886       thread->thread.joinable = TRUE;
887       thread->thread.func = func;
888       thread->thread.data = data;
889       thread->name = name;
890     }
891   G_UNLOCK (g_thread_new);
892
893   return (GThread*) thread;
894 }
895
896 /**
897  * g_thread_exit:
898  * @retval: the return value of this thread
899  *
900  * Terminates the current thread.
901  *
902  * If another thread is waiting for us using g_thread_join() then the
903  * waiting thread will be woken up and get @retval as the return value
904  * of g_thread_join().
905  *
906  * Calling <literal>g_thread_exit (retval)</literal> is equivalent to
907  * returning @retval from the function @func, as given to g_thread_new().
908  *
909  * <note><para>
910  *   You must only call g_thread_exit() from a thread that you created
911  *   yourself with g_thread_new() or related APIs.  You must not call
912  *   this function from a thread created with another threading library
913  *   or or from within a #GThreadPool.
914  * </para></note>
915  */
916 void
917 g_thread_exit (gpointer retval)
918 {
919   GRealThread* real = (GRealThread*) g_thread_self ();
920
921   if G_UNLIKELY (!real->ours)
922     g_error ("attempt to g_thread_exit() a thread not created by GLib");
923
924   real->retval = retval;
925
926   g_system_thread_exit ();
927 }
928
929 /**
930  * g_thread_join:
931  * @thread: a #GThread
932  *
933  * Waits until @thread finishes, i.e. the function @func, as
934  * given to g_thread_new(), returns or g_thread_exit() is called.
935  * If @thread has already terminated, then g_thread_join()
936  * returns immediately.
937  *
938  * Any thread can wait for any other thread by calling g_thread_join(),
939  * not just its 'creator'. Calling g_thread_join() from multiple threads
940  * for the same @thread leads to undefined behaviour.
941  *
942  * The value returned by @func or given to g_thread_exit() is
943  * returned by this function.
944  *
945  * g_thread_join() consumes the reference to the passed-in @thread.
946  * This will usually cause the #GThread struct and associated resources
947  * to be freed. Use g_thread_ref() to obtain an extra reference if you
948  * want to keep the GThread alive beyond the g_thread_join() call.
949  *
950  * Returns: the return value of the thread
951  */
952 gpointer
953 g_thread_join (GThread *thread)
954 {
955   GRealThread *real = (GRealThread*) thread;
956   gpointer retval;
957
958   g_return_val_if_fail (thread, NULL);
959   g_return_val_if_fail (real->ours, NULL);
960
961   g_system_thread_wait (real);
962
963   retval = real->retval;
964
965   /* Just to make sure, this isn't used any more */
966   thread->joinable = 0;
967
968   g_thread_unref (thread);
969
970   return retval;
971 }
972
973 /**
974  * g_thread_self:
975  *
976  * This functions returns the #GThread corresponding to the
977  * current thread. Note that this function does not increase
978  * the reference count of the returned struct.
979  *
980  * This function will return a #GThread even for threads that
981  * were not created by GLib (i.e. those created by other threading
982  * APIs). This may be useful for thread identification purposes
983  * (i.e. comparisons) but you must not use GLib functions (such
984  * as g_thread_join()) on these threads.
985  *
986  * Returns: the #GThread representing the current thread
987  */
988 GThread*
989 g_thread_self (void)
990 {
991   GRealThread* thread = g_private_get (&g_thread_specific_private);
992
993   if (!thread)
994     {
995       /* If no thread data is available, provide and set one.
996        * This can happen for the main thread and for threads
997        * that are not created by GLib.
998        */
999       thread = g_slice_new0 (GRealThread);
1000       thread->ref_count = 1;
1001
1002       g_private_set (&g_thread_specific_private, thread);
1003     }
1004
1005   return (GThread*) thread;
1006 }
1007
1008 /* Epilogue {{{1 */
1009 /* vim: set foldmethod=marker: */