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