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