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