ffac638a15fc0aab2dbce68cddcc04b6eb2a865c
[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 are thread-safe and need no further
148  * application-level locking to be accessed from multiple threads.
149  * Most refcounting functions such as g_object_ref() are also thread-safe.
150  */
151
152 /* G_LOCK Documentation {{{1 ---------------------------------------------- */
153
154 /**
155  * G_LOCK_DEFINE:
156  * @name: the name of the lock
157  *
158  * The <literal>G_LOCK_*</literal> macros provide a convenient interface to #GMutex.
159  * #G_LOCK_DEFINE defines a lock. It can appear in any place where
160  * variable definitions may appear in programs, i.e. in the first block
161  * of a function or outside of functions. The @name parameter will be
162  * mangled to get the name of the #GMutex. This means that you
163  * can use names of existing variables as the parameter - e.g. the name
164  * of the variable you intend to protect with the lock. Look at our
165  * <function>give_me_next_number()</function> example using the
166  * <literal>G_LOCK_*</literal> macros:
167  *
168  * <example>
169  *  <title>Using the <literal>G_LOCK_*</literal> convenience macros</title>
170  *  <programlisting>
171  *   G_LOCK_DEFINE (current_number);
172  *
173  *   int
174  *   give_me_next_number (void)
175  *   {
176  *     static int current_number = 0;
177  *     int ret_val;
178  *
179  *     G_LOCK (current_number);
180  *     ret_val = current_number = calc_next_number (current_number);
181  *     G_UNLOCK (current_number);
182  *
183  *     return ret_val;
184  *   }
185  *  </programlisting>
186  * </example>
187  */
188
189 /**
190  * G_LOCK_DEFINE_STATIC:
191  * @name: the name of the lock
192  *
193  * This works like #G_LOCK_DEFINE, but it creates a static object.
194  */
195
196 /**
197  * G_LOCK_EXTERN:
198  * @name: the name of the lock
199  *
200  * This declares a lock, that is defined with #G_LOCK_DEFINE in another
201  * module.
202  */
203
204 /**
205  * G_LOCK:
206  * @name: the name of the lock
207  *
208  * Works like g_mutex_lock(), but for a lock defined with
209  * #G_LOCK_DEFINE.
210  */
211
212 /**
213  * G_TRYLOCK:
214  * @name: the name of the lock
215  *
216  * Works like g_mutex_trylock(), but for a lock defined with
217  * #G_LOCK_DEFINE.
218  *
219  * Returns: %TRUE, if the lock could be locked.
220  */
221
222 /**
223  * G_UNLOCK:
224  * @name: the name of the lock
225  *
226  * Works like g_mutex_unlock(), but for a lock defined with
227  * #G_LOCK_DEFINE.
228  */
229
230 /* GMutex Documentation {{{1 ------------------------------------------ */
231
232 /**
233  * GMutex:
234  *
235  * The #GMutex struct is an opaque data structure to represent a mutex
236  * (mutual exclusion). It can be used to protect data against shared
237  * access. Take for example the following function:
238  *
239  * <example>
240  *  <title>A function which will not work in a threaded environment</title>
241  *  <programlisting>
242  *   int
243  *   give_me_next_number (void)
244  *   {
245  *     static int current_number = 0;
246  *
247  *     /<!-- -->* now do a very complicated calculation to calculate the new
248  *      * number, this might for example be a random number generator
249  *      *<!-- -->/
250  *     current_number = calc_next_number (current_number);
251  *
252  *     return current_number;
253  *   }
254  *  </programlisting>
255  * </example>
256  *
257  * It is easy to see that this won't work in a multi-threaded
258  * application. There current_number must be protected against shared
259  * access. A #GMutex can be used as a solution to this problem:
260  *
261  * <example>
262  *  <title>Using GMutex to protected a shared variable</title>
263  *  <programlisting>
264  *   int
265  *   give_me_next_number (void)
266  *   {
267  *     static GMutex mutex;
268  *     static int current_number = 0;
269  *     int ret_val;
270  *
271  *     g_mutex_lock (&amp;mutex);
272  *     ret_val = current_number = calc_next_number (current_number);
273  *     g_mutex_unlock (&amp;mutex);
274  *
275  *     return ret_val;
276  *   }
277  *  </programlisting>
278  * </example>
279  *
280  * Notice that the #GMutex is not initialised to any particular value.
281  * Its placement in static storage ensures that it will be initialised
282  * to all-zeros, which is appropriate.
283  *
284  * If a #GMutex is placed in other contexts (eg: embedded in a struct)
285  * then it must be explicitly initialised using g_mutex_init().
286  *
287  * A #GMutex should only be accessed via <function>g_mutex_</function>
288  * functions.
289  */
290
291 /* GRecMutex Documentation {{{1 -------------------------------------- */
292
293 /**
294  * GRecMutex:
295  *
296  * The GRecMutex struct is an opaque data structure to represent a
297  * recursive mutex. It is similar to a #GMutex with the difference
298  * that it is possible to lock a GRecMutex multiple times in the same
299  * thread without deadlock. When doing so, care has to be taken to
300  * unlock the recursive mutex as often as it has been locked.
301  *
302  * If a #GRecMutex is allocated in static storage then it can be used
303  * without initialisation.  Otherwise, you should call
304  * g_rec_mutex_init() on it and g_rec_mutex_clear() when done.
305  *
306  * A GRecMutex should only be accessed with the
307  * <function>g_rec_mutex_</function> functions.
308  *
309  * Since: 2.32
310  */
311
312 /* GRWLock Documentation {{{1 ---------------------------------------- */
313
314 /**
315  * GRWLock:
316  *
317  * The GRWLock struct is an opaque data structure to represent a
318  * reader-writer lock. It is similar to a #GMutex in that it allows
319  * multiple threads to coordinate access to a shared resource.
320  *
321  * The difference to a mutex is that a reader-writer lock discriminates
322  * between read-only ('reader') and full ('writer') access. While only
323  * one thread at a time is allowed write access (by holding the 'writer'
324  * lock via g_rw_lock_writer_lock()), multiple threads can gain
325  * simultaneous read-only access (by holding the 'reader' lock via
326  * g_rw_lock_reader_lock()).
327  *
328  * <example>
329  *  <title>An array with access functions</title>
330  *  <programlisting>
331  *   GRWLock lock;
332  *   GPtrArray *array;
333  *
334  *   gpointer
335  *   my_array_get (guint index)
336  *   {
337  *     gpointer retval = NULL;
338  *
339  *     if (!array)
340  *       return NULL;
341  *
342  *     g_rw_lock_reader_lock (&amp;lock);
343  *     if (index &lt; array->len)
344  *       retval = g_ptr_array_index (array, index);
345  *     g_rw_lock_reader_unlock (&amp;lock);
346  *
347  *     return retval;
348  *   }
349  *
350  *   void
351  *   my_array_set (guint index, gpointer data)
352  *   {
353  *     g_rw_lock_writer_lock (&amp;lock);
354  *
355  *     if (!array)
356  *       array = g_ptr_array_new (<!-- -->);
357  *
358  *     if (index >= array->len)
359  *       g_ptr_array_set_size (array, index+1);
360  *     g_ptr_array_index (array, index) = data;
361  *
362  *     g_rw_lock_writer_unlock (&amp;lock);
363  *   }
364  *  </programlisting>
365  *  <para>
366  *    This example shows an array which can be accessed by many readers
367  *    (the <function>my_array_get()</function> function) simultaneously,
368  *    whereas the writers (the <function>my_array_set()</function>
369  *    function) will only be allowed once at a time and only if no readers
370  *    currently access the array. This is because of the potentially
371  *    dangerous resizing of the array. Using these functions is fully
372  *    multi-thread safe now.
373  *  </para>
374  * </example>
375  *
376  * If a #GRWLock is allocated in static storage then it can be used
377  * without initialisation.  Otherwise, you should call
378  * g_rw_lock_init() on it and g_rw_lock_clear() when done.
379  *
380  * A GRWLock should only be accessed with the
381  * <function>g_rw_lock_</function> functions.
382  *
383  * Since: 2.32
384  */
385
386 /* GCond Documentation {{{1 ------------------------------------------ */
387
388 /**
389  * GCond:
390  *
391  * The #GCond struct is an opaque data structure that represents a
392  * condition. Threads can block on a #GCond if they find a certain
393  * condition to be false. If other threads change the state of this
394  * condition they signal the #GCond, and that causes the waiting
395  * threads to be woken up.
396  *
397  * Consider the following example of a shared variable.  One or more
398  * threads can wait for data to be published to the variable and when
399  * another thread publishes the data, it can signal one of the waiting
400  * threads to wake up to collect the data.
401  *
402  * <example>
403  *  <title>
404  *   Using GCond to block a thread until a condition is satisfied
405  *  </title>
406  *  <programlisting>
407  *   gpointer current_data = NULL;
408  *   GMutex data_mutex;
409  *   GCond data_cond;
410  *
411  *   void
412  *   push_data (gpointer data)
413  *   {
414  *     g_mutex_lock (&data_mutex);
415  *     current_data = data;
416  *     g_cond_signal (&data_cond);
417  *     g_mutex_unlock (&data_mutex);
418  *   }
419  *
420  *   gpointer
421  *   pop_data (void)
422  *   {
423  *     gpointer data;
424  *
425  *     g_mutex_lock (&data_mutex);
426  *     while (!current_data)
427  *       g_cond_wait (&data_cond, &data_mutex);
428  *     data = current_data;
429  *     current_data = NULL;
430  *     g_mutex_unlock (&data_mutex);
431  *
432  *     return data;
433  *   }
434  *  </programlisting>
435  * </example>
436  *
437  * Whenever a thread calls pop_data() now, it will wait until
438  * current_data is non-%NULL, i.e. until some other thread
439  * has called push_data().
440  *
441  * The example shows that use of a condition variable must always be
442  * paired with a mutex.  Without the use of a mutex, there would be a
443  * race between the check of <varname>current_data</varname> by the
444  * while loop in <function>pop_data</function> and waiting.
445  * Specifically, another thread could set <varname>pop_data</varname>
446  * after the check, and signal the cond (with nobody waiting on it)
447  * before the first thread goes to sleep.  #GCond is specifically useful
448  * for its ability to release the mutex and go to sleep atomically.
449  *
450  * It is also important to use the g_cond_wait() and g_cond_wait_until()
451  * functions only inside a loop which checks for the condition to be
452  * true.  See g_cond_wait() for an explanation of why the condition may
453  * not be true even after it returns.
454  *
455  * If a #GCond is allocated in static storage then it can be used
456  * without initialisation.  Otherwise, you should call g_cond_init() on
457  * it and g_cond_clear() when done.
458  *
459  * A #GCond should only be accessed via the <function>g_cond_</function>
460  * functions.
461  */
462
463 /* GThread Documentation {{{1 ---------------------------------------- */
464
465 /**
466  * GThread:
467  *
468  * The #GThread struct represents a running thread. This struct
469  * is returned by g_thread_new() or g_thread_try_new(). You can
470  * obtain the #GThread struct representing the current thead by
471  * calling g_thread_self().
472  *
473  * GThread is refcounted, see g_thread_ref() and g_thread_unref().
474  * The thread represented by it holds a reference while it is running,
475  * and g_thread_join() consumes the reference that it is given, so
476  * it is normally not necessary to manage GThread references
477  * explicitly.
478  *
479  * The structure is opaque -- none of its fields may be directly
480  * accessed.
481  */
482
483 /**
484  * GThreadFunc:
485  * @data: data passed to the thread
486  *
487  * Specifies the type of the @func functions passed to g_thread_new()
488  * or g_thread_try_new().
489  *
490  * Returns: the return value of the thread
491  */
492
493 /**
494  * g_thread_supported:
495  *
496  * This macro returns %TRUE if the thread system is initialized,
497  * and %FALSE if it is not.
498  *
499  * For language bindings, g_thread_get_initialized() provides
500  * the same functionality as a function.
501  *
502  * Returns: %TRUE, if the thread system is initialized
503  */
504
505 /* GThreadError {{{1 ------------------------------------------------------- */
506 /**
507  * GThreadError:
508  * @G_THREAD_ERROR_AGAIN: a thread couldn't be created due to resource
509  *                        shortage. Try again later.
510  *
511  * Possible errors of thread related functions.
512  **/
513
514 /**
515  * G_THREAD_ERROR:
516  *
517  * The error domain of the GLib thread subsystem.
518  **/
519 G_DEFINE_QUARK (g_thread_error, g_thread_error)
520
521 /* Local Data {{{1 -------------------------------------------------------- */
522
523 static GMutex    g_once_mutex;
524 static GCond     g_once_cond;
525 static GSList   *g_once_init_list = NULL;
526
527 static void g_thread_cleanup (gpointer data);
528 static GPrivate     g_thread_specific_private = G_PRIVATE_INIT (g_thread_cleanup);
529
530 G_LOCK_DEFINE_STATIC (g_thread_new);
531
532 /* GOnce {{{1 ------------------------------------------------------------- */
533
534 /**
535  * GOnce:
536  * @status: the status of the #GOnce
537  * @retval: the value returned by the call to the function, if @status
538  *          is %G_ONCE_STATUS_READY
539  *
540  * A #GOnce struct controls a one-time initialization function. Any
541  * one-time initialization function must have its own unique #GOnce
542  * struct.
543  *
544  * Since: 2.4
545  */
546
547 /**
548  * G_ONCE_INIT:
549  *
550  * A #GOnce must be initialized with this macro before it can be used.
551  *
552  * |[
553  *   GOnce my_once = G_ONCE_INIT;
554  * ]|
555  *
556  * Since: 2.4
557  */
558
559 /**
560  * GOnceStatus:
561  * @G_ONCE_STATUS_NOTCALLED: the function has not been called yet.
562  * @G_ONCE_STATUS_PROGRESS: the function call is currently in progress.
563  * @G_ONCE_STATUS_READY: the function has been called.
564  *
565  * The possible statuses of a one-time initialization function
566  * controlled by a #GOnce struct.
567  *
568  * Since: 2.4
569  */
570
571 /**
572  * g_once:
573  * @once: a #GOnce structure
574  * @func: the #GThreadFunc function associated to @once. This function
575  *        is called only once, regardless of the number of times it and
576  *        its associated #GOnce struct are passed to g_once().
577  * @arg: data to be passed to @func
578  *
579  * The first call to this routine by a process with a given #GOnce
580  * struct calls @func with the given argument. Thereafter, subsequent
581  * calls to g_once()  with the same #GOnce struct do not call @func
582  * again, but return the stored result of the first call. On return
583  * from g_once(), the status of @once will be %G_ONCE_STATUS_READY.
584  *
585  * For example, a mutex or a thread-specific data key must be created
586  * exactly once. In a threaded environment, calling g_once() ensures
587  * that the initialization is serialized across multiple threads.
588  *
589  * Calling g_once() recursively on the same #GOnce struct in
590  * @func will lead to a deadlock.
591  *
592  * |[
593  *   gpointer
594  *   get_debug_flags (void)
595  *   {
596  *     static GOnce my_once = G_ONCE_INIT;
597  *
598  *     g_once (&my_once, parse_debug_flags, NULL);
599  *
600  *     return my_once.retval;
601  *   }
602  * ]|
603  *
604  * Since: 2.4
605  */
606 gpointer
607 g_once_impl (GOnce       *once,
608              GThreadFunc  func,
609              gpointer     arg)
610 {
611   g_mutex_lock (&g_once_mutex);
612
613   while (once->status == G_ONCE_STATUS_PROGRESS)
614     g_cond_wait (&g_once_cond, &g_once_mutex);
615
616   if (once->status != G_ONCE_STATUS_READY)
617     {
618       once->status = G_ONCE_STATUS_PROGRESS;
619       g_mutex_unlock (&g_once_mutex);
620
621       once->retval = func (arg);
622
623       g_mutex_lock (&g_once_mutex);
624       once->status = G_ONCE_STATUS_READY;
625       g_cond_broadcast (&g_once_cond);
626     }
627
628   g_mutex_unlock (&g_once_mutex);
629
630   return once->retval;
631 }
632
633 /**
634  * g_once_init_enter:
635  * @location: location of a static initializable variable containing 0
636  *
637  * Function to be called when starting a critical initialization
638  * section. The argument @location must point to a static
639  * 0-initialized variable that will be set to a value other than 0 at
640  * the end of the initialization section. In combination with
641  * g_once_init_leave() and the unique address @value_location, it can
642  * be ensured that an initialization section will be executed only once
643  * during a program's life time, and that concurrent threads are
644  * blocked until initialization completed. To be used in constructs
645  * like this:
646  *
647  * |[
648  *   static gsize initialization_value = 0;
649  *
650  *   if (g_once_init_enter (&amp;initialization_value))
651  *     {
652  *       gsize setup_value = 42; /&ast;* initialization code here *&ast;/
653  *
654  *       g_once_init_leave (&amp;initialization_value, setup_value);
655  *     }
656  *
657  *   /&ast;* use initialization_value here *&ast;/
658  * ]|
659  *
660  * Returns: %TRUE if the initialization section should be entered,
661  *     %FALSE and blocks otherwise
662  *
663  * Since: 2.14
664  */
665 gboolean
666 (g_once_init_enter) (volatile void *location)
667 {
668   volatile gsize *value_location = location;
669   gboolean need_init = FALSE;
670   g_mutex_lock (&g_once_mutex);
671   if (g_atomic_pointer_get (value_location) == NULL)
672     {
673       if (!g_slist_find (g_once_init_list, (void*) value_location))
674         {
675           need_init = TRUE;
676           g_once_init_list = g_slist_prepend (g_once_init_list, (void*) value_location);
677         }
678       else
679         do
680           g_cond_wait (&g_once_cond, &g_once_mutex);
681         while (g_slist_find (g_once_init_list, (void*) value_location));
682     }
683   g_mutex_unlock (&g_once_mutex);
684   return need_init;
685 }
686
687 /**
688  * g_once_init_leave:
689  * @location: location of a static initializable variable containing 0
690  * @result: new non-0 value for *@value_location
691  *
692  * Counterpart to g_once_init_enter(). Expects a location of a static
693  * 0-initialized initialization variable, and an initialization value
694  * other than 0. Sets the variable to the initialization value, and
695  * releases concurrent threads blocking in g_once_init_enter() on this
696  * initialization variable.
697  *
698  * Since: 2.14
699  */
700 void
701 (g_once_init_leave) (volatile void *location,
702                      gsize          result)
703 {
704   volatile gsize *value_location = location;
705
706   g_return_if_fail (g_atomic_pointer_get (value_location) == NULL);
707   g_return_if_fail (result != 0);
708   g_return_if_fail (g_once_init_list != NULL);
709
710   g_atomic_pointer_set (value_location, result);
711   g_mutex_lock (&g_once_mutex);
712   g_once_init_list = g_slist_remove (g_once_init_list, (void*) value_location);
713   g_cond_broadcast (&g_once_cond);
714   g_mutex_unlock (&g_once_mutex);
715 }
716
717 /* GThread {{{1 -------------------------------------------------------- */
718
719 /**
720  * g_thread_ref:
721  * @thread: a #GThread
722  *
723  * Increase the reference count on @thread.
724  *
725  * Returns: a new reference to @thread
726  *
727  * Since: 2.32
728  */
729 GThread *
730 g_thread_ref (GThread *thread)
731 {
732   GRealThread *real = (GRealThread *) thread;
733
734   g_atomic_int_inc (&real->ref_count);
735
736   return thread;
737 }
738
739 /**
740  * g_thread_unref:
741  * @thread: a #GThread
742  *
743  * Decrease the reference count on @thread, possibly freeing all
744  * resources associated with it.
745  *
746  * Note that each thread holds a reference to its #GThread while
747  * it is running, so it is safe to drop your own reference to it
748  * if you don't need it anymore.
749  *
750  * Since: 2.32
751  */
752 void
753 g_thread_unref (GThread *thread)
754 {
755   GRealThread *real = (GRealThread *) thread;
756
757   if (g_atomic_int_dec_and_test (&real->ref_count))
758     {
759       if (real->ours)
760         g_system_thread_free (real);
761       else
762         g_slice_free (GRealThread, real);
763     }
764 }
765
766 static void
767 g_thread_cleanup (gpointer data)
768 {
769   g_thread_unref (data);
770 }
771
772 gpointer
773 g_thread_proxy (gpointer data)
774 {
775   GRealThread* thread = data;
776
777   g_assert (data);
778
779   /* This has to happen before G_LOCK, as that might call g_thread_self */
780   g_private_set (&g_thread_specific_private, data);
781
782   /* The lock makes sure that g_thread_new_internal() has a chance to
783    * setup 'func' and 'data' before we make the call.
784    */
785   G_LOCK (g_thread_new);
786   G_UNLOCK (g_thread_new);
787
788   if (thread->name)
789     {
790       g_system_thread_set_name (thread->name);
791       g_free (thread->name);
792       thread->name = NULL;
793     }
794
795   thread->retval = thread->thread.func (thread->thread.data);
796
797   return NULL;
798 }
799
800 /**
801  * g_thread_new:
802  * @name: (allow-none): an (optional) name for the new thread
803  * @func: a function to execute in the new thread
804  * @data: an argument to supply to the new thread
805  *
806  * This function creates a new thread. The new thread starts by invoking
807  * @func with the argument data. The thread will run until @func returns
808  * or until g_thread_exit() is called from the new thread. The return value
809  * of @func becomes the return value of the thread, which can be obtained
810  * with g_thread_join().
811  *
812  * The @name can be useful for discriminating threads in a debugger.
813  * It is not used for other purposes and does not have to be unique.
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: (allow-none): an (optional) 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 = g_strdup (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  * You must only call g_thread_exit() from a thread that you created
910  * yourself with g_thread_new() or related APIs.  You must not call
911  * this function from a thread created with another threading library
912  * or or from within a #GThreadPool.
913  */
914 void
915 g_thread_exit (gpointer retval)
916 {
917   GRealThread* real = (GRealThread*) g_thread_self ();
918
919   if G_UNLIKELY (!real->ours)
920     g_error ("attempt to g_thread_exit() a thread not created by GLib");
921
922   real->retval = retval;
923
924   g_system_thread_exit ();
925 }
926
927 /**
928  * g_thread_join:
929  * @thread: a #GThread
930  *
931  * Waits until @thread finishes, i.e. the function @func, as
932  * given to g_thread_new(), returns or g_thread_exit() is called.
933  * If @thread has already terminated, then g_thread_join()
934  * returns immediately.
935  *
936  * Any thread can wait for any other thread by calling g_thread_join(),
937  * not just its 'creator'. Calling g_thread_join() from multiple threads
938  * for the same @thread leads to undefined behaviour.
939  *
940  * The value returned by @func or given to g_thread_exit() is
941  * returned by this function.
942  *
943  * g_thread_join() consumes the reference to the passed-in @thread.
944  * This will usually cause the #GThread struct and associated resources
945  * to be freed. Use g_thread_ref() to obtain an extra reference if you
946  * want to keep the GThread alive beyond the g_thread_join() call.
947  *
948  * Returns: the return value of the thread
949  */
950 gpointer
951 g_thread_join (GThread *thread)
952 {
953   GRealThread *real = (GRealThread*) thread;
954   gpointer retval;
955
956   g_return_val_if_fail (thread, NULL);
957   g_return_val_if_fail (real->ours, NULL);
958
959   g_system_thread_wait (real);
960
961   retval = real->retval;
962
963   /* Just to make sure, this isn't used any more */
964   thread->joinable = 0;
965
966   g_thread_unref (thread);
967
968   return retval;
969 }
970
971 /**
972  * g_thread_self:
973  *
974  * This functions returns the #GThread corresponding to the
975  * current thread. Note that this function does not increase
976  * the reference count of the returned struct.
977  *
978  * This function will return a #GThread even for threads that
979  * were not created by GLib (i.e. those created by other threading
980  * APIs). This may be useful for thread identification purposes
981  * (i.e. comparisons) but you must not use GLib functions (such
982  * as g_thread_join()) on these threads.
983  *
984  * Returns: the #GThread representing the current thread
985  */
986 GThread*
987 g_thread_self (void)
988 {
989   GRealThread* thread = g_private_get (&g_thread_specific_private);
990
991   if (!thread)
992     {
993       /* If no thread data is available, provide and set one.
994        * This can happen for the main thread and for threads
995        * that are not created by GLib.
996        */
997       thread = g_slice_new0 (GRealThread);
998       thread->ref_count = 1;
999
1000       g_private_set (&g_thread_specific_private, thread);
1001     }
1002
1003   return (GThread*) thread;
1004 }
1005
1006 /**
1007  * g_get_num_processors:
1008  *
1009  * Determine the approximate number of threads that the system will
1010  * schedule simultaneously for this process.  This is intended to be
1011  * used as a parameter to g_thread_pool_new() for CPU bound tasks and
1012  * similar cases.
1013  *
1014  * Returns: Number of schedulable threads, always greater than 0
1015  *
1016  * Since: 2.36
1017  */
1018 guint
1019 g_get_num_processors (void)
1020 {
1021 #ifdef G_OS_WIN32
1022   DWORD_PTR process_cpus;
1023   DWORD_PTR system_cpus;
1024
1025   if (GetProcessAffinityMask (GetCurrentProcess (),
1026                               &process_cpus, &system_cpus))
1027     {
1028       unsigned int count;
1029
1030       for (count = 0; process_cpus != 0; process_cpus >>= 1)
1031         if (process_cpus & 1)
1032           count++;
1033
1034       if (count > 0)
1035         return count;
1036     }
1037 #elif defined(_SC_NPROCESSORS_ONLN)
1038   {
1039     int count;
1040
1041     count = sysconf (_SC_NPROCESSORS_ONLN);
1042     if (count > 0)
1043       return count;
1044   }
1045 #elif defined HW_NCPU
1046   {
1047     int mib[2], count = 0;
1048     size_t len;
1049
1050     mib[0] = CTL_HW;
1051     mib[1] = HW_NCPU;
1052     len = sizeof(count);
1053
1054     if (sysctl (mib, 2, &count, &len, NULL, 0) == 0 && count > 0)
1055       return count;
1056   }
1057 #endif
1058
1059   return 1; /* Fallback */
1060 }
1061
1062 /* Epilogue {{{1 */
1063 /* vim: set foldmethod=marker: */