Update German translation
[glib.git] / glib / gthread.c
blobfdb367398ec1c1e8a2543ce64eaf4454a9b9b8e5
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
6 * Owen Taylor
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 of the License, or (at your option) any later version.
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.
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/>.
22 /* Prelude {{{1 ----------------------------------------------------------- */
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/.
32 * MT safe
35 /* implement gthread.h's inline functions */
36 #define G_IMPLEMENT_INLINES 1
37 #define __G_THREAD_C__
39 #include "config.h"
41 #include "gthread.h"
42 #include "gthreadprivate.h"
44 #include <string.h>
46 #ifdef G_OS_UNIX
47 #include <unistd.h>
48 #endif
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 */
57 #include "gslice.h"
58 #include "gstrfuncs.h"
59 #include "gtestutils.h"
60 #include "glib_trace.h"
62 /**
63 * SECTION:threads
64 * @title: Threads
65 * @short_description: portable support for threads, mutexes, locks,
66 * conditions and thread private data
67 * @see_also: #GThreadPool, #GAsyncQueue
69 * Threads act almost like processes, but unlike processes all threads
70 * of one process share the same memory. This is good, as it provides
71 * easy communication between the involved threads via this shared
72 * memory, and it is bad, because strange things (so called
73 * "Heisenbugs") might happen if the program is not carefully designed.
74 * In particular, due to the concurrent nature of threads, no
75 * assumptions on the order of execution of code running in different
76 * threads can be made, unless order is explicitly forced by the
77 * programmer through synchronization primitives.
79 * The aim of the thread-related functions in GLib is to provide a
80 * portable means for writing multi-threaded software. There are
81 * primitives for mutexes to protect the access to portions of memory
82 * (#GMutex, #GRecMutex and #GRWLock). There is a facility to use
83 * individual bits for locks (g_bit_lock()). There are primitives
84 * for condition variables to allow synchronization of threads (#GCond).
85 * There are primitives for thread-private data - data that every
86 * thread has a private instance of (#GPrivate). There are facilities
87 * for one-time initialization (#GOnce, g_once_init_enter()). Finally,
88 * there are primitives to create and manage threads (#GThread).
90 * The GLib threading system used to be initialized with g_thread_init().
91 * This is no longer necessary. Since version 2.32, the GLib threading
92 * system is automatically initialized at the start of your program,
93 * and all thread-creation functions and synchronization primitives
94 * are available right away.
96 * Note that it is not safe to assume that your program has no threads
97 * even if you don't call g_thread_new() yourself. GLib and GIO can
98 * and will create threads for their own purposes in some cases, such
99 * as when using g_unix_signal_source_new() or when using GDBus.
101 * Originally, UNIX did not have threads, and therefore some traditional
102 * UNIX APIs are problematic in threaded programs. Some notable examples
103 * are
105 * - C library functions that return data in statically allocated
106 * buffers, such as strtok() or strerror(). For many of these,
107 * there are thread-safe variants with a _r suffix, or you can
108 * look at corresponding GLib APIs (like g_strsplit() or g_strerror()).
110 * - The functions setenv() and unsetenv() manipulate the process
111 * environment in a not thread-safe way, and may interfere with getenv()
112 * calls in other threads. Note that getenv() calls may be hidden behind
113 * other APIs. For example, GNU gettext() calls getenv() under the
114 * covers. In general, it is best to treat the environment as readonly.
115 * If you absolutely have to modify the environment, do it early in
116 * main(), when no other threads are around yet.
118 * - The setlocale() function changes the locale for the entire process,
119 * affecting all threads. Temporary changes to the locale are often made
120 * to change the behavior of string scanning or formatting functions
121 * like scanf() or printf(). GLib offers a number of string APIs
122 * (like g_ascii_formatd() or g_ascii_strtod()) that can often be
123 * used as an alternative. Or you can use the uselocale() function
124 * to change the locale only for the current thread.
126 * - The fork() function only takes the calling thread into the child's
127 * copy of the process image. If other threads were executing in critical
128 * sections they could have left mutexes locked which could easily
129 * cause deadlocks in the new child. For this reason, you should
130 * call exit() or exec() as soon as possible in the child and only
131 * make signal-safe library calls before that.
133 * - The daemon() function uses fork() in a way contrary to what is
134 * described above. It should not be used with GLib programs.
136 * GLib itself is internally completely thread-safe (all global data is
137 * automatically locked), but individual data structure instances are
138 * not automatically locked for performance reasons. For example,
139 * you must coordinate accesses to the same #GHashTable from multiple
140 * threads. The two notable exceptions from this rule are #GMainLoop
141 * and #GAsyncQueue, which are thread-safe and need no further
142 * application-level locking to be accessed from multiple threads.
143 * Most refcounting functions such as g_object_ref() are also thread-safe.
145 * A common use for #GThreads is to move a long-running blocking operation out
146 * of the main thread and into a worker thread. For GLib functions, such as
147 * single GIO operations, this is not necessary, and complicates the code.
148 * Instead, the `…_async()` version of the function should be used from the main
149 * thread, eliminating the need for locking and synchronisation between multiple
150 * threads. If an operation does need to be moved to a worker thread, consider
151 * using g_task_run_in_thread(), or a #GThreadPool. #GThreadPool is often a
152 * better choice than #GThread, as it handles thread reuse and task queueing;
153 * #GTask uses this internally.
155 * However, if multiple blocking operations need to be performed in sequence,
156 * and it is not possible to use #GTask for them, moving them to a worker thread
157 * can clarify the code.
160 /* G_LOCK Documentation {{{1 ---------------------------------------------- */
163 * G_LOCK_DEFINE:
164 * @name: the name of the lock
166 * The #G_LOCK_ macros provide a convenient interface to #GMutex.
167 * #G_LOCK_DEFINE defines a lock. It can appear in any place where
168 * variable definitions may appear in programs, i.e. in the first block
169 * of a function or outside of functions. The @name parameter will be
170 * mangled to get the name of the #GMutex. This means that you
171 * can use names of existing variables as the parameter - e.g. the name
172 * of the variable you intend to protect with the lock. Look at our
173 * give_me_next_number() example using the #G_LOCK macros:
175 * Here is an example for using the #G_LOCK convenience macros:
176 * |[<!-- language="C" -->
177 * G_LOCK_DEFINE (current_number);
179 * int
180 * give_me_next_number (void)
182 * static int current_number = 0;
183 * int ret_val;
185 * G_LOCK (current_number);
186 * ret_val = current_number = calc_next_number (current_number);
187 * G_UNLOCK (current_number);
189 * return ret_val;
191 * ]|
195 * G_LOCK_DEFINE_STATIC:
196 * @name: the name of the lock
198 * This works like #G_LOCK_DEFINE, but it creates a static object.
202 * G_LOCK_EXTERN:
203 * @name: the name of the lock
205 * This declares a lock, that is defined with #G_LOCK_DEFINE in another
206 * module.
210 * G_LOCK:
211 * @name: the name of the lock
213 * Works like g_mutex_lock(), but for a lock defined with
214 * #G_LOCK_DEFINE.
218 * G_TRYLOCK:
219 * @name: the name of the lock
221 * Works like g_mutex_trylock(), but for a lock defined with
222 * #G_LOCK_DEFINE.
224 * Returns: %TRUE, if the lock could be locked.
228 * G_UNLOCK:
229 * @name: the name of the lock
231 * Works like g_mutex_unlock(), but for a lock defined with
232 * #G_LOCK_DEFINE.
235 /* GMutex Documentation {{{1 ------------------------------------------ */
238 * GMutex:
240 * The #GMutex struct is an opaque data structure to represent a mutex
241 * (mutual exclusion). It can be used to protect data against shared
242 * access.
244 * Take for example the following function:
245 * |[<!-- language="C" -->
246 * int
247 * give_me_next_number (void)
249 * static int current_number = 0;
251 * // now do a very complicated calculation to calculate the new
252 * // number, this might for example be a random number generator
253 * current_number = calc_next_number (current_number);
255 * return current_number;
257 * ]|
258 * It is easy to see that this won't work in a multi-threaded
259 * application. There current_number must be protected against shared
260 * access. A #GMutex can be used as a solution to this problem:
261 * |[<!-- language="C" -->
262 * int
263 * give_me_next_number (void)
265 * static GMutex mutex;
266 * static int current_number = 0;
267 * int ret_val;
269 * g_mutex_lock (&mutex);
270 * ret_val = current_number = calc_next_number (current_number);
271 * g_mutex_unlock (&mutex);
273 * return ret_val;
275 * ]|
276 * Notice that the #GMutex is not initialised to any particular value.
277 * Its placement in static storage ensures that it will be initialised
278 * to all-zeros, which is appropriate.
280 * If a #GMutex is placed in other contexts (eg: embedded in a struct)
281 * then it must be explicitly initialised using g_mutex_init().
283 * A #GMutex should only be accessed via g_mutex_ functions.
286 /* GRecMutex Documentation {{{1 -------------------------------------- */
289 * GRecMutex:
291 * The GRecMutex struct is an opaque data structure to represent a
292 * recursive mutex. It is similar to a #GMutex with the difference
293 * that it is possible to lock a GRecMutex multiple times in the same
294 * thread without deadlock. When doing so, care has to be taken to
295 * unlock the recursive mutex as often as it has been locked.
297 * If a #GRecMutex is allocated in static storage then it can be used
298 * without initialisation. Otherwise, you should call
299 * g_rec_mutex_init() on it and g_rec_mutex_clear() when done.
301 * A GRecMutex should only be accessed with the
302 * g_rec_mutex_ functions.
304 * Since: 2.32
307 /* GRWLock Documentation {{{1 ---------------------------------------- */
310 * GRWLock:
312 * The GRWLock struct is an opaque data structure to represent a
313 * reader-writer lock. It is similar to a #GMutex in that it allows
314 * multiple threads to coordinate access to a shared resource.
316 * The difference to a mutex is that a reader-writer lock discriminates
317 * between read-only ('reader') and full ('writer') access. While only
318 * one thread at a time is allowed write access (by holding the 'writer'
319 * lock via g_rw_lock_writer_lock()), multiple threads can gain
320 * simultaneous read-only access (by holding the 'reader' lock via
321 * g_rw_lock_reader_lock()).
323 * Here is an example for an array with access functions:
324 * |[<!-- language="C" -->
325 * GRWLock lock;
326 * GPtrArray *array;
328 * gpointer
329 * my_array_get (guint index)
331 * gpointer retval = NULL;
333 * if (!array)
334 * return NULL;
336 * g_rw_lock_reader_lock (&lock);
337 * if (index < array->len)
338 * retval = g_ptr_array_index (array, index);
339 * g_rw_lock_reader_unlock (&lock);
341 * return retval;
344 * void
345 * my_array_set (guint index, gpointer data)
347 * g_rw_lock_writer_lock (&lock);
349 * if (!array)
350 * array = g_ptr_array_new ();
352 * if (index >= array->len)
353 * g_ptr_array_set_size (array, index+1);
354 * g_ptr_array_index (array, index) = data;
356 * g_rw_lock_writer_unlock (&lock);
358 * ]|
359 * This example shows an array which can be accessed by many readers
360 * (the my_array_get() function) simultaneously, whereas the writers
361 * (the my_array_set() function) will only be allowed one at a time
362 * and only if no readers currently access the array. This is because
363 * of the potentially dangerous resizing of the array. Using these
364 * functions is fully multi-thread safe now.
366 * If a #GRWLock is allocated in static storage then it can be used
367 * without initialisation. Otherwise, you should call
368 * g_rw_lock_init() on it and g_rw_lock_clear() when done.
370 * A GRWLock should only be accessed with the g_rw_lock_ functions.
372 * Since: 2.32
375 /* GCond Documentation {{{1 ------------------------------------------ */
378 * GCond:
380 * The #GCond struct is an opaque data structure that represents a
381 * condition. Threads can block on a #GCond if they find a certain
382 * condition to be false. If other threads change the state of this
383 * condition they signal the #GCond, and that causes the waiting
384 * threads to be woken up.
386 * Consider the following example of a shared variable. One or more
387 * threads can wait for data to be published to the variable and when
388 * another thread publishes the data, it can signal one of the waiting
389 * threads to wake up to collect the data.
391 * Here is an example for using GCond to block a thread until a condition
392 * is satisfied:
393 * |[<!-- language="C" -->
394 * gpointer current_data = NULL;
395 * GMutex data_mutex;
396 * GCond data_cond;
398 * void
399 * push_data (gpointer data)
401 * g_mutex_lock (&data_mutex);
402 * current_data = data;
403 * g_cond_signal (&data_cond);
404 * g_mutex_unlock (&data_mutex);
407 * gpointer
408 * pop_data (void)
410 * gpointer data;
412 * g_mutex_lock (&data_mutex);
413 * while (!current_data)
414 * g_cond_wait (&data_cond, &data_mutex);
415 * data = current_data;
416 * current_data = NULL;
417 * g_mutex_unlock (&data_mutex);
419 * return data;
421 * ]|
422 * Whenever a thread calls pop_data() now, it will wait until
423 * current_data is non-%NULL, i.e. until some other thread
424 * has called push_data().
426 * The example shows that use of a condition variable must always be
427 * paired with a mutex. Without the use of a mutex, there would be a
428 * race between the check of @current_data by the while loop in
429 * pop_data() and waiting. Specifically, another thread could set
430 * @current_data after the check, and signal the cond (with nobody
431 * waiting on it) before the first thread goes to sleep. #GCond is
432 * specifically useful for its ability to release the mutex and go
433 * to sleep atomically.
435 * It is also important to use the g_cond_wait() and g_cond_wait_until()
436 * functions only inside a loop which checks for the condition to be
437 * true. See g_cond_wait() for an explanation of why the condition may
438 * not be true even after it returns.
440 * If a #GCond is allocated in static storage then it can be used
441 * without initialisation. Otherwise, you should call g_cond_init()
442 * on it and g_cond_clear() when done.
444 * A #GCond should only be accessed via the g_cond_ functions.
447 /* GThread Documentation {{{1 ---------------------------------------- */
450 * GThread:
452 * The #GThread struct represents a running thread. This struct
453 * is returned by g_thread_new() or g_thread_try_new(). You can
454 * obtain the #GThread struct representing the current thread by
455 * calling g_thread_self().
457 * GThread is refcounted, see g_thread_ref() and g_thread_unref().
458 * The thread represented by it holds a reference while it is running,
459 * and g_thread_join() consumes the reference that it is given, so
460 * it is normally not necessary to manage GThread references
461 * explicitly.
463 * The structure is opaque -- none of its fields may be directly
464 * accessed.
468 * GThreadFunc:
469 * @data: data passed to the thread
471 * Specifies the type of the @func functions passed to g_thread_new()
472 * or g_thread_try_new().
474 * Returns: the return value of the thread
478 * g_thread_supported:
480 * This macro returns %TRUE if the thread system is initialized,
481 * and %FALSE if it is not.
483 * For language bindings, g_thread_get_initialized() provides
484 * the same functionality as a function.
486 * Returns: %TRUE, if the thread system is initialized
489 /* GThreadError {{{1 ------------------------------------------------------- */
491 * GThreadError:
492 * @G_THREAD_ERROR_AGAIN: a thread couldn't be created due to resource
493 * shortage. Try again later.
495 * Possible errors of thread related functions.
499 * G_THREAD_ERROR:
501 * The error domain of the GLib thread subsystem.
503 G_DEFINE_QUARK (g_thread_error, g_thread_error)
505 /* Local Data {{{1 -------------------------------------------------------- */
507 static GMutex g_once_mutex;
508 static GCond g_once_cond;
509 static GSList *g_once_init_list = NULL;
511 static void g_thread_cleanup (gpointer data);
512 static GPrivate g_thread_specific_private = G_PRIVATE_INIT (g_thread_cleanup);
514 G_LOCK_DEFINE_STATIC (g_thread_new);
516 /* GOnce {{{1 ------------------------------------------------------------- */
519 * GOnce:
520 * @status: the status of the #GOnce
521 * @retval: the value returned by the call to the function, if @status
522 * is %G_ONCE_STATUS_READY
524 * A #GOnce struct controls a one-time initialization function. Any
525 * one-time initialization function must have its own unique #GOnce
526 * struct.
528 * Since: 2.4
532 * G_ONCE_INIT:
534 * A #GOnce must be initialized with this macro before it can be used.
536 * |[<!-- language="C" -->
537 * GOnce my_once = G_ONCE_INIT;
538 * ]|
540 * Since: 2.4
544 * GOnceStatus:
545 * @G_ONCE_STATUS_NOTCALLED: the function has not been called yet.
546 * @G_ONCE_STATUS_PROGRESS: the function call is currently in progress.
547 * @G_ONCE_STATUS_READY: the function has been called.
549 * The possible statuses of a one-time initialization function
550 * controlled by a #GOnce struct.
552 * Since: 2.4
556 * g_once:
557 * @once: a #GOnce structure
558 * @func: the #GThreadFunc function associated to @once. This function
559 * is called only once, regardless of the number of times it and
560 * its associated #GOnce struct are passed to g_once().
561 * @arg: data to be passed to @func
563 * The first call to this routine by a process with a given #GOnce
564 * struct calls @func with the given argument. Thereafter, subsequent
565 * calls to g_once() with the same #GOnce struct do not call @func
566 * again, but return the stored result of the first call. On return
567 * from g_once(), the status of @once will be %G_ONCE_STATUS_READY.
569 * For example, a mutex or a thread-specific data key must be created
570 * exactly once. In a threaded environment, calling g_once() ensures
571 * that the initialization is serialized across multiple threads.
573 * Calling g_once() recursively on the same #GOnce struct in
574 * @func will lead to a deadlock.
576 * |[<!-- language="C" -->
577 * gpointer
578 * get_debug_flags (void)
580 * static GOnce my_once = G_ONCE_INIT;
582 * g_once (&my_once, parse_debug_flags, NULL);
584 * return my_once.retval;
586 * ]|
588 * Since: 2.4
590 gpointer
591 g_once_impl (GOnce *once,
592 GThreadFunc func,
593 gpointer arg)
595 g_mutex_lock (&g_once_mutex);
597 while (once->status == G_ONCE_STATUS_PROGRESS)
598 g_cond_wait (&g_once_cond, &g_once_mutex);
600 if (once->status != G_ONCE_STATUS_READY)
602 once->status = G_ONCE_STATUS_PROGRESS;
603 g_mutex_unlock (&g_once_mutex);
605 once->retval = func (arg);
607 g_mutex_lock (&g_once_mutex);
608 once->status = G_ONCE_STATUS_READY;
609 g_cond_broadcast (&g_once_cond);
612 g_mutex_unlock (&g_once_mutex);
614 return once->retval;
618 * g_once_init_enter:
619 * @location: (not nullable): location of a static initializable variable
620 * containing 0
622 * Function to be called when starting a critical initialization
623 * section. The argument @location must point to a static
624 * 0-initialized variable that will be set to a value other than 0 at
625 * the end of the initialization section. In combination with
626 * g_once_init_leave() and the unique address @value_location, it can
627 * be ensured that an initialization section will be executed only once
628 * during a program's life time, and that concurrent threads are
629 * blocked until initialization completed. To be used in constructs
630 * like this:
632 * |[<!-- language="C" -->
633 * static gsize initialization_value = 0;
635 * if (g_once_init_enter (&initialization_value))
637 * gsize setup_value = 42; // initialization code here
639 * g_once_init_leave (&initialization_value, setup_value);
642 * // use initialization_value here
643 * ]|
645 * Returns: %TRUE if the initialization section should be entered,
646 * %FALSE and blocks otherwise
648 * Since: 2.14
650 gboolean
651 (g_once_init_enter) (volatile void *location)
653 volatile gsize *value_location = location;
654 gboolean need_init = FALSE;
655 g_mutex_lock (&g_once_mutex);
656 if (g_atomic_pointer_get (value_location) == NULL)
658 if (!g_slist_find (g_once_init_list, (void*) value_location))
660 need_init = TRUE;
661 g_once_init_list = g_slist_prepend (g_once_init_list, (void*) value_location);
663 else
665 g_cond_wait (&g_once_cond, &g_once_mutex);
666 while (g_slist_find (g_once_init_list, (void*) value_location));
668 g_mutex_unlock (&g_once_mutex);
669 return need_init;
673 * g_once_init_leave:
674 * @location: (not nullable): location of a static initializable variable
675 * containing 0
676 * @result: new non-0 value for *@value_location
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.
684 * Since: 2.14
686 void
687 (g_once_init_leave) (volatile void *location,
688 gsize result)
690 volatile gsize *value_location = location;
692 g_return_if_fail (g_atomic_pointer_get (value_location) == NULL);
693 g_return_if_fail (result != 0);
694 g_return_if_fail (g_once_init_list != NULL);
696 g_atomic_pointer_set (value_location, result);
697 g_mutex_lock (&g_once_mutex);
698 g_once_init_list = g_slist_remove (g_once_init_list, (void*) value_location);
699 g_cond_broadcast (&g_once_cond);
700 g_mutex_unlock (&g_once_mutex);
703 /* GThread {{{1 -------------------------------------------------------- */
706 * g_thread_ref:
707 * @thread: a #GThread
709 * Increase the reference count on @thread.
711 * Returns: a new reference to @thread
713 * Since: 2.32
715 GThread *
716 g_thread_ref (GThread *thread)
718 GRealThread *real = (GRealThread *) thread;
720 g_atomic_int_inc (&real->ref_count);
722 return thread;
726 * g_thread_unref:
727 * @thread: a #GThread
729 * Decrease the reference count on @thread, possibly freeing all
730 * resources associated with it.
732 * Note that each thread holds a reference to its #GThread while
733 * it is running, so it is safe to drop your own reference to it
734 * if you don't need it anymore.
736 * Since: 2.32
738 void
739 g_thread_unref (GThread *thread)
741 GRealThread *real = (GRealThread *) thread;
743 if (g_atomic_int_dec_and_test (&real->ref_count))
745 if (real->ours)
746 g_system_thread_free (real);
747 else
748 g_slice_free (GRealThread, real);
752 static void
753 g_thread_cleanup (gpointer data)
755 g_thread_unref (data);
758 gpointer
759 g_thread_proxy (gpointer data)
761 GRealThread* thread = data;
763 g_assert (data);
765 /* This has to happen before G_LOCK, as that might call g_thread_self */
766 g_private_set (&g_thread_specific_private, data);
768 /* The lock makes sure that g_thread_new_internal() has a chance to
769 * setup 'func' and 'data' before we make the call.
771 G_LOCK (g_thread_new);
772 G_UNLOCK (g_thread_new);
774 TRACE (GLIB_THREAD_SPAWNED (thread->thread.func, thread->thread.data,
775 thread->name));
777 if (thread->name)
779 g_system_thread_set_name (thread->name);
780 g_free (thread->name);
781 thread->name = NULL;
784 thread->retval = thread->thread.func (thread->thread.data);
786 return NULL;
790 * g_thread_new:
791 * @name: (nullable): an (optional) name for the new thread
792 * @func: a function to execute in the new thread
793 * @data: an argument to supply to the new thread
795 * This function creates a new thread. The new thread starts by invoking
796 * @func with the argument data. The thread will run until @func returns
797 * or until g_thread_exit() is called from the new thread. The return value
798 * of @func becomes the return value of the thread, which can be obtained
799 * with g_thread_join().
801 * The @name can be useful for discriminating threads in a debugger.
802 * It is not used for other purposes and does not have to be unique.
803 * Some systems restrict the length of @name to 16 bytes.
805 * If the thread can not be created the program aborts. See
806 * g_thread_try_new() if you want to attempt to deal with failures.
808 * If you are using threads to offload (potentially many) short-lived tasks,
809 * #GThreadPool may be more appropriate than manually spawning and tracking
810 * multiple #GThreads.
812 * To free the struct returned by this function, use g_thread_unref().
813 * Note that g_thread_join() implicitly unrefs the #GThread as well.
815 * Returns: the new #GThread
817 * Since: 2.32
819 GThread *
820 g_thread_new (const gchar *name,
821 GThreadFunc func,
822 gpointer data)
824 GError *error = NULL;
825 GThread *thread;
827 thread = g_thread_new_internal (name, g_thread_proxy, func, data, 0, &error);
829 if G_UNLIKELY (thread == NULL)
830 g_error ("creating thread '%s': %s", name ? name : "", error->message);
832 return thread;
836 * g_thread_try_new:
837 * @name: (nullable): an (optional) name for the new thread
838 * @func: a function to execute in the new thread
839 * @data: an argument to supply to the new thread
840 * @error: return location for error, or %NULL
842 * This function is the same as g_thread_new() except that
843 * it allows for the possibility of failure.
845 * If a thread can not be created (due to resource limits),
846 * @error is set and %NULL is returned.
848 * Returns: the new #GThread, or %NULL if an error occurred
850 * Since: 2.32
852 GThread *
853 g_thread_try_new (const gchar *name,
854 GThreadFunc func,
855 gpointer data,
856 GError **error)
858 return g_thread_new_internal (name, g_thread_proxy, func, data, 0, error);
861 GThread *
862 g_thread_new_internal (const gchar *name,
863 GThreadFunc proxy,
864 GThreadFunc func,
865 gpointer data,
866 gsize stack_size,
867 GError **error)
869 GRealThread *thread;
871 g_return_val_if_fail (func != NULL, NULL);
873 G_LOCK (g_thread_new);
874 thread = g_system_thread_new (proxy, stack_size, error);
875 if (thread)
877 thread->ref_count = 2;
878 thread->ours = TRUE;
879 thread->thread.joinable = TRUE;
880 thread->thread.func = func;
881 thread->thread.data = data;
882 thread->name = g_strdup (name);
884 G_UNLOCK (g_thread_new);
886 return (GThread*) thread;
890 * g_thread_exit:
891 * @retval: the return value of this thread
893 * Terminates the current thread.
895 * If another thread is waiting for us using g_thread_join() then the
896 * waiting thread will be woken up and get @retval as the return value
897 * of g_thread_join().
899 * Calling g_thread_exit() with a parameter @retval is equivalent to
900 * returning @retval from the function @func, as given to g_thread_new().
902 * You must only call g_thread_exit() from a thread that you created
903 * yourself with g_thread_new() or related APIs. You must not call
904 * this function from a thread created with another threading library
905 * or or from within a #GThreadPool.
907 void
908 g_thread_exit (gpointer retval)
910 GRealThread* real = (GRealThread*) g_thread_self ();
912 if G_UNLIKELY (!real->ours)
913 g_error ("attempt to g_thread_exit() a thread not created by GLib");
915 real->retval = retval;
917 g_system_thread_exit ();
921 * g_thread_join:
922 * @thread: a #GThread
924 * Waits until @thread finishes, i.e. the function @func, as
925 * given to g_thread_new(), returns or g_thread_exit() is called.
926 * If @thread has already terminated, then g_thread_join()
927 * returns immediately.
929 * Any thread can wait for any other thread by calling g_thread_join(),
930 * not just its 'creator'. Calling g_thread_join() from multiple threads
931 * for the same @thread leads to undefined behaviour.
933 * The value returned by @func or given to g_thread_exit() is
934 * returned by this function.
936 * g_thread_join() consumes the reference to the passed-in @thread.
937 * This will usually cause the #GThread struct and associated resources
938 * to be freed. Use g_thread_ref() to obtain an extra reference if you
939 * want to keep the GThread alive beyond the g_thread_join() call.
941 * Returns: the return value of the thread
943 gpointer
944 g_thread_join (GThread *thread)
946 GRealThread *real = (GRealThread*) thread;
947 gpointer retval;
949 g_return_val_if_fail (thread, NULL);
950 g_return_val_if_fail (real->ours, NULL);
952 g_system_thread_wait (real);
954 retval = real->retval;
956 /* Just to make sure, this isn't used any more */
957 thread->joinable = 0;
959 g_thread_unref (thread);
961 return retval;
965 * g_thread_self:
967 * This function returns the #GThread corresponding to the
968 * current thread. Note that this function does not increase
969 * the reference count of the returned struct.
971 * This function will return a #GThread even for threads that
972 * were not created by GLib (i.e. those created by other threading
973 * APIs). This may be useful for thread identification purposes
974 * (i.e. comparisons) but you must not use GLib functions (such
975 * as g_thread_join()) on these threads.
977 * Returns: the #GThread representing the current thread
979 GThread*
980 g_thread_self (void)
982 GRealThread* thread = g_private_get (&g_thread_specific_private);
984 if (!thread)
986 /* If no thread data is available, provide and set one.
987 * This can happen for the main thread and for threads
988 * that are not created by GLib.
990 thread = g_slice_new0 (GRealThread);
991 thread->ref_count = 1;
993 g_private_set (&g_thread_specific_private, thread);
996 return (GThread*) thread;
1000 * g_get_num_processors:
1002 * Determine the approximate number of threads that the system will
1003 * schedule simultaneously for this process. This is intended to be
1004 * used as a parameter to g_thread_pool_new() for CPU bound tasks and
1005 * similar cases.
1007 * Returns: Number of schedulable threads, always greater than 0
1009 * Since: 2.36
1011 guint
1012 g_get_num_processors (void)
1014 #ifdef G_OS_WIN32
1015 unsigned int count;
1016 SYSTEM_INFO sysinfo;
1017 DWORD_PTR process_cpus;
1018 DWORD_PTR system_cpus;
1020 /* This *never* fails, use it as fallback */
1021 GetNativeSystemInfo (&sysinfo);
1022 count = (int) sysinfo.dwNumberOfProcessors;
1024 if (GetProcessAffinityMask (GetCurrentProcess (),
1025 &process_cpus, &system_cpus))
1027 unsigned int af_count;
1029 for (af_count = 0; process_cpus != 0; process_cpus >>= 1)
1030 if (process_cpus & 1)
1031 af_count++;
1033 /* Prefer affinity-based result, if available */
1034 if (af_count > 0)
1035 count = af_count;
1038 if (count > 0)
1039 return count;
1040 #elif defined(_SC_NPROCESSORS_ONLN)
1042 int count;
1044 count = sysconf (_SC_NPROCESSORS_ONLN);
1045 if (count > 0)
1046 return count;
1048 #elif defined HW_NCPU
1050 int mib[2], count = 0;
1051 size_t len;
1053 mib[0] = CTL_HW;
1054 mib[1] = HW_NCPU;
1055 len = sizeof(count);
1057 if (sysctl (mib, 2, &count, &len, NULL, 0) == 0 && count > 0)
1058 return count;
1060 #endif
1062 return 1; /* Fallback */
1065 /* Epilogue {{{1 */
1066 /* vim: set foldmethod=marker: */