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