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