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