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