Docs: Don't use the note tag
[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, see <http://www.gnu.org/licenses/>.
20  */
21
22 /* Prelude {{{1 ----------------------------------------------------------- */
23
24 /*
25  * Modified by the GLib Team and others 1997-2000.  See the AUTHORS
26  * file for a list of people on the GLib Team.  See the ChangeLog
27  * files for a list of changes.  These files are distributed with
28  * GLib at ftp://ftp.gtk.org/pub/gtk/.
29  */
30
31 /*
32  * MT safe
33  */
34
35 /* implement gthread.h's inline functions */
36 #define G_IMPLEMENT_INLINES 1
37 #define __G_THREAD_C__
38
39 #include "config.h"
40
41 #include "gthread.h"
42 #include "gthreadprivate.h"
43
44 #include <string.h>
45
46 #ifdef G_OS_UNIX
47 #include <unistd.h>
48 #endif
49
50 #ifndef G_OS_WIN32
51 #include <sys/time.h>
52 #include <time.h>
53 #else
54 #include <windows.h>
55 #endif /* G_OS_WIN32 */
56
57 #include "gslice.h"
58 #include "gstrfuncs.h"
59 #include "gtestutils.h"
60
61 /**
62  * SECTION:threads
63  * @title: Threads
64  * @short_description: portable support for threads, mutexes, locks,
65  *     conditions and thread private data
66  * @see_also: #GThreadPool, #GAsyncQueue
67  *
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.
77  *
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, #GRecMutex and #GRWLock). There is a facility to use
82  * individual bits for locks (g_bit_lock()). There are primitives
83  * for condition variables to allow synchronization of threads (#GCond).
84  * There are primitives for thread-private data - data that every
85  * thread has a private instance of (#GPrivate). There are facilities
86  * for one-time initialization (#GOnce, g_once_init_enter()). Finally,
87  * there are primitives to create and manage threads (#GThread).
88  *
89  * The GLib threading system used to be initialized with g_thread_init().
90  * This is no longer necessary. Since version 2.32, the GLib threading
91  * system is automatically initialized at the start of your program,
92  * and all thread-creation functions and synchronization primitives
93  * are available right away.
94  *
95  * Note that it is not safe to assume that your program has no threads
96  * even if you don't call g_thread_new() yourself. GLib and GIO can
97  * and will create threads for their own purposes in some cases, such
98  * as when using g_unix_signal_source_new() or when using GDBus.
99  *
100  * Originally, UNIX did not have threads, and therefore some traditional
101  * UNIX APIs are problematic in threaded programs. Some notable examples
102  * are
103  * <itemizedlist>
104  *   <listitem>
105  *     C library functions that return data in statically allocated
106  *     buffers, such as strtok() or strerror(). For many of these,
107  *     there are thread-safe variants with a _r suffix, or you can
108  *     look at corresponding GLib APIs (like g_strsplit() or g_strerror()).
109  *   </listitem>
110  *   <listitem>
111  *     setenv() and unsetenv() manipulate the process environment in
112  *     a not thread-safe way, and may interfere with getenv() calls
113  *     in other threads. Note that getenv() calls may be
114  *     <quote>hidden</quote> behind other APIs. For example, GNU gettext()
115  *     calls getenv() under the covers. In general, it is best to treat
116  *     the environment as readonly. If you absolutely have to modify the
117  *     environment, do it early in main(), when no other threads are around yet.
118  *   </listitem>
119  *   <listitem>
120  *     setlocale() changes the locale for the entire process, affecting
121  *     all threads. Temporary changes to the locale are often made to
122  *     change the behavior of string scanning or formatting functions
123  *     like scanf() or printf(). GLib offers a number of string APIs
124  *     (like g_ascii_formatd() or g_ascii_strtod()) that can often be
125  *     used as an alternative. Or you can use the uselocale() function
126  *     to change the locale only for the current thread.
127  *   </listitem>
128  *   <listitem>
129  *     fork() only takes the calling thread into the child's copy of the
130  *     process image.  If other threads were executing in critical
131  *     sections they could have left mutexes locked which could easily
132  *     cause deadlocks in the new child.  For this reason, you should
133  *     call exit() or exec() as soon as possible in the child and only
134  *     make signal-safe library calls before that.
135  *   </listitem>
136  *   <listitem>
137  *     daemon() uses fork() in a way contrary to what is described
138  *     above.  It should not be used with GLib programs.
139  *   </listitem>
140  * </itemizedlist>
141  *
142  * GLib itself is internally completely thread-safe (all global data is
143  * automatically locked), but individual data structure instances are
144  * not automatically locked for performance reasons. For example,
145  * you must coordinate accesses to the same #GHashTable from multiple
146  * threads. The two notable exceptions from this rule are #GMainLoop
147  * and #GAsyncQueue, which <emphasis>are</emphasis> thread-safe and
148  * need no further application-level locking to be accessed from
149  * multiple threads. Most refcounting functions such as g_object_ref()
150  * are also thread-safe.
151  */
152
153 /* G_LOCK Documentation {{{1 ---------------------------------------------- */
154
155 /**
156  * G_LOCK_DEFINE:
157  * @name: the name of the lock
158  *
159  * The <literal>G_LOCK_*</literal> macros provide a convenient interface to #GMutex.
160  * #G_LOCK_DEFINE defines a lock. It can appear in any place where
161  * variable definitions may appear in programs, i.e. in the first block
162  * of a function or outside of functions. The @name parameter will be
163  * mangled to get the name of the #GMutex. This means that you
164  * can use names of existing variables as the parameter - e.g. the name
165  * of the variable you intend to protect with the lock. Look at our
166  * <function>give_me_next_number()</function> example using the
167  * <literal>G_LOCK_*</literal> macros:
168  *
169  * <example>
170  *  <title>Using the <literal>G_LOCK_*</literal> convenience macros</title>
171  *  <programlisting>
172  *   G_LOCK_DEFINE (current_number);
173  *
174  *   int
175  *   give_me_next_number (void)
176  *   {
177  *     static int current_number = 0;
178  *     int ret_val;
179  *
180  *     G_LOCK (current_number);
181  *     ret_val = current_number = calc_next_number (current_number);
182  *     G_UNLOCK (current_number);
183  *
184  *     return ret_val;
185  *   }
186  *  </programlisting>
187  * </example>
188  */
189
190 /**
191  * G_LOCK_DEFINE_STATIC:
192  * @name: the name of the lock
193  *
194  * This works like #G_LOCK_DEFINE, but it creates a static object.
195  */
196
197 /**
198  * G_LOCK_EXTERN:
199  * @name: the name of the lock
200  *
201  * This declares a lock, that is defined with #G_LOCK_DEFINE in another
202  * module.
203  */
204
205 /**
206  * G_LOCK:
207  * @name: the name of the lock
208  *
209  * Works like g_mutex_lock(), but for a lock defined with
210  * #G_LOCK_DEFINE.
211  */
212
213 /**
214  * G_TRYLOCK:
215  * @name: the name of the lock
216  *
217  * Works like g_mutex_trylock(), but for a lock defined with
218  * #G_LOCK_DEFINE.
219  *
220  * Returns: %TRUE, if the lock could be locked.
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 G_DEFINE_QUARK (g_thread_error, g_thread_error)
521
522 /* Local Data {{{1 -------------------------------------------------------- */
523
524 static GMutex    g_once_mutex;
525 static GCond     g_once_cond;
526 static GSList   *g_once_init_list = NULL;
527
528 static void g_thread_cleanup (gpointer data);
529 static GPrivate     g_thread_specific_private = G_PRIVATE_INIT (g_thread_cleanup);
530
531 G_LOCK_DEFINE_STATIC (g_thread_new);
532
533 /* GOnce {{{1 ------------------------------------------------------------- */
534
535 /**
536  * GOnce:
537  * @status: the status of the #GOnce
538  * @retval: the value returned by the call to the function, if @status
539  *          is %G_ONCE_STATUS_READY
540  *
541  * A #GOnce struct controls a one-time initialization function. Any
542  * one-time initialization function must have its own unique #GOnce
543  * struct.
544  *
545  * Since: 2.4
546  */
547
548 /**
549  * G_ONCE_INIT:
550  *
551  * A #GOnce must be initialized with this macro before it can be used.
552  *
553  * |[
554  *   GOnce my_once = G_ONCE_INIT;
555  * ]|
556  *
557  * Since: 2.4
558  */
559
560 /**
561  * GOnceStatus:
562  * @G_ONCE_STATUS_NOTCALLED: the function has not been called yet.
563  * @G_ONCE_STATUS_PROGRESS: the function call is currently in progress.
564  * @G_ONCE_STATUS_READY: the function has been called.
565  *
566  * The possible statuses of a one-time initialization function
567  * controlled by a #GOnce struct.
568  *
569  * Since: 2.4
570  */
571
572 /**
573  * g_once:
574  * @once: a #GOnce structure
575  * @func: the #GThreadFunc function associated to @once. This function
576  *        is called only once, regardless of the number of times it and
577  *        its associated #GOnce struct are passed to g_once().
578  * @arg: data to be passed to @func
579  *
580  * The first call to this routine by a process with a given #GOnce
581  * struct calls @func with the given argument. Thereafter, subsequent
582  * calls to g_once()  with the same #GOnce struct do not call @func
583  * again, but return the stored result of the first call. On return
584  * from g_once(), the status of @once will be %G_ONCE_STATUS_READY.
585  *
586  * For example, a mutex or a thread-specific data key must be created
587  * exactly once. In a threaded environment, calling g_once() ensures
588  * that the initialization is serialized across multiple threads.
589  *
590  * Calling g_once() recursively on the same #GOnce struct in
591  * @func will lead to a deadlock.
592  *
593  * |[
594  *   gpointer
595  *   get_debug_flags (void)
596  *   {
597  *     static GOnce my_once = G_ONCE_INIT;
598  *
599  *     g_once (&my_once, parse_debug_flags, NULL);
600  *
601  *     return my_once.retval;
602  *   }
603  * ]|
604  *
605  * Since: 2.4
606  */
607 gpointer
608 g_once_impl (GOnce       *once,
609              GThreadFunc  func,
610              gpointer     arg)
611 {
612   g_mutex_lock (&g_once_mutex);
613
614   while (once->status == G_ONCE_STATUS_PROGRESS)
615     g_cond_wait (&g_once_cond, &g_once_mutex);
616
617   if (once->status != G_ONCE_STATUS_READY)
618     {
619       once->status = G_ONCE_STATUS_PROGRESS;
620       g_mutex_unlock (&g_once_mutex);
621
622       once->retval = func (arg);
623
624       g_mutex_lock (&g_once_mutex);
625       once->status = G_ONCE_STATUS_READY;
626       g_cond_broadcast (&g_once_cond);
627     }
628
629   g_mutex_unlock (&g_once_mutex);
630
631   return once->retval;
632 }
633
634 /**
635  * g_once_init_enter:
636  * @location: location of a static initializable variable containing 0
637  *
638  * Function to be called when starting a critical initialization
639  * section. The argument @location must point to a static
640  * 0-initialized variable that will be set to a value other than 0 at
641  * the end of the initialization section. In combination with
642  * g_once_init_leave() and the unique address @value_location, it can
643  * be ensured that an initialization section will be executed only once
644  * during a program's life time, and that concurrent threads are
645  * blocked until initialization completed. To be used in constructs
646  * like this:
647  *
648  * |[
649  *   static gsize initialization_value = 0;
650  *
651  *   if (g_once_init_enter (&amp;initialization_value))
652  *     {
653  *       gsize setup_value = 42; /&ast;* initialization code here *&ast;/
654  *
655  *       g_once_init_leave (&amp;initialization_value, setup_value);
656  *     }
657  *
658  *   /&ast;* use initialization_value here *&ast;/
659  * ]|
660  *
661  * Returns: %TRUE if the initialization section should be entered,
662  *     %FALSE and blocks otherwise
663  *
664  * Since: 2.14
665  */
666 gboolean
667 (g_once_init_enter) (volatile void *location)
668 {
669   volatile gsize *value_location = location;
670   gboolean need_init = FALSE;
671   g_mutex_lock (&g_once_mutex);
672   if (g_atomic_pointer_get (value_location) == NULL)
673     {
674       if (!g_slist_find (g_once_init_list, (void*) value_location))
675         {
676           need_init = TRUE;
677           g_once_init_list = g_slist_prepend (g_once_init_list, (void*) value_location);
678         }
679       else
680         do
681           g_cond_wait (&g_once_cond, &g_once_mutex);
682         while (g_slist_find (g_once_init_list, (void*) value_location));
683     }
684   g_mutex_unlock (&g_once_mutex);
685   return need_init;
686 }
687
688 /**
689  * g_once_init_leave:
690  * @location: location of a static initializable variable containing 0
691  * @result: new non-0 value for *@value_location
692  *
693  * Counterpart to g_once_init_enter(). Expects a location of a static
694  * 0-initialized initialization variable, and an initialization value
695  * other than 0. Sets the variable to the initialization value, and
696  * releases concurrent threads blocking in g_once_init_enter() on this
697  * initialization variable.
698  *
699  * Since: 2.14
700  */
701 void
702 (g_once_init_leave) (volatile void *location,
703                      gsize          result)
704 {
705   volatile gsize *value_location = location;
706
707   g_return_if_fail (g_atomic_pointer_get (value_location) == NULL);
708   g_return_if_fail (result != 0);
709   g_return_if_fail (g_once_init_list != NULL);
710
711   g_atomic_pointer_set (value_location, result);
712   g_mutex_lock (&g_once_mutex);
713   g_once_init_list = g_slist_remove (g_once_init_list, (void*) value_location);
714   g_cond_broadcast (&g_once_cond);
715   g_mutex_unlock (&g_once_mutex);
716 }
717
718 /* GThread {{{1 -------------------------------------------------------- */
719
720 /**
721  * g_thread_ref:
722  * @thread: a #GThread
723  *
724  * Increase the reference count on @thread.
725  *
726  * Returns: a new reference to @thread
727  *
728  * Since: 2.32
729  */
730 GThread *
731 g_thread_ref (GThread *thread)
732 {
733   GRealThread *real = (GRealThread *) thread;
734
735   g_atomic_int_inc (&real->ref_count);
736
737   return thread;
738 }
739
740 /**
741  * g_thread_unref:
742  * @thread: a #GThread
743  *
744  * Decrease the reference count on @thread, possibly freeing all
745  * resources associated with it.
746  *
747  * Note that each thread holds a reference to its #GThread while
748  * it is running, so it is safe to drop your own reference to it
749  * if you don't need it anymore.
750  *
751  * Since: 2.32
752  */
753 void
754 g_thread_unref (GThread *thread)
755 {
756   GRealThread *real = (GRealThread *) thread;
757
758   if (g_atomic_int_dec_and_test (&real->ref_count))
759     {
760       if (real->ours)
761         g_system_thread_free (real);
762       else
763         g_slice_free (GRealThread, real);
764     }
765 }
766
767 static void
768 g_thread_cleanup (gpointer data)
769 {
770   g_thread_unref (data);
771 }
772
773 gpointer
774 g_thread_proxy (gpointer data)
775 {
776   GRealThread* thread = data;
777
778   g_assert (data);
779
780   /* This has to happen before G_LOCK, as that might call g_thread_self */
781   g_private_set (&g_thread_specific_private, data);
782
783   /* The lock makes sure that g_thread_new_internal() has a chance to
784    * setup 'func' and 'data' before we make the call.
785    */
786   G_LOCK (g_thread_new);
787   G_UNLOCK (g_thread_new);
788
789   if (thread->name)
790     {
791       g_system_thread_set_name (thread->name);
792       g_free (thread->name);
793       thread->name = NULL;
794     }
795
796   thread->retval = thread->thread.func (thread->thread.data);
797
798   return NULL;
799 }
800
801 /**
802  * g_thread_new:
803  * @name: (allow-none): an (optional) 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  * It is not used for other purposes and does not have to be unique.
815  * Some systems restrict the length of @name to 16 bytes.
816  *
817  * If the thread can not be created the program aborts. See
818  * g_thread_try_new() if you want to attempt to deal with failures.
819  *
820  * To free the struct returned by this function, use g_thread_unref().
821  * Note that g_thread_join() implicitly unrefs the #GThread as well.
822  *
823  * Returns: the new #GThread
824  *
825  * Since: 2.32
826  */
827 GThread *
828 g_thread_new (const gchar *name,
829               GThreadFunc  func,
830               gpointer     data)
831 {
832   GError *error = NULL;
833   GThread *thread;
834
835   thread = g_thread_new_internal (name, g_thread_proxy, func, data, 0, &error);
836
837   if G_UNLIKELY (thread == NULL)
838     g_error ("creating thread '%s': %s", name ? name : "", error->message);
839
840   return thread;
841 }
842
843 /**
844  * g_thread_try_new:
845  * @name: (allow-none): an (optional) name for the new thread
846  * @func: a function to execute in the new thread
847  * @data: an argument to supply to the new thread
848  * @error: return location for error, or %NULL
849  *
850  * This function is the same as g_thread_new() except that
851  * it allows for the possibility of failure.
852  *
853  * If a thread can not be created (due to resource limits),
854  * @error is set and %NULL is returned.
855  *
856  * Returns: the new #GThread, or %NULL if an error occurred
857  *
858  * Since: 2.32
859  */
860 GThread *
861 g_thread_try_new (const gchar  *name,
862                   GThreadFunc   func,
863                   gpointer      data,
864                   GError      **error)
865 {
866   return g_thread_new_internal (name, g_thread_proxy, func, data, 0, error);
867 }
868
869 GThread *
870 g_thread_new_internal (const gchar   *name,
871                        GThreadFunc    proxy,
872                        GThreadFunc    func,
873                        gpointer       data,
874                        gsize          stack_size,
875                        GError       **error)
876 {
877   GRealThread *thread;
878
879   g_return_val_if_fail (func != NULL, NULL);
880
881   G_LOCK (g_thread_new);
882   thread = g_system_thread_new (proxy, stack_size, error);
883   if (thread)
884     {
885       thread->ref_count = 2;
886       thread->ours = TRUE;
887       thread->thread.joinable = TRUE;
888       thread->thread.func = func;
889       thread->thread.data = data;
890       thread->name = g_strdup (name);
891     }
892   G_UNLOCK (g_thread_new);
893
894   return (GThread*) thread;
895 }
896
897 /**
898  * g_thread_exit:
899  * @retval: the return value of this thread
900  *
901  * Terminates the current thread.
902  *
903  * If another thread is waiting for us using g_thread_join() then the
904  * waiting thread will be woken up and get @retval as the return value
905  * of g_thread_join().
906  *
907  * Calling <literal>g_thread_exit (retval)</literal> is equivalent to
908  * returning @retval from the function @func, as given to g_thread_new().
909  *
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  */
915 void
916 g_thread_exit (gpointer retval)
917 {
918   GRealThread* real = (GRealThread*) g_thread_self ();
919
920   if G_UNLIKELY (!real->ours)
921     g_error ("attempt to g_thread_exit() a thread not created by GLib");
922
923   real->retval = retval;
924
925   g_system_thread_exit ();
926 }
927
928 /**
929  * g_thread_join:
930  * @thread: a #GThread
931  *
932  * Waits until @thread finishes, i.e. the function @func, as
933  * given to g_thread_new(), returns or g_thread_exit() is called.
934  * If @thread has already terminated, then g_thread_join()
935  * returns immediately.
936  *
937  * Any thread can wait for any other thread by calling g_thread_join(),
938  * not just its 'creator'. Calling g_thread_join() from multiple threads
939  * for the same @thread leads to undefined behaviour.
940  *
941  * The value returned by @func or given to g_thread_exit() is
942  * returned by this function.
943  *
944  * g_thread_join() consumes the reference to the passed-in @thread.
945  * This will usually cause the #GThread struct and associated resources
946  * to be freed. Use g_thread_ref() to obtain an extra reference if you
947  * want to keep the GThread alive beyond the g_thread_join() call.
948  *
949  * Returns: the return value of the thread
950  */
951 gpointer
952 g_thread_join (GThread *thread)
953 {
954   GRealThread *real = (GRealThread*) thread;
955   gpointer retval;
956
957   g_return_val_if_fail (thread, NULL);
958   g_return_val_if_fail (real->ours, NULL);
959
960   g_system_thread_wait (real);
961
962   retval = real->retval;
963
964   /* Just to make sure, this isn't used any more */
965   thread->joinable = 0;
966
967   g_thread_unref (thread);
968
969   return retval;
970 }
971
972 /**
973  * g_thread_self:
974  *
975  * This functions returns the #GThread corresponding to the
976  * current thread. Note that this function does not increase
977  * the reference count of the returned struct.
978  *
979  * This function will return a #GThread even for threads that
980  * were not created by GLib (i.e. those created by other threading
981  * APIs). This may be useful for thread identification purposes
982  * (i.e. comparisons) but you must not use GLib functions (such
983  * as g_thread_join()) on these threads.
984  *
985  * Returns: the #GThread representing the current thread
986  */
987 GThread*
988 g_thread_self (void)
989 {
990   GRealThread* thread = g_private_get (&g_thread_specific_private);
991
992   if (!thread)
993     {
994       /* If no thread data is available, provide and set one.
995        * This can happen for the main thread and for threads
996        * that are not created by GLib.
997        */
998       thread = g_slice_new0 (GRealThread);
999       thread->ref_count = 1;
1000
1001       g_private_set (&g_thread_specific_private, thread);
1002     }
1003
1004   return (GThread*) thread;
1005 }
1006
1007 /**
1008  * g_get_num_processors:
1009  *
1010  * Determine the approximate number of threads that the system will
1011  * schedule simultaneously for this process.  This is intended to be
1012  * used as a parameter to g_thread_pool_new() for CPU bound tasks and
1013  * similar cases.
1014  *
1015  * Returns: Number of schedulable threads, always greater than 0
1016  *
1017  * Since: 2.36
1018  */
1019 guint
1020 g_get_num_processors (void)
1021 {
1022 #ifdef G_OS_WIN32
1023   DWORD_PTR process_cpus;
1024   DWORD_PTR system_cpus;
1025
1026   if (GetProcessAffinityMask (GetCurrentProcess (),
1027                               &process_cpus, &system_cpus))
1028     {
1029       unsigned int count;
1030
1031       for (count = 0; process_cpus != 0; process_cpus >>= 1)
1032         if (process_cpus & 1)
1033           count++;
1034
1035       if (count > 0)
1036         return count;
1037     }
1038 #elif defined(_SC_NPROCESSORS_ONLN)
1039   {
1040     int count;
1041
1042     count = sysconf (_SC_NPROCESSORS_ONLN);
1043     if (count > 0)
1044       return count;
1045   }
1046 #elif defined HW_NCPU
1047   {
1048     int mib[2], count = 0;
1049     size_t len;
1050
1051     mib[0] = CTL_HW;
1052     mib[1] = HW_NCPU;
1053     len = sizeof(count);
1054
1055     if (sysctl (mib, 2, &count, &len, NULL, 0) == 0 && count > 0)
1056       return count;
1057   }
1058 #endif
1059
1060   return 1; /* Fallback */
1061 }
1062
1063 /* Epilogue {{{1 */
1064 /* vim: set foldmethod=marker: */