Mark g_thread_create_with_stack_size as new API
[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 "deprecated/gthread.h"
44 #include "gthreadprivate.h"
45 #include "gslice.h"
46 #include "gmain.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 <string.h>
60
61 #include "garray.h"
62 #include "gbitlock.h"
63 #include "gslist.h"
64 #include "gtestutils.h"
65 #include "gtimer.h"
66
67 /**
68  * SECTION:threads
69  * @title: Threads
70  * @short_description: portable support for threads, mutexes, locks,
71  *     conditions and thread private data
72  * @see_also: #GThreadPool, #GAsyncQueue
73  *
74  * Threads act almost like processes, but unlike processes all threads
75  * of one process share the same memory. This is good, as it provides
76  * easy communication between the involved threads via this shared
77  * memory, and it is bad, because strange things (so called
78  * "Heisenbugs") might happen if the program is not carefully designed.
79  * In particular, due to the concurrent nature of threads, no
80  * assumptions on the order of execution of code running in different
81  * threads can be made, unless order is explicitly forced by the
82  * programmer through synchronization primitives.
83  *
84  * The aim of the thread-related functions in GLib is to provide a
85  * portable means for writing multi-threaded software. There are
86  * primitives for mutexes to protect the access to portions of memory
87  * (#GMutex, #GRecMutex and #GRWLock). There is a facility to use
88  * individual bits for locks (g_bit_lock()). There are primitives
89  * for condition variables to allow synchronization of threads (#GCond).
90  * There are primitives for thread-private data - data that every thread
91  * has a private instance of (#GPrivate, #GStaticPrivate). There are
92  * facilities for one-time initialization (#GOnce, g_once_init_enter()).
93  * Finally there are primitives to create and manage threads (#GThread).
94  *
95  * The threading system is initialized with g_thread_init().
96  * You may call any other glib functions in the main thread before
97  * g_thread_init() as long as g_thread_init() is not called from
98  * a GLib callback, or with any locks held. However, many libraries
99  * above GLib does not support late initialization of threads, so
100  * doing this should be avoided if possible.
101  *
102  * Please note that since version 2.24 the GObject initialization
103  * function g_type_init() initializes threads. Since 2.32, creating
104  * a mainloop will do so too. As a consequence, most applications,
105  * including those using GTK+ will run with threads enabled.
106  *
107  * After calling g_thread_init(), GLib is completely thread safe
108  * (all global data is automatically locked), but individual data
109  * structure instances are not automatically locked for performance
110  * reasons. So, for example you must coordinate accesses to the same
111  * #GHashTable from multiple threads. The two notable exceptions from
112  * this rule are #GMainLoop and #GAsyncQueue, which <emphasis>are</emphasis>
113  * threadsafe and need no further application-level locking to be
114  * accessed from multiple threads.
115  */
116
117 /**
118  * G_THREADS_IMPL_POSIX:
119  *
120  * This macro is defined if POSIX style threads are used.
121  */
122
123 /**
124  * G_THREADS_IMPL_WIN32:
125  *
126  * This macro is defined if Windows style threads are used.
127  */
128
129 /* G_LOCK Documentation {{{1 ---------------------------------------------- */
130
131 /**
132  * G_LOCK_DEFINE:
133  * @name: the name of the lock.
134  *
135  * The %G_LOCK_* macros provide a convenient interface to #GMutex
136  * with the advantage that they will expand to nothing in programs
137  * compiled against a thread-disabled GLib, saving code and memory
138  * there. #G_LOCK_DEFINE defines a lock. It can appear anywhere
139  * variable definitions may appear in programs, i.e. in the first block
140  * of a function or outside of functions. The @name parameter will be
141  * mangled to get the name of the #GMutex. This means that you
142  * can use names of existing variables as the parameter - e.g. the name
143  * of the variable you intent to protect with the lock. Look at our
144  * <function>give_me_next_number()</function> example using the
145  * %G_LOCK_* macros:
146  *
147  * <example>
148  *  <title>Using the %G_LOCK_* convenience macros</title>
149  *  <programlisting>
150  *   G_LOCK_DEFINE (current_number);
151  *
152  *   int
153  *   give_me_next_number (void)
154  *   {
155  *     static int current_number = 0;
156  *     int ret_val;
157  *
158  *     G_LOCK (current_number);
159  *     ret_val = current_number = calc_next_number (current_number);
160  *     G_UNLOCK (current_number);
161  *
162  *     return ret_val;
163  *   }
164  *  </programlisting>
165  * </example>
166  */
167
168 /**
169  * G_LOCK_DEFINE_STATIC:
170  * @name: the name of the lock.
171  *
172  * This works like #G_LOCK_DEFINE, but it creates a static object.
173  */
174
175 /**
176  * G_LOCK_EXTERN:
177  * @name: the name of the lock.
178  *
179  * This declares a lock, that is defined with #G_LOCK_DEFINE in another
180  * module.
181  */
182
183 /**
184  * G_LOCK:
185  * @name: the name of the lock.
186  *
187  * Works like g_mutex_lock(), but for a lock defined with
188  * #G_LOCK_DEFINE.
189  */
190
191 /**
192  * G_TRYLOCK:
193  * @name: the name of the lock.
194  * @Returns: %TRUE, if the lock could be locked.
195  *
196  * Works like g_mutex_trylock(), but for a lock defined with
197  * #G_LOCK_DEFINE.
198  */
199
200 /**
201  * G_UNLOCK:
202  * @name: the name of the lock.
203  *
204  * Works like g_mutex_unlock(), but for a lock defined with
205  * #G_LOCK_DEFINE.
206  */
207
208 /* GMutex Documentation {{{1 ------------------------------------------ */
209
210 /**
211  * GMutex:
212  *
213  * The #GMutex struct is an opaque data structure to represent a mutex
214  * (mutual exclusion). It can be used to protect data against shared
215  * access. Take for example the following function:
216  *
217  * <example>
218  *  <title>A function which will not work in a threaded environment</title>
219  *  <programlisting>
220  *   int
221  *   give_me_next_number (void)
222  *   {
223  *     static int current_number = 0;
224  *
225  *     /<!-- -->* now do a very complicated calculation to calculate the new
226  *      * number, this might for example be a random number generator
227  *      *<!-- -->/
228  *     current_number = calc_next_number (current_number);
229  *
230  *     return current_number;
231  *   }
232  *  </programlisting>
233  * </example>
234  *
235  * It is easy to see that this won't work in a multi-threaded
236  * application. There current_number must be protected against shared
237  * access. A first naive implementation would be:
238  *
239  * <example>
240  *  <title>The wrong way to write a thread-safe function</title>
241  *  <programlisting>
242  *   int
243  *   give_me_next_number (void)
244  *   {
245  *     static int current_number = 0;
246  *     int ret_val;
247  *     static GMutex * mutex = NULL;
248  *
249  *     if (!mutex) mutex = g_mutex_new (<!-- -->);
250  *
251  *     g_mutex_lock (mutex);
252  *     ret_val = current_number = calc_next_number (current_number);
253  *     g_mutex_unlock (mutex);
254  *
255  *     return ret_val;
256  *   }
257  *  </programlisting>
258  * </example>
259  *
260  * This looks like it would work, but there is a race condition while
261  * constructing the mutex and this code cannot work reliable. Please do
262  * not use such constructs in your own programs! One working solution
263  * is:
264  *
265  * <example>
266  *  <title>A correct thread-safe function</title>
267  *  <programlisting>
268  *   static GMutex *give_me_next_number_mutex = NULL;
269  *
270  *   /<!-- -->* this function must be called before any call to
271  *    * give_me_next_number(<!-- -->)
272  *    *
273  *    * it must be called exactly once.
274  *    *<!-- -->/
275  *   void
276  *   init_give_me_next_number (void)
277  *   {
278  *     g_assert (give_me_next_number_mutex == NULL);
279  *     give_me_next_number_mutex = g_mutex_new (<!-- -->);
280  *   }
281  *
282  *   int
283  *   give_me_next_number (void)
284  *   {
285  *     static int current_number = 0;
286  *     int ret_val;
287  *
288  *     g_mutex_lock (give_me_next_number_mutex);
289  *     ret_val = current_number = calc_next_number (current_number);
290  *     g_mutex_unlock (give_me_next_number_mutex);
291  *
292  *     return ret_val;
293  *   }
294  *  </programlisting>
295  * </example>
296  *
297  * A statically initialized #GMutex provides an even simpler and safer
298  * way of doing this:
299  *
300  * <example>
301  *  <title>Using a statically allocated mutex</title>
302  *  <programlisting>
303  *   int
304  *   give_me_next_number (void)
305  *   {
306  *     static GMutex mutex = G_MUTEX_INIT;
307  *     static int current_number = 0;
308  *     int ret_val;
309  *
310  *     g_mutex_lock (&amp;mutex);
311  *     ret_val = current_number = calc_next_number (current_number);
312  *     g_mutex_unlock (&amp;mutex);
313  *
314  *     return ret_val;
315  *   }
316  *  </programlisting>
317  * </example>
318  *
319  * A #GMutex should only be accessed via <function>g_mutex_</function>
320  * functions.
321  */
322
323 /**
324  * G_MUTEX_INIT:
325  *
326  * Initializer for statically allocated #GMutexes.
327  * Alternatively, g_mutex_init() can be used.
328  *
329  * |[
330  *   GMutex mutex = G_MUTEX_INIT;
331  * ]|
332  *
333  * Since: 2.32
334  */
335
336 /* GRecMutex Documentation {{{1 -------------------------------------- */
337
338 /**
339  * GRecMutex:
340  *
341  * The GRecMutex struct is an opaque data structure to represent a
342  * recursive mutex. It is similar to a #GMutex with the difference
343  * that it is possible to lock a GRecMutex multiple times in the same
344  * thread without deadlock. When doing so, care has to be taken to
345  * unlock the recursive mutex as often as it has been locked.
346  *
347  * A GRecMutex should only be accessed with the
348  * <function>g_rec_mutex_</function> functions. Before a GRecMutex
349  * can be used, it has to be initialized with #G_REC_MUTEX_INIT or
350  * g_rec_mutex_init().
351  *
352  * Since: 2.32
353  */
354
355 /**
356  * G_REC_MUTEX_INIT:
357  *
358  * Initializer for statically allocated #GRecMutexes.
359  * Alternatively, g_rec_mutex_init() can be used.
360  *
361  * |[
362  *   GRecMutex mutex = G_REC_MUTEX_INIT;
363  * ]|
364  *
365  * Since: 2.32
366  */
367
368 /* GRWLock Documentation {{{1 ---------------------------------------- */
369
370 /**
371  * GRWLock:
372  *
373  * The GRWLock struct is an opaque data structure to represent a
374  * reader-writer lock. It is similar to a #GMutex in that it allows
375  * multiple threads to coordinate access to a shared resource.
376  *
377  * The difference to a mutex is that a reader-writer lock discriminates
378  * between read-only ('reader') and full ('writer') access. While only
379  * one thread at a time is allowed write access (by holding the 'writer'
380  * lock via g_rw_lock_writer_lock()), multiple threads can gain
381  * simultaneous read-only access (by holding the 'reader' lock via
382  * g_rw_lock_reader_lock()).
383  *
384  * <example>
385  *  <title>An array with access functions</title>
386  *  <programlisting>
387  *   GRWLock lock = G_RW_LOCK_INIT;
388  *   GPtrArray *array;
389  *
390  *   gpointer
391  *   my_array_get (guint index)
392  *   {
393  *     gpointer retval = NULL;
394  *
395  *     if (!array)
396  *       return NULL;
397  *
398  *     g_rw_lock_reader_lock (&amp;lock);
399  *     if (index &lt; array->len)
400  *       retval = g_ptr_array_index (array, index);
401  *     g_rw_lock_reader_unlock (&amp;lock);
402  *
403  *     return retval;
404  *   }
405  *
406  *   void
407  *   my_array_set (guint index, gpointer data)
408  *   {
409  *     g_rw_lock_writer_lock (&amp;lock);
410  *
411  *     if (!array)
412  *       array = g_ptr_array_new (<!-- -->);
413  *
414  *     if (index >= array->len)
415  *       g_ptr_array_set_size (array, index+1);
416  *     g_ptr_array_index (array, index) = data;
417  *
418  *     g_rw_lock_writer_unlock (&amp;lock);
419  *   }
420  *  </programlisting>
421  *  <para>
422  *    This example shows an array which can be accessed by many readers
423  *    (the <function>my_array_get()</function> function) simultaneously,
424  *    whereas the writers (the <function>my_array_set()</function>
425  *    function) will only be allowed once at a time and only if no readers
426  *    currently access the array. This is because of the potentially
427  *    dangerous resizing of the array. Using these functions is fully
428  *    multi-thread safe now.
429  *  </para>
430  * </example>
431  *
432  * A GRWLock should only be accessed with the
433  * <function>g_rw_lock_</function> functions. Before it can be used,
434  * it has to be initialized with #G_RW_LOCK_INIT or g_rw_lock_init().
435  *
436  * Since: 2.32
437  */
438
439 /**
440  * G_RW_LOCK_INIT:
441  *
442  * Initializer for statically allocated #GRWLocks.
443  * Alternatively, g_rw_lock_init_init() can be used.
444  *
445  * |[
446  *   GRWLock lock = G_RW_LOCK_INIT;
447  * ]|
448  *
449  * Since: 2.32
450  */
451
452 /* GCond Documentation {{{1 ------------------------------------------ */
453
454 /**
455  * GCond:
456  *
457  * The #GCond struct is an opaque data structure that represents a
458  * condition. Threads can block on a #GCond if they find a certain
459  * condition to be false. If other threads change the state of this
460  * condition they signal the #GCond, and that causes the waiting
461  * threads to be woken up.
462  *
463  * <example>
464  *  <title>
465  *   Using GCond to block a thread until a condition is satisfied
466  *  </title>
467  *  <programlisting>
468  *   GCond* data_cond = NULL; /<!-- -->* Must be initialized somewhere *<!-- -->/
469  *   GMutex* data_mutex = NULL; /<!-- -->* Must be initialized somewhere *<!-- -->/
470  *   gpointer current_data = NULL;
471  *
472  *   void
473  *   push_data (gpointer data)
474  *   {
475  *     g_mutex_lock (data_mutex);
476  *     current_data = data;
477  *     g_cond_signal (data_cond);
478  *     g_mutex_unlock (data_mutex);
479  *   }
480  *
481  *   gpointer
482  *   pop_data (void)
483  *   {
484  *     gpointer data;
485  *
486  *     g_mutex_lock (data_mutex);
487  *     while (!current_data)
488  *       g_cond_wait (data_cond, data_mutex);
489  *     data = current_data;
490  *     current_data = NULL;
491  *     g_mutex_unlock (data_mutex);
492  *
493  *     return data;
494  *   }
495  *  </programlisting>
496  * </example>
497  *
498  * Whenever a thread calls pop_data() now, it will wait until
499  * current_data is non-%NULL, i.e. until some other thread
500  * has called push_data().
501  *
502  * <note><para>It is important to use the g_cond_wait() and
503  * g_cond_timed_wait() functions only inside a loop which checks for the
504  * condition to be true.  It is not guaranteed that the waiting thread
505  * will find the condition fulfilled after it wakes up, even if the
506  * signaling thread left the condition in that state: another thread may
507  * have altered the condition before the waiting thread got the chance
508  * to be woken up, even if the condition itself is protected by a
509  * #GMutex, like above.</para></note>
510  *
511  * A #GCond should only be accessed via the <function>g_cond_</function>
512  * functions.
513  */
514
515 /**
516  * G_COND_INIT:
517  *
518  * Initializer for statically allocated #GConds.
519  * Alternatively, g_cond_init() can be used.
520  *
521  * |[
522  *   GCond cond = G_COND_INIT;
523  * ]|
524  *
525  * Since: 2.32
526  */
527
528 /* GPrivate Documentation {{{1 --------------------------------------- */
529
530 /**
531  * GPrivate:
532  *
533  * <note><para>
534  * #GStaticPrivate is a better choice for most uses.
535  * </para></note>
536  *
537  * The #GPrivate struct is an opaque data structure to represent a
538  * thread private data key. Threads can thereby obtain and set a
539  * pointer which is private to the current thread. Take our
540  * <function>give_me_next_number(<!-- -->)</function> example from
541  * above.  Suppose we don't want <literal>current_number</literal> to be
542  * shared between the threads, but instead to be private to each thread.
543  * This can be done as follows:
544  *
545  * <example>
546  *  <title>Using GPrivate for per-thread data</title>
547  *  <programlisting>
548  *   GPrivate* current_number_key = NULL; /<!-- -->* Must be initialized somewhere
549  *                                           with g_private_new (g_free); *<!-- -->/
550  *
551  *   int
552  *   give_me_next_number (void)
553  *   {
554  *     int *current_number = g_private_get (current_number_key);
555  *
556  *     if (!current_number)
557  *       {
558  *         current_number = g_new (int, 1);
559  *         *current_number = 0;
560  *         g_private_set (current_number_key, current_number);
561  *       }
562  *
563  *     *current_number = calc_next_number (*current_number);
564  *
565  *     return *current_number;
566  *   }
567  *  </programlisting>
568  * </example>
569  *
570  * Here the pointer belonging to the key
571  * <literal>current_number_key</literal> is read. If it is %NULL, it has
572  * not been set yet. Then get memory for an integer value, assign this
573  * memory to the pointer and write the pointer back. Now we have an
574  * integer value that is private to the current thread.
575  *
576  * The #GPrivate struct should only be accessed via the
577  * <function>g_private_</function> functions.
578  */
579
580 /* GThread Documentation {{{1 ---------------------------------------- */
581
582 /**
583  * GThread:
584  *
585  * The #GThread struct represents a running thread.
586  *
587  * Resources for a joinable thread are not fully released
588  * until g_thread_join() is called for that thread.
589  */
590
591 /**
592  * GThreadFunc:
593  * @data: data passed to the thread
594  * @Returns: the return value of the thread, which will be returned by
595  *     g_thread_join()
596  *
597  * Specifies the type of the @func functions passed to
598  * g_thread_create() or g_thread_create_full().
599  */
600
601 /**
602  * g_thread_supported:
603  *
604  * This macro returns %TRUE if the thread system is initialized,
605  * and %FALSE if it is not.
606  *
607  * For language bindings, g_thread_get_initialized() provides
608  * the same functionality as a function.
609  *
610  * Returns: %TRUE, if the thread system is initialized
611  */
612
613 /* GThreadError {{{1 ------------------------------------------------------- */
614 /**
615  * GThreadError:
616  * @G_THREAD_ERROR_AGAIN: a thread couldn't be created due to resource
617  *                        shortage. Try again later.
618  *
619  * Possible errors of thread related functions.
620  **/
621
622 /**
623  * G_THREAD_ERROR:
624  *
625  * The error domain of the GLib thread subsystem.
626  **/
627 GQuark
628 g_thread_error_quark (void)
629 {
630   return g_quark_from_static_string ("g_thread_error");
631 }
632
633 /* Miscellaneous Structures {{{1 ------------------------------------------ */
634
635 typedef struct _GRealThread GRealThread;
636 struct  _GRealThread
637 {
638   GThread thread;
639   /* Bit 0 protects private_data. To avoid deadlocks,
640    * do not block while holding this (particularly on
641    * the g_thread lock).
642    */
643   volatile gint private_data_lock;
644   GArray *private_data;
645   GRealThread *next;
646   gpointer retval;
647   GSystemThread system_thread;
648 };
649
650 #define LOCK_PRIVATE_DATA(self)   g_bit_lock (&(self)->private_data_lock, 0)
651 #define UNLOCK_PRIVATE_DATA(self) g_bit_unlock (&(self)->private_data_lock, 0)
652
653 /* Local Data {{{1 -------------------------------------------------------- */
654
655 gboolean         g_threads_got_initialized = FALSE;
656 GSystemThread    zero_thread; /* This is initialized to all zero */
657 GMutex           g_once_mutex = G_MUTEX_INIT;
658
659 static GCond     g_once_cond = G_COND_INIT;
660 static GPrivate  g_thread_specific_private;
661 static GRealThread *g_thread_all_threads = NULL;
662 static GSList   *g_thread_free_indices = NULL;
663 static GSList*   g_once_init_list = NULL;
664
665 G_LOCK_DEFINE_STATIC (g_thread);
666
667 /* Initialisation {{{1 ---------------------------------------------------- */
668
669 /**
670  * g_thread_init:
671  * @vtable: a function table of type #GThreadFunctions, that provides
672  *     the entry points to the thread system to be used. Since 2.32,
673  *     this parameter is ignored and should always be %NULL
674  *
675  * If you use GLib from more than one thread, you must initialize the
676  * thread system by calling g_thread_init().
677  *
678  * Since version 2.24, calling g_thread_init() multiple times is allowed,
679  * but nothing happens except for the first call.
680  *
681  * Since version 2.32, GLib does not support custom thread implementations
682  * anymore and the @vtable parameter is ignored and you should pass %NULL.
683  *
684  * <note><para>g_thread_init() must not be called directly or indirectly
685  * in a callback from GLib. Also no mutexes may be currently locked while
686  * calling g_thread_init().</para></note>
687  *
688  * <note><para>To use g_thread_init() in your program, you have to link
689  * with the libraries that the command <command>pkg-config --libs
690  * gthread-2.0</command> outputs. This is not the case for all the
691  * other thread-related functions of GLib. Those can be used without
692  * having to link with the thread libraries.</para></note>
693  */
694
695 static void g_thread_cleanup (gpointer data);
696
697 void
698 g_thread_init_glib (void)
699 {
700   static gboolean already_done;
701   GRealThread* main_thread;
702
703   if (already_done)
704     return;
705
706   already_done = TRUE;
707
708   /* We let the main thread (the one that calls g_thread_init) inherit
709    * the static_private data set before calling g_thread_init
710    */
711   main_thread = (GRealThread*) g_thread_self ();
712
713   /* setup the basic threading system */
714   g_threads_got_initialized = TRUE;
715   g_private_init (&g_thread_specific_private, g_thread_cleanup);
716   g_private_set (&g_thread_specific_private, main_thread);
717   g_system_thread_self (&main_thread->system_thread);
718
719   /* accomplish log system initialization to enable messaging */
720   _g_messages_thread_init_nomessage ();
721 }
722
723 /**
724  * g_thread_get_initialized:
725  *
726  * Indicates if g_thread_init() has been called.
727  *
728  * Returns: %TRUE if threads have been initialized.
729  *
730  * Since: 2.20
731  */
732 gboolean
733 g_thread_get_initialized (void)
734 {
735   return g_thread_supported ();
736 }
737
738 /* GOnce {{{1 ------------------------------------------------------------- */
739
740 /**
741  * GOnce:
742  * @status: the status of the #GOnce
743  * @retval: the value returned by the call to the function, if @status
744  *          is %G_ONCE_STATUS_READY
745  *
746  * A #GOnce struct controls a one-time initialization function. Any
747  * one-time initialization function must have its own unique #GOnce
748  * struct.
749  *
750  * Since: 2.4
751  */
752
753 /**
754  * G_ONCE_INIT:
755  *
756  * A #GOnce must be initialized with this macro before it can be used.
757  *
758  * |[
759  *   GOnce my_once = G_ONCE_INIT;
760  * ]|
761  *
762  * Since: 2.4
763  */
764
765 /**
766  * GOnceStatus:
767  * @G_ONCE_STATUS_NOTCALLED: the function has not been called yet.
768  * @G_ONCE_STATUS_PROGRESS: the function call is currently in progress.
769  * @G_ONCE_STATUS_READY: the function has been called.
770  *
771  * The possible statuses of a one-time initialization function
772  * controlled by a #GOnce struct.
773  *
774  * Since: 2.4
775  */
776
777 /**
778  * g_once:
779  * @once: a #GOnce structure
780  * @func: the #GThreadFunc function associated to @once. This function
781  *        is called only once, regardless of the number of times it and
782  *        its associated #GOnce struct are passed to g_once().
783  * @arg: data to be passed to @func
784  *
785  * The first call to this routine by a process with a given #GOnce
786  * struct calls @func with the given argument. Thereafter, subsequent
787  * calls to g_once()  with the same #GOnce struct do not call @func
788  * again, but return the stored result of the first call. On return
789  * from g_once(), the status of @once will be %G_ONCE_STATUS_READY.
790  *
791  * For example, a mutex or a thread-specific data key must be created
792  * exactly once. In a threaded environment, calling g_once() ensures
793  * that the initialization is serialized across multiple threads.
794  *
795  * Calling g_once() recursively on the same #GOnce struct in
796  * @func will lead to a deadlock.
797  *
798  * |[
799  *   gpointer
800  *   get_debug_flags (void)
801  *   {
802  *     static GOnce my_once = G_ONCE_INIT;
803  *
804  *     g_once (&my_once, parse_debug_flags, NULL);
805  *
806  *     return my_once.retval;
807  *   }
808  * ]|
809  *
810  * Since: 2.4
811  */
812 gpointer
813 g_once_impl (GOnce       *once,
814              GThreadFunc  func,
815              gpointer     arg)
816 {
817   g_mutex_lock (&g_once_mutex);
818
819   while (once->status == G_ONCE_STATUS_PROGRESS)
820     g_cond_wait (&g_once_cond, &g_once_mutex);
821
822   if (once->status != G_ONCE_STATUS_READY)
823     {
824       once->status = G_ONCE_STATUS_PROGRESS;
825       g_mutex_unlock (&g_once_mutex);
826
827       once->retval = func (arg);
828
829       g_mutex_lock (&g_once_mutex);
830       once->status = G_ONCE_STATUS_READY;
831       g_cond_broadcast (&g_once_cond);
832     }
833
834   g_mutex_unlock (&g_once_mutex);
835
836   return once->retval;
837 }
838
839 /**
840  * g_once_init_enter:
841  * @value_location: location of a static initializable variable
842  *     containing 0
843  *
844  * Function to be called when starting a critical initialization
845  * section. The argument @value_location must point to a static
846  * 0-initialized variable that will be set to a value other than 0 at
847  * the end of the initialization section. In combination with
848  * g_once_init_leave() and the unique address @value_location, it can
849  * be ensured that an initialization section will be executed only once
850  * during a program's life time, and that concurrent threads are
851  * blocked until initialization completed. To be used in constructs
852  * like this:
853  *
854  * |[
855  *   static gsize initialization_value = 0;
856  *
857  *   if (g_once_init_enter (&amp;initialization_value))
858  *     {
859  *       gsize setup_value = 42; /&ast;* initialization code here *&ast;/
860  *
861  *       g_once_init_leave (&amp;initialization_value, setup_value);
862  *     }
863  *
864  *   /&ast;* use initialization_value here *&ast;/
865  * ]|
866  *
867  * Returns: %TRUE if the initialization section should be entered,
868  *     %FALSE and blocks otherwise
869  *
870  * Since: 2.14
871  */
872 gboolean
873 g_once_init_enter_impl (volatile gsize *value_location)
874 {
875   gboolean need_init = FALSE;
876   g_mutex_lock (&g_once_mutex);
877   if (g_atomic_pointer_get (value_location) == NULL)
878     {
879       if (!g_slist_find (g_once_init_list, (void*) value_location))
880         {
881           need_init = TRUE;
882           g_once_init_list = g_slist_prepend (g_once_init_list, (void*) value_location);
883         }
884       else
885         do
886           g_cond_wait (&g_once_cond, &g_once_mutex);
887         while (g_slist_find (g_once_init_list, (void*) value_location));
888     }
889   g_mutex_unlock (&g_once_mutex);
890   return need_init;
891 }
892
893 /**
894  * g_once_init_leave:
895  * @value_location: location of a static initializable variable
896  *     containing 0
897  * @initialization_value: new non-0 value for *@value_location
898  *
899  * Counterpart to g_once_init_enter(). Expects a location of a static
900  * 0-initialized initialization variable, and an initialization value
901  * other than 0. Sets the variable to the initialization value, and
902  * releases concurrent threads blocking in g_once_init_enter() on this
903  * initialization variable.
904  *
905  * Since: 2.14
906  */
907 void
908 g_once_init_leave (volatile gsize *value_location,
909                    gsize           initialization_value)
910 {
911   g_return_if_fail (g_atomic_pointer_get (value_location) == NULL);
912   g_return_if_fail (initialization_value != 0);
913   g_return_if_fail (g_once_init_list != NULL);
914
915   g_atomic_pointer_set (value_location, initialization_value);
916   g_mutex_lock (&g_once_mutex);
917   g_once_init_list = g_slist_remove (g_once_init_list, (void*) value_location);
918   g_cond_broadcast (&g_once_cond);
919   g_mutex_unlock (&g_once_mutex);
920 }
921
922 /* GStaticPrivate {{{1 ---------------------------------------------------- */
923
924 typedef struct _GStaticPrivateNode GStaticPrivateNode;
925 struct _GStaticPrivateNode
926 {
927   gpointer       data;
928   GDestroyNotify destroy;
929 };
930
931 /**
932  * GStaticPrivate:
933  *
934  * A #GStaticPrivate works almost like a #GPrivate, but it has one
935  * significant advantage. It doesn't need to be created at run-time
936  * like a #GPrivate, but can be defined at compile-time. This is
937  * similar to the difference between #GMutex and #GStaticMutex. Now
938  * look at our <function>give_me_next_number()</function> example with
939  * #GStaticPrivate:
940  *
941  * <example>
942  *  <title>Using GStaticPrivate for per-thread data</title>
943  *  <programlisting>
944  *   int
945  *   give_me_next_number (<!-- -->)
946  *   {
947  *     static GStaticPrivate current_number_key = G_STATIC_PRIVATE_INIT;
948  *     int *current_number = g_static_private_get (&amp;current_number_key);
949  *
950  *     if (!current_number)
951  *       {
952  *         current_number = g_new (int,1);
953  *         *current_number = 0;
954  *         g_static_private_set (&amp;current_number_key, current_number, g_free);
955  *       }
956  *
957  *     *current_number = calc_next_number (*current_number);
958  *
959  *     return *current_number;
960  *   }
961  *  </programlisting>
962  * </example>
963  */
964
965 /**
966  * G_STATIC_PRIVATE_INIT:
967  *
968  * Every #GStaticPrivate must be initialized with this macro, before it
969  * can be used.
970  *
971  * |[
972  *   GStaticPrivate my_private = G_STATIC_PRIVATE_INIT;
973  * ]|
974  */
975
976 /**
977  * g_static_private_init:
978  * @private_key: a #GStaticPrivate to be initialized
979  *
980  * Initializes @private_key. Alternatively you can initialize it with
981  * #G_STATIC_PRIVATE_INIT.
982  */
983 void
984 g_static_private_init (GStaticPrivate *private_key)
985 {
986   private_key->index = 0;
987 }
988
989 /**
990  * g_static_private_get:
991  * @private_key: a #GStaticPrivate
992  *
993  * Works like g_private_get() only for a #GStaticPrivate.
994  *
995  * This function works even if g_thread_init() has not yet been called.
996  *
997  * Returns: the corresponding pointer
998  */
999 gpointer
1000 g_static_private_get (GStaticPrivate *private_key)
1001 {
1002   GRealThread *self = (GRealThread*) g_thread_self ();
1003   GArray *array;
1004   gpointer ret = NULL;
1005
1006   LOCK_PRIVATE_DATA (self);
1007
1008   array = self->private_data;
1009
1010   if (array && private_key->index != 0 && private_key->index <= array->len)
1011     ret = g_array_index (array, GStaticPrivateNode,
1012                          private_key->index - 1).data;
1013
1014   UNLOCK_PRIVATE_DATA (self);
1015   return ret;
1016 }
1017
1018 /**
1019  * g_static_private_set:
1020  * @private_key: a #GStaticPrivate
1021  * @data: the new pointer
1022  * @notify: a function to be called with the pointer whenever the
1023  *     current thread ends or sets this pointer again
1024  *
1025  * Sets the pointer keyed to @private_key for the current thread and
1026  * the function @notify to be called with that pointer (%NULL or
1027  * non-%NULL), whenever the pointer is set again or whenever the
1028  * current thread ends.
1029  *
1030  * This function works even if g_thread_init() has not yet been called.
1031  * If g_thread_init() is called later, the @data keyed to @private_key
1032  * will be inherited only by the main thread, i.e. the one that called
1033  * g_thread_init().
1034  *
1035  * <note><para>@notify is used quite differently from @destructor in
1036  * g_private_new().</para></note>
1037  */
1038 void
1039 g_static_private_set (GStaticPrivate *private_key,
1040                       gpointer        data,
1041                       GDestroyNotify  notify)
1042 {
1043   GRealThread *self = (GRealThread*) g_thread_self ();
1044   GArray *array;
1045   static guint next_index = 0;
1046   GStaticPrivateNode *node;
1047   gpointer ddata = NULL;
1048   GDestroyNotify ddestroy = NULL;
1049
1050   if (!private_key->index)
1051     {
1052       G_LOCK (g_thread);
1053
1054       if (!private_key->index)
1055         {
1056           if (g_thread_free_indices)
1057             {
1058               private_key->index =
1059                 GPOINTER_TO_UINT (g_thread_free_indices->data);
1060               g_thread_free_indices =
1061                 g_slist_delete_link (g_thread_free_indices,
1062                                      g_thread_free_indices);
1063             }
1064           else
1065             private_key->index = ++next_index;
1066         }
1067
1068       G_UNLOCK (g_thread);
1069     }
1070
1071   LOCK_PRIVATE_DATA (self);
1072
1073   array = self->private_data;
1074   if (!array)
1075     {
1076       array = g_array_new (FALSE, TRUE, sizeof (GStaticPrivateNode));
1077       self->private_data = array;
1078     }
1079
1080   if (private_key->index > array->len)
1081     g_array_set_size (array, private_key->index);
1082
1083   node = &g_array_index (array, GStaticPrivateNode, private_key->index - 1);
1084
1085   ddata = node->data;
1086   ddestroy = node->destroy;
1087
1088   node->data = data;
1089   node->destroy = notify;
1090
1091   UNLOCK_PRIVATE_DATA (self);
1092
1093   if (ddestroy)
1094     ddestroy (ddata);
1095 }
1096
1097 /**
1098  * g_static_private_free:
1099  * @private_key: a #GStaticPrivate to be freed
1100  *
1101  * Releases all resources allocated to @private_key.
1102  *
1103  * You don't have to call this functions for a #GStaticPrivate with an
1104  * unbounded lifetime, i.e. objects declared 'static', but if you have
1105  * a #GStaticPrivate as a member of a structure and the structure is
1106  * freed, you should also free the #GStaticPrivate.
1107  */
1108 void
1109 g_static_private_free (GStaticPrivate *private_key)
1110 {
1111   guint idx = private_key->index;
1112   GRealThread *thread, *next;
1113   GArray *garbage = NULL;
1114
1115   if (!idx)
1116     return;
1117
1118   private_key->index = 0;
1119
1120   G_LOCK (g_thread);
1121
1122   thread = g_thread_all_threads;
1123
1124   for (thread = g_thread_all_threads; thread; thread = next)
1125     {
1126       GArray *array;
1127
1128       next = thread->next;
1129
1130       LOCK_PRIVATE_DATA (thread);
1131
1132       array = thread->private_data;
1133
1134       if (array && idx <= array->len)
1135         {
1136           GStaticPrivateNode *node = &g_array_index (array,
1137                                                      GStaticPrivateNode,
1138                                                      idx - 1);
1139           gpointer ddata = node->data;
1140           GDestroyNotify ddestroy = node->destroy;
1141
1142           node->data = NULL;
1143           node->destroy = NULL;
1144
1145           if (ddestroy)
1146             {
1147               /* defer non-trivial destruction til after we've finished
1148                * iterating, since we must continue to hold the lock */
1149               if (garbage == NULL)
1150                 garbage = g_array_new (FALSE, TRUE,
1151                                        sizeof (GStaticPrivateNode));
1152
1153               g_array_set_size (garbage, garbage->len + 1);
1154
1155               node = &g_array_index (garbage, GStaticPrivateNode,
1156                                      garbage->len - 1);
1157               node->data = ddata;
1158               node->destroy = ddestroy;
1159             }
1160         }
1161
1162       UNLOCK_PRIVATE_DATA (thread);
1163     }
1164   g_thread_free_indices = g_slist_prepend (g_thread_free_indices,
1165                                            GUINT_TO_POINTER (idx));
1166   G_UNLOCK (g_thread);
1167
1168   if (garbage)
1169     {
1170       guint i;
1171
1172       for (i = 0; i < garbage->len; i++)
1173         {
1174           GStaticPrivateNode *node;
1175
1176           node = &g_array_index (garbage, GStaticPrivateNode, i);
1177           node->destroy (node->data);
1178         }
1179
1180       g_array_free (garbage, TRUE);
1181     }
1182 }
1183
1184 /* GThread {{{1 -------------------------------------------------------- */
1185
1186 static void
1187 g_thread_cleanup (gpointer data)
1188 {
1189   if (data)
1190     {
1191       GRealThread* thread = data;
1192       GArray *array;
1193
1194       LOCK_PRIVATE_DATA (thread);
1195       array = thread->private_data;
1196       thread->private_data = NULL;
1197       UNLOCK_PRIVATE_DATA (thread);
1198
1199       if (array)
1200         {
1201           guint i;
1202
1203           for (i = 0; i < array->len; i++ )
1204             {
1205               GStaticPrivateNode *node =
1206                 &g_array_index (array, GStaticPrivateNode, i);
1207               if (node->destroy)
1208                 node->destroy (node->data);
1209             }
1210           g_array_free (array, TRUE);
1211         }
1212
1213       /* We only free the thread structure if it isn't joinable.
1214        * If it is, the structure is freed in g_thread_join()
1215        */
1216       if (!thread->thread.joinable)
1217         {
1218           GRealThread *t, *p;
1219
1220           G_LOCK (g_thread);
1221           for (t = g_thread_all_threads, p = NULL; t; p = t, t = t->next)
1222             {
1223               if (t == thread)
1224                 {
1225                   if (p)
1226                     p->next = t->next;
1227                   else
1228                     g_thread_all_threads = t->next;
1229                   break;
1230                 }
1231             }
1232           G_UNLOCK (g_thread);
1233
1234           /* Just to make sure, this isn't used any more */
1235           g_system_thread_assign (thread->system_thread, zero_thread);
1236           g_free (thread);
1237         }
1238     }
1239 }
1240
1241 static gpointer
1242 g_thread_create_proxy (gpointer data)
1243 {
1244   GRealThread* thread = data;
1245
1246   g_assert (data);
1247
1248   /* This has to happen before G_LOCK, as that might call g_thread_self */
1249   g_private_set (&g_thread_specific_private, data);
1250
1251   /* The lock makes sure that thread->system_thread is written,
1252    * before thread->thread.func is called. See g_thread_create().
1253    */
1254   G_LOCK (g_thread);
1255   G_UNLOCK (g_thread);
1256
1257   thread->retval = thread->thread.func (thread->thread.data);
1258
1259   return NULL;
1260 }
1261
1262 /**
1263  * g_thread_create:
1264  * @func: a function to execute in the new thread
1265  * @data: an argument to supply to the new thread
1266  * @joinable: should this thread be joinable?
1267  * @error: return location for error, or %NULL
1268  *
1269  * This function creates a new thread.
1270  *
1271  * If @joinable is %TRUE, you can wait for this threads termination
1272  * calling g_thread_join(). Otherwise the thread will just disappear
1273  * when it terminates.
1274  *
1275  * The new thread executes the function @func with the argument @data.
1276  * If the thread was created successfully, it is returned.
1277  *
1278  * @error can be %NULL to ignore errors, or non-%NULL to report errors.
1279  * The error is set, if and only if the function returns %NULL.
1280  *
1281  * Returns: the new #GThread on success
1282  */
1283 GThread *
1284 g_thread_create (GThreadFunc   func,
1285                  gpointer      data,
1286                  gboolean      joinable,
1287                  GError      **error)
1288 {
1289   return g_thread_create_with_stack_size (func, data, joinable, 0, error);
1290 }
1291
1292 /**
1293  * g_thread_create_with_stack_size:
1294  * @func: a function to execute in the new thread
1295  * @data: an argument to supply to the new thread
1296  * @joinable: should this thread be joinable?
1297  * @stack_size: a stack size for the new thread
1298  * @error: return location for error
1299  *
1300  * This function creates a new thread. If the underlying thread
1301  * implementation supports it, the thread gets a stack size of
1302  * @stack_size or the default value for the current platform, if
1303  * @stack_size is 0.
1304  *
1305  * If @joinable is %TRUE, you can wait for this threads termination
1306  * calling g_thread_join(). Otherwise the thread will just disappear
1307  * when it terminates.
1308  *
1309  * The new thread executes the function @func with the argument @data.
1310  * If the thread was created successfully, it is returned.
1311  *
1312  * @error can be %NULL to ignore errors, or non-%NULL to report errors.
1313  * The error is set, if and only if the function returns %NULL.
1314  *
1315  * <note><para>Only use g_thread_create_with_stack_size() if you
1316  * really can't use g_thread_create() instead. g_thread_create()
1317  * does not take @stack_size, as it should only be used in cases
1318  * in which it is unavoidable.</para></note>
1319  *
1320  * Returns: the new #GThread on success
1321  *
1322  * Since: 2.32
1323  */
1324 GThread*
1325 g_thread_create_with_stack_size (GThreadFunc   func,
1326                                  gpointer      data,
1327                                  gboolean      joinable,
1328                                  gsize         stack_size,
1329                                  GError      **error)
1330 {
1331   GRealThread* result;
1332   GError *local_error = NULL;
1333   g_return_val_if_fail (func, NULL);
1334
1335   result = g_new0 (GRealThread, 1);
1336
1337   result->thread.joinable = joinable;
1338   result->thread.func = func;
1339   result->thread.data = data;
1340   result->private_data = NULL;
1341   G_LOCK (g_thread);
1342   g_system_thread_create (g_thread_create_proxy, result,
1343                           stack_size, joinable,
1344                           &result->system_thread, &local_error);
1345   if (!local_error)
1346     {
1347       result->next = g_thread_all_threads;
1348       g_thread_all_threads = result;
1349     }
1350   G_UNLOCK (g_thread);
1351
1352   if (local_error)
1353     {
1354       g_propagate_error (error, local_error);
1355       g_free (result);
1356       return NULL;
1357     }
1358
1359   return (GThread*) result;
1360 }
1361
1362 /**
1363  * g_thread_exit:
1364  * @retval: the return value of this thread
1365  *
1366  * Exits the current thread. If another thread is waiting for that
1367  * thread using g_thread_join() and the current thread is joinable, the
1368  * waiting thread will be woken up and get @retval as the return value
1369  * of g_thread_join(). If the current thread is not joinable, @retval
1370  * is ignored. Calling
1371  *
1372  * |[
1373  *   g_thread_exit (retval);
1374  * ]|
1375  *
1376  * is equivalent to returning @retval from the function @func, as given
1377  * to g_thread_create().
1378  *
1379  * <note><para>Never call g_thread_exit() from within a thread of a
1380  * #GThreadPool, as that will mess up the bookkeeping and lead to funny
1381  * and unwanted results.</para></note>
1382  */
1383 void
1384 g_thread_exit (gpointer retval)
1385 {
1386   GRealThread* real = (GRealThread*) g_thread_self ();
1387   real->retval = retval;
1388
1389   g_system_thread_exit ();
1390 }
1391
1392 /**
1393  * g_thread_join:
1394  * @thread: a #GThread to be waited for
1395  *
1396  * Waits until @thread finishes, i.e. the function @func, as given to
1397  * g_thread_create(), returns or g_thread_exit() is called by @thread.
1398  * All resources of @thread including the #GThread struct are released.
1399  * @thread must have been created with @joinable=%TRUE in
1400  * g_thread_create(). The value returned by @func or given to
1401  * g_thread_exit() by @thread is returned by this function.
1402  *
1403  * Returns: the return value of the thread
1404  */
1405 gpointer
1406 g_thread_join (GThread* thread)
1407 {
1408   GRealThread* real = (GRealThread*) thread;
1409   GRealThread *p, *t;
1410   gpointer retval;
1411
1412   g_return_val_if_fail (thread, NULL);
1413   g_return_val_if_fail (thread->joinable, NULL);
1414   g_return_val_if_fail (!g_system_thread_equal (&real->system_thread, &zero_thread), NULL);
1415
1416   g_system_thread_join (&real->system_thread);
1417
1418   retval = real->retval;
1419
1420   G_LOCK (g_thread);
1421   for (t = g_thread_all_threads, p = NULL; t; p = t, t = t->next)
1422     {
1423       if (t == (GRealThread*) thread)
1424         {
1425           if (p)
1426             p->next = t->next;
1427           else
1428             g_thread_all_threads = t->next;
1429           break;
1430         }
1431     }
1432   G_UNLOCK (g_thread);
1433
1434   /* Just to make sure, this isn't used any more */
1435   thread->joinable = 0;
1436   g_system_thread_assign (real->system_thread, zero_thread);
1437
1438   /* the thread structure for non-joinable threads is freed upon
1439    * thread end. We free the memory here. This will leave a loose end,
1440    * if a joinable thread is not joined.
1441    */
1442   g_free (thread);
1443
1444   return retval;
1445 }
1446
1447 /**
1448  * g_thread_self:
1449  *
1450  * This functions returns the #GThread corresponding to the calling
1451  * thread.
1452  *
1453  * Returns: the current thread
1454  */
1455 GThread*
1456 g_thread_self (void)
1457 {
1458   GRealThread* thread = g_private_get (&g_thread_specific_private);
1459
1460   if (!thread)
1461     {
1462       /* If no thread data is available, provide and set one.
1463        * This can happen for the main thread and for threads
1464        * that are not created by GLib.
1465        */
1466       thread = g_new0 (GRealThread, 1);
1467       thread->thread.joinable = FALSE; /* This is a safe guess */
1468       thread->thread.func = NULL;
1469       thread->thread.data = NULL;
1470       thread->private_data = NULL;
1471
1472       g_system_thread_self (&thread->system_thread);
1473
1474       g_private_set (&g_thread_specific_private, thread);
1475
1476       G_LOCK (g_thread);
1477       thread->next = g_thread_all_threads;
1478       g_thread_all_threads = thread;
1479       G_UNLOCK (g_thread);
1480     }
1481
1482   return (GThread*)thread;
1483 }
1484
1485 /**
1486  * g_thread_foreach:
1487  * @thread_func: function to call for all #GThread structures
1488  * @user_data: second argument to @thread_func
1489  *
1490  * Call @thread_func on all existing #GThread structures.
1491  * Note that threads may decide to exit while @thread_func is
1492  * running, so without intimate knowledge about the lifetime of
1493  * foreign threads, @thread_func shouldn't access the GThread*
1494  * pointer passed in as first argument. However, @thread_func will
1495  * not be called for threads which are known to have exited already.
1496  *
1497  * Due to thread lifetime checks, this function has an execution complexity
1498  * which is quadratic in the number of existing threads.
1499  *
1500  * Since: 2.10
1501  */
1502 void
1503 g_thread_foreach (GFunc    thread_func,
1504                   gpointer user_data)
1505 {
1506   GSList *slist = NULL;
1507   GRealThread *thread;
1508   g_return_if_fail (thread_func != NULL);
1509   /* snapshot the list of threads for iteration */
1510   G_LOCK (g_thread);
1511   for (thread = g_thread_all_threads; thread; thread = thread->next)
1512     slist = g_slist_prepend (slist, thread);
1513   G_UNLOCK (g_thread);
1514   /* walk the list, skipping non-existent threads */
1515   while (slist)
1516     {
1517       GSList *node = slist;
1518       slist = node->next;
1519       /* check whether the current thread still exists */
1520       G_LOCK (g_thread);
1521       for (thread = g_thread_all_threads; thread; thread = thread->next)
1522         if (thread == node->data)
1523           break;
1524       G_UNLOCK (g_thread);
1525       if (thread)
1526         thread_func (thread, user_data);
1527       g_slist_free_1 (node);
1528     }
1529 }
1530
1531 /* GMutex {{{1 ------------------------------------------------------ */
1532
1533 /**
1534  * g_mutex_new:
1535  *
1536  * Allocated and initializes a new #GMutex.
1537  *
1538  * Returns: a newly allocated #GMutex. Use g_mutex_free() to free
1539  */
1540 GMutex *
1541 g_mutex_new (void)
1542 {
1543   GMutex *mutex;
1544
1545   mutex = g_slice_new (GMutex);
1546   g_mutex_init (mutex);
1547
1548   return mutex;
1549 }
1550
1551 /**
1552  * g_mutex_free:
1553  * @mutex: a #GMutex
1554  *
1555  * Destroys a @mutex that has been created with g_mutex_new().
1556  *
1557  * Calling g_mutex_free() on a locked mutex may result
1558  * in undefined behaviour.
1559  */
1560 void
1561 g_mutex_free (GMutex *mutex)
1562 {
1563   g_mutex_clear (mutex);
1564   g_slice_free (GMutex, mutex);
1565 }
1566
1567 /* GCond {{{1 ------------------------------------------------------ */
1568
1569 /**
1570  * g_cond_new:
1571  *
1572  * Allocates and initializes a new #GCond.
1573  *
1574  * Returns: a newly allocated #GCond. Free with g_cond_free()
1575  */
1576 GCond *
1577 g_cond_new (void)
1578 {
1579   GCond *cond;
1580
1581   cond = g_slice_new (GCond);
1582   g_cond_init (cond);
1583
1584   return cond;
1585 }
1586
1587 /**
1588  * g_cond_free:
1589  * @cond: a #GCond
1590  *
1591  * Destroys a #GCond that has been created with g_cond_new().
1592  */
1593 void
1594 g_cond_free (GCond *cond)
1595 {
1596   g_cond_clear (cond);
1597   g_slice_free (GCond, cond);
1598 }
1599
1600 /* GPrivate {{{1 ------------------------------------------------------ */
1601
1602 /**
1603  * g_private_new:
1604  * @destructor: a function to destroy the data keyed to
1605  *     the #GPrivate when a thread ends
1606  *
1607  * Creates a new #GPrivate. If @destructor is non-%NULL, it is a
1608  * pointer to a destructor function. Whenever a thread ends and the
1609  * corresponding pointer keyed to this instance of #GPrivate is
1610  * non-%NULL, the destructor is called with this pointer as the
1611  * argument.
1612  *
1613  * <note><para>
1614  * #GStaticPrivate is a better choice for most uses.
1615  * </para></note>
1616  *
1617  * <note><para>@destructor is used quite differently from @notify in
1618  * g_static_private_set().</para></note>
1619  *
1620  * <note><para>A #GPrivate cannot be freed. Reuse it instead, if you
1621  * can, to avoid shortage, or use #GStaticPrivate.</para></note>
1622  *
1623  * <note><para>This function will abort if g_thread_init() has not been
1624  * called yet.</para></note>
1625  *
1626  * Returns: a newly allocated #GPrivate
1627  */
1628 GPrivate *
1629 g_private_new (GDestroyNotify notify)
1630 {
1631   GPrivate *key;
1632
1633   key = g_slice_new (GPrivate);
1634   g_private_init (key, notify);
1635
1636   return key;
1637 }
1638
1639  /* vim: set foldmethod=marker: */