Expand thread docs a bit
[platform/upstream/glib.git] / glib / gthread.c
1 /* GLIB - Library of useful routines for C programming
2  * Copyright (C) 1995-1997  Peter Mattis, Spencer Kimball and Josh MacDonald
3  *
4  * gthread.c: MT safety related functions
5  * Copyright 1998 Sebastian Wilhelmi; University of Karlsruhe
6  *                Owen Taylor
7  *
8  * This library is free software; you can redistribute it and/or
9  * modify it under the terms of the GNU Lesser General Public
10  * License as published by the Free Software Foundation; either
11  * version 2 of the License, or (at your option) any later version.
12  *
13  * This library is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
16  * Lesser General Public License for more details.
17  *
18  * You should have received a copy of the GNU Lesser General Public
19  * License along with this library; if not, write to the
20  * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
21  * Boston, MA 02111-1307, USA.
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 HAVE_UNISTD_H
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 "gtestutils.h"
61
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
68  *
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.
78  *
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).
89  *
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.
95  *
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.
100  *
101  * Originally, UNIX did not have threads, and therefore some traditional
102  * UNIX APIs are problematic in threaded programs. Some notable examples
103  * are
104  * <itemizedlist>
105  *   <listitem>
106  *     C library functions that return data in statically allocated
107  *     buffers, such as strtok() or strerror(). For many of these,
108  *     there are thread-safe variants with a _r suffix, or you can
109  *     look at corresponding GLib APIs (like g_strsplit() or g_strerror()).
110  *   </listitem>
111  *   <listitem>
112  *     setenv() and unsetenv() manipulate the process environment in
113  *     a not thread-safe way, and may interfere with getenv() calls
114  *     in other threads. Note that getenv() calls may be
115  *     <quote>hidden</quote> behind other APIs. For example, GNU gettext()
116  *     calls getenv() under the covers. In general, it is best to treat
117  *     the environment as readonly. If you absolutely have to modify the
118  *     environment, do it early in main(), when no other threads are around yet.
119  *   </listitem>
120  *   <listitem>
121  *     setlocale() changes the locale for the entire process, affecting
122  *     all threads. Temporary changes to the locale are often made to
123  *     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.
128  *   </listitem>
129  * </itemizedlist>
130  *
131  * GLib itself is internally completely thread-safe (all global data is
132  * automatically locked), but individual data structure instances are
133  * not automatically locked for performance reasons. For example,
134  * you must coordinate accesses to the same #GHashTable from multiple
135  * threads. The two notable exceptions from this rule are #GMainLoop
136  * and #GAsyncQueue, which <emphasis>are</emphasis> thread-safe and
137  * need no further application-level locking to be accessed from
138  * multiple threads. Most refcounting functions such as g_object_ref()
139  * are also thread-safe.
140  */
141
142 /* G_LOCK Documentation {{{1 ---------------------------------------------- */
143
144 /**
145  * G_LOCK_DEFINE:
146  * @name: the name of the lock
147  *
148  * The %G_LOCK_* macros provide a convenient interface to #GMutex.
149  * #G_LOCK_DEFINE defines a lock. It can appear in any place where
150  * variable definitions may appear in programs, i.e. in the first block
151  * of a function or outside of functions. The @name parameter will be
152  * mangled to get the name of the #GMutex. This means that you
153  * can use names of existing variables as the parameter - e.g. the name
154  * of the variable you intend to protect with the lock. Look at our
155  * <function>give_me_next_number()</function> example using the
156  * %G_LOCK_* macros:
157  *
158  * <example>
159  *  <title>Using the %G_LOCK_* convenience macros</title>
160  *  <programlisting>
161  *   G_LOCK_DEFINE (current_number);
162  *
163  *   int
164  *   give_me_next_number (void)
165  *   {
166  *     static int current_number = 0;
167  *     int ret_val;
168  *
169  *     G_LOCK (current_number);
170  *     ret_val = current_number = calc_next_number (current_number);
171  *     G_UNLOCK (current_number);
172  *
173  *     return ret_val;
174  *   }
175  *  </programlisting>
176  * </example>
177  */
178
179 /**
180  * G_LOCK_DEFINE_STATIC:
181  * @name: the name of the lock
182  *
183  * This works like #G_LOCK_DEFINE, but it creates a static object.
184  */
185
186 /**
187  * G_LOCK_EXTERN:
188  * @name: the name of the lock
189  *
190  * This declares a lock, that is defined with #G_LOCK_DEFINE in another
191  * module.
192  */
193
194 /**
195  * G_LOCK:
196  * @name: the name of the lock
197  *
198  * Works like g_mutex_lock(), but for a lock defined with
199  * #G_LOCK_DEFINE.
200  */
201
202 /**
203  * G_TRYLOCK:
204  * @name: the name of the lock
205  * @Returns: %TRUE, if the lock could be locked.
206  *
207  * Works like g_mutex_trylock(), but for a lock defined with
208  * #G_LOCK_DEFINE.
209  */
210
211 /**
212  * G_UNLOCK:
213  * @name: the name of the lock
214  *
215  * Works like g_mutex_unlock(), but for a lock defined with
216  * #G_LOCK_DEFINE.
217  */
218
219 /* GMutex Documentation {{{1 ------------------------------------------ */
220
221 /**
222  * GMutex:
223  *
224  * The #GMutex struct is an opaque data structure to represent a mutex
225  * (mutual exclusion). It can be used to protect data against shared
226  * access. Take for example the following function:
227  *
228  * <example>
229  *  <title>A function which will not work in a threaded environment</title>
230  *  <programlisting>
231  *   int
232  *   give_me_next_number (void)
233  *   {
234  *     static int current_number = 0;
235  *
236  *     /<!-- -->* now do a very complicated calculation to calculate the new
237  *      * number, this might for example be a random number generator
238  *      *<!-- -->/
239  *     current_number = calc_next_number (current_number);
240  *
241  *     return current_number;
242  *   }
243  *  </programlisting>
244  * </example>
245  *
246  * It is easy to see that this won't work in a multi-threaded
247  * application. There current_number must be protected against shared
248  * access. A #GMutex can be used as a solution to this problem:
249  *
250  * <example>
251  *  <title>Using GMutex to protected a shared variable</title>
252  *  <programlisting>
253  *   int
254  *   give_me_next_number (void)
255  *   {
256  *     static GMutex mutex;
257  *     static int current_number = 0;
258  *     int ret_val;
259  *
260  *     g_mutex_lock (&amp;mutex);
261  *     ret_val = current_number = calc_next_number (current_number);
262  *     g_mutex_unlock (&amp;mutex);
263  *
264  *     return ret_val;
265  *   }
266  *  </programlisting>
267  * </example>
268  *
269  * Notice that the #GMutex is not initialised to any particular value.
270  * Its placement in static storage ensures that it will be initialised
271  * to all-zeros, which is appropriate.
272  *
273  * If a #GMutex is placed in other contexts (eg: embedded in a struct)
274  * then it must be explicitly initialised using g_mutex_init().
275  *
276  * A #GMutex should only be accessed via <function>g_mutex_</function>
277  * functions.
278  */
279
280 /* GRecMutex Documentation {{{1 -------------------------------------- */
281
282 /**
283  * GRecMutex:
284  *
285  * The GRecMutex struct is an opaque data structure to represent a
286  * recursive mutex. It is similar to a #GMutex with the difference
287  * that it is possible to lock a GRecMutex multiple times in the same
288  * thread without deadlock. When doing so, care has to be taken to
289  * unlock the recursive mutex as often as it has been locked.
290  *
291  * If a #GRecMutex is allocated in static storage then it can be used
292  * without initialisation.  Otherwise, you should call
293  * g_rec_mutex_init() on it and g_rec_mutex_clear() when done.
294  *
295  * A GRecMutex should only be accessed with the
296  * <function>g_rec_mutex_</function> functions.
297  *
298  * Since: 2.32
299  */
300
301 /* GRWLock Documentation {{{1 ---------------------------------------- */
302
303 /**
304  * GRWLock:
305  *
306  * The GRWLock struct is an opaque data structure to represent a
307  * reader-writer lock. It is similar to a #GMutex in that it allows
308  * multiple threads to coordinate access to a shared resource.
309  *
310  * The difference to a mutex is that a reader-writer lock discriminates
311  * between read-only ('reader') and full ('writer') access. While only
312  * one thread at a time is allowed write access (by holding the 'writer'
313  * lock via g_rw_lock_writer_lock()), multiple threads can gain
314  * simultaneous read-only access (by holding the 'reader' lock via
315  * g_rw_lock_reader_lock()).
316  *
317  * <example>
318  *  <title>An array with access functions</title>
319  *  <programlisting>
320  *   GRWLock lock;
321  *   GPtrArray *array;
322  *
323  *   gpointer
324  *   my_array_get (guint index)
325  *   {
326  *     gpointer retval = NULL;
327  *
328  *     if (!array)
329  *       return NULL;
330  *
331  *     g_rw_lock_reader_lock (&amp;lock);
332  *     if (index &lt; array->len)
333  *       retval = g_ptr_array_index (array, index);
334  *     g_rw_lock_reader_unlock (&amp;lock);
335  *
336  *     return retval;
337  *   }
338  *
339  *   void
340  *   my_array_set (guint index, gpointer data)
341  *   {
342  *     g_rw_lock_writer_lock (&amp;lock);
343  *
344  *     if (!array)
345  *       array = g_ptr_array_new (<!-- -->);
346  *
347  *     if (index >= array->len)
348  *       g_ptr_array_set_size (array, index+1);
349  *     g_ptr_array_index (array, index) = data;
350  *
351  *     g_rw_lock_writer_unlock (&amp;lock);
352  *   }
353  *  </programlisting>
354  *  <para>
355  *    This example shows an array which can be accessed by many readers
356  *    (the <function>my_array_get()</function> function) simultaneously,
357  *    whereas the writers (the <function>my_array_set()</function>
358  *    function) will only be allowed once at a time and only if no readers
359  *    currently access the array. This is because of the potentially
360  *    dangerous resizing of the array. Using these functions is fully
361  *    multi-thread safe now.
362  *  </para>
363  * </example>
364  *
365  * If a #GRWLock is allocated in static storage then it can be used
366  * without initialisation.  Otherwise, you should call
367  * g_rw_lock_init() on it and g_rw_lock_clear() when done.
368  *
369  * A GRWLock should only be accessed with the
370  * <function>g_rw_lock_</function> functions.
371  *
372  * Since: 2.32
373  */
374
375 /* GCond Documentation {{{1 ------------------------------------------ */
376
377 /**
378  * GCond:
379  *
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.
385  *
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.
390  *
391  * <example>
392  *  <title>
393  *   Using GCond to block a thread until a condition is satisfied
394  *  </title>
395  *  <programlisting>
396  *   gpointer current_data = NULL;
397  *   GMutex data_mutex;
398  *   GCond data_cond;
399  *
400  *   void
401  *   push_data (gpointer data)
402  *   {
403  *     g_mutex_lock (&data_mutex);
404  *     current_data = data;
405  *     g_cond_signal (&data_cond);
406  *     g_mutex_unlock (&data_mutex);
407  *   }
408  *
409  *   gpointer
410  *   pop_data (void)
411  *   {
412  *     gpointer data;
413  *
414  *     g_mutex_lock (&data_mutex);
415  *     while (!current_data)
416  *       g_cond_wait (&data_cond, &data_mutex);
417  *     data = current_data;
418  *     current_data = NULL;
419  *     g_mutex_unlock (&data_mutex);
420  *
421  *     return data;
422  *   }
423  *  </programlisting>
424  * </example>
425  *
426  * Whenever a thread calls pop_data() now, it will wait until
427  * current_data is non-%NULL, i.e. until some other thread
428  * has called push_data().
429  *
430  * The example shows that use of a condition variable must always be
431  * paired with a mutex.  Without the use of a mutex, there would be a
432  * race between the check of <varname>current_data</varname> by the
433  * while loop in <function>pop_data</function> and waiting.
434  * Specifically, another thread could set <varname>pop_data</varname>
435  * after the check, and signal the cond (with nobody waiting on it)
436  * before the first thread goes to sleep.  #GCond is specifically useful
437  * for its ability to release the mutex and go to sleep atomically.
438  *
439  * It is also important to use the g_cond_wait() and g_cond_wait_until()
440  * functions only inside a loop which checks for the condition to be
441  * true.  See g_cond_wait() for an explanation of why the condition may
442  * not be true even after it returns.
443  *
444  * If a #GCond is allocated in static storage then it can be used
445  * without initialisation.  Otherwise, you should call g_cond_init() on
446  * it and g_cond_clear() when done.
447  *
448  * A #GCond should only be accessed via the <function>g_cond_</function>
449  * functions.
450  */
451
452 /* GThread Documentation {{{1 ---------------------------------------- */
453
454 /**
455  * GThread:
456  *
457  * The #GThread struct represents a running thread. This struct
458  * is returned by g_thread_new() or g_thread_try_new(). You can
459  * obtain the #GThread struct representing the current thead by
460  * calling g_thread_self().
461  *
462  * GThread is refcounted, see g_thread_ref() and g_thread_unref().
463  * The thread represented by it holds a reference while it is running,
464  * and g_thread_join() consumes the reference that it is given, so
465  * it is normally not necessary to manage GThread references
466  * explicitly.
467  *
468  * The structure is opaque -- none of its fields may be directly
469  * accessed.
470  */
471
472 /**
473  * GThreadFunc:
474  * @data: data passed to the thread
475  *
476  * Specifies the type of the @func functions passed to g_thread_new()
477  * or g_thread_try_new().
478  *
479  * Returns: the return value of the thread
480  */
481
482 /**
483  * g_thread_supported:
484  *
485  * This macro returns %TRUE if the thread system is initialized,
486  * and %FALSE if it is not.
487  *
488  * For language bindings, g_thread_get_initialized() provides
489  * the same functionality as a function.
490  *
491  * Returns: %TRUE, if the thread system is initialized
492  */
493
494 /* GThreadError {{{1 ------------------------------------------------------- */
495 /**
496  * GThreadError:
497  * @G_THREAD_ERROR_AGAIN: a thread couldn't be created due to resource
498  *                        shortage. Try again later.
499  *
500  * Possible errors of thread related functions.
501  **/
502
503 /**
504  * G_THREAD_ERROR:
505  *
506  * The error domain of the GLib thread subsystem.
507  **/
508 GQuark
509 g_thread_error_quark (void)
510 {
511   return g_quark_from_static_string ("g_thread_error");
512 }
513
514 /* Local Data {{{1 -------------------------------------------------------- */
515
516 static GMutex    g_once_mutex;
517 static GCond     g_once_cond;
518 static GSList   *g_once_init_list = NULL;
519
520 static void g_thread_cleanup (gpointer data);
521 static GPrivate     g_thread_specific_private = G_PRIVATE_INIT (g_thread_cleanup);
522
523 G_LOCK_DEFINE_STATIC (g_thread_new);
524
525 /* GOnce {{{1 ------------------------------------------------------------- */
526
527 /**
528  * GOnce:
529  * @status: the status of the #GOnce
530  * @retval: the value returned by the call to the function, if @status
531  *          is %G_ONCE_STATUS_READY
532  *
533  * A #GOnce struct controls a one-time initialization function. Any
534  * one-time initialization function must have its own unique #GOnce
535  * struct.
536  *
537  * Since: 2.4
538  */
539
540 /**
541  * G_ONCE_INIT:
542  *
543  * A #GOnce must be initialized with this macro before it can be used.
544  *
545  * |[
546  *   GOnce my_once = G_ONCE_INIT;
547  * ]|
548  *
549  * Since: 2.4
550  */
551
552 /**
553  * GOnceStatus:
554  * @G_ONCE_STATUS_NOTCALLED: the function has not been called yet.
555  * @G_ONCE_STATUS_PROGRESS: the function call is currently in progress.
556  * @G_ONCE_STATUS_READY: the function has been called.
557  *
558  * The possible statuses of a one-time initialization function
559  * controlled by a #GOnce struct.
560  *
561  * Since: 2.4
562  */
563
564 /**
565  * g_once:
566  * @once: a #GOnce structure
567  * @func: the #GThreadFunc function associated to @once. This function
568  *        is called only once, regardless of the number of times it and
569  *        its associated #GOnce struct are passed to g_once().
570  * @arg: data to be passed to @func
571  *
572  * The first call to this routine by a process with a given #GOnce
573  * struct calls @func with the given argument. Thereafter, subsequent
574  * calls to g_once()  with the same #GOnce struct do not call @func
575  * again, but return the stored result of the first call. On return
576  * from g_once(), the status of @once will be %G_ONCE_STATUS_READY.
577  *
578  * For example, a mutex or a thread-specific data key must be created
579  * exactly once. In a threaded environment, calling g_once() ensures
580  * that the initialization is serialized across multiple threads.
581  *
582  * Calling g_once() recursively on the same #GOnce struct in
583  * @func will lead to a deadlock.
584  *
585  * |[
586  *   gpointer
587  *   get_debug_flags (void)
588  *   {
589  *     static GOnce my_once = G_ONCE_INIT;
590  *
591  *     g_once (&my_once, parse_debug_flags, NULL);
592  *
593  *     return my_once.retval;
594  *   }
595  * ]|
596  *
597  * Since: 2.4
598  */
599 gpointer
600 g_once_impl (GOnce       *once,
601              GThreadFunc  func,
602              gpointer     arg)
603 {
604   g_mutex_lock (&g_once_mutex);
605
606   while (once->status == G_ONCE_STATUS_PROGRESS)
607     g_cond_wait (&g_once_cond, &g_once_mutex);
608
609   if (once->status != G_ONCE_STATUS_READY)
610     {
611       once->status = G_ONCE_STATUS_PROGRESS;
612       g_mutex_unlock (&g_once_mutex);
613
614       once->retval = func (arg);
615
616       g_mutex_lock (&g_once_mutex);
617       once->status = G_ONCE_STATUS_READY;
618       g_cond_broadcast (&g_once_cond);
619     }
620
621   g_mutex_unlock (&g_once_mutex);
622
623   return once->retval;
624 }
625
626 /**
627  * g_once_init_enter:
628  * @value_location: location of a static initializable variable
629  *     containing 0
630  *
631  * Function to be called when starting a critical initialization
632  * section. The argument @value_location must point to a static
633  * 0-initialized variable that will be set to a value other than 0 at
634  * the end of the initialization section. In combination with
635  * g_once_init_leave() and the unique address @value_location, it can
636  * be ensured that an initialization section will be executed only once
637  * during a program's life time, and that concurrent threads are
638  * blocked until initialization completed. To be used in constructs
639  * like this:
640  *
641  * |[
642  *   static gsize initialization_value = 0;
643  *
644  *   if (g_once_init_enter (&amp;initialization_value))
645  *     {
646  *       gsize setup_value = 42; /&ast;* initialization code here *&ast;/
647  *
648  *       g_once_init_leave (&amp;initialization_value, setup_value);
649  *     }
650  *
651  *   /&ast;* use initialization_value here *&ast;/
652  * ]|
653  *
654  * Returns: %TRUE if the initialization section should be entered,
655  *     %FALSE and blocks otherwise
656  *
657  * Since: 2.14
658  */
659 gboolean
660 (g_once_init_enter) (volatile void *pointer)
661 {
662   volatile gsize *value_location = pointer;
663   gboolean need_init = FALSE;
664   g_mutex_lock (&g_once_mutex);
665   if (g_atomic_pointer_get (value_location) == NULL)
666     {
667       if (!g_slist_find (g_once_init_list, (void*) value_location))
668         {
669           need_init = TRUE;
670           g_once_init_list = g_slist_prepend (g_once_init_list, (void*) value_location);
671         }
672       else
673         do
674           g_cond_wait (&g_once_cond, &g_once_mutex);
675         while (g_slist_find (g_once_init_list, (void*) value_location));
676     }
677   g_mutex_unlock (&g_once_mutex);
678   return need_init;
679 }
680
681 /**
682  * g_once_init_leave:
683  * @value_location: location of a static initializable variable
684  *     containing 0
685  * @result: new non-0 value for *@value_location
686  *
687  * Counterpart to g_once_init_enter(). Expects a location of a static
688  * 0-initialized initialization variable, and an initialization value
689  * other than 0. Sets the variable to the initialization value, and
690  * releases concurrent threads blocking in g_once_init_enter() on this
691  * initialization variable.
692  *
693  * Since: 2.14
694  */
695 void
696 (g_once_init_leave) (volatile void *pointer,
697                      gsize          result)
698 {
699   volatile gsize *value_location = pointer;
700
701   g_return_if_fail (g_atomic_pointer_get (value_location) == NULL);
702   g_return_if_fail (result != 0);
703   g_return_if_fail (g_once_init_list != NULL);
704
705   g_atomic_pointer_set (value_location, result);
706   g_mutex_lock (&g_once_mutex);
707   g_once_init_list = g_slist_remove (g_once_init_list, (void*) value_location);
708   g_cond_broadcast (&g_once_cond);
709   g_mutex_unlock (&g_once_mutex);
710 }
711
712 /* GThread {{{1 -------------------------------------------------------- */
713
714 /**
715  * g_thread_ref:
716  * @thread: a #GThread
717  *
718  * Increase the reference count on @thread.
719  *
720  * Returns: a new reference to @thread
721  *
722  * Since: 2.32
723  */
724 GThread *
725 g_thread_ref (GThread *thread)
726 {
727   GRealThread *real = (GRealThread *) thread;
728
729   g_atomic_int_inc (&real->ref_count);
730
731   return thread;
732 }
733
734 /**
735  * g_thread_unref:
736  * @thread: a #GThread
737  *
738  * Decrease the reference count on @thread, possibly freeing all
739  * resources associated with it.
740  *
741  * Note that each thread holds a reference to its #GThread while
742  * it is running, so it is safe to drop your own reference to it
743  * if you don't need it anymore.
744  *
745  * Since: 2.32
746  */
747 void
748 g_thread_unref (GThread *thread)
749 {
750   GRealThread *real = (GRealThread *) thread;
751
752   if (g_atomic_int_dec_and_test (&real->ref_count))
753     {
754       if (real->ours)
755         g_system_thread_free (real);
756       else
757         g_slice_free (GRealThread, real);
758     }
759 }
760
761 static void
762 g_thread_cleanup (gpointer data)
763 {
764   g_thread_unref (data);
765 }
766
767 gpointer
768 g_thread_proxy (gpointer data)
769 {
770   GRealThread* thread = data;
771
772   g_assert (data);
773
774   if (thread->name)
775     g_system_thread_set_name (thread->name);
776
777   /* This has to happen before G_LOCK, as that might call g_thread_self */
778   g_private_set (&g_thread_specific_private, data);
779
780   /* The lock makes sure that g_thread_new_internal() has a chance to
781    * setup 'func' and 'data' before we make the call.
782    */
783   G_LOCK (g_thread_new);
784   G_UNLOCK (g_thread_new);
785
786   thread->retval = thread->thread.func (thread->thread.data);
787
788   return NULL;
789 }
790
791 /**
792  * g_thread_new:
793  * @name: a name for the new thread
794  * @func: a function to execute in the new thread
795  * @data: an argument to supply to the new thread
796  *
797  * This function creates a new thread. The new thread starts by invoking
798  * @func with the argument data. The thread will run until @func returns
799  * or until g_thread_exit() is called from the new thread. The return value
800  * of @func becomes the return value of the thread, which can be obtained
801  * with g_thread_join().
802  *
803  * The @name can be useful for discriminating threads in a debugger.
804  * Some systems restrict the length of @name to 16 bytes.
805  *
806  * If the thread can not be created the program aborts. See
807  * g_thread_try_new() if you want to attempt to deal with failures.
808  *
809  * To free the struct returned by this function, use g_thread_unref().
810  * Note that g_thread_join() implicitly unrefs the #GThread as well.
811  *
812  * Returns: the new #GThread
813  *
814  * Since: 2.32
815  */
816 GThread *
817 g_thread_new (const gchar *name,
818               GThreadFunc  func,
819               gpointer     data)
820 {
821   GError *error = NULL;
822   GThread *thread;
823
824   thread = g_thread_new_internal (name, g_thread_proxy, func, data, 0, &error);
825
826   if G_UNLIKELY (thread == NULL)
827     g_error ("creating thread '%s': %s", name ? name : "", error->message);
828
829   return thread;
830 }
831
832 /**
833  * g_thread_try_new:
834  * @name: a name for the new thread
835  * @func: a function to execute in the new thread
836  * @data: an argument to supply to the new thread
837  * @error: return location for error, or %NULL
838  *
839  * This function is the same as g_thread_new() except that
840  * it allows for the possibility of failure.
841  *
842  * If a thread can not be created (due to resource limits),
843  * @error is set and %NULL is returned.
844  *
845  * Returns: the new #GThread, or %NULL if an error occurred
846  *
847  * Since: 2.32
848  */
849 GThread *
850 g_thread_try_new (const gchar  *name,
851                   GThreadFunc   func,
852                   gpointer      data,
853                   GError      **error)
854 {
855   return g_thread_new_internal (name, g_thread_proxy, func, data, 0, error);
856 }
857
858 GThread *
859 g_thread_new_internal (const gchar   *name,
860                        GThreadFunc    proxy,
861                        GThreadFunc    func,
862                        gpointer       data,
863                        gsize          stack_size,
864                        GError       **error)
865 {
866   GRealThread *thread;
867
868   g_return_val_if_fail (func != NULL, NULL);
869
870   G_LOCK (g_thread_new);
871   thread = g_system_thread_new (proxy, stack_size, error);
872   if (thread)
873     {
874       thread->ref_count = 2;
875       thread->ours = TRUE;
876       thread->thread.joinable = TRUE;
877       thread->thread.func = func;
878       thread->thread.data = data;
879       thread->name = name;
880     }
881   G_UNLOCK (g_thread_new);
882
883   return (GThread*) thread;
884 }
885
886 /**
887  * g_thread_exit:
888  * @retval: the return value of this thread
889  *
890  * Terminates the current thread.
891  *
892  * If another thread is waiting for us using g_thread_join() then the
893  * waiting thread will be woken up and get @retval as the return value
894  * of g_thread_join().
895  *
896  * Calling <literal>g_thread_exit (retval)</literal> is equivalent to
897  * returning @retval from the function @func, as given to g_thread_new().
898  *
899  * <note><para>
900  *   You must only call g_thread_exit() from a thread that you created
901  *   yourself with g_thread_new() or related APIs.  You must not call
902  *   this function from a thread created with another threading library
903  *   or or from within a #GThreadPool.
904  * </para></note>
905  */
906 void
907 g_thread_exit (gpointer retval)
908 {
909   GRealThread* real = (GRealThread*) g_thread_self ();
910
911   if G_UNLIKELY (!real->ours)
912     g_error ("attempt to g_thread_exit() a thread not created by GLib");
913
914   real->retval = retval;
915
916   g_system_thread_exit ();
917 }
918
919 /**
920  * g_thread_join:
921  * @thread: a #GThread
922  *
923  * Waits until @thread finishes, i.e. the function @func, as
924  * given to g_thread_new(), returns or g_thread_exit() is called.
925  * If @thread has already terminated, then g_thread_join()
926  * returns immediately.
927  *
928  * Any thread can wait for any other thread by calling g_thread_join(),
929  * not just its 'creator'. Calling g_thread_join() from multiple threads
930  * for the same @thread leads to undefined behaviour.
931  *
932  * The value returned by @func or given to g_thread_exit() is
933  * returned by this function.
934  *
935  * g_thread_join() consumes the reference to the passed-in @thread.
936  * This will usually cause the #GThread struct and associated resources
937  * to be freed. Use g_thread_ref() to obtain an extra reference if you
938  * want to keep the GThread alive beyond the g_thread_join() call.
939  *
940  * Returns: the return value of the thread
941  */
942 gpointer
943 g_thread_join (GThread *thread)
944 {
945   GRealThread *real = (GRealThread*) thread;
946   gpointer retval;
947
948   g_return_val_if_fail (thread, NULL);
949   g_return_val_if_fail (real->ours, NULL);
950
951   g_system_thread_wait (real);
952
953   retval = real->retval;
954
955   /* Just to make sure, this isn't used any more */
956   thread->joinable = 0;
957
958   g_thread_unref (thread);
959
960   return retval;
961 }
962
963 /**
964  * g_thread_self:
965  *
966  * This functions returns the #GThread corresponding to the
967  * current thread. Note that this function does not increase
968  * the reference count of the returned struct.
969  *
970  * This function will return a #GThread even for threads that
971  * were not created by GLib (i.e. those created by other threading
972  * APIs). This may be useful for thread identification purposes
973  * (i.e. comparisons) but you must not use GLib functions (such
974  * as g_thread_join()) on these threads.
975  *
976  * Returns: the #GThread representing the current thread
977  */
978 GThread*
979 g_thread_self (void)
980 {
981   GRealThread* thread = g_private_get (&g_thread_specific_private);
982
983   if (!thread)
984     {
985       /* If no thread data is available, provide and set one.
986        * This can happen for the main thread and for threads
987        * that are not created by GLib.
988        */
989       thread = g_slice_new0 (GRealThread);
990       thread->ref_count = 1;
991
992       g_private_set (&g_thread_specific_private, thread);
993     }
994
995   return (GThread*) thread;
996 }
997
998 /* Epilogue {{{1 */
999 /* vim: set foldmethod=marker: */