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