gslice: move initialisation to glib-ctor
[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 #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: thread abstraction; including threads, different
71  *                     mutexes, 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, #GStaticMutex, #G_LOCK_DEFINE, #GStaticRecMutex and
88  * #GStaticRWLock). There is a facility to use individual bits for
89  * locks (g_bit_lock()). There are primitives for condition variables to
90  * allow synchronization of threads (#GCond).  There are primitives for
91  * thread-private data - data that every thread has a private instance
92  * of (#GPrivate, #GStaticPrivate). There are facilities for one-time
93  * initialization (#GOnce, g_once_init_enter()). Last but definitely
94  * not least there are primitives to portably create and manage
95  * threads (#GThread).
96  *
97  * The threading system is initialized with g_thread_init(), which
98  * takes an optional custom thread implementation or %NULL for the
99  * default implementation. If you want to call g_thread_init() with a
100  * non-%NULL argument this must be done before executing any other GLib
101  * functions (except g_mem_set_vtable()). This is a requirement even if
102  * no threads are in fact ever created by the process.
103  *
104  * Calling g_thread_init() with a %NULL argument is somewhat more
105  * relaxed. You may call any other glib functions in the main thread
106  * before g_thread_init() as long as g_thread_init() is not called from
107  * a glib callback, or with any locks held. However, many libraries
108  * above glib does not support late initialization of threads, so doing
109  * this should be avoided if possible.
110  *
111  * Please note that since version 2.24 the GObject initialization
112  * function g_type_init() initializes threads (with a %NULL argument),
113  * so most applications, including those using Gtk+ will run with
114  * threads enabled. If you want a special thread implementation, make
115  * sure you call g_thread_init() before g_type_init() is called.
116  *
117  * After calling g_thread_init(), GLib is completely thread safe (all
118  * global data is automatically locked), but individual data structure
119  * instances are not automatically locked for performance reasons. So,
120  * for example you must coordinate accesses to the same #GHashTable
121  * from multiple threads.  The two notable exceptions from this rule
122  * are #GMainLoop and #GAsyncQueue, which <emphasis>are</emphasis>
123  * threadsafe and need no further application-level locking to be
124  * accessed from multiple threads.
125  *
126  * To help debugging problems in multithreaded applications, GLib
127  * supports error-checking mutexes that will give you helpful error
128  * messages on common problems. To use error-checking mutexes, define
129  * the symbol #G_ERRORCHECK_MUTEXES when compiling the application.
130  **/
131
132 /**
133  * G_THREADS_IMPL_POSIX:
134  *
135  * This macro is defined if POSIX style threads are used.
136  **/
137
138 /**
139  * G_THREADS_ENABLED:
140  *
141  * This macro is defined, for backward compatibility, to indicate that
142  * GLib has been compiled with thread support. As of glib 2.28, it is
143  * always defined.
144  **/
145
146 /**
147  * G_THREADS_IMPL_NONE:
148  *
149  * This macro is defined if no thread implementation is used. You can,
150  * however, provide one to g_thread_init() to make GLib multi-thread
151  * safe.
152  **/
153
154 /* G_LOCK Documentation {{{1 ---------------------------------------------- */
155
156 /* IMPLEMENTATION NOTE:
157  *
158  * G_LOCK_DEFINE and friends are convenience macros defined in
159  * gthread.h.  Their documentation lives here.
160  */
161
162 /**
163  * G_LOCK_DEFINE:
164  * @name: the name of the lock.
165  *
166  * The %G_LOCK_* macros provide a convenient interface to #GStaticMutex
167  * with the advantage that they will expand to nothing in programs
168  * compiled against a thread-disabled GLib, saving code and memory
169  * there. #G_LOCK_DEFINE defines a lock. It can appear anywhere
170  * variable definitions may appear in programs, i.e. in the first block
171  * of a function or outside of functions. The @name parameter will be
172  * mangled to get the name of the #GStaticMutex. This means that you
173  * can use names of existing variables as the parameter - e.g. the name
174  * of the variable you intent to protect with the lock. Look at our
175  * <function>give_me_next_number()</function> example using the
176  * %G_LOCK_* macros:
177  *
178  * <example>
179  *  <title>Using the %G_LOCK_* convenience macros</title>
180  *  <programlisting>
181  *   G_LOCK_DEFINE (current_number);
182  *
183  *   int
184  *   give_me_next_number (void)
185  *   {
186  *     static int current_number = 0;
187  *     int ret_val;
188  *
189  *     G_LOCK (current_number);
190  *     ret_val = current_number = calc_next_number (current_number);
191  *     G_UNLOCK (current_number);
192  *
193  *     return ret_val;
194  *   }
195  *  </programlisting>
196  * </example>
197  **/
198
199 /**
200  * G_LOCK_DEFINE_STATIC:
201  * @name: the name of the lock.
202  *
203  * This works like #G_LOCK_DEFINE, but it creates a static object.
204  **/
205
206 /**
207  * G_LOCK_EXTERN:
208  * @name: the name of the lock.
209  *
210  * This declares a lock, that is defined with #G_LOCK_DEFINE in another
211  * module.
212  **/
213
214 /**
215  * G_LOCK:
216  * @name: the name of the lock.
217  *
218  * Works like g_mutex_lock(), but for a lock defined with
219  * #G_LOCK_DEFINE.
220  **/
221
222 /**
223  * G_TRYLOCK:
224  * @name: the name of the lock.
225  * @Returns: %TRUE, if the lock could be locked.
226  *
227  * Works like g_mutex_trylock(), but for a lock defined with
228  * #G_LOCK_DEFINE.
229  **/
230
231 /**
232  * G_UNLOCK:
233  * @name: the name of the lock.
234  *
235  * Works like g_mutex_unlock(), but for a lock defined with
236  * #G_LOCK_DEFINE.
237  **/
238
239 /* GThreadError {{{1 ------------------------------------------------------- */
240 /**
241  * GThreadError:
242  * @G_THREAD_ERROR_AGAIN: a thread couldn't be created due to resource
243  *                        shortage. Try again later.
244  *
245  * Possible errors of thread related functions.
246  **/
247
248 /**
249  * G_THREAD_ERROR:
250  *
251  * The error domain of the GLib thread subsystem.
252  **/
253 GQuark
254 g_thread_error_quark (void)
255 {
256   return g_quark_from_static_string ("g_thread_error");
257 }
258
259 /* Miscellaneous Structures {{{1 ------------------------------------------ */
260 typedef struct _GRealThread GRealThread;
261 struct  _GRealThread
262 {
263   GThread thread;
264   /* Bit 0 protects private_data. To avoid deadlocks, do not block while
265    * holding this (particularly on the g_thread lock). */
266   volatile gint private_data_lock;
267   GArray *private_data;
268   GRealThread *next;
269   gpointer retval;
270   GSystemThread system_thread;
271 };
272
273 #define LOCK_PRIVATE_DATA(self)   g_bit_lock (&(self)->private_data_lock, 0)
274 #define UNLOCK_PRIVATE_DATA(self) g_bit_unlock (&(self)->private_data_lock, 0)
275
276 typedef struct _GStaticPrivateNode GStaticPrivateNode;
277 struct _GStaticPrivateNode
278 {
279   gpointer       data;
280   GDestroyNotify destroy;
281 };
282
283 static void    g_thread_cleanup (gpointer data);
284 static void    g_thread_fail (void);
285 static guint64 gettime (void);
286
287 guint64        (*g_thread_gettime) (void) = gettime;
288
289 /* Global Variables {{{1 -------------------------------------------------- */
290
291 static GSystemThread zero_thread; /* This is initialized to all zero */
292 gboolean g_thread_use_default_impl = TRUE;
293
294 /**
295  * g_thread_supported:
296  * @Returns: %TRUE, if the thread system is initialized.
297  *
298  * This function returns %TRUE if the thread system is initialized, and
299  * %FALSE if it is not.
300  *
301  * <note><para>This function is actually a macro. Apart from taking the
302  * address of it you can however use it as if it was a
303  * function.</para></note>
304  **/
305
306 /* IMPLEMENTATION NOTE:
307  *
308  * g_thread_supported() is just returns g_threads_got_initialized
309  */
310 gboolean g_threads_got_initialized = FALSE;
311
312
313 /* Thread Implementation Virtual Function Table {{{1 ---------------------- */
314 /* Virtual Function Table Documentation {{{2 ------------------------------ */
315 /**
316  * GThreadFunctions:
317  * @mutex_new: virtual function pointer for g_mutex_new()
318  * @mutex_lock: virtual function pointer for g_mutex_lock()
319  * @mutex_trylock: virtual function pointer for g_mutex_trylock()
320  * @mutex_unlock: virtual function pointer for g_mutex_unlock()
321  * @mutex_free: virtual function pointer for g_mutex_free()
322  * @cond_new: virtual function pointer for g_cond_new()
323  * @cond_signal: virtual function pointer for g_cond_signal()
324  * @cond_broadcast: virtual function pointer for g_cond_broadcast()
325  * @cond_wait: virtual function pointer for g_cond_wait()
326  * @cond_timed_wait: virtual function pointer for g_cond_timed_wait()
327  * @cond_free: virtual function pointer for g_cond_free()
328  * @private_new: virtual function pointer for g_private_new()
329  * @private_get: virtual function pointer for g_private_get()
330  * @private_set: virtual function pointer for g_private_set()
331  * @thread_create: virtual function pointer for g_thread_create()
332  * @thread_yield: virtual function pointer for g_thread_yield()
333  * @thread_join: virtual function pointer for g_thread_join()
334  * @thread_exit: virtual function pointer for g_thread_exit()
335  * @thread_set_priority: virtual function pointer for
336  *                       g_thread_set_priority()
337  * @thread_self: virtual function pointer for g_thread_self()
338  * @thread_equal: used internally by recursive mutex locks and by some
339  *                assertion checks
340  *
341  * This function table is used by g_thread_init() to initialize the
342  * thread system. The functions in the table are directly used by their
343  * g_* prepended counterparts (described in this document).  For
344  * example, if you call g_mutex_new() then mutex_new() from the table
345  * provided to g_thread_init() will be called.
346  *
347  * <note><para>Do not use this struct unless you know what you are
348  * doing.</para></note>
349  **/
350
351 /* IMPLEMENTATION NOTE:
352  *
353  * g_thread_functions_for_glib_use is a global symbol that gets used by
354  * most of the "primitive" threading calls.  g_mutex_lock(), for
355  * example, is just a macro that calls the appropriate virtual function
356  * out of this table.
357  *
358  * For that reason, all of those macros are documented here.
359  */
360 static GThreadFunctions g_thread_functions_for_glib_use_old = {
361 /* GMutex Virtual Functions {{{2 ------------------------------------------ */
362
363 /**
364  * GMutex:
365  *
366  * The #GMutex struct is an opaque data structure to represent a mutex
367  * (mutual exclusion). It can be used to protect data against shared
368  * access. Take for example the following function:
369  *
370  * <example>
371  *  <title>A function which will not work in a threaded environment</title>
372  *  <programlisting>
373  *   int
374  *   give_me_next_number (void)
375  *   {
376  *     static int current_number = 0;
377  *
378  *     /<!-- -->* now do a very complicated calculation to calculate the new
379  *      * number, this might for example be a random number generator
380  *      *<!-- -->/
381  *     current_number = calc_next_number (current_number);
382  *
383  *     return current_number;
384  *   }
385  *  </programlisting>
386  * </example>
387  *
388  * It is easy to see that this won't work in a multi-threaded
389  * application. There current_number must be protected against shared
390  * access. A first naive implementation would be:
391  *
392  * <example>
393  *  <title>The wrong way to write a thread-safe function</title>
394  *  <programlisting>
395  *   int
396  *   give_me_next_number (void)
397  *   {
398  *     static int current_number = 0;
399  *     int ret_val;
400  *     static GMutex * mutex = NULL;
401  *
402  *     if (!mutex) mutex = g_mutex_new (<!-- -->);
403  *
404  *     g_mutex_lock (mutex);
405  *     ret_val = current_number = calc_next_number (current_number);
406  *     g_mutex_unlock (mutex);
407  *
408  *     return ret_val;
409  *   }
410  *  </programlisting>
411  * </example>
412  *
413  * This looks like it would work, but there is a race condition while
414  * constructing the mutex and this code cannot work reliable. Please do
415  * not use such constructs in your own programs! One working solution
416  * is:
417  *
418  * <example>
419  *  <title>A correct thread-safe function</title>
420  *  <programlisting>
421  *   static GMutex *give_me_next_number_mutex = NULL;
422  *
423  *   /<!-- -->* this function must be called before any call to
424  *    * give_me_next_number(<!-- -->)
425  *    *
426  *    * it must be called exactly once.
427  *    *<!-- -->/
428  *   void
429  *   init_give_me_next_number (void)
430  *   {
431  *     g_assert (give_me_next_number_mutex == NULL);
432  *     give_me_next_number_mutex = g_mutex_new (<!-- -->);
433  *   }
434  *
435  *   int
436  *   give_me_next_number (void)
437  *   {
438  *     static int current_number = 0;
439  *     int ret_val;
440  *
441  *     g_mutex_lock (give_me_next_number_mutex);
442  *     ret_val = current_number = calc_next_number (current_number);
443  *     g_mutex_unlock (give_me_next_number_mutex);
444  *
445  *     return ret_val;
446  *   }
447  *  </programlisting>
448  * </example>
449  *
450  * #GStaticMutex provides a simpler and safer way of doing this.
451  *
452  * If you want to use a mutex, and your code should also work without
453  * calling g_thread_init() first, then you cannot use a #GMutex, as
454  * g_mutex_new() requires that the thread system be initialized. Use a
455  * #GStaticMutex instead.
456  *
457  * A #GMutex should only be accessed via the following functions.
458  *
459  * <note><para>All of the <function>g_mutex_*</function> functions are
460  * actually macros. Apart from taking their addresses, you can however
461  * use them as if they were functions.</para></note>
462  **/
463
464 /**
465  * g_mutex_new:
466  * @Returns: a new #GMutex.
467  *
468  * Creates a new #GMutex.
469  *
470  * <note><para>This function will abort if g_thread_init() has not been
471  * called yet.</para></note>
472  **/
473   (GMutex*(*)())g_thread_fail,
474
475 /**
476  * g_mutex_lock:
477  * @mutex: a #GMutex.
478  *
479  * Locks @mutex. If @mutex is already locked by another thread, the
480  * current thread will block until @mutex is unlocked by the other
481  * thread.
482  *
483  * This function can be used even if g_thread_init() has not yet been
484  * called, and, in that case, will do nothing.
485  *
486  * <note><para>#GMutex is neither guaranteed to be recursive nor to be
487  * non-recursive, i.e. a thread could deadlock while calling
488  * g_mutex_lock(), if it already has locked @mutex. Use
489  * #GStaticRecMutex, if you need recursive mutexes.</para></note>
490  **/
491   NULL,
492
493 /**
494  * g_mutex_trylock:
495  * @mutex: a #GMutex.
496  * @Returns: %TRUE, if @mutex could be locked.
497  *
498  * Tries to lock @mutex. If @mutex is already locked by another thread,
499  * it immediately returns %FALSE. Otherwise it locks @mutex and returns
500  * %TRUE.
501  *
502  * This function can be used even if g_thread_init() has not yet been
503  * called, and, in that case, will immediately return %TRUE.
504  *
505  * <note><para>#GMutex is neither guaranteed to be recursive nor to be
506  * non-recursive, i.e. the return value of g_mutex_trylock() could be
507  * both %FALSE or %TRUE, if the current thread already has locked
508  * @mutex. Use #GStaticRecMutex, if you need recursive
509  * mutexes.</para></note>
510  **/
511   NULL,
512
513 /**
514  * g_mutex_unlock:
515  * @mutex: a #GMutex.
516  *
517  * Unlocks @mutex. If another thread is blocked in a g_mutex_lock()
518  * call for @mutex, it will be woken and can lock @mutex itself.
519  *
520  * This function can be used even if g_thread_init() has not yet been
521  * called, and, in that case, will do nothing.
522  **/
523   NULL,
524
525 /**
526  * g_mutex_free:
527  * @mutex: a #GMutex.
528  *
529  * Destroys @mutex.
530  *
531  * <note><para>Calling g_mutex_free() on a locked mutex may result in
532  * undefined behaviour.</para></note>
533  **/
534   NULL,
535
536 /* GCond Virtual Functions {{{2 ------------------------------------------ */
537
538 /**
539  * GCond:
540  *
541  * The #GCond struct is an opaque data structure that represents a
542  * condition. Threads can block on a #GCond if they find a certain
543  * condition to be false. If other threads change the state of this
544  * condition they signal the #GCond, and that causes the waiting
545  * threads to be woken up.
546  *
547  * <example>
548  *  <title>
549  *   Using GCond to block a thread until a condition is satisfied
550  *  </title>
551  *  <programlisting>
552  *   GCond* data_cond = NULL; /<!-- -->* Must be initialized somewhere *<!-- -->/
553  *   GMutex* data_mutex = NULL; /<!-- -->* Must be initialized somewhere *<!-- -->/
554  *   gpointer current_data = NULL;
555  *
556  *   void
557  *   push_data (gpointer data)
558  *   {
559  *     g_mutex_lock (data_mutex);
560  *     current_data = data;
561  *     g_cond_signal (data_cond);
562  *     g_mutex_unlock (data_mutex);
563  *   }
564  *
565  *   gpointer
566  *   pop_data (void)
567  *   {
568  *     gpointer data;
569  *
570  *     g_mutex_lock (data_mutex);
571  *     while (!current_data)
572  *       g_cond_wait (data_cond, data_mutex);
573  *     data = current_data;
574  *     current_data = NULL;
575  *     g_mutex_unlock (data_mutex);
576  *
577  *     return data;
578  *   }
579  *  </programlisting>
580  * </example>
581  *
582  * Whenever a thread calls <function>pop_data()</function> now, it will
583  * wait until current_data is non-%NULL, i.e. until some other thread
584  * has called <function>push_data()</function>.
585  *
586  * <note><para>It is important to use the g_cond_wait() and
587  * g_cond_timed_wait() functions only inside a loop which checks for the
588  * condition to be true.  It is not guaranteed that the waiting thread
589  * will find the condition fulfilled after it wakes up, even if the
590  * signaling thread left the condition in that state: another thread may
591  * have altered the condition before the waiting thread got the chance
592  * to be woken up, even if the condition itself is protected by a
593  * #GMutex, like above.</para></note>
594  *
595  * A #GCond should only be accessed via the following functions.
596  *
597  * <note><para>All of the <function>g_cond_*</function> functions are
598  * actually macros. Apart from taking their addresses, you can however
599  * use them as if they were functions.</para></note>
600  **/
601
602 /**
603  * g_cond_new:
604  * @Returns: a new #GCond.
605  *
606  * Creates a new #GCond. This function will abort, if g_thread_init()
607  * has not been called yet.
608  **/
609   (GCond*(*)())g_thread_fail,
610
611 /**
612  * g_cond_signal:
613  * @cond: a #GCond.
614  *
615  * If threads are waiting for @cond, exactly one of them is woken up.
616  * It is good practice to hold the same lock as the waiting thread
617  * while calling this function, though not required.
618  *
619  * This function can be used even if g_thread_init() has not yet been
620  * called, and, in that case, will do nothing.
621  **/
622   NULL,
623
624 /**
625  * g_cond_broadcast:
626  * @cond: a #GCond.
627  *
628  * If threads are waiting for @cond, all of them are woken up. It is
629  * good practice to lock the same mutex as the waiting threads, while
630  * calling this function, though not required.
631  *
632  * This function can be used even if g_thread_init() has not yet been
633  * called, and, in that case, will do nothing.
634  **/
635   NULL,
636
637 /**
638  * g_cond_wait:
639  * @cond: a #GCond.
640  * @mutex: a #GMutex, that is currently locked.
641  *
642  * Waits until this thread is woken up on @cond. The @mutex is unlocked
643  * before falling asleep and locked again before resuming.
644  *
645  * This function can be used even if g_thread_init() has not yet been
646  * called, and, in that case, will immediately return.
647  **/
648   NULL,
649
650 /**
651  * g_cond_timed_wait:
652  * @cond: a #GCond.
653  * @mutex: a #GMutex that is currently locked.
654  * @abs_time: a #GTimeVal, determining the final time.
655  * @Returns: %TRUE if @cond was signalled, or %FALSE on timeout.
656  *
657  * Waits until this thread is woken up on @cond, but not longer than
658  * until the time specified by @abs_time. The @mutex is unlocked before
659  * falling asleep and locked again before resuming.
660  *
661  * If @abs_time is %NULL, g_cond_timed_wait() acts like g_cond_wait().
662  *
663  * This function can be used even if g_thread_init() has not yet been
664  * called, and, in that case, will immediately return %TRUE.
665  *
666  * To easily calculate @abs_time a combination of g_get_current_time()
667  * and g_time_val_add() can be used.
668  **/
669   NULL,
670
671 /**
672  * g_cond_free:
673  * @cond: a #GCond.
674  *
675  * Destroys the #GCond.
676  **/
677   NULL,
678
679 /* GPrivate Virtual Functions {{{2 --------------------------------------- */
680
681 /**
682  * GPrivate:
683  *
684  * <note><para>
685  * #GStaticPrivate is a better choice for most uses.
686  * </para></note>
687  *
688  * The #GPrivate struct is an opaque data structure to represent a
689  * thread private data key. Threads can thereby obtain and set a
690  * pointer which is private to the current thread. Take our
691  * <function>give_me_next_number(<!-- -->)</function> example from
692  * above.  Suppose we don't want <literal>current_number</literal> to be
693  * shared between the threads, but instead to be private to each thread.
694  * This can be done as follows:
695  *
696  * <example>
697  *  <title>Using GPrivate for per-thread data</title>
698  *  <programlisting>
699  *   GPrivate* current_number_key = NULL; /<!-- -->* Must be initialized somewhere
700  *                                           with g_private_new (g_free); *<!-- -->/
701  *
702  *   int
703  *   give_me_next_number (void)
704  *   {
705  *     int *current_number = g_private_get (current_number_key);
706  *
707  *     if (!current_number)
708  *       {
709  *         current_number = g_new (int, 1);
710  *         *current_number = 0;
711  *         g_private_set (current_number_key, current_number);
712  *       }
713  *
714  *     *current_number = calc_next_number (*current_number);
715  *
716  *     return *current_number;
717  *   }
718  *  </programlisting>
719  * </example>
720  *
721  * Here the pointer belonging to the key
722  * <literal>current_number_key</literal> is read. If it is %NULL, it has
723  * not been set yet. Then get memory for an integer value, assign this
724  * memory to the pointer and write the pointer back. Now we have an
725  * integer value that is private to the current thread.
726  *
727  * The #GPrivate struct should only be accessed via the following
728  * functions.
729  *
730  * <note><para>All of the <function>g_private_*</function> functions are
731  * actually macros. Apart from taking their addresses, you can however
732  * use them as if they were functions.</para></note>
733  **/
734
735 /**
736  * g_private_new:
737  * @destructor: a function to destroy the data keyed to #GPrivate when
738  *              a thread ends.
739  * @Returns: a new #GPrivate.
740  *
741  * Creates a new #GPrivate. If @destructor is non-%NULL, it is a
742  * pointer to a destructor function. Whenever a thread ends and the
743  * corresponding pointer keyed to this instance of #GPrivate is
744  * non-%NULL, the destructor is called with this pointer as the
745  * argument.
746  *
747  * <note><para>
748  * #GStaticPrivate is a better choice for most uses.
749  * </para></note>
750  *
751  * <note><para>@destructor is used quite differently from @notify in
752  * g_static_private_set().</para></note>
753  *
754  * <note><para>A #GPrivate cannot be freed. Reuse it instead, if you
755  * can, to avoid shortage, or use #GStaticPrivate.</para></note>
756  *
757  * <note><para>This function will abort if g_thread_init() has not been
758  * called yet.</para></note>
759  **/
760   (GPrivate*(*)(GDestroyNotify))g_thread_fail,
761
762 /**
763  * g_private_get:
764  * @private_key: a #GPrivate.
765  * @Returns: the corresponding pointer.
766  *
767  * Returns the pointer keyed to @private_key for the current thread. If
768  * g_private_set() hasn't been called for the current @private_key and
769  * thread yet, this pointer will be %NULL.
770  *
771  * This function can be used even if g_thread_init() has not yet been
772  * called, and, in that case, will return the value of @private_key
773  * casted to #gpointer. Note however, that private data set
774  * <emphasis>before</emphasis> g_thread_init() will
775  * <emphasis>not</emphasis> be retained <emphasis>after</emphasis> the
776  * call. Instead, %NULL will be returned in all threads directly after
777  * g_thread_init(), regardless of any g_private_set() calls issued
778  * before threading system intialization.
779  **/
780   NULL,
781
782 /**
783  * g_private_set:
784  * @private_key: a #GPrivate.
785  * @data: the new pointer.
786  *
787  * Sets the pointer keyed to @private_key for the current thread.
788  *
789  * This function can be used even if g_thread_init() has not yet been
790  * called, and, in that case, will set @private_key to @data casted to
791  * #GPrivate*. See g_private_get() for resulting caveats.
792  **/
793   NULL,
794
795 /* GThread Virtual Functions {{{2 ---------------------------------------- */
796 /**
797  * GThread:
798  *
799  * The #GThread struct represents a running thread. It has three public
800  * read-only members, but the underlying struct is bigger, so you must
801  * not copy this struct.
802  *
803  * <note><para>Resources for a joinable thread are not fully released
804  * until g_thread_join() is called for that thread.</para></note>
805  **/
806
807 /**
808  * GThreadFunc:
809  * @data: data passed to the thread.
810  * @Returns: the return value of the thread, which will be returned by
811  *           g_thread_join().
812  *
813  * Specifies the type of the @func functions passed to
814  * g_thread_create() or g_thread_create_full().
815  **/
816
817 /**
818  * GThreadPriority:
819  * @G_THREAD_PRIORITY_LOW: a priority lower than normal
820  * @G_THREAD_PRIORITY_NORMAL: the default priority
821  * @G_THREAD_PRIORITY_HIGH: a priority higher than normal
822  * @G_THREAD_PRIORITY_URGENT: the highest priority
823  *
824  * Specifies the priority of a thread.
825  *
826  * <note><para>It is not guaranteed that threads with different priorities
827  * really behave accordingly. On some systems (e.g. Linux) there are no
828  * thread priorities. On other systems (e.g. Solaris) there doesn't
829  * seem to be different scheduling for different priorities. All in all
830  * try to avoid being dependent on priorities.</para></note>
831  **/
832
833 /**
834  * g_thread_create:
835  * @func: a function to execute in the new thread.
836  * @data: an argument to supply to the new thread.
837  * @joinable: should this thread be joinable?
838  * @error: return location for error.
839  * @Returns: the new #GThread on success.
840  *
841  * This function creates a new thread with the default priority.
842  *
843  * If @joinable is %TRUE, you can wait for this threads termination
844  * calling g_thread_join(). Otherwise the thread will just disappear
845  * when it terminates.
846  *
847  * The new thread executes the function @func with the argument @data.
848  * If the thread was created successfully, it is returned.
849  *
850  * @error can be %NULL to ignore errors, or non-%NULL to report errors.
851  * The error is set, if and only if the function returns %NULL.
852  **/
853   (void(*)(GThreadFunc, gpointer, gulong,
854            gboolean, gboolean, GThreadPriority,
855            gpointer, GError**))g_thread_fail,
856
857 /**
858  * g_thread_yield:
859  *
860  * Gives way to other threads waiting to be scheduled.
861  *
862  * This function is often used as a method to make busy wait less evil.
863  * But in most cases you will encounter, there are better methods to do
864  * that. So in general you shouldn't use this function.
865  **/
866   NULL,
867
868   NULL,                                        /* thread_join */
869   NULL,                                        /* thread_exit */
870   NULL,                                        /* thread_set_priority */
871   NULL,                                        /* thread_self */
872   NULL                                         /* thread_equal */
873 };
874
875 /* Local Data {{{1 -------------------------------------------------------- */
876
877 static GMutex    g_once_mutex = G_MUTEX_INIT;
878 static GCond     g_once_cond = G_COND_INIT;
879 static GPrivate  g_thread_specific_private;
880 static GRealThread *g_thread_all_threads = NULL;
881 static GSList   *g_thread_free_indices = NULL;
882 static GSList*   g_once_init_list = NULL;
883
884 G_LOCK_DEFINE_STATIC (g_thread);
885
886 /* Initialisation {{{1 ---------------------------------------------------- */
887
888 /**
889  * g_thread_init:
890  * @vtable: a function table of type #GThreadFunctions, that provides
891  *          the entry points to the thread system to be used.
892  *
893  * If you use GLib from more than one thread, you must initialize the
894  * thread system by calling g_thread_init(). Most of the time you will
895  * only have to call <literal>g_thread_init (NULL)</literal>.
896  *
897  * <note><para>Do not call g_thread_init() with a non-%NULL parameter unless
898  * you really know what you are doing.</para></note>
899  *
900  * <note><para>g_thread_init() must not be called directly or indirectly as a
901  * callback from GLib. Also no mutexes may be currently locked while
902  * calling g_thread_init().</para></note>
903  *
904  * <note><para>g_thread_init() changes the way in which #GTimer measures
905  * elapsed time. As a consequence, timers that are running while
906  * g_thread_init() is called may report unreliable times.</para></note>
907  *
908  * Calling g_thread_init() multiple times is allowed (since version
909  * 2.24), but nothing happens except for the first call. If the
910  * argument is non-%NULL on such a call a warning will be printed, but
911  * otherwise the argument is ignored.
912  *
913  * If no thread system is available and @vtable is %NULL or if not all
914  * elements of @vtable are non-%NULL, then g_thread_init() will abort.
915  *
916  * <note><para>To use g_thread_init() in your program, you have to link with
917  * the libraries that the command <command>pkg-config --libs
918  * gthread-2.0</command> outputs. This is not the case for all the
919  * other thread related functions of GLib. Those can be used without
920  * having to link with the thread libraries.</para></note>
921  **/
922
923 /* This must be called only once, before any threads are created.
924  * It will only be called from g_thread_init() in -lgthread.
925  */
926 void
927 g_thread_init_glib (void)
928 {
929   static gboolean already_done;
930
931   if (already_done)
932     return;
933
934   already_done = TRUE;
935
936   _g_thread_impl_init ();
937
938   /* We let the main thread (the one that calls g_thread_init) inherit
939    * the static_private data set before calling g_thread_init
940    */
941   GRealThread* main_thread = (GRealThread*) g_thread_self ();
942
943   /* we may only create mutex and cond in here */
944   _g_mem_thread_init_noprivate_nomessage ();
945
946   /* setup the basic threading system */
947   g_threads_got_initialized = TRUE;
948   g_private_init (&g_thread_specific_private, g_thread_cleanup);
949   g_private_set (&g_thread_specific_private, main_thread);
950   G_THREAD_UF (thread_self, (&main_thread->system_thread));
951
952   /* accomplish log system initialization to enable messaging */
953   _g_messages_thread_init_nomessage ();
954 }
955
956 /* The following sections implement: GOnce, GStaticMutex, GStaticRecMutex,
957  * GStaticPrivate, 
958  **/
959
960 /* GOnce {{{1 ------------------------------------------------------------- */
961
962 /**
963  * GOnce:
964  * @status: the status of the #GOnce
965  * @retval: the value returned by the call to the function, if @status
966  *          is %G_ONCE_STATUS_READY
967  *
968  * A #GOnce struct controls a one-time initialization function. Any
969  * one-time initialization function must have its own unique #GOnce
970  * struct.
971  *
972  * Since: 2.4
973  **/
974
975 /**
976  * G_ONCE_INIT:
977  *
978  * A #GOnce must be initialized with this macro before it can be used.
979  *
980  * <informalexample>
981  *  <programlisting>
982  *   GOnce my_once = G_ONCE_INIT;
983  *  </programlisting>
984  * </informalexample>
985  *
986  * Since: 2.4
987  **/
988
989 /**
990  * GOnceStatus:
991  * @G_ONCE_STATUS_NOTCALLED: the function has not been called yet.
992  * @G_ONCE_STATUS_PROGRESS: the function call is currently in progress.
993  * @G_ONCE_STATUS_READY: the function has been called.
994  *
995  * The possible statuses of a one-time initialization function
996  * controlled by a #GOnce struct.
997  *
998  * Since: 2.4
999  **/
1000
1001 /**
1002  * g_once:
1003  * @once: a #GOnce structure
1004  * @func: the #GThreadFunc function associated to @once. This function
1005  *        is called only once, regardless of the number of times it and
1006  *        its associated #GOnce struct are passed to g_once().
1007  * @arg: data to be passed to @func
1008  *
1009  * The first call to this routine by a process with a given #GOnce
1010  * struct calls @func with the given argument. Thereafter, subsequent
1011  * calls to g_once()  with the same #GOnce struct do not call @func
1012  * again, but return the stored result of the first call. On return
1013  * from g_once(), the status of @once will be %G_ONCE_STATUS_READY.
1014  *
1015  * For example, a mutex or a thread-specific data key must be created
1016  * exactly once. In a threaded environment, calling g_once() ensures
1017  * that the initialization is serialized across multiple threads.
1018  *
1019  * <note><para>Calling g_once() recursively on the same #GOnce struct in
1020  * @func will lead to a deadlock.</para></note>
1021  *
1022  * <informalexample>
1023  *  <programlisting>
1024  *   gpointer
1025  *   get_debug_flags (void)
1026  *   {
1027  *     static GOnce my_once = G_ONCE_INIT;
1028  *
1029  *     g_once (&my_once, parse_debug_flags, NULL);
1030  *
1031  *     return my_once.retval;
1032  *   }
1033  *  </programlisting>
1034  * </informalexample>
1035  *
1036  * Since: 2.4
1037  **/
1038 gpointer
1039 g_once_impl (GOnce       *once,
1040              GThreadFunc  func,
1041              gpointer     arg)
1042 {
1043   g_mutex_lock (&g_once_mutex);
1044
1045   while (once->status == G_ONCE_STATUS_PROGRESS)
1046     g_cond_wait (&g_once_cond, &g_once_mutex);
1047
1048   if (once->status != G_ONCE_STATUS_READY)
1049     {
1050       once->status = G_ONCE_STATUS_PROGRESS;
1051       g_mutex_unlock (&g_once_mutex);
1052
1053       once->retval = func (arg);
1054
1055       g_mutex_lock (&g_once_mutex);
1056       once->status = G_ONCE_STATUS_READY;
1057       g_cond_broadcast (&g_once_cond);
1058     }
1059
1060   g_mutex_unlock (&g_once_mutex);
1061
1062   return once->retval;
1063 }
1064
1065 /**
1066  * g_once_init_enter:
1067  * @value_location: location of a static initializable variable
1068  *                  containing 0.
1069  * @Returns: %TRUE if the initialization section should be entered,
1070  *           %FALSE and blocks otherwise
1071  *
1072  * Function to be called when starting a critical initialization
1073  * section. The argument @value_location must point to a static
1074  * 0-initialized variable that will be set to a value other than 0 at
1075  * the end of the initialization section. In combination with
1076  * g_once_init_leave() and the unique address @value_location, it can
1077  * be ensured that an initialization section will be executed only once
1078  * during a program's life time, and that concurrent threads are
1079  * blocked until initialization completed. To be used in constructs
1080  * like this:
1081  *
1082  * <informalexample>
1083  *  <programlisting>
1084  *   static gsize initialization_value = 0;
1085  *
1086  *   if (g_once_init_enter (&amp;initialization_value))
1087  *     {
1088  *       gsize setup_value = 42; /<!-- -->* initialization code here *<!-- -->/
1089  *
1090  *       g_once_init_leave (&amp;initialization_value, setup_value);
1091  *     }
1092  *
1093  *   /<!-- -->* use initialization_value here *<!-- -->/
1094  *  </programlisting>
1095  * </informalexample>
1096  *
1097  * Since: 2.14
1098  **/
1099 gboolean
1100 g_once_init_enter_impl (volatile gsize *value_location)
1101 {
1102   gboolean need_init = FALSE;
1103   g_mutex_lock (&g_once_mutex);
1104   if (g_atomic_pointer_get (value_location) == NULL)
1105     {
1106       if (!g_slist_find (g_once_init_list, (void*) value_location))
1107         {
1108           need_init = TRUE;
1109           g_once_init_list = g_slist_prepend (g_once_init_list, (void*) value_location);
1110         }
1111       else
1112         do
1113           g_cond_wait (&g_once_cond, &g_once_mutex);
1114         while (g_slist_find (g_once_init_list, (void*) value_location));
1115     }
1116   g_mutex_unlock (&g_once_mutex);
1117   return need_init;
1118 }
1119
1120 /**
1121  * g_once_init_leave:
1122  * @value_location: location of a static initializable variable
1123  *                  containing 0.
1124  * @initialization_value: new non-0 value for *@value_location.
1125  *
1126  * Counterpart to g_once_init_enter(). Expects a location of a static
1127  * 0-initialized initialization variable, and an initialization value
1128  * other than 0. Sets the variable to the initialization value, and
1129  * releases concurrent threads blocking in g_once_init_enter() on this
1130  * initialization variable.
1131  *
1132  * Since: 2.14
1133  **/
1134 void
1135 g_once_init_leave (volatile gsize *value_location,
1136                    gsize           initialization_value)
1137 {
1138   g_return_if_fail (g_atomic_pointer_get (value_location) == NULL);
1139   g_return_if_fail (initialization_value != 0);
1140   g_return_if_fail (g_once_init_list != NULL);
1141
1142   g_atomic_pointer_set (value_location, initialization_value);
1143   g_mutex_lock (&g_once_mutex);
1144   g_once_init_list = g_slist_remove (g_once_init_list, (void*) value_location);
1145   g_cond_broadcast (&g_once_cond);
1146   g_mutex_unlock (&g_once_mutex);
1147 }
1148
1149 /* GStaticMutex {{{1 ------------------------------------------------------ */
1150
1151 /**
1152  * GStaticMutex:
1153  *
1154  * A #GStaticMutex works like a #GMutex, but it has one significant
1155  * advantage. It doesn't need to be created at run-time like a #GMutex,
1156  * but can be defined at compile-time. Here is a shorter, easier and
1157  * safer version of our <function>give_me_next_number()</function>
1158  * example:
1159  *
1160  * <example>
1161  *  <title>
1162  *   Using <structname>GStaticMutex</structname>
1163  *   to simplify thread-safe programming
1164  *  </title>
1165  *  <programlisting>
1166  *   int
1167  *   give_me_next_number (void)
1168  *   {
1169  *     static int current_number = 0;
1170  *     int ret_val;
1171  *     static GStaticMutex mutex = G_STATIC_MUTEX_INIT;
1172  *
1173  *     g_static_mutex_lock (&amp;mutex);
1174  *     ret_val = current_number = calc_next_number (current_number);
1175  *     g_static_mutex_unlock (&amp;mutex);
1176  *
1177  *     return ret_val;
1178  *   }
1179  *  </programlisting>
1180  * </example>
1181  *
1182  * Sometimes you would like to dynamically create a mutex. If you don't
1183  * want to require prior calling to g_thread_init(), because your code
1184  * should also be usable in non-threaded programs, you are not able to
1185  * use g_mutex_new() and thus #GMutex, as that requires a prior call to
1186  * g_thread_init(). In theses cases you can also use a #GStaticMutex.
1187  * It must be initialized with g_static_mutex_init() before using it
1188  * and freed with with g_static_mutex_free() when not needed anymore to
1189  * free up any allocated resources.
1190  *
1191  * Even though #GStaticMutex is not opaque, it should only be used with
1192  * the following functions, as it is defined differently on different
1193  * platforms.
1194  *
1195  * All of the <function>g_static_mutex_*</function> functions apart
1196  * from <function>g_static_mutex_get_mutex</function> can also be used
1197  * even if g_thread_init() has not yet been called. Then they do
1198  * nothing, apart from <function>g_static_mutex_trylock</function>,
1199  * which does nothing but returning %TRUE.
1200  *
1201  * <note><para>All of the <function>g_static_mutex_*</function>
1202  * functions are actually macros. Apart from taking their addresses, you
1203  * can however use them as if they were functions.</para></note>
1204  **/
1205
1206 /**
1207  * G_STATIC_MUTEX_INIT:
1208  *
1209  * A #GStaticMutex must be initialized with this macro, before it can
1210  * be used. This macro can used be to initialize a variable, but it
1211  * cannot be assigned to a variable. In that case you have to use
1212  * g_static_mutex_init().
1213  *
1214  * <informalexample>
1215  *  <programlisting>
1216  *   GStaticMutex my_mutex = G_STATIC_MUTEX_INIT;
1217  *  </programlisting>
1218  * </informalexample>
1219  **/
1220
1221 /**
1222  * g_static_mutex_init:
1223  * @mutex: a #GStaticMutex to be initialized.
1224  *
1225  * Initializes @mutex. Alternatively you can initialize it with
1226  * #G_STATIC_MUTEX_INIT.
1227  **/
1228 void
1229 g_static_mutex_init (GStaticMutex *mutex)
1230 {
1231   static const GStaticMutex init_mutex = G_STATIC_MUTEX_INIT;
1232
1233   g_return_if_fail (mutex);
1234
1235   *mutex = init_mutex;
1236 }
1237
1238 /* IMPLEMENTATION NOTE:
1239  *
1240  * On some platforms a GStaticMutex is actually a normal GMutex stored
1241  * inside of a structure instead of being allocated dynamically.  We can
1242  * only do this for platforms on which we know, in advance, how to
1243  * allocate (size) and initialise (value) that memory.
1244  *
1245  * On other platforms, a GStaticMutex is nothing more than a pointer to
1246  * a GMutex.  In that case, the first access we make to the static mutex
1247  * must first allocate the normal GMutex and store it into the pointer.
1248  *
1249  * configure.ac writes macros into glibconfig.h to determine if
1250  * g_static_mutex_get_mutex() accesses the structure in memory directly
1251  * (on platforms where we are able to do that) or if it ends up here,
1252  * where we may have to allocate the GMutex before returning it.
1253  */
1254
1255 /**
1256  * g_static_mutex_get_mutex:
1257  * @mutex: a #GStaticMutex.
1258  * @Returns: the #GMutex corresponding to @mutex.
1259  *
1260  * For some operations (like g_cond_wait()) you must have a #GMutex
1261  * instead of a #GStaticMutex. This function will return the
1262  * corresponding #GMutex for @mutex.
1263  **/
1264 GMutex *
1265 g_static_mutex_get_mutex_impl (GMutex** mutex)
1266 {
1267   GMutex *result;
1268
1269   if (!g_thread_supported ())
1270     return NULL;
1271
1272   result = g_atomic_pointer_get (mutex);
1273
1274   if (!result)
1275     {
1276       g_mutex_lock (&g_once_mutex);
1277
1278       result = *mutex;
1279       if (!result)
1280         {
1281           result = g_mutex_new ();
1282           g_atomic_pointer_set (mutex, result);
1283         }
1284
1285       g_mutex_unlock (&g_once_mutex);
1286     }
1287
1288   return result;
1289 }
1290
1291 /* IMPLEMENTATION NOTE:
1292  *
1293  * g_static_mutex_lock(), g_static_mutex_trylock() and
1294  * g_static_mutex_unlock() are all preprocessor macros that wrap the
1295  * corresponding g_mutex_*() function around a call to
1296  * g_static_mutex_get_mutex().
1297  */
1298
1299 /**
1300  * g_static_mutex_lock:
1301  * @mutex: a #GStaticMutex.
1302  *
1303  * Works like g_mutex_lock(), but for a #GStaticMutex.
1304  **/
1305
1306 /**
1307  * g_static_mutex_trylock:
1308  * @mutex: a #GStaticMutex.
1309  * @Returns: %TRUE, if the #GStaticMutex could be locked.
1310  *
1311  * Works like g_mutex_trylock(), but for a #GStaticMutex.
1312  **/
1313
1314 /**
1315  * g_static_mutex_unlock:
1316  * @mutex: a #GStaticMutex.
1317  *
1318  * Works like g_mutex_unlock(), but for a #GStaticMutex.
1319  **/
1320
1321 /**
1322  * g_static_mutex_free:
1323  * @mutex: a #GStaticMutex to be freed.
1324  *
1325  * Releases all resources allocated to @mutex.
1326  *
1327  * You don't have to call this functions for a #GStaticMutex with an
1328  * unbounded lifetime, i.e. objects declared 'static', but if you have
1329  * a #GStaticMutex as a member of a structure and the structure is
1330  * freed, you should also free the #GStaticMutex.
1331  *
1332  * <note><para>Calling g_static_mutex_free() on a locked mutex may
1333  * result in undefined behaviour.</para></note>
1334  **/
1335 void
1336 g_static_mutex_free (GStaticMutex* mutex)
1337 {
1338   GMutex **runtime_mutex;
1339
1340   g_return_if_fail (mutex);
1341
1342   /* The runtime_mutex is the first (or only) member of GStaticMutex,
1343    * see both versions (of glibconfig.h) in configure.ac. Note, that
1344    * this variable is NULL, if g_thread_init() hasn't been called or
1345    * if we're using the default thread implementation and it provides
1346    * static mutexes. */
1347   runtime_mutex = ((GMutex**)mutex);
1348
1349   if (*runtime_mutex)
1350     g_mutex_free (*runtime_mutex);
1351
1352   *runtime_mutex = NULL;
1353 }
1354
1355 /* ------------------------------------------------------------------------ */
1356
1357 /**
1358  * GStaticRecMutex:
1359  *
1360  * A #GStaticRecMutex works like a #GStaticMutex, but it can be locked
1361  * multiple times by one thread. If you enter it n times, you have to
1362  * unlock it n times again to let other threads lock it. An exception
1363  * is the function g_static_rec_mutex_unlock_full(): that allows you to
1364  * unlock a #GStaticRecMutex completely returning the depth, (i.e. the
1365  * number of times this mutex was locked). The depth can later be used
1366  * to restore the state of the #GStaticRecMutex by calling
1367  * g_static_rec_mutex_lock_full().
1368  *
1369  * Even though #GStaticRecMutex is not opaque, it should only be used
1370  * with the following functions.
1371  *
1372  * All of the <function>g_static_rec_mutex_*</function> functions can
1373  * be used even if g_thread_init() has not been called. Then they do
1374  * nothing, apart from <function>g_static_rec_mutex_trylock</function>,
1375  * which does nothing but returning %TRUE.
1376  **/
1377
1378 /**
1379  * G_STATIC_REC_MUTEX_INIT:
1380  *
1381  * A #GStaticRecMutex must be initialized with this macro before it can
1382  * be used. This macro can used be to initialize a variable, but it
1383  * cannot be assigned to a variable. In that case you have to use
1384  * g_static_rec_mutex_init().
1385  *
1386  * <informalexample>
1387  *  <programlisting>
1388  *   GStaticRecMutex my_mutex = G_STATIC_REC_MUTEX_INIT;
1389  * </programlisting>
1390  </informalexample>
1391  **/
1392
1393 /**
1394  * g_static_rec_mutex_init:
1395  * @mutex: a #GStaticRecMutex to be initialized.
1396  *
1397  * A #GStaticRecMutex must be initialized with this function before it
1398  * can be used. Alternatively you can initialize it with
1399  * #G_STATIC_REC_MUTEX_INIT.
1400  **/
1401 void
1402 g_static_rec_mutex_init (GStaticRecMutex *mutex)
1403 {
1404   static const GStaticRecMutex init_mutex = G_STATIC_REC_MUTEX_INIT;
1405
1406   g_return_if_fail (mutex);
1407
1408   *mutex = init_mutex;
1409 }
1410
1411 /**
1412  * g_static_rec_mutex_lock:
1413  * @mutex: a #GStaticRecMutex to lock.
1414  *
1415  * Locks @mutex. If @mutex is already locked by another thread, the
1416  * current thread will block until @mutex is unlocked by the other
1417  * thread. If @mutex is already locked by the calling thread, this
1418  * functions increases the depth of @mutex and returns immediately.
1419  **/
1420 void
1421 g_static_rec_mutex_lock (GStaticRecMutex* mutex)
1422 {
1423   GSystemThread self;
1424
1425   g_return_if_fail (mutex);
1426
1427   if (!g_thread_supported ())
1428     return;
1429
1430   G_THREAD_UF (thread_self, (&self));
1431
1432   if (g_system_thread_equal (self, mutex->owner))
1433     {
1434       mutex->depth++;
1435       return;
1436     }
1437   g_static_mutex_lock (&mutex->mutex);
1438   g_system_thread_assign (mutex->owner, self);
1439   mutex->depth = 1;
1440 }
1441
1442 /**
1443  * g_static_rec_mutex_trylock:
1444  * @mutex: a #GStaticRecMutex to lock.
1445  * @Returns: %TRUE, if @mutex could be locked.
1446  *
1447  * Tries to lock @mutex. If @mutex is already locked by another thread,
1448  * it immediately returns %FALSE. Otherwise it locks @mutex and returns
1449  * %TRUE. If @mutex is already locked by the calling thread, this
1450  * functions increases the depth of @mutex and immediately returns
1451  * %TRUE.
1452  **/
1453 gboolean
1454 g_static_rec_mutex_trylock (GStaticRecMutex* mutex)
1455 {
1456   GSystemThread self;
1457
1458   g_return_val_if_fail (mutex, FALSE);
1459
1460   if (!g_thread_supported ())
1461     return TRUE;
1462
1463   G_THREAD_UF (thread_self, (&self));
1464
1465   if (g_system_thread_equal (self, mutex->owner))
1466     {
1467       mutex->depth++;
1468       return TRUE;
1469     }
1470
1471   if (!g_static_mutex_trylock (&mutex->mutex))
1472     return FALSE;
1473
1474   g_system_thread_assign (mutex->owner, self);
1475   mutex->depth = 1;
1476   return TRUE;
1477 }
1478
1479 /**
1480  * g_static_rec_mutex_unlock:
1481  * @mutex: a #GStaticRecMutex to unlock.
1482  *
1483  * Unlocks @mutex. Another thread will be allowed to lock @mutex only
1484  * when it has been unlocked as many times as it had been locked
1485  * before. If @mutex is completely unlocked and another thread is
1486  * blocked in a g_static_rec_mutex_lock() call for @mutex, it will be
1487  * woken and can lock @mutex itself.
1488  **/
1489 void
1490 g_static_rec_mutex_unlock (GStaticRecMutex* mutex)
1491 {
1492   g_return_if_fail (mutex);
1493
1494   if (!g_thread_supported ())
1495     return;
1496
1497   if (mutex->depth > 1)
1498     {
1499       mutex->depth--;
1500       return;
1501     }
1502   g_system_thread_assign (mutex->owner, zero_thread);
1503   g_static_mutex_unlock (&mutex->mutex);
1504 }
1505
1506 /**
1507  * g_static_rec_mutex_lock_full:
1508  * @mutex: a #GStaticRecMutex to lock.
1509  * @depth: number of times this mutex has to be unlocked to be
1510  *         completely unlocked.
1511  *
1512  * Works like calling g_static_rec_mutex_lock() for @mutex @depth times.
1513  **/
1514 void
1515 g_static_rec_mutex_lock_full   (GStaticRecMutex *mutex,
1516                                 guint            depth)
1517 {
1518   GSystemThread self;
1519   g_return_if_fail (mutex);
1520
1521   if (!g_thread_supported ())
1522     return;
1523
1524   if (depth == 0)
1525     return;
1526
1527   G_THREAD_UF (thread_self, (&self));
1528
1529   if (g_system_thread_equal (self, mutex->owner))
1530     {
1531       mutex->depth += depth;
1532       return;
1533     }
1534   g_static_mutex_lock (&mutex->mutex);
1535   g_system_thread_assign (mutex->owner, self);
1536   mutex->depth = depth;
1537 }
1538
1539 /**
1540  * g_static_rec_mutex_unlock_full:
1541  * @mutex: a #GStaticRecMutex to completely unlock.
1542  * @Returns: number of times @mutex has been locked by the current
1543  *           thread.
1544  *
1545  * Completely unlocks @mutex. If another thread is blocked in a
1546  * g_static_rec_mutex_lock() call for @mutex, it will be woken and can
1547  * lock @mutex itself. This function returns the number of times that
1548  * @mutex has been locked by the current thread. To restore the state
1549  * before the call to g_static_rec_mutex_unlock_full() you can call
1550  * g_static_rec_mutex_lock_full() with the depth returned by this
1551  * function.
1552  **/
1553 guint
1554 g_static_rec_mutex_unlock_full (GStaticRecMutex *mutex)
1555 {
1556   guint depth;
1557
1558   g_return_val_if_fail (mutex, 0);
1559
1560   if (!g_thread_supported ())
1561     return 1;
1562
1563   depth = mutex->depth;
1564
1565   g_system_thread_assign (mutex->owner, zero_thread);
1566   mutex->depth = 0;
1567   g_static_mutex_unlock (&mutex->mutex);
1568
1569   return depth;
1570 }
1571
1572 /**
1573  * g_static_rec_mutex_free:
1574  * @mutex: a #GStaticRecMutex to be freed.
1575  *
1576  * Releases all resources allocated to a #GStaticRecMutex.
1577  *
1578  * You don't have to call this functions for a #GStaticRecMutex with an
1579  * unbounded lifetime, i.e. objects declared 'static', but if you have
1580  * a #GStaticRecMutex as a member of a structure and the structure is
1581  * freed, you should also free the #GStaticRecMutex.
1582  **/
1583 void
1584 g_static_rec_mutex_free (GStaticRecMutex *mutex)
1585 {
1586   g_return_if_fail (mutex);
1587
1588   g_static_mutex_free (&mutex->mutex);
1589 }
1590
1591 /* GStaticPrivate {{{1 ---------------------------------------------------- */
1592
1593 /**
1594  * GStaticPrivate:
1595  *
1596  * A #GStaticPrivate works almost like a #GPrivate, but it has one
1597  * significant advantage. It doesn't need to be created at run-time
1598  * like a #GPrivate, but can be defined at compile-time. This is
1599  * similar to the difference between #GMutex and #GStaticMutex. Now
1600  * look at our <function>give_me_next_number()</function> example with
1601  * #GStaticPrivate:
1602  *
1603  * <example>
1604  *  <title>Using GStaticPrivate for per-thread data</title>
1605  *  <programlisting>
1606  *   int
1607  *   give_me_next_number (<!-- -->)
1608  *   {
1609  *     static GStaticPrivate current_number_key = G_STATIC_PRIVATE_INIT;
1610  *     int *current_number = g_static_private_get (&amp;current_number_key);
1611  *
1612  *     if (!current_number)
1613  *       {
1614  *         current_number = g_new (int,1);
1615  *         *current_number = 0;
1616  *         g_static_private_set (&amp;current_number_key, current_number, g_free);
1617  *       }
1618  *
1619  *     *current_number = calc_next_number (*current_number);
1620  *
1621  *     return *current_number;
1622  *   }
1623  *  </programlisting>
1624  * </example>
1625  **/
1626
1627 /**
1628  * G_STATIC_PRIVATE_INIT:
1629  *
1630  * Every #GStaticPrivate must be initialized with this macro, before it
1631  * can be used.
1632  *
1633  * <informalexample>
1634  *  <programlisting>
1635  *   GStaticPrivate my_private = G_STATIC_PRIVATE_INIT;
1636  *  </programlisting>
1637  * </informalexample>
1638  **/
1639
1640 /**
1641  * g_static_private_init:
1642  * @private_key: a #GStaticPrivate to be initialized.
1643  *
1644  * Initializes @private_key. Alternatively you can initialize it with
1645  * #G_STATIC_PRIVATE_INIT.
1646  **/
1647 void
1648 g_static_private_init (GStaticPrivate *private_key)
1649 {
1650   private_key->index = 0;
1651 }
1652
1653 /**
1654  * g_static_private_get:
1655  * @private_key: a #GStaticPrivate.
1656  * @Returns: the corresponding pointer.
1657  *
1658  * Works like g_private_get() only for a #GStaticPrivate.
1659  *
1660  * This function works even if g_thread_init() has not yet been called.
1661  **/
1662 gpointer
1663 g_static_private_get (GStaticPrivate *private_key)
1664 {
1665   GRealThread *self = (GRealThread*) g_thread_self ();
1666   GArray *array;
1667   gpointer ret = NULL;
1668
1669   LOCK_PRIVATE_DATA (self);
1670
1671   array = self->private_data;
1672
1673   if (array && private_key->index != 0 && private_key->index <= array->len)
1674     ret = g_array_index (array, GStaticPrivateNode,
1675                          private_key->index - 1).data;
1676
1677   UNLOCK_PRIVATE_DATA (self);
1678   return ret;
1679 }
1680
1681 /**
1682  * g_static_private_set:
1683  * @private_key: a #GStaticPrivate.
1684  * @data: the new pointer.
1685  * @notify: a function to be called with the pointer whenever the
1686  *          current thread ends or sets this pointer again.
1687  *
1688  * Sets the pointer keyed to @private_key for the current thread and
1689  * the function @notify to be called with that pointer (%NULL or
1690  * non-%NULL), whenever the pointer is set again or whenever the
1691  * current thread ends.
1692  *
1693  * This function works even if g_thread_init() has not yet been called.
1694  * If g_thread_init() is called later, the @data keyed to @private_key
1695  * will be inherited only by the main thread, i.e. the one that called
1696  * g_thread_init().
1697  *
1698  * <note><para>@notify is used quite differently from @destructor in
1699  * g_private_new().</para></note>
1700  **/
1701 void
1702 g_static_private_set (GStaticPrivate *private_key,
1703                       gpointer        data,
1704                       GDestroyNotify  notify)
1705 {
1706   GRealThread *self = (GRealThread*) g_thread_self ();
1707   GArray *array;
1708   static guint next_index = 0;
1709   GStaticPrivateNode *node;
1710   gpointer ddata = NULL;
1711   GDestroyNotify ddestroy = NULL;
1712
1713   if (!private_key->index)
1714     {
1715       G_LOCK (g_thread);
1716
1717       if (!private_key->index)
1718         {
1719           if (g_thread_free_indices)
1720             {
1721               private_key->index =
1722                 GPOINTER_TO_UINT (g_thread_free_indices->data);
1723               g_thread_free_indices =
1724                 g_slist_delete_link (g_thread_free_indices,
1725                                      g_thread_free_indices);
1726             }
1727           else
1728             private_key->index = ++next_index;
1729         }
1730
1731       G_UNLOCK (g_thread);
1732     }
1733
1734   LOCK_PRIVATE_DATA (self);
1735
1736   array = self->private_data;
1737   if (!array)
1738     {
1739       array = g_array_new (FALSE, TRUE, sizeof (GStaticPrivateNode));
1740       self->private_data = array;
1741     }
1742
1743   if (private_key->index > array->len)
1744     g_array_set_size (array, private_key->index);
1745
1746   node = &g_array_index (array, GStaticPrivateNode, private_key->index - 1);
1747
1748   ddata = node->data;
1749   ddestroy = node->destroy;
1750
1751   node->data = data;
1752   node->destroy = notify;
1753
1754   UNLOCK_PRIVATE_DATA (self);
1755
1756   if (ddestroy)
1757     ddestroy (ddata);
1758 }
1759
1760 /**
1761  * g_static_private_free:
1762  * @private_key: a #GStaticPrivate to be freed.
1763  *
1764  * Releases all resources allocated to @private_key.
1765  *
1766  * You don't have to call this functions for a #GStaticPrivate with an
1767  * unbounded lifetime, i.e. objects declared 'static', but if you have
1768  * a #GStaticPrivate as a member of a structure and the structure is
1769  * freed, you should also free the #GStaticPrivate.
1770  **/
1771 void
1772 g_static_private_free (GStaticPrivate *private_key)
1773 {
1774   guint idx = private_key->index;
1775   GRealThread *thread, *next;
1776   GArray *garbage = NULL;
1777
1778   if (!idx)
1779     return;
1780
1781   private_key->index = 0;
1782
1783   G_LOCK (g_thread);
1784
1785   thread = g_thread_all_threads;
1786
1787   for (thread = g_thread_all_threads; thread; thread = next)
1788     {
1789       GArray *array;
1790
1791       next = thread->next;
1792
1793       LOCK_PRIVATE_DATA (thread);
1794
1795       array = thread->private_data;
1796
1797       if (array && idx <= array->len)
1798         {
1799           GStaticPrivateNode *node = &g_array_index (array,
1800                                                      GStaticPrivateNode,
1801                                                      idx - 1);
1802           gpointer ddata = node->data;
1803           GDestroyNotify ddestroy = node->destroy;
1804
1805           node->data = NULL;
1806           node->destroy = NULL;
1807
1808           if (ddestroy)
1809             {
1810               /* defer non-trivial destruction til after we've finished
1811                * iterating, since we must continue to hold the lock */
1812               if (garbage == NULL)
1813                 garbage = g_array_new (FALSE, TRUE,
1814                                        sizeof (GStaticPrivateNode));
1815
1816               g_array_set_size (garbage, garbage->len + 1);
1817
1818               node = &g_array_index (garbage, GStaticPrivateNode,
1819                                      garbage->len - 1);
1820               node->data = ddata;
1821               node->destroy = ddestroy;
1822             }
1823         }
1824
1825       UNLOCK_PRIVATE_DATA (thread);
1826     }
1827   g_thread_free_indices = g_slist_prepend (g_thread_free_indices,
1828                                            GUINT_TO_POINTER (idx));
1829   G_UNLOCK (g_thread);
1830
1831   if (garbage)
1832     {
1833       guint i;
1834
1835       for (i = 0; i < garbage->len; i++)
1836         {
1837           GStaticPrivateNode *node;
1838
1839           node = &g_array_index (garbage, GStaticPrivateNode, i);
1840           node->destroy (node->data);
1841         }
1842
1843       g_array_free (garbage, TRUE);
1844     }
1845 }
1846
1847 /* GThread Extra Functions {{{1 ------------------------------------------- */
1848 static void
1849 g_thread_cleanup (gpointer data)
1850 {
1851   if (data)
1852     {
1853       GRealThread* thread = data;
1854       GArray *array;
1855
1856       LOCK_PRIVATE_DATA (thread);
1857       array = thread->private_data;
1858       thread->private_data = NULL;
1859       UNLOCK_PRIVATE_DATA (thread);
1860
1861       if (array)
1862         {
1863           guint i;
1864
1865           for (i = 0; i < array->len; i++ )
1866             {
1867               GStaticPrivateNode *node =
1868                 &g_array_index (array, GStaticPrivateNode, i);
1869               if (node->destroy)
1870                 node->destroy (node->data);
1871             }
1872           g_array_free (array, TRUE);
1873         }
1874
1875       /* We only free the thread structure, if it isn't joinable. If
1876          it is, the structure is freed in g_thread_join */
1877       if (!thread->thread.joinable)
1878         {
1879           GRealThread *t, *p;
1880
1881           G_LOCK (g_thread);
1882           for (t = g_thread_all_threads, p = NULL; t; p = t, t = t->next)
1883             {
1884               if (t == thread)
1885                 {
1886                   if (p)
1887                     p->next = t->next;
1888                   else
1889                     g_thread_all_threads = t->next;
1890                   break;
1891                 }
1892             }
1893           G_UNLOCK (g_thread);
1894
1895           /* Just to make sure, this isn't used any more */
1896           g_system_thread_assign (thread->system_thread, zero_thread);
1897           g_free (thread);
1898         }
1899     }
1900 }
1901
1902 static void
1903 g_thread_fail (void)
1904 {
1905   g_error ("The thread system is not yet initialized.");
1906 }
1907
1908 #define G_NSEC_PER_SEC 1000000000
1909
1910 static guint64
1911 gettime (void)
1912 {
1913   return g_get_monotonic_time () * 1000;
1914 }
1915
1916 static gpointer
1917 g_thread_create_proxy (gpointer data)
1918 {
1919   GRealThread* thread = data;
1920
1921   g_assert (data);
1922
1923   /* This has to happen before G_LOCK, as that might call g_thread_self */
1924   g_private_set (&g_thread_specific_private, data);
1925
1926   /* the lock makes sure, that thread->system_thread is written,
1927      before thread->thread.func is called. See g_thread_create. */
1928   G_LOCK (g_thread);
1929   G_UNLOCK (g_thread);
1930
1931   thread->retval = thread->thread.func (thread->thread.data);
1932
1933   return NULL;
1934 }
1935
1936 /**
1937  * g_thread_create_full:
1938  * @func: a function to execute in the new thread.
1939  * @data: an argument to supply to the new thread.
1940  * @stack_size: a stack size for the new thread.
1941  * @joinable: should this thread be joinable?
1942  * @bound: should this thread be bound to a system thread?
1943  * @priority: a priority for the thread.
1944  * @error: return location for error.
1945  * @Returns: the new #GThread on success.
1946  *
1947  * This function creates a new thread with the priority @priority. If
1948  * the underlying thread implementation supports it, the thread gets a
1949  * stack size of @stack_size or the default value for the current
1950  * platform, if @stack_size is 0.
1951  *
1952  * If @joinable is %TRUE, you can wait for this threads termination
1953  * calling g_thread_join(). Otherwise the thread will just disappear
1954  * when it terminates. If @bound is %TRUE, this thread will be
1955  * scheduled in the system scope, otherwise the implementation is free
1956  * to do scheduling in the process scope. The first variant is more
1957  * expensive resource-wise, but generally faster. On some systems (e.g.
1958  * Linux) all threads are bound.
1959  *
1960  * The new thread executes the function @func with the argument @data.
1961  * If the thread was created successfully, it is returned.
1962  *
1963  * @error can be %NULL to ignore errors, or non-%NULL to report errors.
1964  * The error is set, if and only if the function returns %NULL.
1965  *
1966  * <note><para>It is not guaranteed that threads with different priorities
1967  * really behave accordingly. On some systems (e.g. Linux) there are no
1968  * thread priorities. On other systems (e.g. Solaris) there doesn't
1969  * seem to be different scheduling for different priorities. All in all
1970  * try to avoid being dependent on priorities. Use
1971  * %G_THREAD_PRIORITY_NORMAL here as a default.</para></note>
1972  *
1973  * <note><para>Only use g_thread_create_full() if you really can't use
1974  * g_thread_create() instead. g_thread_create() does not take
1975  * @stack_size, @bound, and @priority as arguments, as they should only
1976  * be used in cases in which it is unavoidable.</para></note>
1977  **/
1978 GThread*
1979 g_thread_create_full (GThreadFunc       func,
1980                       gpointer          data,
1981                       gulong            stack_size,
1982                       gboolean          joinable,
1983                       gboolean          bound,
1984                       GThreadPriority   priority,
1985                       GError          **error)
1986 {
1987   GRealThread* result;
1988   GError *local_error = NULL;
1989   g_return_val_if_fail (func, NULL);
1990   g_return_val_if_fail (priority >= G_THREAD_PRIORITY_LOW, NULL);
1991   g_return_val_if_fail (priority <= G_THREAD_PRIORITY_URGENT, NULL);
1992
1993   result = g_new0 (GRealThread, 1);
1994
1995   result->thread.joinable = joinable;
1996   result->thread.priority = priority;
1997   result->thread.func = func;
1998   result->thread.data = data;
1999   result->private_data = NULL;
2000   G_LOCK (g_thread);
2001   G_THREAD_UF (thread_create, (g_thread_create_proxy, result,
2002                                stack_size, joinable, bound, priority,
2003                                &result->system_thread, &local_error));
2004   if (!local_error)
2005     {
2006       result->next = g_thread_all_threads;
2007       g_thread_all_threads = result;
2008     }
2009   G_UNLOCK (g_thread);
2010
2011   if (local_error)
2012     {
2013       g_propagate_error (error, local_error);
2014       g_free (result);
2015       return NULL;
2016     }
2017
2018   return (GThread*) result;
2019 }
2020
2021 /**
2022  * g_thread_exit:
2023  * @retval: the return value of this thread.
2024  *
2025  * Exits the current thread. If another thread is waiting for that
2026  * thread using g_thread_join() and the current thread is joinable, the
2027  * waiting thread will be woken up and get @retval as the return value
2028  * of g_thread_join(). If the current thread is not joinable, @retval
2029  * is ignored. Calling
2030  *
2031  * <informalexample>
2032  *  <programlisting>
2033  *   g_thread_exit (retval);
2034  *  </programlisting>
2035  * </informalexample>
2036  *
2037  * is equivalent to returning @retval from the function @func, as given
2038  * to g_thread_create().
2039  *
2040  * <note><para>Never call g_thread_exit() from within a thread of a
2041  * #GThreadPool, as that will mess up the bookkeeping and lead to funny
2042  * and unwanted results.</para></note>
2043  **/
2044 void
2045 g_thread_exit (gpointer retval)
2046 {
2047   GRealThread* real = (GRealThread*) g_thread_self ();
2048   real->retval = retval;
2049   G_THREAD_CF (thread_exit, (void)0, ());
2050 }
2051
2052 /**
2053  * g_thread_join:
2054  * @thread: a #GThread to be waited for.
2055  * @Returns: the return value of the thread.
2056  *
2057  * Waits until @thread finishes, i.e. the function @func, as given to
2058  * g_thread_create(), returns or g_thread_exit() is called by @thread.
2059  * All resources of @thread including the #GThread struct are released.
2060  * @thread must have been created with @joinable=%TRUE in
2061  * g_thread_create(). The value returned by @func or given to
2062  * g_thread_exit() by @thread is returned by this function.
2063  **/
2064 gpointer
2065 g_thread_join (GThread* thread)
2066 {
2067   GRealThread* real = (GRealThread*) thread;
2068   GRealThread *p, *t;
2069   gpointer retval;
2070
2071   g_return_val_if_fail (thread, NULL);
2072   g_return_val_if_fail (thread->joinable, NULL);
2073   g_return_val_if_fail (!g_system_thread_equal (real->system_thread,
2074                                                 zero_thread), NULL);
2075
2076   G_THREAD_UF (thread_join, (&real->system_thread));
2077
2078   retval = real->retval;
2079
2080   G_LOCK (g_thread);
2081   for (t = g_thread_all_threads, p = NULL; t; p = t, t = t->next)
2082     {
2083       if (t == (GRealThread*) thread)
2084         {
2085           if (p)
2086             p->next = t->next;
2087           else
2088             g_thread_all_threads = t->next;
2089           break;
2090         }
2091     }
2092   G_UNLOCK (g_thread);
2093
2094   /* Just to make sure, this isn't used any more */
2095   thread->joinable = 0;
2096   g_system_thread_assign (real->system_thread, zero_thread);
2097
2098   /* the thread structure for non-joinable threads is freed upon
2099      thread end. We free the memory here. This will leave a loose end,
2100      if a joinable thread is not joined. */
2101
2102   g_free (thread);
2103
2104   return retval;
2105 }
2106
2107 /**
2108  * g_thread_set_priority:
2109  * @thread: a #GThread.
2110  * @priority: a new priority for @thread.
2111  *
2112  * Changes the priority of @thread to @priority.
2113  *
2114  * <note><para>It is not guaranteed that threads with different
2115  * priorities really behave accordingly. On some systems (e.g. Linux)
2116  * there are no thread priorities. On other systems (e.g. Solaris) there
2117  * doesn't seem to be different scheduling for different priorities. All
2118  * in all try to avoid being dependent on priorities.</para></note>
2119  **/
2120 void
2121 g_thread_set_priority (GThread* thread,
2122                        GThreadPriority priority)
2123 {
2124   GRealThread* real = (GRealThread*) thread;
2125
2126   g_return_if_fail (thread);
2127   g_return_if_fail (!g_system_thread_equal (real->system_thread, zero_thread));
2128   g_return_if_fail (priority >= G_THREAD_PRIORITY_LOW);
2129   g_return_if_fail (priority <= G_THREAD_PRIORITY_URGENT);
2130
2131   thread->priority = priority;
2132
2133   G_THREAD_CF (thread_set_priority, (void)0,
2134                (&real->system_thread, priority));
2135 }
2136
2137 /**
2138  * g_thread_self:
2139  * @Returns: the current thread.
2140  *
2141  * This functions returns the #GThread corresponding to the calling
2142  * thread.
2143  **/
2144 GThread*
2145 g_thread_self (void)
2146 {
2147   GRealThread* thread = g_private_get (&g_thread_specific_private);
2148
2149   if (!thread)
2150     {
2151       /* If no thread data is available, provide and set one.  This
2152          can happen for the main thread and for threads, that are not
2153          created by GLib. */
2154       thread = g_new0 (GRealThread, 1);
2155       thread->thread.joinable = FALSE; /* This is a save guess */
2156       thread->thread.priority = G_THREAD_PRIORITY_NORMAL; /* This is
2157                                                              just a guess */
2158       thread->thread.func = NULL;
2159       thread->thread.data = NULL;
2160       thread->private_data = NULL;
2161
2162       G_THREAD_UF (thread_self, (&thread->system_thread));
2163
2164       g_private_set (&g_thread_specific_private, thread);
2165
2166       G_LOCK (g_thread);
2167       thread->next = g_thread_all_threads;
2168       g_thread_all_threads = thread;
2169       G_UNLOCK (g_thread);
2170     }
2171
2172   return (GThread*)thread;
2173 }
2174
2175 /* GStaticRWLock {{{1 ----------------------------------------------------- */
2176
2177 /**
2178  * GStaticRWLock:
2179  *
2180  * The #GStaticRWLock struct represents a read-write lock. A read-write
2181  * lock can be used for protecting data that some portions of code only
2182  * read from, while others also write. In such situations it is
2183  * desirable that several readers can read at once, whereas of course
2184  * only one writer may write at a time. Take a look at the following
2185  * example:
2186  *
2187  * <example>
2188  *  <title>An array with access functions</title>
2189  *  <programlisting>
2190  *   GStaticRWLock rwlock = G_STATIC_RW_LOCK_INIT;
2191  *   GPtrArray *array;
2192  *
2193  *   gpointer
2194  *   my_array_get (guint index)
2195  *   {
2196  *     gpointer retval = NULL;
2197  *
2198  *     if (!array)
2199  *       return NULL;
2200  *
2201  *     g_static_rw_lock_reader_lock (&amp;rwlock);
2202  *     if (index &lt; array->len)
2203  *       retval = g_ptr_array_index (array, index);
2204  *     g_static_rw_lock_reader_unlock (&amp;rwlock);
2205  *
2206  *     return retval;
2207  *   }
2208  *
2209  *   void
2210  *   my_array_set (guint index, gpointer data)
2211  *   {
2212  *     g_static_rw_lock_writer_lock (&amp;rwlock);
2213  *
2214  *     if (!array)
2215  *       array = g_ptr_array_new (<!-- -->);
2216  *
2217  *     if (index >= array->len)
2218  *       g_ptr_array_set_size (array, index+1);
2219  *     g_ptr_array_index (array, index) = data;
2220  *
2221  *     g_static_rw_lock_writer_unlock (&amp;rwlock);
2222  *   }
2223  *  </programlisting>
2224  * </example>
2225  *
2226  * This example shows an array which can be accessed by many readers
2227  * (the <function>my_array_get()</function> function) simultaneously,
2228  * whereas the writers (the <function>my_array_set()</function>
2229  * function) will only be allowed once at a time and only if no readers
2230  * currently access the array. This is because of the potentially
2231  * dangerous resizing of the array. Using these functions is fully
2232  * multi-thread safe now.
2233  *
2234  * Most of the time, writers should have precedence over readers. That
2235  * means, for this implementation, that as soon as a writer wants to
2236  * lock the data, no other reader is allowed to lock the data, whereas,
2237  * of course, the readers that already have locked the data are allowed
2238  * to finish their operation. As soon as the last reader unlocks the
2239  * data, the writer will lock it.
2240  *
2241  * Even though #GStaticRWLock is not opaque, it should only be used
2242  * with the following functions.
2243  *
2244  * All of the <function>g_static_rw_lock_*</function> functions can be
2245  * used even if g_thread_init() has not been called. Then they do
2246  * nothing, apart from <function>g_static_rw_lock_*_trylock</function>,
2247  * which does nothing but returning %TRUE.
2248  *
2249  * <note><para>A read-write lock has a higher overhead than a mutex. For
2250  * example, both g_static_rw_lock_reader_lock() and
2251  * g_static_rw_lock_reader_unlock() have to lock and unlock a
2252  * #GStaticMutex, so it takes at least twice the time to lock and unlock
2253  * a #GStaticRWLock that it does to lock and unlock a #GStaticMutex. So
2254  * only data structures that are accessed by multiple readers, and which
2255  * keep the lock for a considerable time justify a #GStaticRWLock. The
2256  * above example most probably would fare better with a
2257  * #GStaticMutex.</para></note>
2258  **/
2259
2260 /**
2261  * G_STATIC_RW_LOCK_INIT:
2262  *
2263  * A #GStaticRWLock must be initialized with this macro before it can
2264  * be used. This macro can used be to initialize a variable, but it
2265  * cannot be assigned to a variable. In that case you have to use
2266  * g_static_rw_lock_init().
2267  *
2268  * <informalexample>
2269  *  <programlisting>
2270  *   GStaticRWLock my_lock = G_STATIC_RW_LOCK_INIT;
2271  *  </programlisting>
2272  * </informalexample>
2273  **/
2274
2275 /**
2276  * g_static_rw_lock_init:
2277  * @lock: a #GStaticRWLock to be initialized.
2278  *
2279  * A #GStaticRWLock must be initialized with this function before it
2280  * can be used. Alternatively you can initialize it with
2281  * #G_STATIC_RW_LOCK_INIT.
2282  **/
2283 void
2284 g_static_rw_lock_init (GStaticRWLock* lock)
2285 {
2286   static const GStaticRWLock init_lock = G_STATIC_RW_LOCK_INIT;
2287
2288   g_return_if_fail (lock);
2289
2290   *lock = init_lock;
2291 }
2292
2293 inline static void
2294 g_static_rw_lock_wait (GCond** cond, GStaticMutex* mutex)
2295 {
2296   if (!*cond)
2297       *cond = g_cond_new ();
2298   g_cond_wait (*cond, g_static_mutex_get_mutex (mutex));
2299 }
2300
2301 inline static void
2302 g_static_rw_lock_signal (GStaticRWLock* lock)
2303 {
2304   if (lock->want_to_write && lock->write_cond)
2305     g_cond_signal (lock->write_cond);
2306   else if (lock->want_to_read && lock->read_cond)
2307     g_cond_broadcast (lock->read_cond);
2308 }
2309
2310 /**
2311  * g_static_rw_lock_reader_lock:
2312  * @lock: a #GStaticRWLock to lock for reading.
2313  *
2314  * Locks @lock for reading. There may be unlimited concurrent locks for
2315  * reading of a #GStaticRWLock at the same time.  If @lock is already
2316  * locked for writing by another thread or if another thread is already
2317  * waiting to lock @lock for writing, this function will block until
2318  * @lock is unlocked by the other writing thread and no other writing
2319  * threads want to lock @lock. This lock has to be unlocked by
2320  * g_static_rw_lock_reader_unlock().
2321  *
2322  * #GStaticRWLock is not recursive. It might seem to be possible to
2323  * recursively lock for reading, but that can result in a deadlock, due
2324  * to writer preference.
2325  **/
2326 void
2327 g_static_rw_lock_reader_lock (GStaticRWLock* lock)
2328 {
2329   g_return_if_fail (lock);
2330
2331   if (!g_threads_got_initialized)
2332     return;
2333
2334   g_static_mutex_lock (&lock->mutex);
2335   lock->want_to_read++;
2336   while (lock->have_writer || lock->want_to_write)
2337     g_static_rw_lock_wait (&lock->read_cond, &lock->mutex);
2338   lock->want_to_read--;
2339   lock->read_counter++;
2340   g_static_mutex_unlock (&lock->mutex);
2341 }
2342
2343 /**
2344  * g_static_rw_lock_reader_trylock:
2345  * @lock: a #GStaticRWLock to lock for reading.
2346  * @Returns: %TRUE, if @lock could be locked for reading.
2347  *
2348  * Tries to lock @lock for reading. If @lock is already locked for
2349  * writing by another thread or if another thread is already waiting to
2350  * lock @lock for writing, immediately returns %FALSE. Otherwise locks
2351  * @lock for reading and returns %TRUE. This lock has to be unlocked by
2352  * g_static_rw_lock_reader_unlock().
2353  **/
2354 gboolean
2355 g_static_rw_lock_reader_trylock (GStaticRWLock* lock)
2356 {
2357   gboolean ret_val = FALSE;
2358
2359   g_return_val_if_fail (lock, FALSE);
2360
2361   if (!g_threads_got_initialized)
2362     return TRUE;
2363
2364   g_static_mutex_lock (&lock->mutex);
2365   if (!lock->have_writer && !lock->want_to_write)
2366     {
2367       lock->read_counter++;
2368       ret_val = TRUE;
2369     }
2370   g_static_mutex_unlock (&lock->mutex);
2371   return ret_val;
2372 }
2373
2374 /**
2375  * g_static_rw_lock_reader_unlock:
2376  * @lock: a #GStaticRWLock to unlock after reading.
2377  *
2378  * Unlocks @lock. If a thread waits to lock @lock for writing and all
2379  * locks for reading have been unlocked, the waiting thread is woken up
2380  * and can lock @lock for writing.
2381  **/
2382 void
2383 g_static_rw_lock_reader_unlock  (GStaticRWLock* lock)
2384 {
2385   g_return_if_fail (lock);
2386
2387   if (!g_threads_got_initialized)
2388     return;
2389
2390   g_static_mutex_lock (&lock->mutex);
2391   lock->read_counter--;
2392   if (lock->read_counter == 0)
2393     g_static_rw_lock_signal (lock);
2394   g_static_mutex_unlock (&lock->mutex);
2395 }
2396
2397 /**
2398  * g_static_rw_lock_writer_lock:
2399  * @lock: a #GStaticRWLock to lock for writing.
2400  *
2401  * Locks @lock for writing. If @lock is already locked for writing or
2402  * reading by other threads, this function will block until @lock is
2403  * completely unlocked and then lock @lock for writing. While this
2404  * functions waits to lock @lock, no other thread can lock @lock for
2405  * reading. When @lock is locked for writing, no other thread can lock
2406  * @lock (neither for reading nor writing). This lock has to be
2407  * unlocked by g_static_rw_lock_writer_unlock().
2408  **/
2409 void
2410 g_static_rw_lock_writer_lock (GStaticRWLock* lock)
2411 {
2412   g_return_if_fail (lock);
2413
2414   if (!g_threads_got_initialized)
2415     return;
2416
2417   g_static_mutex_lock (&lock->mutex);
2418   lock->want_to_write++;
2419   while (lock->have_writer || lock->read_counter)
2420     g_static_rw_lock_wait (&lock->write_cond, &lock->mutex);
2421   lock->want_to_write--;
2422   lock->have_writer = TRUE;
2423   g_static_mutex_unlock (&lock->mutex);
2424 }
2425
2426 /**
2427  * g_static_rw_lock_writer_trylock:
2428  * @lock: a #GStaticRWLock to lock for writing.
2429  * @Returns: %TRUE, if @lock could be locked for writing.
2430  *
2431  * Tries to lock @lock for writing. If @lock is already locked (for
2432  * either reading or writing) by another thread, it immediately returns
2433  * %FALSE. Otherwise it locks @lock for writing and returns %TRUE. This
2434  * lock has to be unlocked by g_static_rw_lock_writer_unlock().
2435  **/
2436 gboolean
2437 g_static_rw_lock_writer_trylock (GStaticRWLock* lock)
2438 {
2439   gboolean ret_val = FALSE;
2440
2441   g_return_val_if_fail (lock, FALSE);
2442
2443   if (!g_threads_got_initialized)
2444     return TRUE;
2445
2446   g_static_mutex_lock (&lock->mutex);
2447   if (!lock->have_writer && !lock->read_counter)
2448     {
2449       lock->have_writer = TRUE;
2450       ret_val = TRUE;
2451     }
2452   g_static_mutex_unlock (&lock->mutex);
2453   return ret_val;
2454 }
2455
2456 /**
2457  * g_static_rw_lock_writer_unlock:
2458  * @lock: a #GStaticRWLock to unlock after writing.
2459  *
2460  * Unlocks @lock. If a thread is waiting to lock @lock for writing and
2461  * all locks for reading have been unlocked, the waiting thread is
2462  * woken up and can lock @lock for writing. If no thread is waiting to
2463  * lock @lock for writing, and some thread or threads are waiting to
2464  * lock @lock for reading, the waiting threads are woken up and can
2465  * lock @lock for reading.
2466  **/
2467 void
2468 g_static_rw_lock_writer_unlock (GStaticRWLock* lock)
2469 {
2470   g_return_if_fail (lock);
2471
2472   if (!g_threads_got_initialized)
2473     return;
2474
2475   g_static_mutex_lock (&lock->mutex);
2476   lock->have_writer = FALSE;
2477   g_static_rw_lock_signal (lock);
2478   g_static_mutex_unlock (&lock->mutex);
2479 }
2480
2481 /**
2482  * g_static_rw_lock_free:
2483  * @lock: a #GStaticRWLock to be freed.
2484  *
2485  * Releases all resources allocated to @lock.
2486  *
2487  * You don't have to call this functions for a #GStaticRWLock with an
2488  * unbounded lifetime, i.e. objects declared 'static', but if you have
2489  * a #GStaticRWLock as a member of a structure, and the structure is
2490  * freed, you should also free the #GStaticRWLock.
2491  **/
2492 void
2493 g_static_rw_lock_free (GStaticRWLock* lock)
2494 {
2495   g_return_if_fail (lock);
2496
2497   if (lock->read_cond)
2498     {
2499       g_cond_free (lock->read_cond);
2500       lock->read_cond = NULL;
2501     }
2502   if (lock->write_cond)
2503     {
2504       g_cond_free (lock->write_cond);
2505       lock->write_cond = NULL;
2506     }
2507   g_static_mutex_free (&lock->mutex);
2508 }
2509
2510 /* Unsorted {{{1 ---------------------------------------------------------- */
2511
2512 /**
2513  * g_thread_foreach
2514  * @thread_func: function to call for all GThread structures
2515  * @user_data:   second argument to @thread_func
2516  *
2517  * Call @thread_func on all existing #GThread structures. Note that
2518  * threads may decide to exit while @thread_func is running, so
2519  * without intimate knowledge about the lifetime of foreign threads,
2520  * @thread_func shouldn't access the GThread* pointer passed in as
2521  * first argument. However, @thread_func will not be called for threads
2522  * which are known to have exited already.
2523  *
2524  * Due to thread lifetime checks, this function has an execution complexity
2525  * which is quadratic in the number of existing threads.
2526  *
2527  * Since: 2.10
2528  */
2529 void
2530 g_thread_foreach (GFunc    thread_func,
2531                   gpointer user_data)
2532 {
2533   GSList *slist = NULL;
2534   GRealThread *thread;
2535   g_return_if_fail (thread_func != NULL);
2536   /* snapshot the list of threads for iteration */
2537   G_LOCK (g_thread);
2538   for (thread = g_thread_all_threads; thread; thread = thread->next)
2539     slist = g_slist_prepend (slist, thread);
2540   G_UNLOCK (g_thread);
2541   /* walk the list, skipping non-existent threads */
2542   while (slist)
2543     {
2544       GSList *node = slist;
2545       slist = node->next;
2546       /* check whether the current thread still exists */
2547       G_LOCK (g_thread);
2548       for (thread = g_thread_all_threads; thread; thread = thread->next)
2549         if (thread == node->data)
2550           break;
2551       G_UNLOCK (g_thread);
2552       if (thread)
2553         thread_func (thread, user_data);
2554       g_slist_free_1 (node);
2555     }
2556 }
2557
2558 /**
2559  * g_thread_get_initialized
2560  *
2561  * Indicates if g_thread_init() has been called.
2562  *
2563  * Returns: %TRUE if threads have been initialized.
2564  *
2565  * Since: 2.20
2566  */
2567 gboolean
2568 g_thread_get_initialized ()
2569 {
2570   return g_thread_supported ();
2571 }
2572
2573 GMutex *
2574 g_mutex_new (void)
2575 {
2576   GMutex *mutex;
2577
2578   mutex = g_slice_new (GMutex);
2579   g_mutex_init (mutex);
2580
2581   return mutex;
2582 }
2583
2584 void
2585 g_mutex_free (GMutex *mutex)
2586 {
2587   g_mutex_clear (mutex);
2588   g_slice_free (GMutex, mutex);
2589 }
2590
2591 GCond *
2592 g_cond_new (void)
2593 {
2594   GCond *cond;
2595
2596   cond = g_slice_new (GCond);
2597   g_cond_init (cond);
2598
2599   return cond;
2600 }
2601
2602 void
2603 g_cond_free (GCond *cond)
2604 {
2605   g_cond_clear (cond);
2606   g_slice_free (GCond, cond);
2607 }