Move includes to the top of the file
[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
67
68 static void
69 g_thread_abort (gint         status,
70                 const gchar *function)
71 {
72   fprintf (stderr, "GLib (gthread-posix.c): Unexpected error from C library during '%s': %s.  Aborting.\n",
73            strerror (status), function);
74   abort ();
75 }
76
77 /* {{{1 GMutex */
78
79 /**
80  * G_MUTEX_INIT:
81  *
82  * Initializer for statically allocated #GMutexes.
83  * Alternatively, g_mutex_init() can be used.
84  *
85  * |[
86  *   GMutex mutex = G_MUTEX_INIT;
87  * ]|
88  *
89  * Since: 2.32
90  */
91
92 /**
93  * g_mutex_init:
94  * @mutex: an uninitialized #GMutex
95  *
96  * Initializes a #GMutex so that it can be used.
97  *
98  * This function is useful to initialize a mutex that has been
99  * allocated on the stack, or as part of a larger structure.
100  * It is not necessary to initialize a mutex that has been
101  * created with g_mutex_new(). Also see #G_MUTEX_INIT for an
102  * alternative way to initialize statically allocated mutexes.
103  *
104  * |[
105  *   typedef struct {
106  *     GMutex m;
107  *     ...
108  *   } Blob;
109  *
110  * Blob *b;
111  *
112  * b = g_new (Blob, 1);
113  * g_mutex_init (&b->m);
114  * ]|
115  *
116  * To undo the effect of g_mutex_init() when a mutex is no longer
117  * needed, use g_mutex_clear().
118  *
119  * Calling g_mutex_init() on an already initialized #GMutex leads
120  * to undefined behaviour.
121  *
122  * Since: 2.32
123  */
124 void
125 g_mutex_init (GMutex *mutex)
126 {
127   gint status;
128   pthread_mutexattr_t *pattr = NULL;
129 #ifdef PTHREAD_ADAPTIVE_MUTEX_INITIALIZER_NP
130   pthread_mutexattr_t attr;
131   pthread_mutexattr_init (&attr);
132   pthread_mutexattr_settype (&attr, PTHREAD_MUTEX_ADAPTIVE_NP);
133   pattr = &attr;
134 #endif
135
136   if G_UNLIKELY ((status = pthread_mutex_init (&mutex->impl, pattr)) != 0)
137     g_thread_abort (status, "pthread_mutex_init");
138
139 #ifdef PTHREAD_ADAPTIVE_MUTEX_NP
140   pthread_mutexattr_destroy (&attr);
141 #endif
142 }
143
144 /**
145  * g_mutex_clear:
146  * @mutex: an initialized #GMutex
147  *
148  * Frees the resources allocated to a mutex with g_mutex_init().
149  *
150  * #GMutexes that have have been created with g_mutex_new() should
151  * be freed with g_mutex_free() instead.
152  *
153  * Calling g_mutex_clear() on a locked mutex leads to undefined
154  * behaviour.
155  *
156  * Sine: 2.32
157  */
158 void
159 g_mutex_clear (GMutex *mutex)
160 {
161   gint status;
162
163   if G_UNLIKELY ((status = pthread_mutex_destroy (&mutex->impl)) != 0)
164     g_thread_abort (status, "pthread_mutex_destroy");
165 }
166
167 /**
168  * g_mutex_lock:
169  * @mutex: a #GMutex
170  *
171  * Locks @mutex. If @mutex is already locked by another thread, the
172  * current thread will block until @mutex is unlocked by the other
173  * thread.
174  *
175  * This function can be used even if g_thread_init() has not yet been
176  * called, and, in that case, will do nothing.
177  *
178  * <note>#GMutex is neither guaranteed to be recursive nor to be
179  * non-recursive, i.e. a thread could deadlock while calling
180  * g_mutex_lock(), if it already has locked @mutex. Use
181  * #GRecMutex if you need recursive mutexes.</note>
182  */
183 void
184 g_mutex_lock (GMutex *mutex)
185 {
186   gint status;
187
188   if G_UNLIKELY ((status = pthread_mutex_lock (&mutex->impl)) != 0)
189     g_thread_abort (status, "pthread_mutex_lock");
190 }
191
192 /**
193  * g_mutex_unlock:
194  * @mutex: a #GMutex
195  *
196  * Unlocks @mutex. If another thread is blocked in a g_mutex_lock()
197  * call for @mutex, it will become unblocked and can lock @mutex itself.
198  *
199  * Calling g_mutex_unlock() on a mutex that is not locked by the
200  * current thread leads to undefined behaviour.
201  *
202  * This function can be used even if g_thread_init() has not yet been
203  * called, and, in that case, will do nothing.
204  */
205 void
206 g_mutex_unlock (GMutex *mutex)
207 {
208   gint status;
209
210   if G_UNLIKELY ((status = pthread_mutex_unlock (&mutex->impl)) != 0)
211     g_thread_abort (status, "pthread_mutex_lock");
212 }
213
214 /**
215  * g_mutex_trylock:
216  * @mutex: a #GMutex
217  *
218  * Tries to lock @mutex. If @mutex is already locked by another thread,
219  * it immediately returns %FALSE. Otherwise it locks @mutex and returns
220  * %TRUE.
221  *
222  * This function can be used even if g_thread_init() has not yet been
223  * called, and, in that case, will immediately return %TRUE.
224  *
225  * <note>#GMutex is neither guaranteed to be recursive nor to be
226  * non-recursive, i.e. the return value of g_mutex_trylock() could be
227  * both %FALSE or %TRUE, if the current thread already has locked
228  * @mutex. Use #GRecMutex if you need recursive mutexes.</note>
229
230  * Returns: %TRUE if @mutex could be locked
231  */
232 gboolean
233 g_mutex_trylock (GMutex *mutex)
234 {
235   gint status;
236
237   if G_LIKELY ((status = pthread_mutex_trylock (&mutex->impl)) == 0)
238     return TRUE;
239
240   if G_UNLIKELY (status != EBUSY)
241     g_thread_abort (status, "pthread_mutex_trylock");
242
243   return FALSE;
244 }
245
246 /* {{{1 GRecMutex */
247
248 /**
249  * GRecMutex:
250  *
251  * The GRecMutex struct is an opaque data structure to represent a
252  * recursive mutex. It is similar to a #GMutex with the difference
253  * that it is possible to lock a GRecMutex multiple times in the same
254  * thread without deadlock. When doing so, care has to be taken to
255  * unlock the recursive mutex as often as it has been locked.
256  *
257  * A GRecMutex should only be accessed with the
258  * <function>g_rec_mutex_</function> functions. Before a GRecMutex
259  * can be used, it has to be initialized with #G_REC_MUTEX_INIT or
260  * g_rec_mutex_init().
261  *
262  * Since: 2.32
263  */
264
265 static pthread_mutex_t *
266 g_rec_mutex_impl_new (void)
267 {
268   pthread_mutexattr_t attr;
269   pthread_mutex_t *mutex;
270
271   mutex = g_slice_new (pthread_mutex_t);
272   pthread_mutexattr_init (&attr);
273   pthread_mutexattr_settype (&attr, PTHREAD_MUTEX_RECURSIVE);
274   pthread_mutex_init (mutex, &attr);
275   pthread_mutexattr_destroy (&attr);
276
277   return mutex;
278 }
279
280 static void
281 g_rec_mutex_impl_free (pthread_mutex_t *mutex)
282 {
283   pthread_mutex_destroy (mutex);
284   g_slice_free (pthread_mutex_t, mutex);
285 }
286
287 static pthread_mutex_t *
288 g_rec_mutex_get_impl (GRecMutex *mutex)
289 {
290   pthread_mutex_t *impl = mutex->impl;
291
292   if G_UNLIKELY (mutex->impl == NULL)
293     {
294       impl = g_rec_mutex_impl_new ();
295       if (!g_atomic_pointer_compare_and_exchange (&mutex->impl, NULL, impl))
296         g_rec_mutex_impl_free (impl);
297       impl = mutex->impl;
298     }
299
300   return impl;
301 }
302
303 /**
304  * G_REC_MUTEX_INIT:
305  *
306  * Initializer for statically allocated #GRecMutexes.
307  * Alternatively, g_rec_mutex_init() can be used.
308  *
309  * |[
310  *   GRecMutex mutex = G_REC_MUTEX_INIT;
311  * ]|
312  *
313  * Since: 2.32
314  */
315
316 /**
317  * g_rec_mutex_init:
318  * @rec_mutex: an uninitialized #GRecMutex
319  *
320  * Initializes a #GRecMutex so that it can be used.
321  *
322  * This function is useful to initialize a recursive mutex
323  * that has been allocated on the stack, or as part of a larger
324  * structure.
325  * It is not necessary to initialize a recursive mutex that has
326  * been created with g_rec_mutex_new(). Also see #G_REC_MUTEX_INIT
327  * for an alternative way to initialize statically allocated
328  * recursive mutexes.
329  *
330  * |[
331  *   typedef struct {
332  *     GRecMutex m;
333  *     ...
334  *   } Blob;
335  *
336  * Blob *b;
337  *
338  * b = g_new (Blob, 1);
339  * g_rec_mutex_init (&b->m);
340  * ]|
341  *
342  * Calling g_rec_mutex_init() on an already initialized #GRecMutex
343  * leads to undefined behaviour.
344  *
345  * To undo the effect of g_rec_mutex_init() when a recursive mutex
346  * is no longer needed, use g_rec_mutex_clear().
347  *
348  * Since: 2.32
349  */
350 void
351 g_rec_mutex_init (GRecMutex *rec_mutex)
352 {
353   rec_mutex->impl = g_rec_mutex_impl_new ();
354 }
355
356 /**
357  * g_rec_mutex_clear:
358  * @rec_mutex: an initialized #GRecMutex
359  *
360  * Frees the resources allocated to a recursive mutex with
361  * g_rec_mutex_init().
362  *
363  * #GRecMutexes that have have been created with g_rec_mutex_new()
364  * should be freed with g_rec_mutex_free() instead.
365  *
366  * Calling g_rec_mutex_clear() on a locked recursive mutex leads
367  * to undefined behaviour.
368  *
369  * Sine: 2.32
370  */
371 void
372 g_rec_mutex_clear (GRecMutex *rec_mutex)
373 {
374   if (rec_mutex->impl)
375     g_rec_mutex_impl_free (rec_mutex->impl);
376 }
377
378 /**
379  * g_rec_mutex_lock:
380  * @rec_mutex: a #GRecMutex
381  *
382  * Locks @rec_mutex. If @rec_mutex is already locked by another
383  * thread, the current thread will block until @rec_mutex is
384  * unlocked by the other thread. If @rec_mutex is already locked
385  * by the current thread, the 'lock count' of @rec_mutex is increased.
386  * The mutex will only become available again when it is unlocked
387  * as many times as it has been locked.
388  *
389  * Since: 2.32
390  */
391 void
392 g_rec_mutex_lock (GRecMutex *mutex)
393 {
394   pthread_mutex_lock (g_rec_mutex_get_impl (mutex));
395 }
396
397 /**
398  * g_rec_mutex_unlock:
399  * @rec_mutex: a #RecGMutex
400  *
401  * Unlocks @rec_mutex. If another thread is blocked in a
402  * g_rec_mutex_lock() call for @rec_mutex, it will become unblocked
403  * and can lock @rec_mutex itself.
404  *
405  * Calling g_rec_mutex_unlock() on a recursive mutex that is not
406  * locked by the current thread leads to undefined behaviour.
407  *
408  * Since: 2.32
409  */
410 void
411 g_rec_mutex_unlock (GRecMutex *rec_mutex)
412 {
413   pthread_mutex_unlock (rec_mutex->impl);
414 }
415
416 /**
417  * g_rec_mutex_trylock:
418  * @rec_mutex: a #GRecMutex
419  *
420  * Tries to lock @rec_mutex. If @rec_mutex is already locked
421  * by another thread, it immediately returns %FALSE. Otherwise
422  * it locks @rec_mutex and returns %TRUE.
423  *
424  * Returns: %TRUE if @rec_mutex could be locked
425  *
426  * Since: 2.32
427  */
428 gboolean
429 g_rec_mutex_trylock (GRecMutex *rec_mutex)
430 {
431   if (pthread_mutex_trylock (g_rec_mutex_get_impl (rec_mutex)) != 0)
432     return FALSE;
433
434   return TRUE;
435 }
436
437 /* {{{1 GRWLock */
438
439 /**
440  * GRWLock:
441  *
442  * The GRWLock struct is an opaque data structure to represent a
443  * reader-writer lock. It is similar to a #GMutex in that it allows
444  * multiple threads to coordinate access to a shared resource.
445  *
446  * The difference to a mutex is that a reader-writer lock discriminates
447  * between read-only ('reader') and full ('writer') access. While only
448  * one thread at a time is allowed write access (by holding the 'writer'
449  * lock via g_rw_lock_writer_lock()), multiple threads can gain
450  * simultaneous read-only access (by holding the 'reader' lock via
451  * g_rw_lock_reader_lock()).
452  *
453  * <example>
454  *  <title>An array with access functions</title>
455  *  <programlisting>
456  *   GRWLock lock = G_RW_LOCK_INIT;
457  *   GPtrArray *array;
458  *
459  *   gpointer
460  *   my_array_get (guint index)
461  *   {
462  *     gpointer retval = NULL;
463  *
464  *     if (!array)
465  *       return NULL;
466  *
467  *     g_rw_lock_reader_lock (&amp;lock);
468  *     if (index &lt; array->len)
469  *       retval = g_ptr_array_index (array, index);
470  *     g_rw_lock_reader_unlock (&amp;lock);
471  *
472  *     return retval;
473  *   }
474  *
475  *   void
476  *   my_array_set (guint index, gpointer data)
477  *   {
478  *     g_rw_lock_writer_lock (&amp;lock);
479  *
480  *     if (!array)
481  *       array = g_ptr_array_new (<!-- -->);
482  *
483  *     if (index >= array->len)
484  *       g_ptr_array_set_size (array, index+1);
485  *     g_ptr_array_index (array, index) = data;
486  *
487  *     g_rw_lock_writer_unlock (&amp;lock);
488  *   }
489  *  </programlisting>
490  *  <para>
491  *    This example shows an array which can be accessed by many readers
492  *    (the <function>my_array_get()</function> function) simultaneously,
493  *    whereas the writers (the <function>my_array_set()</function>
494  *    function) will only be allowed once at a time and only if no readers
495  *    currently access the array. This is because of the potentially
496  *    dangerous resizing of the array. Using these functions is fully
497  *    multi-thread safe now.
498  *  </para>
499  * </example>
500  *
501  * A GRWLock should only be accessed with the
502  * <function>g_rw_lock_</function> functions. Before it can be used,
503  * it has to be initialized with #G_RW_LOCK_INIT or g_rw_lock_init().
504  *
505  * Since: 2.32
506  */
507
508 /**
509  * G_RW_LOCK_INIT:
510  *
511  * Initializer for statically allocated #GRWLocks.
512  * Alternatively, g_rw_lock_init_init() can be used.
513  *
514  * |[
515  *   GRWLock lock = G_RW_LOCK_INIT;
516  * ]|
517  *
518  * Since: 2.32
519  */
520
521 /**
522  * g_rw_lock_init:
523  * @lock: an uninitialized #GRWLock
524  *
525  * Initializes a #GRWLock so that it can be used.
526  *
527  * This function is useful to initialize a lock that has been
528  * allocated on the stack, or as part of a larger structure.
529  * Also see #G_RW_LOCK_INIT for an alternative way to initialize
530  * statically allocated locks.
531  *
532  * |[
533  *   typedef struct {
534  *     GRWLock l;
535  *     ...
536  *   } Blob;
537  *
538  * Blob *b;
539  *
540  * b = g_new (Blob, 1);
541  * g_rw_lock_init (&b->l);
542  * ]|
543  *
544  * To undo the effect of g_rw_lock_init() when a lock is no longer
545  * needed, use g_rw_lock_clear().
546  *
547  * Calling g_rw_lock_init() on an already initialized #GRWLock leads
548  * to undefined behaviour.
549  *
550  * Since: 2.32
551  */
552 void
553 g_rw_lock_init (GRWLock *lock)
554 {
555   pthread_rwlock_init (&lock->impl, NULL);
556 }
557
558 /**
559  * g_rw_lock_clear:
560  * @lock: an initialized #GRWLock
561  *
562  * Frees the resources allocated to a lock with g_rw_lock_init().
563  *
564  * Calling g_rw_lock_clear() when any thread holds the lock
565  * leads to undefined behaviour.
566  *
567  * Sine: 2.32
568  */
569 void
570 g_rw_lock_clear (GRWLock *lock)
571 {
572   pthread_rwlock_destroy (&lock->impl);
573 }
574
575 /**
576  * g_rw_lock_writer_lock:
577  * @lock: a #GRWLock
578  *
579  * Obtain a write lock on @lock. If any thread already holds
580  * a read or write lock on @lock, the current thread will block
581  * until all other threads have dropped their locks on @lock.
582  *
583  * Since: 2.32
584  */
585 void
586 g_rw_lock_writer_lock (GRWLock *lock)
587 {
588   pthread_rwlock_wrlock (&lock->impl);
589 }
590
591 /**
592  * g_rw_lock_writer_trylock:
593  * @lock: a #GRWLock
594  *
595  * Tries to obtain a write lock on @lock. If any other thread holds
596  * a read or write lock on @lock, it immediately returns %FALSE.
597  * Otherwise it locks @lock and returns %TRUE.
598  *
599  * Returns: %TRUE if @lock could be locked
600  *
601  * Since: 2.32
602  */
603 gboolean
604 g_rw_lock_writer_trylock (GRWLock *lock)
605 {
606   if (pthread_rwlock_trywrlock (&lock->impl) != 0)
607     return FALSE;
608
609   return TRUE;
610 }
611
612 /**
613  * g_rw_lock_writer_unlock:
614  * @lock: a #GRWLock
615  *
616  * Release a write lock on @lock.
617  *
618  * Calling g_rw_lock_writer_unlock() on a lock that is not held
619  * by the current thread leads to undefined behaviour.
620  *
621  * Since: 2.32
622  */
623 void
624 g_rw_lock_writer_unlock (GRWLock *lock)
625 {
626   pthread_rwlock_unlock (&lock->impl);
627 }
628
629 /**
630  * g_rw_lock_reader_lock:
631  * @lock: a #GRWLock
632  *
633  * Obtain a read lock on @lock. If another thread currently holds
634  * the write lock on @lock or blocks waiting for it, the current
635  * thread will block. Read locks can be taken recursively.
636  *
637  * It is implementation-defined how many threads are allowed to
638  * hold read locks on the same lock simultaneously.
639  *
640  * Since: 2.32
641  */
642 void
643 g_rw_lock_reader_lock (GRWLock *lock)
644 {
645   pthread_rwlock_rdlock (&lock->impl);
646 }
647
648 /**
649  * g_rw_lock_reader_trylock:
650  * @lock: a #GRWLock
651  *
652  * Tries to obtain a read lock on @lock and returns %TRUE if
653  * the read lock was successfully obtained. Otherwise it
654  * returns %FALSE.
655  *
656  * Returns: %TRUE if @lock could be locked
657  *
658  * Since: 2.32
659  */
660 gboolean
661 g_rw_lock_reader_trylock (GRWLock *lock)
662 {
663   if (pthread_rwlock_tryrdlock (&lock->impl) != 0)
664     return FALSE;
665
666   return TRUE;
667 }
668
669 /**
670  * g_rw_lock_reader_unlock:
671  * @lock: a #GRWLock
672  *
673  * Release a read lock on @lock.
674  *
675  * Calling g_rw_lock_reader_unlock() on a lock that is not held
676  * by the current thread leads to undefined behaviour.
677  *
678  * Since: 2.32
679  */
680 void
681 g_rw_lock_reader_unlock (GRWLock *lock)
682 {
683   pthread_rwlock_unlock (&lock->impl);
684 }
685
686 /* {{{1 GCond */
687
688 /**
689  * G_COND_INIT:
690  *
691  * Initializer for statically allocated #GConds.
692  * Alternatively, g_cond_init() can be used.
693  *
694  * |[
695  *   GCond cond = G_COND_INIT;
696  * ]|
697  *
698  * Since: 2.32
699  */
700
701 /**
702  * g_cond_init:
703  * @cond: an uninitialized #GCond
704  *
705  * Initialized a #GCond so that it can be used.
706  *
707  * This function is useful to initialize a #GCond that has been
708  * allocated on the stack, or as part of a larger structure.
709  * It is not necessary to initialize a #GCond that has been
710  * created with g_cond_new(). Also see #G_COND_INIT for an
711  * alternative way to initialize statically allocated #GConds.
712  *
713  * To undo the effect of g_cond_init() when a #GCond is no longer
714  * needed, use g_cond_clear().
715  *
716  * Calling g_cond_init() on an already initialized #GCond leads
717  * to undefined behaviour.
718  *
719  * Since: 2.32
720  */
721 void
722 g_cond_init (GCond *cond)
723 {
724   gint status;
725
726   if G_UNLIKELY ((status = pthread_cond_init (&cond->impl, NULL)) != 0)
727     g_thread_abort (status, "pthread_cond_init");
728 }
729
730 /**
731  * g_cond_clear:
732  * @cond: an initialized #GCond
733  *
734  * Frees the resources allocated to a #GCond with g_cond_init().
735  *
736  * #GConds that have been created with g_cond_new() should
737  * be freed with g_cond_free() instead.
738  *
739  * Calling g_cond_clear() for a #GCond on which threads are
740  * blocking leads to undefined behaviour.
741  *
742  * Since: 2.32
743  */
744 void
745 g_cond_clear (GCond *cond)
746 {
747   gint status;
748
749   if G_UNLIKELY ((status = pthread_cond_destroy (&cond->impl)) != 0)
750     g_thread_abort (status, "pthread_cond_destroy");
751 }
752
753 /**
754  * g_cond_wait:
755  * @cond: a #GCond
756  * @mutex: a #GMutex that is currently locked
757  *
758  * Waits until this thread is woken up on @cond. The @mutex is unlocked
759  * before falling asleep and locked again before resuming.
760  *
761  * This function can be used even if g_thread_init() has not yet been
762  * called, and, in that case, will immediately return.
763  */
764 void
765 g_cond_wait (GCond  *cond,
766              GMutex *mutex)
767 {
768   gint status;
769
770   if G_UNLIKELY ((status = pthread_cond_wait (&cond->impl, &mutex->impl)) != 0)
771     g_thread_abort (status, "pthread_cond_wait");
772 }
773
774 /**
775  * g_cond_signal:
776  * @cond: a #GCond
777  *
778  * If threads are waiting for @cond, at least one of them is unblocked.
779  * If no threads are waiting for @cond, this function has no effect.
780  * It is good practice to hold the same lock as the waiting thread
781  * while calling this function, though not required.
782  *
783  * This function can be used even if g_thread_init() has not yet been
784  * called, and, in that case, will do nothing.
785  */
786 void
787 g_cond_signal (GCond *cond)
788 {
789   gint status;
790
791   if G_UNLIKELY ((status = pthread_cond_signal (&cond->impl)) != 0)
792     g_thread_abort (status, "pthread_cond_signal");
793 }
794
795 /**
796  * g_cond_broadcast:
797  * @cond: a #GCond
798  *
799  * If threads are waiting for @cond, all of them are unblocked.
800  * If no threads are waiting for @cond, this function has no effect.
801  * It is good practice to lock the same mutex as the waiting threads
802  * while calling this function, though not required.
803  *
804  * This function can be used even if g_thread_init() has not yet been
805  * called, and, in that case, will do nothing.
806  */
807 void
808 g_cond_broadcast (GCond *cond)
809 {
810   gint status;
811
812   if G_UNLIKELY ((status = pthread_cond_broadcast (&cond->impl)) != 0)
813     g_thread_abort (status, "pthread_cond_broadcast");
814 }
815
816 /**
817  * g_cond_timed_wait:
818  * @cond: a #GCond
819  * @mutex: a #GMutex that is currently locked
820  * @abs_time: a #GTimeVal, determining the final time
821  *
822  * Waits until this thread is woken up on @cond, but not longer than
823  * until the time specified by @abs_time. The @mutex is unlocked before
824  * falling asleep and locked again before resuming.
825  *
826  * If @abs_time is %NULL, g_cond_timed_wait() acts like g_cond_wait().
827  *
828  * This function can be used even if g_thread_init() has not yet been
829  * called, and, in that case, will immediately return %TRUE.
830  *
831  * To easily calculate @abs_time a combination of g_get_current_time()
832  * and g_time_val_add() can be used.
833  *
834  * Returns: %TRUE if @cond was signalled, or %FALSE on timeout
835  */
836 gboolean
837 g_cond_timed_wait (GCond    *cond,
838                    GMutex   *mutex,
839                    GTimeVal *abs_time)
840 {
841   struct timespec end_time;
842   gint status;
843
844   if (abs_time == NULL)
845     {
846       g_cond_wait (cond, mutex);
847       return TRUE;
848     }
849
850   end_time.tv_sec = abs_time->tv_sec;
851   end_time.tv_nsec = abs_time->tv_usec * 1000;
852
853   if ((status = pthread_cond_timedwait (&cond->impl, &mutex->impl, &end_time)) == 0)
854     return TRUE;
855
856   if G_UNLIKELY (status != ETIMEDOUT)
857     g_thread_abort (status, "pthread_cond_timedwait");
858
859   return FALSE;
860 }
861
862 /**
863  * g_cond_timedwait:
864  * @cond: a #GCond
865  * @mutex: a #GMutex that is currently locked
866  * @abs_time: the final time, in microseconds
867  *
868  * A variant of g_cond_timed_wait() that takes @abs_time
869  * as a #gint64 instead of a #GTimeVal.
870  * See g_cond_timed_wait() for details.
871  *
872  * Returns: %TRUE if @cond was signalled, or %FALSE on timeout
873  *
874  * Since: 2.32
875  */
876 gboolean
877 g_cond_timedwait (GCond  *cond,
878                   GMutex *mutex,
879                   gint64  abs_time)
880 {
881   struct timespec end_time;
882   gint status;
883
884   end_time.tv_sec = abs_time / 1000000;
885   end_time.tv_nsec = (abs_time % 1000000) * 1000;
886
887   if ((status = pthread_cond_timedwait (&cond->impl, &mutex->impl, &end_time)) == 0)
888     return TRUE;
889
890   if G_UNLIKELY (status != ETIMEDOUT)
891     g_thread_abort (status, "pthread_cond_timedwait");
892
893   return FALSE;
894 }
895
896 /* {{{1 GPrivate */
897
898 void
899 g_private_init (GPrivate       *key,
900                 GDestroyNotify  notify)
901 {
902   pthread_key_create (&key->key, notify);
903   key->ready = TRUE;
904 }
905
906 /**
907  * g_private_get:
908  * @private_key: a #GPrivate
909  *
910  * Returns the pointer keyed to @private_key for the current thread. If
911  * g_private_set() hasn't been called for the current @private_key and
912  * thread yet, this pointer will be %NULL.
913  *
914  * This function can be used even if g_thread_init() has not yet been
915  * called, and, in that case, will return the value of @private_key
916  * casted to #gpointer. Note however, that private data set
917  * <emphasis>before</emphasis> g_thread_init() will
918  * <emphasis>not</emphasis> be retained <emphasis>after</emphasis> the
919  * call. Instead, %NULL will be returned in all threads directly after
920  * g_thread_init(), regardless of any g_private_set() calls issued
921  * before threading system initialization.
922  *
923  * Returns: the corresponding pointer
924  */
925 gpointer
926 g_private_get (GPrivate *key)
927 {
928   if (!key->ready)
929     return key->single_value;
930
931   /* quote POSIX: No errors are returned from pthread_getspecific(). */
932   return pthread_getspecific (key->key);
933 }
934
935 /**
936  * g_private_set:
937  * @private_key: a #GPrivate
938  * @data: the new pointer
939  *
940  * Sets the pointer keyed to @private_key for the current thread.
941  *
942  * This function can be used even if g_thread_init() has not yet been
943  * called, and, in that case, will set @private_key to @data casted to
944  * #GPrivate*. See g_private_get() for resulting caveats.
945  */
946 void
947 g_private_set (GPrivate *key,
948                gpointer  value)
949 {
950   gint status;
951
952   if (!key->ready)
953     {
954       key->single_value = value;
955       return;
956     }
957
958   if G_UNLIKELY ((status = pthread_setspecific (key->key, value)) != 0)
959     g_thread_abort (status, "pthread_setspecific");
960 }
961
962 /* {{{1 GThread */
963
964 #define posix_check_err(err, name) G_STMT_START{                        \
965   int error = (err);                                                    \
966   if (error)                                                            \
967     g_error ("file %s: line %d (%s): error '%s' during '%s'",           \
968            __FILE__, __LINE__, G_STRFUNC,                               \
969            g_strerror (error), name);                                   \
970   }G_STMT_END
971
972 #define posix_check_cmd(cmd) posix_check_err (cmd, #cmd)
973
974 void
975 g_system_thread_create (GThreadFunc       thread_func,
976                         gpointer          arg,
977                         gulong            stack_size,
978                         gboolean          joinable,
979                         gpointer          thread,
980                         GError          **error)
981 {
982   pthread_attr_t attr;
983   gint ret;
984
985   g_return_if_fail (thread_func);
986
987   posix_check_cmd (pthread_attr_init (&attr));
988
989 #ifdef HAVE_PTHREAD_ATTR_SETSTACKSIZE
990   if (stack_size)
991     {
992 #ifdef _SC_THREAD_STACK_MIN
993       stack_size = MAX (sysconf (_SC_THREAD_STACK_MIN), stack_size);
994 #endif /* _SC_THREAD_STACK_MIN */
995       /* No error check here, because some systems can't do it and
996        * we simply don't want threads to fail because of that. */
997       pthread_attr_setstacksize (&attr, stack_size);
998     }
999 #endif /* HAVE_PTHREAD_ATTR_SETSTACKSIZE */
1000
1001   posix_check_cmd (pthread_attr_setdetachstate (&attr,
1002           joinable ? PTHREAD_CREATE_JOINABLE : PTHREAD_CREATE_DETACHED));
1003
1004   ret = pthread_create (thread, &attr, (void* (*)(void*))thread_func, arg);
1005
1006   posix_check_cmd (pthread_attr_destroy (&attr));
1007
1008   if (ret == EAGAIN)
1009     {
1010       g_set_error (error, G_THREAD_ERROR, G_THREAD_ERROR_AGAIN, 
1011                    "Error creating thread: %s", g_strerror (ret));
1012       return;
1013     }
1014
1015   posix_check_err (ret, "pthread_create");
1016 }
1017
1018 /**
1019  * g_thread_yield:
1020  *
1021  * Gives way to other threads waiting to be scheduled.
1022  *
1023  * This function is often used as a method to make busy wait less evil.
1024  * But in most cases you will encounter, there are better methods to do
1025  * that. So in general you shouldn't use this function.
1026  */
1027 void
1028 g_thread_yield (void)
1029 {
1030   sched_yield ();
1031 }
1032
1033 void
1034 g_system_thread_join (gpointer thread)
1035 {
1036   gpointer ignore;
1037   posix_check_cmd (pthread_join (*(pthread_t*)thread, &ignore));
1038 }
1039
1040 void
1041 g_system_thread_exit (void)
1042 {
1043   pthread_exit (NULL);
1044 }
1045
1046 void
1047 g_system_thread_self (gpointer thread)
1048 {
1049   *(pthread_t*)thread = pthread_self();
1050 }
1051
1052 gboolean
1053 g_system_thread_equal (gpointer thread1,
1054                        gpointer thread2)
1055 {
1056   return (pthread_equal (*(pthread_t*)thread1, *(pthread_t*)thread2) != 0);
1057 }
1058
1059 /* {{{1 Epilogue */
1060 /* vim:set foldmethod=marker: */