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