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