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