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