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