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