GCond: use monotonic time for timed waits
[platform/upstream/glib.git] / glib / gthread-posix.c
1 /* GLIB - Library of useful routines for C programming
2  * Copyright (C) 1995-1997  Peter Mattis, Spencer Kimball and Josh MacDonald
3  *
4  * gthread.c: posix thread system implementation
5  * Copyright 1998 Sebastian Wilhelmi; University of Karlsruhe
6  *
7  * This library is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU Lesser General Public
9  * License as published by the Free Software Foundation; either
10  * version 2 of the License, or (at your option) any later version.
11  *
12  * This library is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15  * Lesser General Public License for more details.
16  *
17  * You should have received a copy of the GNU Lesser General Public
18  * License along with this library; if not, write to the
19  * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
20  * Boston, MA 02111-1307, USA.
21  */
22
23 /*
24  * Modified by the GLib Team and others 1997-2000.  See the AUTHORS
25  * file for a list of people on the GLib Team.  See the ChangeLog
26  * files for a list of changes.  These files are distributed with
27  * GLib at ftp://ftp.gtk.org/pub/gtk/.
28  */
29
30 /* The GMutex, GCond and GPrivate implementations in this file are some
31  * of the lowest-level code in GLib.  All other parts of GLib (messages,
32  * memory, slices, etc) assume that they can freely use these facilities
33  * without risking recursion.
34  *
35  * As such, these functions are NOT permitted to call any other part of
36  * GLib.
37  *
38  * The thread manipulation functions (create, exit, join, etc.) have
39  * more freedom -- they can do as they please.
40  */
41
42 #include "config.h"
43
44 #include "gthread.h"
45
46 #include "gthreadprivate.h"
47 #include "gslice.h"
48 #include "gmessages.h"
49 #include "gstrfuncs.h"
50
51 #include <stdlib.h>
52 #include <stdio.h>
53 #include <string.h>
54 #include <errno.h>
55 #include <pthread.h>
56
57 #ifdef HAVE_SYS_TIME_H
58 # include <sys/time.h>
59 #endif
60 #ifdef HAVE_UNISTD_H
61 # include <unistd.h>
62 #endif
63 #ifdef HAVE_SCHED_H
64 #include <sched.h>
65 #endif
66 #ifdef HAVE_SYS_PRCTL_H
67 #include <sys/prctl.h>
68 #endif
69
70 static void
71 g_thread_abort (gint         status,
72                 const gchar *function)
73 {
74   fprintf (stderr, "GLib (gthread-posix.c): Unexpected error from C library during '%s': %s.  Aborting.\n",
75            strerror (status), function);
76   abort ();
77 }
78
79 /* {{{1 GMutex */
80
81 static pthread_mutex_t *
82 g_mutex_impl_new (void)
83 {
84   pthread_mutexattr_t *pattr = NULL;
85   pthread_mutex_t *mutex;
86   gint status;
87
88   mutex = malloc (sizeof (pthread_mutex_t));
89   if G_UNLIKELY (mutex == NULL)
90     g_thread_abort (errno, "malloc");
91
92 #ifdef PTHREAD_ADAPTIVE_MUTEX_INITIALIZER_NP
93   pthread_mutexattr_t attr;
94   pthread_mutexattr_init (&attr);
95   pthread_mutexattr_settype (&attr, PTHREAD_MUTEX_ADAPTIVE_NP);
96   pattr = &attr;
97 #endif
98
99   if G_UNLIKELY ((status = pthread_mutex_init (mutex, pattr)) != 0)
100     g_thread_abort (status, "pthread_mutex_init");
101
102 #ifdef PTHREAD_ADAPTIVE_MUTEX_NP
103   pthread_mutexattr_destroy (&attr);
104 #endif
105
106   return mutex;
107 }
108
109 static void
110 g_mutex_impl_free (pthread_mutex_t *mutex)
111 {
112   pthread_mutex_destroy (mutex);
113   free (mutex);
114 }
115
116 static pthread_mutex_t *
117 g_mutex_get_impl (GMutex *mutex)
118 {
119   pthread_mutex_t *impl = mutex->p;
120
121   if G_UNLIKELY (impl == NULL)
122     {
123       impl = g_mutex_impl_new ();
124       if (!g_atomic_pointer_compare_and_exchange (&mutex->p, NULL, impl))
125         g_mutex_impl_free (impl);
126       impl = mutex->p;
127     }
128
129   return impl;
130 }
131
132
133 /**
134  * g_mutex_init:
135  * @mutex: an uninitialized #GMutex
136  *
137  * Initializes a #GMutex so that it can be used.
138  *
139  * This function is useful to initialize a mutex that has been
140  * allocated on the stack, or as part of a larger structure.
141  * It is not necessary to initialize a mutex that has been
142  * created that has been statically allocated.
143  *
144  * |[
145  *   typedef struct {
146  *     GMutex m;
147  *     ...
148  *   } Blob;
149  *
150  * Blob *b;
151  *
152  * b = g_new (Blob, 1);
153  * g_mutex_init (&b->m);
154  * ]|
155  *
156  * To undo the effect of g_mutex_init() when a mutex is no longer
157  * needed, use g_mutex_clear().
158  *
159  * Calling g_mutex_init() on an already initialized #GMutex leads
160  * to undefined behaviour.
161  *
162  * Since: 2.32
163  */
164 void
165 g_mutex_init (GMutex *mutex)
166 {
167   mutex->p = g_mutex_impl_new ();
168 }
169
170 /**
171  * g_mutex_clear:
172  * @mutex: an initialized #GMutex
173  *
174  * Frees the resources allocated to a mutex with g_mutex_init().
175  *
176  * This function should not be used with a #GMutex that has been
177  * statically allocated.
178  *
179  * Calling g_mutex_clear() on a locked mutex leads to undefined
180  * behaviour.
181  *
182  * Sine: 2.32
183  */
184 void
185 g_mutex_clear (GMutex *mutex)
186 {
187   g_mutex_impl_free (mutex->p);
188 }
189
190 /**
191  * g_mutex_lock:
192  * @mutex: a #GMutex
193  *
194  * Locks @mutex. If @mutex is already locked by another thread, the
195  * current thread will block until @mutex is unlocked by the other
196  * thread.
197  *
198  * This function can be used even if g_thread_init() has not yet been
199  * called, and, in that case, will do nothing.
200  *
201  * <note>#GMutex is neither guaranteed to be recursive nor to be
202  * non-recursive.  As such, calling g_mutex_lock() on a #GMutex that has
203  * already been locked by the same thread results in undefined behaviour
204  * (including but not limited to deadlocks).</note>
205  */
206 void
207 g_mutex_lock (GMutex *mutex)
208 {
209   gint status;
210
211   if G_UNLIKELY ((status = pthread_mutex_lock (g_mutex_get_impl (mutex))) != 0)
212     g_thread_abort (status, "pthread_mutex_lock");
213 }
214
215 /**
216  * g_mutex_unlock:
217  * @mutex: a #GMutex
218  *
219  * Unlocks @mutex. If another thread is blocked in a g_mutex_lock()
220  * call for @mutex, it will become unblocked and can lock @mutex itself.
221  *
222  * Calling g_mutex_unlock() on a mutex that is not locked by the
223  * current thread leads to undefined behaviour.
224  *
225  * This function can be used even if g_thread_init() has not yet been
226  * called, and, in that case, will do nothing.
227  */
228 void
229 g_mutex_unlock (GMutex *mutex)
230 {
231   gint status;
232
233   if G_UNLIKELY ((status = pthread_mutex_unlock (g_mutex_get_impl (mutex))) != 0)
234     g_thread_abort (status, "pthread_mutex_lock");
235 }
236
237 /**
238  * g_mutex_trylock:
239  * @mutex: a #GMutex
240  *
241  * Tries to lock @mutex. If @mutex is already locked by another thread,
242  * it immediately returns %FALSE. Otherwise it locks @mutex and returns
243  * %TRUE.
244  *
245  * This function can be used even if g_thread_init() has not yet been
246  * called, and, in that case, will immediately return %TRUE.
247  *
248  * <note>#GMutex is neither guaranteed to be recursive nor to be
249  * non-recursive.  As such, calling g_mutex_lock() on a #GMutex that has
250  * already been locked by the same thread results in undefined behaviour
251  * (including but not limited to deadlocks or arbitrary return values).
252  * </note>
253
254  * Returns: %TRUE if @mutex could be locked
255  */
256 gboolean
257 g_mutex_trylock (GMutex *mutex)
258 {
259   gint status;
260
261   if G_LIKELY ((status = pthread_mutex_trylock (g_mutex_get_impl (mutex))) == 0)
262     return TRUE;
263
264   if G_UNLIKELY (status != EBUSY)
265     g_thread_abort (status, "pthread_mutex_trylock");
266
267   return FALSE;
268 }
269
270 /* {{{1 GRecMutex */
271
272 static pthread_mutex_t *
273 g_rec_mutex_impl_new (void)
274 {
275   pthread_mutexattr_t attr;
276   pthread_mutex_t *mutex;
277
278   mutex = g_slice_new (pthread_mutex_t);
279   pthread_mutexattr_init (&attr);
280   pthread_mutexattr_settype (&attr, PTHREAD_MUTEX_RECURSIVE);
281   pthread_mutex_init (mutex, &attr);
282   pthread_mutexattr_destroy (&attr);
283
284   return mutex;
285 }
286
287 static void
288 g_rec_mutex_impl_free (pthread_mutex_t *mutex)
289 {
290   pthread_mutex_destroy (mutex);
291   g_slice_free (pthread_mutex_t, mutex);
292 }
293
294 static pthread_mutex_t *
295 g_rec_mutex_get_impl (GRecMutex *rec_mutex)
296 {
297   pthread_mutex_t *impl = rec_mutex->p;
298
299   if G_UNLIKELY (impl == NULL)
300     {
301       impl = g_rec_mutex_impl_new ();
302       if (!g_atomic_pointer_compare_and_exchange (&rec_mutex->p, NULL, impl))
303         g_rec_mutex_impl_free (impl);
304       impl = rec_mutex->p;
305     }
306
307   return impl;
308 }
309
310 /**
311  * g_rec_mutex_init:
312  * @rec_mutex: an uninitialized #GRecMutex
313  *
314  * Initializes a #GRecMutex so that it can be used.
315  *
316  * This function is useful to initialize a recursive mutex
317  * that has been allocated on the stack, or as part of a larger
318  * structure.
319  *
320  * It is not necessary to initialise a recursive mutex that has been
321  * statically allocated.
322  *
323  * |[
324  *   typedef struct {
325  *     GRecMutex m;
326  *     ...
327  *   } Blob;
328  *
329  * Blob *b;
330  *
331  * b = g_new (Blob, 1);
332  * g_rec_mutex_init (&b->m);
333  * ]|
334  *
335  * Calling g_rec_mutex_init() on an already initialized #GRecMutex
336  * leads to undefined behaviour.
337  *
338  * To undo the effect of g_rec_mutex_init() when a recursive mutex
339  * is no longer needed, use g_rec_mutex_clear().
340  *
341  * Since: 2.32
342  */
343 void
344 g_rec_mutex_init (GRecMutex *rec_mutex)
345 {
346   rec_mutex->p = g_rec_mutex_impl_new ();
347 }
348
349 /**
350  * g_rec_mutex_clear:
351  * @rec_mutex: an initialized #GRecMutex
352  *
353  * Frees the resources allocated to a recursive mutex with
354  * g_rec_mutex_init().
355  *
356  * This function should not be used with a #GRecMutex that has been
357  * statically allocated.
358  *
359  * Calling g_rec_mutex_clear() on a locked recursive mutex leads
360  * to undefined behaviour.
361  *
362  * Sine: 2.32
363  */
364 void
365 g_rec_mutex_clear (GRecMutex *rec_mutex)
366 {
367   g_rec_mutex_impl_free (rec_mutex->p);
368 }
369
370 /**
371  * g_rec_mutex_lock:
372  * @rec_mutex: a #GRecMutex
373  *
374  * Locks @rec_mutex. If @rec_mutex is already locked by another
375  * thread, the current thread will block until @rec_mutex is
376  * unlocked by the other thread. If @rec_mutex is already locked
377  * by the current thread, the 'lock count' of @rec_mutex is increased.
378  * The mutex will only become available again when it is unlocked
379  * as many times as it has been locked.
380  *
381  * Since: 2.32
382  */
383 void
384 g_rec_mutex_lock (GRecMutex *mutex)
385 {
386   pthread_mutex_lock (g_rec_mutex_get_impl (mutex));
387 }
388
389 /**
390  * g_rec_mutex_unlock:
391  * @rec_mutex: a #RecGMutex
392  *
393  * Unlocks @rec_mutex. If another thread is blocked in a
394  * g_rec_mutex_lock() call for @rec_mutex, it will become unblocked
395  * and can lock @rec_mutex itself.
396  *
397  * Calling g_rec_mutex_unlock() on a recursive mutex that is not
398  * locked by the current thread leads to undefined behaviour.
399  *
400  * Since: 2.32
401  */
402 void
403 g_rec_mutex_unlock (GRecMutex *rec_mutex)
404 {
405   pthread_mutex_unlock (rec_mutex->p);
406 }
407
408 /**
409  * g_rec_mutex_trylock:
410  * @rec_mutex: a #GRecMutex
411  *
412  * Tries to lock @rec_mutex. If @rec_mutex is already locked
413  * by another thread, it immediately returns %FALSE. Otherwise
414  * it locks @rec_mutex and returns %TRUE.
415  *
416  * Returns: %TRUE if @rec_mutex could be locked
417  *
418  * Since: 2.32
419  */
420 gboolean
421 g_rec_mutex_trylock (GRecMutex *rec_mutex)
422 {
423   if (pthread_mutex_trylock (g_rec_mutex_get_impl (rec_mutex)) != 0)
424     return FALSE;
425
426   return TRUE;
427 }
428
429 /* {{{1 GRWLock */
430
431 static pthread_rwlock_t *
432 g_rw_lock_impl_new (void)
433 {
434   pthread_rwlock_t *rwlock;
435   gint status;
436
437   rwlock = malloc (sizeof (pthread_rwlock_t));
438   if G_UNLIKELY (rwlock == NULL)
439     g_thread_abort (errno, "malloc");
440
441   if G_UNLIKELY ((status = pthread_rwlock_init (rwlock, NULL)) != 0)
442     g_thread_abort (status, "pthread_rwlock_init");
443
444   return rwlock;
445 }
446
447 static void
448 g_rw_lock_impl_free (pthread_rwlock_t *rwlock)
449 {
450   pthread_rwlock_destroy (rwlock);
451   free (rwlock);
452 }
453
454 static pthread_rwlock_t *
455 g_rw_lock_get_impl (GRWLock *lock)
456 {
457   pthread_rwlock_t *impl = lock->p;
458
459   if G_UNLIKELY (impl == NULL)
460     {
461       impl = g_rw_lock_impl_new ();
462       if (!g_atomic_pointer_compare_and_exchange (&lock->p, NULL, impl))
463         g_rw_lock_impl_free (impl);
464       impl = lock->p;
465     }
466
467   return impl;
468 }
469
470 /**
471  * g_rw_lock_init:
472  * @rw_lock: an uninitialized #GRWLock
473  *
474  * Initializes a #GRWLock so that it can be used.
475  *
476  * This function is useful to initialize a lock that has been
477  * allocated on the stack, or as part of a larger structure.  It is not
478  * necessary to initialise a reader-writer lock that has been statically
479  * allocated.
480  *
481  * |[
482  *   typedef struct {
483  *     GRWLock l;
484  *     ...
485  *   } Blob;
486  *
487  * Blob *b;
488  *
489  * b = g_new (Blob, 1);
490  * g_rw_lock_init (&b->l);
491  * ]|
492  *
493  * To undo the effect of g_rw_lock_init() when a lock is no longer
494  * needed, use g_rw_lock_clear().
495  *
496  * Calling g_rw_lock_init() on an already initialized #GRWLock leads
497  * to undefined behaviour.
498  *
499  * Since: 2.32
500  */
501 void
502 g_rw_lock_init (GRWLock *rw_lock)
503 {
504   rw_lock->p = g_rw_lock_impl_new ();
505 }
506
507 /**
508  * g_rw_lock_clear:
509  * @rw_lock: an initialized #GRWLock
510  *
511  * Frees the resources allocated to a lock with g_rw_lock_init().
512  *
513  * This function should not be used with a #GRWLock that has been
514  * statically allocated.
515  *
516  * Calling g_rw_lock_clear() when any thread holds the lock
517  * leads to undefined behaviour.
518  *
519  * Sine: 2.32
520  */
521 void
522 g_rw_lock_clear (GRWLock *rw_lock)
523 {
524   g_rw_lock_impl_free (rw_lock->p);
525 }
526
527 /**
528  * g_rw_lock_writer_lock:
529  * @rw_lock: a #GRWLock
530  *
531  * Obtain a write lock on @rw_lock. If any thread already holds
532  * a read or write lock on @rw_lock, the current thread will block
533  * until all other threads have dropped their locks on @rw_lock.
534  *
535  * Since: 2.32
536  */
537 void
538 g_rw_lock_writer_lock (GRWLock *rw_lock)
539 {
540   pthread_rwlock_wrlock (g_rw_lock_get_impl (rw_lock));
541 }
542
543 /**
544  * g_rw_lock_writer_trylock:
545  * @rw_lock: a #GRWLock
546  *
547  * Tries to obtain a write lock on @rw_lock. If any other thread holds
548  * a read or write lock on @rw_lock, it immediately returns %FALSE.
549  * Otherwise it locks @rw_lock and returns %TRUE.
550  *
551  * Returns: %TRUE if @rw_lock could be locked
552  *
553  * Since: 2.32
554  */
555 gboolean
556 g_rw_lock_writer_trylock (GRWLock *rw_lock)
557 {
558   if (pthread_rwlock_trywrlock (g_rw_lock_get_impl (rw_lock)) != 0)
559     return FALSE;
560
561   return TRUE;
562 }
563
564 /**
565  * g_rw_lock_writer_unlock:
566  * @rw_lock: a #GRWLock
567  *
568  * Release a write lock on @rw_lock.
569  *
570  * Calling g_rw_lock_writer_unlock() on a lock that is not held
571  * by the current thread leads to undefined behaviour.
572  *
573  * Since: 2.32
574  */
575 void
576 g_rw_lock_writer_unlock (GRWLock *rw_lock)
577 {
578   pthread_rwlock_unlock (g_rw_lock_get_impl (rw_lock));
579 }
580
581 /**
582  * g_rw_lock_reader_lock:
583  * @rw_lock: a #GRWLock
584  *
585  * Obtain a read lock on @rw_lock. If another thread currently holds
586  * the write lock on @rw_lock or blocks waiting for it, the current
587  * thread will block. Read locks can be taken recursively.
588  *
589  * It is implementation-defined how many threads are allowed to
590  * hold read locks on the same lock simultaneously.
591  *
592  * Since: 2.32
593  */
594 void
595 g_rw_lock_reader_lock (GRWLock *rw_lock)
596 {
597   pthread_rwlock_rdlock (g_rw_lock_get_impl (rw_lock));
598 }
599
600 /**
601  * g_rw_lock_reader_trylock:
602  * @rw_lock: a #GRWLock
603  *
604  * Tries to obtain a read lock on @rw_lock and returns %TRUE if
605  * the read lock was successfully obtained. Otherwise it
606  * returns %FALSE.
607  *
608  * Returns: %TRUE if @rw_lock could be locked
609  *
610  * Since: 2.32
611  */
612 gboolean
613 g_rw_lock_reader_trylock (GRWLock *rw_lock)
614 {
615   if (pthread_rwlock_tryrdlock (g_rw_lock_get_impl (rw_lock)) != 0)
616     return FALSE;
617
618   return TRUE;
619 }
620
621 /**
622  * g_rw_lock_reader_unlock:
623  * @rw_lock: a #GRWLock
624  *
625  * Release a read lock on @rw_lock.
626  *
627  * Calling g_rw_lock_reader_unlock() on a lock that is not held
628  * by the current thread leads to undefined behaviour.
629  *
630  * Since: 2.32
631  */
632 void
633 g_rw_lock_reader_unlock (GRWLock *rw_lock)
634 {
635   pthread_rwlock_unlock (g_rw_lock_get_impl (rw_lock));
636 }
637
638 /* {{{1 GCond */
639
640 static pthread_cond_t *
641 g_cond_impl_new (void)
642 {
643   pthread_condattr_t attr;
644   pthread_cond_t *cond;
645   gint status;
646
647   pthread_condattr_init (&attr);
648 #ifdef CLOCK_MONOTONIC
649   pthread_condattr_setclock (&attr, CLOCK_MONOTONIC);
650 #endif
651
652   cond = malloc (sizeof (pthread_cond_t));
653   if G_UNLIKELY (cond == NULL)
654     g_thread_abort (errno, "malloc");
655
656   if G_UNLIKELY ((status = pthread_cond_init (cond, &attr)) != 0)
657     g_thread_abort (status, "pthread_cond_init");
658
659   pthread_condattr_destroy (&attr);
660
661   return cond;
662 }
663
664 static void
665 g_cond_impl_free (pthread_cond_t *cond)
666 {
667   pthread_cond_destroy (cond);
668   free (cond);
669 }
670
671 static pthread_cond_t *
672 g_cond_get_impl (GCond *cond)
673 {
674   pthread_cond_t *impl = cond->p;
675
676   if G_UNLIKELY (impl == NULL)
677     {
678       impl = g_cond_impl_new ();
679       if (!g_atomic_pointer_compare_and_exchange (&cond->p, NULL, impl))
680         g_cond_impl_free (impl);
681       impl = cond->p;
682     }
683
684   return impl;
685 }
686
687 /**
688  * g_cond_init:
689  * @cond: an uninitialized #GCond
690  *
691  * Initialises a #GCond so that it can be used.
692  *
693  * This function is useful to initialise a #GCond that has been
694  * allocated as part of a larger structure.  It is not necessary to
695  * initialise a #GCond that has been statically allocated.
696  *
697  * To undo the effect of g_cond_init() when a #GCond is no longer
698  * needed, use g_cond_clear().
699  *
700  * Calling g_cond_init() on an already-initialised #GCond leads
701  * to undefined behaviour.
702  *
703  * Since: 2.32
704  */
705 void
706 g_cond_init (GCond *cond)
707 {
708   cond->p = g_cond_impl_new ();
709 }
710
711 /**
712  * g_cond_clear:
713  * @cond: an initialised #GCond
714  *
715  * Frees the resources allocated to a #GCond with g_cond_init().
716  *
717  * This function should not be used with a #GCond that has been
718  * statically allocated.
719  *
720  * Calling g_cond_clear() for a #GCond on which threads are
721  * blocking leads to undefined behaviour.
722  *
723  * Since: 2.32
724  */
725 void
726 g_cond_clear (GCond *cond)
727 {
728   g_cond_impl_free (cond->p);
729 }
730
731 /**
732  * g_cond_wait:
733  * @cond: a #GCond
734  * @mutex: a #GMutex that is currently locked
735  *
736  * Atomically releases @mutex and waits until @cond is signalled.
737  *
738  * When using condition variables, it is possible that a spurious wakeup
739  * may occur (ie: g_cond_wait() returns even though g_cond_signal() was
740  * not called).  It's also possible that a stolen wakeup may occur.
741  * This is when g_cond_signal() is called, but another thread acquires
742  * @mutex before this thread and modifies the state of the program in
743  * such a way that when g_cond_wait() is able to return, the expected
744  * condition is no longer met.
745  *
746  * For this reason, g_cond_wait() must always be used in a loop.  See
747  * the documentation for #GCond for a complete example.
748  **/
749 void
750 g_cond_wait (GCond  *cond,
751              GMutex *mutex)
752 {
753   gint status;
754
755   if G_UNLIKELY ((status = pthread_cond_wait (g_cond_get_impl (cond), g_mutex_get_impl (mutex))) != 0)
756     g_thread_abort (status, "pthread_cond_wait");
757 }
758
759 /**
760  * g_cond_signal:
761  * @cond: a #GCond
762  *
763  * If threads are waiting for @cond, at least one of them is unblocked.
764  * If no threads are waiting for @cond, this function has no effect.
765  * It is good practice to hold the same lock as the waiting thread
766  * while calling this function, though not required.
767  *
768  * This function can be used even if g_thread_init() has not yet been
769  * called, and, in that case, will do nothing.
770  */
771 void
772 g_cond_signal (GCond *cond)
773 {
774   gint status;
775
776   if G_UNLIKELY ((status = pthread_cond_signal (g_cond_get_impl (cond))) != 0)
777     g_thread_abort (status, "pthread_cond_signal");
778 }
779
780 /**
781  * g_cond_broadcast:
782  * @cond: a #GCond
783  *
784  * If threads are waiting for @cond, all of them are unblocked.
785  * If no threads are waiting for @cond, this function has no effect.
786  * It is good practice to lock the same mutex as the waiting threads
787  * while calling this function, though not required.
788  *
789  * This function can be used even if g_thread_init() has not yet been
790  * called, and, in that case, will do nothing.
791  */
792 void
793 g_cond_broadcast (GCond *cond)
794 {
795   gint status;
796
797   if G_UNLIKELY ((status = pthread_cond_broadcast (g_cond_get_impl (cond))) != 0)
798     g_thread_abort (status, "pthread_cond_broadcast");
799 }
800
801 /**
802  * g_cond_wait_until:
803  * @cond: a #GCond
804  * @mutex: a #GMutex that is currently locked
805  * @end_time: the monotonic time to wait until
806  *
807  * Waits until either @cond is signalled or @end_time has passed.
808  *
809  * As with g_cond_wait() it is possible that a spurious or stolen wakeup
810  * could occur.  For that reason, waiting on a condition variable should
811  * always be in a loop, based on an explicitly-checked predicate.
812  *
813  * %TRUE is returned if the condition variable was signalled (or in the
814  * case of a spurious wakeup).  %FALSE is returned if @end_time has
815  * passed.
816  *
817  * The following code shows how to correctly perform a timed wait on a
818  * condition variable (extended the example presented in the
819  * documentation for #GCond):
820  *
821  * |[
822  * gpointer
823  * pop_data_timed (void)
824  * {
825  *   gint64 end_time;
826  *   gpointer data;
827  *
828  *   g_mutex_lock (&data_mutex);
829  *
830  *   end_time = g_get_monotonic_time () + 5 * G_TIME_SPAN_SECOND;
831  *   while (!current_data)
832  *     if (!g_cond_wait_until (&data_cond, &data_mutex, end_time))
833  *       {
834  *         // timeout has passed.
835  *         g_mutex_unlock (&data_mutex);
836  *         return NULL;
837  *       }
838  *
839  *   // there is data for us
840  *   data = current_data;
841  *   current_data = NULL;
842  *
843  *   g_mutex_unlock (&data_mutex);
844  *
845  *   return data;
846  * }
847  * ]|
848  *
849  * Notice that the end time is calculated once, before entering the
850  * loop and reused.  This is the motivation behind the use of absolute
851  * time on this API -- if a relative time of 5 seconds were passed
852  * directly to the call and a spurious wakeup occured, the program would
853  * have to start over waiting again (which would lead to a total wait
854  * time of more than 5 seconds).
855  *
856  * Returns: %TRUE on a signal, %FALSE on a timeout
857  * Since: 2.32
858  **/
859 gboolean
860 g_cond_wait_until (GCond  *cond,
861                    GMutex *mutex,
862                    gint64  end_time)
863 {
864   struct timespec ts;
865   gint status;
866
867   ts.tv_sec = end_time / 1000000;
868   ts.tv_nsec = (end_time % 1000000) * 1000;
869
870   if ((status = pthread_cond_timedwait (g_cond_get_impl (cond), g_mutex_get_impl (mutex), &ts)) == 0)
871     return TRUE;
872
873   if G_UNLIKELY (status != ETIMEDOUT)
874     g_thread_abort (status, "pthread_cond_timedwait");
875
876   return FALSE;
877 }
878
879 /* {{{1 GPrivate */
880
881 /**
882  * GPrivate:
883  *
884  * The #GPrivate struct is an opaque data structure to represent a
885  * thread-local data key. It is approximately equivalent to the
886  * pthread_setspecific()/pthread_getspecific() APIs on POSIX and to
887  * TlsSetValue()/TlsGetValue() on Windows.
888  *
889  * If you don't already know why you might want this functionality,
890  * then you probably don't need it.
891  *
892  * #GPrivate is a very limited resource (as far as 128 per program,
893  * shared between all libraries). It is also not possible to destroy a
894  * #GPrivate after it has been used. As such, it is only ever acceptable
895  * to use #GPrivate in static scope, and even then sparingly so.
896  *
897  * See G_PRIVATE_INIT() for a couple of examples.
898  *
899  * The #GPrivate structure should be considered opaque.  It should only
900  * be accessed via the <function>g_private_</function> functions.
901  */
902
903 /**
904  * G_PRIVATE_INIT:
905  * @notify: a #GDestroyNotify
906  *
907  * A macro to assist with the static initialisation of a #GPrivate.
908  *
909  * This macro is useful for the case that a #GDestroyNotify function
910  * should be associated the key.  This is needed when the key will be
911  * used to point at memory that should be deallocated when the thread
912  * exits.
913  *
914  * Additionally, the #GDestroyNotify will also be called on the previous
915  * value stored in the key when g_private_replace() is used.
916  *
917  * If no #GDestroyNotify is needed, then use of this macro is not
918  * required -- if the #GPrivate is declared in static scope then it will
919  * be properly initialised by default (ie: to all zeros).  See the
920  * examples below.
921  *
922  * |[
923  * static GPrivate name_key = G_PRIVATE_INIT (g_free);
924  *
925  * // return value should not be freed
926  * const gchar *
927  * get_local_name (void)
928  * {
929  *   return g_private_get (&name_key);
930  * }
931  *
932  * void
933  * set_local_name (const gchar *name)
934  * {
935  *   g_private_replace (&name_key, g_strdup (name));
936  * }
937  *
938  *
939  * static GPrivate count_key;   // no free function
940  *
941  * gint
942  * get_local_count (void)
943  * {
944  *   return GPOINTER_TO_INT (g_private_get (&count_key));
945  * }
946  *
947  * void
948  * set_local_count (gint count)
949  * {
950  *   g_private_set (&count_key, GINT_TO_POINTER (count));
951  * }
952  * ]|
953  *
954  * Since: 2.32
955  **/
956
957 static pthread_key_t *
958 g_private_impl_new (GDestroyNotify notify)
959 {
960   pthread_key_t *key;
961   gint status;
962
963   key = malloc (sizeof (pthread_key_t));
964   if G_UNLIKELY (key == NULL)
965     g_thread_abort (errno, "malloc");
966   status = pthread_key_create (key, notify);
967   if G_UNLIKELY (status != 0)
968     g_thread_abort (status, "pthread_key_create");
969
970   return key;
971 }
972
973 static void
974 g_private_impl_free (pthread_key_t *key)
975 {
976   gint status;
977
978   status = pthread_key_delete (*key);
979   if G_UNLIKELY (status != 0)
980     g_thread_abort (status, "pthread_key_delete");
981   free (key);
982 }
983
984 static pthread_key_t *
985 g_private_get_impl (GPrivate *key)
986 {
987   pthread_key_t *impl = key->p;
988
989   if G_UNLIKELY (impl == NULL)
990     {
991       impl = g_private_impl_new (key->notify);
992       if (!g_atomic_pointer_compare_and_exchange (&key->p, NULL, impl))
993         {
994           g_private_impl_free (impl);
995           impl = key->p;
996         }
997     }
998
999   return impl;
1000 }
1001
1002 /**
1003  * g_private_get:
1004  * @key: a #GPrivate
1005  *
1006  * Returns the current value of the thread local variable @key.
1007  *
1008  * If the value has not yet been set in this thread, %NULL is returned.
1009  * Values are never copied between threads (when a new thread is
1010  * created, for example).
1011  *
1012  * Returns: the thread-local value
1013  */
1014 gpointer
1015 g_private_get (GPrivate *key)
1016 {
1017   /* quote POSIX: No errors are returned from pthread_getspecific(). */
1018   return pthread_getspecific (*g_private_get_impl (key));
1019 }
1020
1021 /**
1022  * g_private_set:
1023  * @key: a #GPrivate
1024  * @value: the new value
1025  *
1026  * Sets the thread local variable @key to have the value @value in the
1027  * current thread.
1028  *
1029  * This function differs from g_private_replace() in the following way:
1030  * the #GDestroyNotify for @key is not called on the old value.
1031  */
1032 void
1033 g_private_set (GPrivate *key,
1034                gpointer  value)
1035 {
1036   gint status;
1037
1038   if G_UNLIKELY ((status = pthread_setspecific (*g_private_get_impl (key), value)) != 0)
1039     g_thread_abort (status, "pthread_setspecific");
1040 }
1041
1042 /**
1043  * g_private_replace:
1044  * @key: a #GPrivate
1045  * @value: the new value
1046  *
1047  * Sets the thread local variable @key to have the value @value in the
1048  * current thread.
1049  *
1050  * This function differs from g_private_set() in the following way: if
1051  * the previous value was non-%NULL then the #GDestroyNotify handler for
1052  * @key is run on it.
1053  *
1054  * Since: 2.32
1055  **/
1056 void
1057 g_private_replace (GPrivate *key,
1058                    gpointer  value)
1059 {
1060   pthread_key_t *impl = g_private_get_impl (key);
1061   gpointer old;
1062   gint status;
1063
1064   old = pthread_getspecific (*impl);
1065   if (old && key->notify)
1066     key->notify (old);
1067
1068   if G_UNLIKELY ((status = pthread_setspecific (*impl, value)) != 0)
1069     g_thread_abort (status, "pthread_setspecific");
1070 }
1071
1072 /* {{{1 GThread */
1073
1074 #define posix_check_err(err, name) G_STMT_START{                        \
1075   int error = (err);                                                    \
1076   if (error)                                                            \
1077     g_error ("file %s: line %d (%s): error '%s' during '%s'",           \
1078            __FILE__, __LINE__, G_STRFUNC,                               \
1079            g_strerror (error), name);                                   \
1080   }G_STMT_END
1081
1082 #define posix_check_cmd(cmd) posix_check_err (cmd, #cmd)
1083
1084 typedef struct
1085 {
1086   GRealThread thread;
1087
1088   pthread_t system_thread;
1089   gboolean  joined;
1090   GMutex    lock;
1091 } GThreadPosix;
1092
1093 void
1094 g_system_thread_free (GRealThread *thread)
1095 {
1096   GThreadPosix *pt = (GThreadPosix *) thread;
1097
1098   if (!pt->joined)
1099     pthread_detach (pt->system_thread);
1100
1101   g_mutex_clear (&pt->lock);
1102
1103   g_slice_free (GThreadPosix, pt);
1104 }
1105
1106 GRealThread *
1107 g_system_thread_new (GThreadFunc   thread_func,
1108                      gulong        stack_size,
1109                      GError      **error)
1110 {
1111   GThreadPosix *thread;
1112   pthread_attr_t attr;
1113   gint ret;
1114
1115   thread = g_slice_new0 (GThreadPosix);
1116
1117   posix_check_cmd (pthread_attr_init (&attr));
1118
1119 #ifdef HAVE_PTHREAD_ATTR_SETSTACKSIZE
1120   if (stack_size)
1121     {
1122 #ifdef _SC_THREAD_STACK_MIN
1123       stack_size = MAX (sysconf (_SC_THREAD_STACK_MIN), stack_size);
1124 #endif /* _SC_THREAD_STACK_MIN */
1125       /* No error check here, because some systems can't do it and
1126        * we simply don't want threads to fail because of that. */
1127       pthread_attr_setstacksize (&attr, stack_size);
1128     }
1129 #endif /* HAVE_PTHREAD_ATTR_SETSTACKSIZE */
1130
1131   ret = pthread_create (&thread->system_thread, &attr, (void* (*)(void*))thread_func, thread);
1132
1133   posix_check_cmd (pthread_attr_destroy (&attr));
1134
1135   if (ret == EAGAIN)
1136     {
1137       g_set_error (error, G_THREAD_ERROR, G_THREAD_ERROR_AGAIN, 
1138                    "Error creating thread: %s", g_strerror (ret));
1139       g_slice_free (GThreadPosix, thread);
1140       return NULL;
1141     }
1142
1143   posix_check_err (ret, "pthread_create");
1144
1145   g_mutex_init (&thread->lock);
1146
1147   return (GRealThread *) thread;
1148 }
1149
1150 /**
1151  * g_thread_yield:
1152  *
1153  * Causes the calling thread to voluntarily relinquish the CPU, so
1154  * that other threads can run.
1155  *
1156  * This function is often used as a method to make busy wait less evil.
1157  */
1158 void
1159 g_thread_yield (void)
1160 {
1161   sched_yield ();
1162 }
1163
1164 void
1165 g_system_thread_wait (GRealThread *thread)
1166 {
1167   GThreadPosix *pt = (GThreadPosix *) thread;
1168
1169   g_mutex_lock (&pt->lock);
1170
1171   if (!pt->joined)
1172     {
1173       posix_check_cmd (pthread_join (pt->system_thread, NULL));
1174       pt->joined = TRUE;
1175     }
1176
1177   g_mutex_unlock (&pt->lock);
1178 }
1179
1180 void
1181 g_system_thread_exit (void)
1182 {
1183   pthread_exit (NULL);
1184 }
1185
1186 void
1187 g_system_thread_set_name (const gchar *name)
1188 {
1189 #ifdef HAVE_SYS_PRCTL_H
1190   prctl (PR_SET_NAME, name, 0, 0, 0, 0);
1191 #endif
1192 }
1193
1194 /* {{{1 Epilogue */
1195 /* vim:set foldmethod=marker: */