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