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