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