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