1 /* GLIB - Library of useful routines for C programming
2 * Copyright (C) 1995-1997 Peter Mattis, Spencer Kimball and Josh MacDonald
4 * gthread.c: MT safety related functions
5 * Copyright 1998 Sebastian Wilhelmi; University of Karlsruhe
8 * SPDX-License-Identifier: LGPL-2.1-or-later
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.
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.
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/>.
24 /* Prelude {{{1 ----------------------------------------------------------- */
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/.
37 /* implement gthread.h's inline functions */
38 #define G_IMPLEMENT_INLINES 1
39 #define __G_THREAD_C__
44 #include "gthreadprivate.h"
57 #endif /* G_OS_WIN32 */
60 #include "gstrfuncs.h"
61 #include "gtestutils.h"
62 #include "glib_trace.h"
63 #include "gtrace-private.h"
68 * @short_description: portable support for threads, mutexes, locks,
69 * conditions and thread private data
70 * @see_also: #GThreadPool, #GAsyncQueue
72 * Threads act almost like processes, but unlike processes all threads
73 * of one process share the same memory. This is good, as it provides
74 * easy communication between the involved threads via this shared
75 * memory, and it is bad, because strange things (so called
76 * "Heisenbugs") might happen if the program is not carefully designed.
77 * In particular, due to the concurrent nature of threads, no
78 * assumptions on the order of execution of code running in different
79 * threads can be made, unless order is explicitly forced by the
80 * programmer through synchronization primitives.
82 * The aim of the thread-related functions in GLib is to provide a
83 * portable means for writing multi-threaded software. There are
84 * primitives for mutexes to protect the access to portions of memory
85 * (#GMutex, #GRecMutex and #GRWLock). There is a facility to use
86 * individual bits for locks (g_bit_lock()). There are primitives
87 * for condition variables to allow synchronization of threads (#GCond).
88 * There are primitives for thread-private data - data that every
89 * thread has a private instance of (#GPrivate). There are facilities
90 * for one-time initialization (#GOnce, g_once_init_enter()). Finally,
91 * there are primitives to create and manage threads (#GThread).
93 * The GLib threading system used to be initialized with g_thread_init().
94 * This is no longer necessary. Since version 2.32, the GLib threading
95 * system is automatically initialized at the start of your program,
96 * and all thread-creation functions and synchronization primitives
97 * are available right away.
99 * Note that it is not safe to assume that your program has no threads
100 * even if you don't call g_thread_new() yourself. GLib and GIO can
101 * and will create threads for their own purposes in some cases, such
102 * as when using g_unix_signal_source_new() or when using GDBus.
104 * Originally, UNIX did not have threads, and therefore some traditional
105 * UNIX APIs are problematic in threaded programs. Some notable examples
108 * - C library functions that return data in statically allocated
109 * buffers, such as strtok() or strerror(). For many of these,
110 * there are thread-safe variants with a _r suffix, or you can
111 * look at corresponding GLib APIs (like g_strsplit() or g_strerror()).
113 * - The functions setenv() and unsetenv() manipulate the process
114 * environment in a not thread-safe way, and may interfere with getenv()
115 * calls in other threads. Note that getenv() calls may be hidden behind
116 * other APIs. For example, GNU gettext() calls getenv() under the
117 * covers. In general, it is best to treat the environment as readonly.
118 * If you absolutely have to modify the environment, do it early in
119 * main(), when no other threads are around yet.
121 * - The setlocale() function changes the locale for the entire process,
122 * affecting all threads. Temporary changes to the locale are often made
123 * to change the behavior of string scanning or formatting functions
124 * like scanf() or printf(). GLib offers a number of string APIs
125 * (like g_ascii_formatd() or g_ascii_strtod()) that can often be
126 * used as an alternative. Or you can use the uselocale() function
127 * to change the locale only for the current thread.
129 * - The fork() function only takes the calling thread into the child's
130 * copy of the process image. If other threads were executing in critical
131 * sections they could have left mutexes locked which could easily
132 * cause deadlocks in the new child. For this reason, you should
133 * call exit() or exec() as soon as possible in the child and only
134 * make signal-safe library calls before that.
136 * - The daemon() function uses fork() in a way contrary to what is
137 * described above. It should not be used with GLib programs.
139 * GLib itself is internally completely thread-safe (all global data is
140 * automatically locked), but individual data structure instances are
141 * not automatically locked for performance reasons. For example,
142 * you must coordinate accesses to the same #GHashTable from multiple
143 * threads. The two notable exceptions from this rule are #GMainLoop
144 * and #GAsyncQueue, which are thread-safe and need no further
145 * application-level locking to be accessed from multiple threads.
146 * Most refcounting functions such as g_object_ref() are also thread-safe.
148 * A common use for #GThreads is to move a long-running blocking operation out
149 * of the main thread and into a worker thread. For GLib functions, such as
150 * single GIO operations, this is not necessary, and complicates the code.
151 * Instead, the `…_async()` version of the function should be used from the main
152 * thread, eliminating the need for locking and synchronisation between multiple
153 * threads. If an operation does need to be moved to a worker thread, consider
154 * using g_task_run_in_thread(), or a #GThreadPool. #GThreadPool is often a
155 * better choice than #GThread, as it handles thread reuse and task queueing;
156 * #GTask uses this internally.
158 * However, if multiple blocking operations need to be performed in sequence,
159 * and it is not possible to use #GTask for them, moving them to a worker thread
160 * can clarify the code.
163 /* G_LOCK Documentation {{{1 ---------------------------------------------- */
167 * @name: the name of the lock
169 * The `G_LOCK_` macros provide a convenient interface to #GMutex.
170 * %G_LOCK_DEFINE defines a lock. It can appear in any place where
171 * variable definitions may appear in programs, i.e. in the first block
172 * of a function or outside of functions. The @name parameter will be
173 * mangled to get the name of the #GMutex. This means that you
174 * can use names of existing variables as the parameter - e.g. the name
175 * of the variable you intend to protect with the lock. Look at our
176 * give_me_next_number() example using the `G_LOCK` macros:
178 * Here is an example for using the `G_LOCK` convenience macros:
180 * |[<!-- language="C" -->
181 * G_LOCK_DEFINE (current_number);
184 * give_me_next_number (void)
186 * static int current_number = 0;
189 * G_LOCK (current_number);
190 * ret_val = current_number = calc_next_number (current_number);
191 * G_UNLOCK (current_number);
199 * G_LOCK_DEFINE_STATIC:
200 * @name: the name of the lock
202 * This works like %G_LOCK_DEFINE, but it creates a static object.
207 * @name: the name of the lock
209 * This declares a lock, that is defined with %G_LOCK_DEFINE in another
215 * @name: the name of the lock
217 * Works like g_mutex_lock(), but for a lock defined with
223 * @name: the name of the lock
225 * Works like g_mutex_trylock(), but for a lock defined with
228 * Returns: %TRUE, if the lock could be locked.
233 * @name: the name of the lock
235 * Works like g_mutex_unlock(), but for a lock defined with
239 /* GMutex Documentation {{{1 ------------------------------------------ */
244 * The #GMutex struct is an opaque data structure to represent a mutex
245 * (mutual exclusion). It can be used to protect data against shared
248 * Take for example the following function:
249 * |[<!-- language="C" -->
251 * give_me_next_number (void)
253 * static int current_number = 0;
255 * // now do a very complicated calculation to calculate the new
256 * // number, this might for example be a random number generator
257 * current_number = calc_next_number (current_number);
259 * return current_number;
262 * It is easy to see that this won't work in a multi-threaded
263 * application. There current_number must be protected against shared
264 * access. A #GMutex can be used as a solution to this problem:
265 * |[<!-- language="C" -->
267 * give_me_next_number (void)
269 * static GMutex mutex;
270 * static int current_number = 0;
273 * g_mutex_lock (&mutex);
274 * ret_val = current_number = calc_next_number (current_number);
275 * g_mutex_unlock (&mutex);
280 * Notice that the #GMutex is not initialised to any particular value.
281 * Its placement in static storage ensures that it will be initialised
282 * to all-zeros, which is appropriate.
284 * If a #GMutex is placed in other contexts (eg: embedded in a struct)
285 * then it must be explicitly initialised using g_mutex_init().
287 * A #GMutex should only be accessed via g_mutex_ functions.
290 /* GRecMutex Documentation {{{1 -------------------------------------- */
295 * The GRecMutex struct is an opaque data structure to represent a
296 * recursive mutex. It is similar to a #GMutex with the difference
297 * that it is possible to lock a GRecMutex multiple times in the same
298 * thread without deadlock. When doing so, care has to be taken to
299 * unlock the recursive mutex as often as it has been locked.
301 * If a #GRecMutex is allocated in static storage then it can be used
302 * without initialisation. Otherwise, you should call
303 * g_rec_mutex_init() on it and g_rec_mutex_clear() when done.
305 * A GRecMutex should only be accessed with the
306 * g_rec_mutex_ functions.
311 /* GRWLock Documentation {{{1 ---------------------------------------- */
316 * The GRWLock struct is an opaque data structure to represent a
317 * reader-writer lock. It is similar to a #GMutex in that it allows
318 * multiple threads to coordinate access to a shared resource.
320 * The difference to a mutex is that a reader-writer lock discriminates
321 * between read-only ('reader') and full ('writer') access. While only
322 * one thread at a time is allowed write access (by holding the 'writer'
323 * lock via g_rw_lock_writer_lock()), multiple threads can gain
324 * simultaneous read-only access (by holding the 'reader' lock via
325 * g_rw_lock_reader_lock()).
327 * It is unspecified whether readers or writers have priority in acquiring the
328 * lock when a reader already holds the lock and a writer is queued to acquire
331 * Here is an example for an array with access functions:
332 * |[<!-- language="C" -->
337 * my_array_get (guint index)
339 * gpointer retval = NULL;
344 * g_rw_lock_reader_lock (&lock);
345 * if (index < array->len)
346 * retval = g_ptr_array_index (array, index);
347 * g_rw_lock_reader_unlock (&lock);
353 * my_array_set (guint index, gpointer data)
355 * g_rw_lock_writer_lock (&lock);
358 * array = g_ptr_array_new ();
360 * if (index >= array->len)
361 * g_ptr_array_set_size (array, index+1);
362 * g_ptr_array_index (array, index) = data;
364 * g_rw_lock_writer_unlock (&lock);
367 * This example shows an array which can be accessed by many readers
368 * (the my_array_get() function) simultaneously, whereas the writers
369 * (the my_array_set() function) will only be allowed one at a time
370 * and only if no readers currently access the array. This is because
371 * of the potentially dangerous resizing of the array. Using these
372 * functions is fully multi-thread safe now.
374 * If a #GRWLock is allocated in static storage then it can be used
375 * without initialisation. Otherwise, you should call
376 * g_rw_lock_init() on it and g_rw_lock_clear() when done.
378 * A GRWLock should only be accessed with the g_rw_lock_ functions.
383 /* GCond Documentation {{{1 ------------------------------------------ */
388 * The #GCond struct is an opaque data structure that represents a
389 * condition. Threads can block on a #GCond if they find a certain
390 * condition to be false. If other threads change the state of this
391 * condition they signal the #GCond, and that causes the waiting
392 * threads to be woken up.
394 * Consider the following example of a shared variable. One or more
395 * threads can wait for data to be published to the variable and when
396 * another thread publishes the data, it can signal one of the waiting
397 * threads to wake up to collect the data.
399 * Here is an example for using GCond to block a thread until a condition
401 * |[<!-- language="C" -->
402 * gpointer current_data = NULL;
407 * push_data (gpointer data)
409 * g_mutex_lock (&data_mutex);
410 * current_data = data;
411 * g_cond_signal (&data_cond);
412 * g_mutex_unlock (&data_mutex);
420 * g_mutex_lock (&data_mutex);
421 * while (!current_data)
422 * g_cond_wait (&data_cond, &data_mutex);
423 * data = current_data;
424 * current_data = NULL;
425 * g_mutex_unlock (&data_mutex);
430 * Whenever a thread calls pop_data() now, it will wait until
431 * current_data is non-%NULL, i.e. until some other thread
432 * has called push_data().
434 * The example shows that use of a condition variable must always be
435 * paired with a mutex. Without the use of a mutex, there would be a
436 * race between the check of @current_data by the while loop in
437 * pop_data() and waiting. Specifically, another thread could set
438 * @current_data after the check, and signal the cond (with nobody
439 * waiting on it) before the first thread goes to sleep. #GCond is
440 * specifically useful for its ability to release the mutex and go
441 * to sleep atomically.
443 * It is also important to use the g_cond_wait() and g_cond_wait_until()
444 * functions only inside a loop which checks for the condition to be
445 * true. See g_cond_wait() for an explanation of why the condition may
446 * not be true even after it returns.
448 * If a #GCond is allocated in static storage then it can be used
449 * without initialisation. Otherwise, you should call g_cond_init()
450 * on it and g_cond_clear() when done.
452 * A #GCond should only be accessed via the g_cond_ functions.
455 /* GThread Documentation {{{1 ---------------------------------------- */
460 * The #GThread struct represents a running thread. This struct
461 * is returned by g_thread_new() or g_thread_try_new(). You can
462 * obtain the #GThread struct representing the current thread by
463 * calling g_thread_self().
465 * GThread is refcounted, see g_thread_ref() and g_thread_unref().
466 * The thread represented by it holds a reference while it is running,
467 * and g_thread_join() consumes the reference that it is given, so
468 * it is normally not necessary to manage GThread references
471 * The structure is opaque -- none of its fields may be directly
477 * @data: data passed to the thread
479 * Specifies the type of the @func functions passed to g_thread_new()
480 * or g_thread_try_new().
482 * Returns: the return value of the thread
486 * g_thread_supported:
488 * This macro returns %TRUE if the thread system is initialized,
489 * and %FALSE if it is not.
491 * For language bindings, g_thread_get_initialized() provides
492 * the same functionality as a function.
494 * Returns: %TRUE, if the thread system is initialized
497 /* GThreadError {{{1 ------------------------------------------------------- */
500 * @G_THREAD_ERROR_AGAIN: a thread couldn't be created due to resource
501 * shortage. Try again later.
503 * Possible errors of thread related functions.
509 * The error domain of the GLib thread subsystem.
511 G_DEFINE_QUARK (g_thread_error, g_thread_error)
513 /* Local Data {{{1 -------------------------------------------------------- */
515 static GMutex g_once_mutex;
516 static GCond g_once_cond;
517 static GSList *g_once_init_list = NULL;
519 static guint g_thread_n_created_counter = 0; /* (atomic) */
521 static void g_thread_cleanup (gpointer data);
522 static GPrivate g_thread_specific_private = G_PRIVATE_INIT (g_thread_cleanup);
525 * g_private_set_alloc0:
527 * @size: size of the allocation, in bytes
529 * Sets the thread local variable @key to have a newly-allocated and zero-filled
530 * value of given @size, and returns a pointer to that memory. Allocations made
531 * using this API will be suppressed in valgrind: it is intended to be used for
532 * one-time allocations which are known to be leaked, such as those for
533 * per-thread initialisation data. Otherwise, this function behaves the same as
536 * Returns: (transfer full): new thread-local heap allocation of size @size
541 g_private_set_alloc0 (GPrivate *key,
544 gpointer allocated = g_malloc0 (size);
546 g_private_set (key, allocated);
548 return g_steal_pointer (&allocated);
551 /* GOnce {{{1 ------------------------------------------------------------- */
555 * @status: the status of the #GOnce
556 * @retval: the value returned by the call to the function, if @status
557 * is %G_ONCE_STATUS_READY
559 * A #GOnce struct controls a one-time initialization function. Any
560 * one-time initialization function must have its own unique #GOnce
569 * A #GOnce must be initialized with this macro before it can be used.
571 * |[<!-- language="C" -->
572 * GOnce my_once = G_ONCE_INIT;
580 * @G_ONCE_STATUS_NOTCALLED: the function has not been called yet.
581 * @G_ONCE_STATUS_PROGRESS: the function call is currently in progress.
582 * @G_ONCE_STATUS_READY: the function has been called.
584 * The possible statuses of a one-time initialization function
585 * controlled by a #GOnce struct.
592 * @once: a #GOnce structure
593 * @func: the #GThreadFunc function associated to @once. This function
594 * is called only once, regardless of the number of times it and
595 * its associated #GOnce struct are passed to g_once().
596 * @arg: data to be passed to @func
598 * The first call to this routine by a process with a given #GOnce
599 * struct calls @func with the given argument. Thereafter, subsequent
600 * calls to g_once() with the same #GOnce struct do not call @func
601 * again, but return the stored result of the first call. On return
602 * from g_once(), the status of @once will be %G_ONCE_STATUS_READY.
604 * For example, a mutex or a thread-specific data key must be created
605 * exactly once. In a threaded environment, calling g_once() ensures
606 * that the initialization is serialized across multiple threads.
608 * Calling g_once() recursively on the same #GOnce struct in
609 * @func will lead to a deadlock.
611 * |[<!-- language="C" -->
613 * get_debug_flags (void)
615 * static GOnce my_once = G_ONCE_INIT;
617 * g_once (&my_once, parse_debug_flags, NULL);
619 * return my_once.retval;
626 g_once_impl (GOnce *once,
630 g_mutex_lock (&g_once_mutex);
632 while (once->status == G_ONCE_STATUS_PROGRESS)
633 g_cond_wait (&g_once_cond, &g_once_mutex);
635 if (once->status != G_ONCE_STATUS_READY)
639 once->status = G_ONCE_STATUS_PROGRESS;
640 g_mutex_unlock (&g_once_mutex);
644 g_mutex_lock (&g_once_mutex);
645 /* We prefer the new C11-style atomic extension of GCC if available. If not,
646 * fall back to always locking. */
647 #if defined(G_ATOMIC_LOCK_FREE) && defined(__GCC_HAVE_SYNC_COMPARE_AND_SWAP_4) && defined(__ATOMIC_SEQ_CST)
648 /* Only the second store needs to be atomic, as the two writes are related
649 * by a happens-before relationship here. */
650 once->retval = retval;
651 __atomic_store_n (&once->status, G_ONCE_STATUS_READY, __ATOMIC_RELEASE);
653 once->retval = retval;
654 once->status = G_ONCE_STATUS_READY;
656 g_cond_broadcast (&g_once_cond);
659 g_mutex_unlock (&g_once_mutex);
666 * @location: (not nullable): location of a static initializable variable
669 * Function to be called when starting a critical initialization
670 * section. The argument @location must point to a static
671 * 0-initialized variable that will be set to a value other than 0 at
672 * the end of the initialization section. In combination with
673 * g_once_init_leave() and the unique address @value_location, it can
674 * be ensured that an initialization section will be executed only once
675 * during a program's life time, and that concurrent threads are
676 * blocked until initialization completed. To be used in constructs
679 * |[<!-- language="C" -->
680 * static gsize initialization_value = 0;
682 * if (g_once_init_enter (&initialization_value))
684 * gsize setup_value = 42; // initialization code here
686 * g_once_init_leave (&initialization_value, setup_value);
689 * // use initialization_value here
692 * While @location has a `volatile` qualifier, this is a historical artifact and
693 * the pointer passed to it should not be `volatile`.
695 * Returns: %TRUE if the initialization section should be entered,
696 * %FALSE and blocks otherwise
701 (g_once_init_enter) (volatile void *location)
703 gsize *value_location = (gsize *) location;
704 gboolean need_init = FALSE;
705 g_mutex_lock (&g_once_mutex);
706 if (g_atomic_pointer_get (value_location) == 0)
708 if (!g_slist_find (g_once_init_list, (void*) value_location))
711 g_once_init_list = g_slist_prepend (g_once_init_list, (void*) value_location);
715 g_cond_wait (&g_once_cond, &g_once_mutex);
716 while (g_slist_find (g_once_init_list, (void*) value_location));
718 g_mutex_unlock (&g_once_mutex);
724 * @location: (not nullable): location of a static initializable variable
726 * @result: new non-0 value for *@value_location
728 * Counterpart to g_once_init_enter(). Expects a location of a static
729 * 0-initialized initialization variable, and an initialization value
730 * other than 0. Sets the variable to the initialization value, and
731 * releases concurrent threads blocking in g_once_init_enter() on this
732 * initialization variable.
734 * While @location has a `volatile` qualifier, this is a historical artifact and
735 * the pointer passed to it should not be `volatile`.
740 (g_once_init_leave) (volatile void *location,
743 gsize *value_location = (gsize *) location;
746 g_return_if_fail (result != 0);
748 old_value = (gsize) g_atomic_pointer_exchange (value_location, result);
749 g_return_if_fail (old_value == 0);
751 g_mutex_lock (&g_once_mutex);
752 g_return_if_fail (g_once_init_list != NULL);
753 g_once_init_list = g_slist_remove (g_once_init_list, (void*) value_location);
754 g_cond_broadcast (&g_once_cond);
755 g_mutex_unlock (&g_once_mutex);
758 /* GThread {{{1 -------------------------------------------------------- */
762 * @thread: a #GThread
764 * Increase the reference count on @thread.
766 * Returns: (transfer full): a new reference to @thread
771 g_thread_ref (GThread *thread)
773 GRealThread *real = (GRealThread *) thread;
775 g_atomic_int_inc (&real->ref_count);
782 * @thread: (transfer full): a #GThread
784 * Decrease the reference count on @thread, possibly freeing all
785 * resources associated with it.
787 * Note that each thread holds a reference to its #GThread while
788 * it is running, so it is safe to drop your own reference to it
789 * if you don't need it anymore.
794 g_thread_unref (GThread *thread)
796 GRealThread *real = (GRealThread *) thread;
798 if (g_atomic_int_dec_and_test (&real->ref_count))
801 g_system_thread_free (real);
803 g_slice_free (GRealThread, real);
808 g_thread_cleanup (gpointer data)
810 g_thread_unref (data);
814 g_thread_proxy (gpointer data)
816 GRealThread* thread = data;
819 g_private_set (&g_thread_specific_private, data);
821 TRACE (GLIB_THREAD_SPAWNED (thread->thread.func, thread->thread.data,
826 g_system_thread_set_name (thread->name);
827 g_free (thread->name);
831 thread->retval = thread->thread.func (thread->thread.data);
837 g_thread_n_created (void)
839 return g_atomic_int_get (&g_thread_n_created_counter);
844 * @name: (nullable): an (optional) name for the new thread
845 * @func: (closure data) (scope async): a function to execute in the new thread
846 * @data: (nullable): an argument to supply to the new thread
848 * This function creates a new thread. The new thread starts by invoking
849 * @func with the argument data. The thread will run until @func returns
850 * or until g_thread_exit() is called from the new thread. The return value
851 * of @func becomes the return value of the thread, which can be obtained
852 * with g_thread_join().
854 * The @name can be useful for discriminating threads in a debugger.
855 * It is not used for other purposes and does not have to be unique.
856 * Some systems restrict the length of @name to 16 bytes.
858 * If the thread can not be created the program aborts. See
859 * g_thread_try_new() if you want to attempt to deal with failures.
861 * If you are using threads to offload (potentially many) short-lived tasks,
862 * #GThreadPool may be more appropriate than manually spawning and tracking
863 * multiple #GThreads.
865 * To free the struct returned by this function, use g_thread_unref().
866 * Note that g_thread_join() implicitly unrefs the #GThread as well.
868 * New threads by default inherit their scheduler policy (POSIX) or thread
869 * priority (Windows) of the thread creating the new thread.
871 * This behaviour changed in GLib 2.64: before threads on Windows were not
872 * inheriting the thread priority but were spawned with the default priority.
873 * Starting with GLib 2.64 the behaviour is now consistent between Windows and
874 * POSIX and all threads inherit their parent thread's priority.
876 * Returns: (transfer full): the new #GThread
881 g_thread_new (const gchar *name,
885 GError *error = NULL;
888 thread = g_thread_new_internal (name, g_thread_proxy, func, data, 0, &error);
890 if G_UNLIKELY (thread == NULL)
891 g_error ("creating thread '%s': %s", name ? name : "", error->message);
898 * @name: (nullable): an (optional) name for the new thread
899 * @func: (closure data) (scope async): a function to execute in the new thread
900 * @data: (nullable): an argument to supply to the new thread
901 * @error: return location for error, or %NULL
903 * This function is the same as g_thread_new() except that
904 * it allows for the possibility of failure.
906 * If a thread can not be created (due to resource limits),
907 * @error is set and %NULL is returned.
909 * Returns: (transfer full): the new #GThread, or %NULL if an error occurred
914 g_thread_try_new (const gchar *name,
919 return g_thread_new_internal (name, g_thread_proxy, func, data, 0, error);
923 g_thread_new_internal (const gchar *name,
930 g_return_val_if_fail (func != NULL, NULL);
932 g_atomic_int_inc (&g_thread_n_created_counter);
934 g_trace_mark (G_TRACE_CURRENT_TIME, 0, "GLib", "GThread created", "%s", name ? name : "(unnamed)");
935 return (GThread *) g_system_thread_new (proxy, stack_size, name, func, data, error);
940 * @retval: the return value of this thread
942 * Terminates the current thread.
944 * If another thread is waiting for us using g_thread_join() then the
945 * waiting thread will be woken up and get @retval as the return value
946 * of g_thread_join().
948 * Calling g_thread_exit() with a parameter @retval is equivalent to
949 * returning @retval from the function @func, as given to g_thread_new().
951 * You must only call g_thread_exit() from a thread that you created
952 * yourself with g_thread_new() or related APIs. You must not call
953 * this function from a thread created with another threading library
954 * or or from within a #GThreadPool.
957 g_thread_exit (gpointer retval)
959 GRealThread* real = (GRealThread*) g_thread_self ();
961 if G_UNLIKELY (!real->ours)
962 g_error ("attempt to g_thread_exit() a thread not created by GLib");
964 real->retval = retval;
966 g_system_thread_exit ();
971 * @thread: (transfer full): a #GThread
973 * Waits until @thread finishes, i.e. the function @func, as
974 * given to g_thread_new(), returns or g_thread_exit() is called.
975 * If @thread has already terminated, then g_thread_join()
976 * returns immediately.
978 * Any thread can wait for any other thread by calling g_thread_join(),
979 * not just its 'creator'. Calling g_thread_join() from multiple threads
980 * for the same @thread leads to undefined behaviour.
982 * The value returned by @func or given to g_thread_exit() is
983 * returned by this function.
985 * g_thread_join() consumes the reference to the passed-in @thread.
986 * This will usually cause the #GThread struct and associated resources
987 * to be freed. Use g_thread_ref() to obtain an extra reference if you
988 * want to keep the GThread alive beyond the g_thread_join() call.
990 * Returns: (transfer full): the return value of the thread
993 g_thread_join (GThread *thread)
995 GRealThread *real = (GRealThread*) thread;
998 g_return_val_if_fail (thread, NULL);
999 g_return_val_if_fail (real->ours, NULL);
1001 g_system_thread_wait (real);
1003 retval = real->retval;
1005 /* Just to make sure, this isn't used any more */
1006 thread->joinable = 0;
1008 g_thread_unref (thread);
1016 * This function returns the #GThread corresponding to the
1017 * current thread. Note that this function does not increase
1018 * the reference count of the returned struct.
1020 * This function will return a #GThread even for threads that
1021 * were not created by GLib (i.e. those created by other threading
1022 * APIs). This may be useful for thread identification purposes
1023 * (i.e. comparisons) but you must not use GLib functions (such
1024 * as g_thread_join()) on these threads.
1026 * Returns: (transfer none): the #GThread representing the current thread
1029 g_thread_self (void)
1031 GRealThread* thread = g_private_get (&g_thread_specific_private);
1035 /* If no thread data is available, provide and set one.
1036 * This can happen for the main thread and for threads
1037 * that are not created by GLib.
1039 thread = g_slice_new0 (GRealThread);
1040 thread->ref_count = 1;
1042 g_private_set (&g_thread_specific_private, thread);
1045 return (GThread*) thread;
1049 * g_get_num_processors:
1051 * Determine the approximate number of threads that the system will
1052 * schedule simultaneously for this process. This is intended to be
1053 * used as a parameter to g_thread_pool_new() for CPU bound tasks and
1056 * Returns: Number of schedulable threads, always greater than 0
1061 g_get_num_processors (void)
1065 SYSTEM_INFO sysinfo;
1066 DWORD_PTR process_cpus;
1067 DWORD_PTR system_cpus;
1069 /* This *never* fails, use it as fallback */
1070 GetNativeSystemInfo (&sysinfo);
1071 count = (int) sysinfo.dwNumberOfProcessors;
1073 if (GetProcessAffinityMask (GetCurrentProcess (),
1074 &process_cpus, &system_cpus))
1076 unsigned int af_count;
1078 for (af_count = 0; process_cpus != 0; process_cpus >>= 1)
1079 if (process_cpus & 1)
1082 /* Prefer affinity-based result, if available */
1089 #elif defined(_SC_NPROCESSORS_ONLN)
1093 count = sysconf (_SC_NPROCESSORS_ONLN);
1097 #elif defined HW_NCPU
1099 int mib[2], count = 0;
1104 len = sizeof(count);
1106 if (sysctl (mib, 2, &count, &len, NULL, 0) == 0 && count > 0)
1111 return 1; /* Fallback */
1115 /* vim: set foldmethod=marker: */