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