locks: drop _INIT macros
[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->impl;
120
121   if G_UNLIKELY (impl == NULL)
122     {
123       impl = g_mutex_impl_new ();
124       if (!g_atomic_pointer_compare_and_exchange (&mutex->impl, NULL, impl))
125         g_mutex_impl_free (impl);
126       impl = mutex->impl;
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 with g_mutex_new() or 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->impl = 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  * #GMutexes that have have been created with g_mutex_new() should
177  * be freed with g_mutex_free() instead.
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->impl);
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, i.e. a thread could deadlock while calling
203  * g_mutex_lock(), if it already has locked @mutex. Use
204  * #GRecMutex if you need recursive mutexes.</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, i.e. the return value of g_mutex_trylock() could be
250  * both %FALSE or %TRUE, if the current thread already has locked
251  * @mutex. Use #GRecMutex if you need recursive mutexes.</note>
252
253  * Returns: %TRUE if @mutex could be locked
254  */
255 gboolean
256 g_mutex_trylock (GMutex *mutex)
257 {
258   gint status;
259
260   if G_LIKELY ((status = pthread_mutex_trylock (g_mutex_get_impl (mutex))) == 0)
261     return TRUE;
262
263   if G_UNLIKELY (status != EBUSY)
264     g_thread_abort (status, "pthread_mutex_trylock");
265
266   return FALSE;
267 }
268
269 /* {{{1 GRecMutex */
270
271 static pthread_mutex_t *
272 g_rec_mutex_impl_new (void)
273 {
274   pthread_mutexattr_t attr;
275   pthread_mutex_t *mutex;
276
277   mutex = g_slice_new (pthread_mutex_t);
278   pthread_mutexattr_init (&attr);
279   pthread_mutexattr_settype (&attr, PTHREAD_MUTEX_RECURSIVE);
280   pthread_mutex_init (mutex, &attr);
281   pthread_mutexattr_destroy (&attr);
282
283   return mutex;
284 }
285
286 static void
287 g_rec_mutex_impl_free (pthread_mutex_t *mutex)
288 {
289   pthread_mutex_destroy (mutex);
290   g_slice_free (pthread_mutex_t, mutex);
291 }
292
293 static pthread_mutex_t *
294 g_rec_mutex_get_impl (GRecMutex *rec_mutex)
295 {
296   pthread_mutex_t *impl = rec_mutex->impl;
297
298   if G_UNLIKELY (impl == NULL)
299     {
300       impl = g_rec_mutex_impl_new ();
301       if (!g_atomic_pointer_compare_and_exchange (&rec_mutex->impl, NULL, impl))
302         g_rec_mutex_impl_free (impl);
303       impl = rec_mutex->impl;
304     }
305
306   return impl;
307 }
308
309 /**
310  * g_rec_mutex_init:
311  * @rec_mutex: an uninitialized #GRecMutex
312  *
313  * Initializes a #GRecMutex so that it can be used.
314  *
315  * This function is useful to initialize a recursive mutex
316  * that has been allocated on the stack, or as part of a larger
317  * structure.
318  * It is not necessary to initialize a recursive mutex that has
319  * been created with g_rec_mutex_new(). It is not necessary to
320  * initialise a recursive mutex that has been statically allocated.
321  *
322  * |[
323  *   typedef struct {
324  *     GRecMutex m;
325  *     ...
326  *   } Blob;
327  *
328  * Blob *b;
329  *
330  * b = g_new (Blob, 1);
331  * g_rec_mutex_init (&b->m);
332  * ]|
333  *
334  * Calling g_rec_mutex_init() on an already initialized #GRecMutex
335  * leads to undefined behaviour.
336  *
337  * To undo the effect of g_rec_mutex_init() when a recursive mutex
338  * is no longer needed, use g_rec_mutex_clear().
339  *
340  * Since: 2.32
341  */
342 void
343 g_rec_mutex_init (GRecMutex *rec_mutex)
344 {
345   rec_mutex->impl = g_rec_mutex_impl_new ();
346 }
347
348 /**
349  * g_rec_mutex_clear:
350  * @rec_mutex: an initialized #GRecMutex
351  *
352  * Frees the resources allocated to a recursive mutex with
353  * g_rec_mutex_init().
354  *
355  * #GRecMutexes that have have been created with g_rec_mutex_new()
356  * should be freed with g_rec_mutex_free() instead.
357  *
358  * Calling g_rec_mutex_clear() on a locked recursive mutex leads
359  * to undefined behaviour.
360  *
361  * Sine: 2.32
362  */
363 void
364 g_rec_mutex_clear (GRecMutex *rec_mutex)
365 {
366   g_rec_mutex_impl_free (rec_mutex->impl);
367 }
368
369 /**
370  * g_rec_mutex_lock:
371  * @rec_mutex: a #GRecMutex
372  *
373  * Locks @rec_mutex. If @rec_mutex is already locked by another
374  * thread, the current thread will block until @rec_mutex is
375  * unlocked by the other thread. If @rec_mutex is already locked
376  * by the current thread, the 'lock count' of @rec_mutex is increased.
377  * The mutex will only become available again when it is unlocked
378  * as many times as it has been locked.
379  *
380  * Since: 2.32
381  */
382 void
383 g_rec_mutex_lock (GRecMutex *mutex)
384 {
385   pthread_mutex_lock (g_rec_mutex_get_impl (mutex));
386 }
387
388 /**
389  * g_rec_mutex_unlock:
390  * @rec_mutex: a #RecGMutex
391  *
392  * Unlocks @rec_mutex. If another thread is blocked in a
393  * g_rec_mutex_lock() call for @rec_mutex, it will become unblocked
394  * and can lock @rec_mutex itself.
395  *
396  * Calling g_rec_mutex_unlock() on a recursive mutex that is not
397  * locked by the current thread leads to undefined behaviour.
398  *
399  * Since: 2.32
400  */
401 void
402 g_rec_mutex_unlock (GRecMutex *rec_mutex)
403 {
404   pthread_mutex_unlock (rec_mutex->impl);
405 }
406
407 /**
408  * g_rec_mutex_trylock:
409  * @rec_mutex: a #GRecMutex
410  *
411  * Tries to lock @rec_mutex. If @rec_mutex is already locked
412  * by another thread, it immediately returns %FALSE. Otherwise
413  * it locks @rec_mutex and returns %TRUE.
414  *
415  * Returns: %TRUE if @rec_mutex could be locked
416  *
417  * Since: 2.32
418  */
419 gboolean
420 g_rec_mutex_trylock (GRecMutex *rec_mutex)
421 {
422   if (pthread_mutex_trylock (g_rec_mutex_get_impl (rec_mutex)) != 0)
423     return FALSE;
424
425   return TRUE;
426 }
427
428 /* {{{1 GRWLock */
429
430 static pthread_rwlock_t *
431 g_rw_lock_impl_new (void)
432 {
433   pthread_rwlock_t *rwlock;
434   gint status;
435
436   rwlock = malloc (sizeof (pthread_rwlock_t));
437   if G_UNLIKELY (rwlock == NULL)
438     g_thread_abort (errno, "malloc");
439
440   if G_UNLIKELY ((status = pthread_rwlock_init (rwlock, NULL)) != 0)
441     g_thread_abort (status, "pthread_rwlock_init");
442
443   return rwlock;
444 }
445
446 static void
447 g_rw_lock_impl_free (pthread_rwlock_t *rwlock)
448 {
449   pthread_rwlock_destroy (rwlock);
450   free (rwlock);
451 }
452
453 static pthread_rwlock_t *
454 g_rw_lock_get_impl (GRWLock *lock)
455 {
456   pthread_rwlock_t *impl = lock->impl;
457
458   if G_UNLIKELY (impl == NULL)
459     {
460       impl = g_rw_lock_impl_new ();
461       if (!g_atomic_pointer_compare_and_exchange (&lock->impl, NULL, impl))
462         g_rw_lock_impl_free (impl);
463       impl = lock->impl;
464     }
465
466   return impl;
467 }
468
469 /**
470  * g_rw_lock_init:
471  * @rw_lock: an uninitialized #GRWLock
472  *
473  * Initializes a #GRWLock so that it can be used.
474  *
475  * This function is useful to initialize a lock that has been
476  * allocated on the stack, or as part of a larger structure.  It is not
477  * necessary to initialise a reader-writer lock that has been statically
478  * allocated.
479  *
480  * |[
481  *   typedef struct {
482  *     GRWLock l;
483  *     ...
484  *   } Blob;
485  *
486  * Blob *b;
487  *
488  * b = g_new (Blob, 1);
489  * g_rw_lock_init (&b->l);
490  * ]|
491  *
492  * To undo the effect of g_rw_lock_init() when a lock is no longer
493  * needed, use g_rw_lock_clear().
494  *
495  * Calling g_rw_lock_init() on an already initialized #GRWLock leads
496  * to undefined behaviour.
497  *
498  * Since: 2.32
499  */
500 void
501 g_rw_lock_init (GRWLock *rw_lock)
502 {
503   rw_lock->impl = g_rw_lock_impl_new ();
504 }
505
506 /**
507  * g_rw_lock_clear:
508  * @rw_lock: an initialized #GRWLock
509  *
510  * Frees the resources allocated to a lock with g_rw_lock_init().
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->impl);
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_cond_t *cond;
640   gint status;
641
642   cond = malloc (sizeof (pthread_cond_t));
643   if G_UNLIKELY (cond == NULL)
644     g_thread_abort (errno, "malloc");
645
646   if G_UNLIKELY ((status = pthread_cond_init (cond, NULL)) != 0)
647     g_thread_abort (status, "pthread_cond_init");
648
649   return cond;
650 }
651
652 static void
653 g_cond_impl_free (pthread_cond_t *cond)
654 {
655   pthread_cond_destroy (cond);
656   free (cond);
657 }
658
659 static pthread_cond_t *
660 g_cond_get_impl (GCond *cond)
661 {
662   pthread_cond_t *impl = cond->impl;
663
664   if G_UNLIKELY (impl == NULL)
665     {
666       impl = g_cond_impl_new ();
667       if (!g_atomic_pointer_compare_and_exchange (&cond->impl, NULL, impl))
668         g_cond_impl_free (impl);
669       impl = cond->impl;
670     }
671
672   return impl;
673 }
674
675 /**
676  * g_cond_init:
677  * @cond: an uninitialized #GCond
678  *
679  * Initialized a #GCond so that it can be used.
680  *
681  * This function is useful to initialize a #GCond that has been
682  * allocated on the stack, or as part of a larger structure.
683  * It is not necessary to initialize a #GCond that has been
684  * created with g_cond_new() or that has been statically allocated.
685  *
686  * To undo the effect of g_cond_init() when a #GCond is no longer
687  * needed, use g_cond_clear().
688  *
689  * Calling g_cond_init() on an already initialized #GCond leads
690  * to undefined behaviour.
691  *
692  * Since: 2.32
693  */
694 void
695 g_cond_init (GCond *cond)
696 {
697   cond->impl = g_cond_impl_new ();
698 }
699
700 /**
701  * g_cond_clear:
702  * @cond: an initialized #GCond
703  *
704  * Frees the resources allocated to a #GCond with g_cond_init().
705  *
706  * #GConds that have been created with g_cond_new() should
707  * be freed with g_cond_free() instead.
708  *
709  * Calling g_cond_clear() for a #GCond on which threads are
710  * blocking leads to undefined behaviour.
711  *
712  * Since: 2.32
713  */
714 void
715 g_cond_clear (GCond *cond)
716 {
717   g_cond_impl_free (cond->impl);
718 }
719
720 /**
721  * g_cond_wait:
722  * @cond: a #GCond
723  * @mutex: a #GMutex that is currently locked
724  *
725  * Waits until this thread is woken up on @cond. The @mutex is unlocked
726  * before falling asleep and locked again before resuming.
727  *
728  * This function can be used even if g_thread_init() has not yet been
729  * called, and, in that case, will immediately return.
730  */
731 void
732 g_cond_wait (GCond  *cond,
733              GMutex *mutex)
734 {
735   gint status;
736
737   if G_UNLIKELY ((status = pthread_cond_wait (g_cond_get_impl (cond), g_mutex_get_impl (mutex))) != 0)
738     g_thread_abort (status, "pthread_cond_wait");
739 }
740
741 /**
742  * g_cond_signal:
743  * @cond: a #GCond
744  *
745  * If threads are waiting for @cond, at least one of them is unblocked.
746  * If no threads are waiting for @cond, this function has no effect.
747  * It is good practice to hold the same lock as the waiting thread
748  * while calling this function, though not required.
749  *
750  * This function can be used even if g_thread_init() has not yet been
751  * called, and, in that case, will do nothing.
752  */
753 void
754 g_cond_signal (GCond *cond)
755 {
756   gint status;
757
758   if G_UNLIKELY ((status = pthread_cond_signal (g_cond_get_impl (cond))) != 0)
759     g_thread_abort (status, "pthread_cond_signal");
760 }
761
762 /**
763  * g_cond_broadcast:
764  * @cond: a #GCond
765  *
766  * If threads are waiting for @cond, all of them are unblocked.
767  * If no threads are waiting for @cond, this function has no effect.
768  * It is good practice to lock the same mutex as the waiting threads
769  * while calling this function, though not required.
770  *
771  * This function can be used even if g_thread_init() has not yet been
772  * called, and, in that case, will do nothing.
773  */
774 void
775 g_cond_broadcast (GCond *cond)
776 {
777   gint status;
778
779   if G_UNLIKELY ((status = pthread_cond_broadcast (g_cond_get_impl (cond))) != 0)
780     g_thread_abort (status, "pthread_cond_broadcast");
781 }
782
783 /**
784  * g_cond_timed_wait:
785  * @cond: a #GCond
786  * @mutex: a #GMutex that is currently locked
787  * @abs_time: a #GTimeVal, determining the final time
788  *
789  * Waits until this thread is woken up on @cond, but not longer than
790  * until the time specified by @abs_time. The @mutex is unlocked before
791  * falling asleep and locked again before resuming.
792  *
793  * If @abs_time is %NULL, g_cond_timed_wait() acts like g_cond_wait().
794  *
795  * This function can be used even if g_thread_init() has not yet been
796  * called, and, in that case, will immediately return %TRUE.
797  *
798  * To easily calculate @abs_time a combination of g_get_current_time()
799  * and g_time_val_add() can be used.
800  *
801  * Returns: %TRUE if @cond was signalled, or %FALSE on timeout
802  */
803 gboolean
804 g_cond_timed_wait (GCond    *cond,
805                    GMutex   *mutex,
806                    GTimeVal *abs_time)
807 {
808   struct timespec end_time;
809   gint status;
810
811   if (abs_time == NULL)
812     {
813       g_cond_wait (cond, mutex);
814       return TRUE;
815     }
816
817   end_time.tv_sec = abs_time->tv_sec;
818   end_time.tv_nsec = abs_time->tv_usec * 1000;
819
820   if ((status = pthread_cond_timedwait (g_cond_get_impl (cond), g_mutex_get_impl (mutex), &end_time)) == 0)
821     return TRUE;
822
823   if G_UNLIKELY (status != ETIMEDOUT)
824     g_thread_abort (status, "pthread_cond_timedwait");
825
826   return FALSE;
827 }
828
829 /**
830  * g_cond_timedwait:
831  * @cond: a #GCond
832  * @mutex: a #GMutex that is currently locked
833  * @abs_time: the final time, in microseconds
834  *
835  * A variant of g_cond_timed_wait() that takes @abs_time
836  * as a #gint64 instead of a #GTimeVal.
837  * See g_cond_timed_wait() for details.
838  *
839  * Returns: %TRUE if @cond was signalled, or %FALSE on timeout
840  *
841  * Since: 2.32
842  */
843 gboolean
844 g_cond_timedwait (GCond  *cond,
845                   GMutex *mutex,
846                   gint64  abs_time)
847 {
848   struct timespec end_time;
849   gint status;
850
851   end_time.tv_sec = abs_time / 1000000;
852   end_time.tv_nsec = (abs_time % 1000000) * 1000;
853
854   if ((status = pthread_cond_timedwait (g_cond_get_impl (cond), g_mutex_get_impl (mutex), &end_time)) == 0)
855     return TRUE;
856
857   if G_UNLIKELY (status != ETIMEDOUT)
858     g_thread_abort (status, "pthread_cond_timedwait");
859
860   return FALSE;
861 }
862
863 /* {{{1 GPrivate */
864
865 /**
866  * GPrivate:
867  *
868  * The #GPrivate struct is an opaque data structure to represent a
869  * thread-local data key.  It is approximately equivalent to the
870  * <function>pthread_setspecific()</function>/<function>pthread_getspecific()</function>
871  * APIs on POSIX and to
872  * <function>TlsSetValue()</function>/<function>TlsGetValue<()/function> on
873  * Windows.
874  *
875  * If you don't already know why you might want this functionality, then
876  * you probably don't need it.
877  *
878  * #GPrivate is a very limited resource (as far as 128 per program,
879  * shared between all libraries).  It is also not possible to destroy a
880  * #GPrivate after it has been used. As such, it is only ever acceptable
881  * to use #GPrivate in static scope, and even then sparingly so.
882  *
883  * See G_PRIVATE_INIT() for a couple of examples.
884  *
885  * The #GPrivate structure should be considered opaque.  It should only
886  * be accessed via the <function>g_private_</function> functions.
887  */
888
889 /**
890  * G_PRIVATE_INIT:
891  * @notify: a #GDestroyNotify
892  *
893  * A macro to assist with the static initialisation of a #GPrivate.
894  *
895  * This macro is useful for the case that a #GDestroyNotify function
896  * should be associated the key.  This is needed when the key will be
897  * used to point at memory that should be deallocated when the thread
898  * exits.
899  *
900  * Additionally, the #GDestroyNotify will also be called on the previous
901  * value stored in the key when g_private_replace() is used.
902  *
903  * If no #GDestroyNotify is needed, then use of this macro is not
904  * required -- if the #GPrivate is declared in static scope then it will
905  * be properly initialised by default (ie: to all zeros).  See the
906  * examples below.
907  *
908  * |[
909  * static GPrivate name_key = G_PRIVATE_INIT (g_free);
910  *
911  * // return value should not be freed
912  * const gchar *
913  * get_local_name (void)
914  * {
915  *   return g_private_get (&name_key);
916  * }
917  *
918  * void
919  * set_local_name (const gchar *name)
920  * {
921  *   g_private_replace (&name_key, g_strdup (name));
922  * }
923  *
924  *
925  * static GPrivate count_key;   // no free function
926  *
927  * gint
928  * get_local_count (void)
929  * {
930  *   return GPOINTER_TO_INT (g_private_get (&count_key));
931  * }
932  *
933  * void
934  * set_local_count (gint count)
935  * {
936  *   g_private_set (&count_key, GINT_TO_POINTER (count));
937  * }
938  * ]|
939  *
940  * Since: 2.32
941  **/
942
943 static pthread_key_t *
944 g_private_impl_new (GDestroyNotify notify)
945 {
946   pthread_key_t *key;
947   gint status;
948
949   key = malloc (sizeof (pthread_key_t));
950   if G_UNLIKELY (key == NULL)
951     g_thread_abort (errno, "malloc");
952   status = pthread_key_create (key, notify);
953   if G_UNLIKELY (status != 0)
954     g_thread_abort (status, "pthread_key_create");
955
956   return key;
957 }
958
959 static void
960 g_private_impl_free (pthread_key_t *key)
961 {
962   gint status;
963
964   status = pthread_key_delete (*key);
965   if G_UNLIKELY (status != 0)
966     g_thread_abort (status, "pthread_key_delete");
967   free (key);
968 }
969
970 static pthread_key_t *
971 g_private_get_impl (GPrivate *key)
972 {
973   pthread_key_t *impl = key->p;
974
975   if G_UNLIKELY (impl == NULL)
976     {
977       impl = g_private_impl_new (key->notify);
978       if (!g_atomic_pointer_compare_and_exchange (&key->p, NULL, impl))
979         {
980           g_private_impl_free (impl);
981           impl = key->p;
982         }
983     }
984
985   return impl;
986 }
987
988 /**
989  * g_private_get:
990  * @key: a #GPrivate
991  *
992  * Returns the current value of the thread local variable @key.
993  *
994  * If the value has not yet been set in this thread, %NULL is returned.
995  * Values are never copied between threads (when a new thread is
996  * created, for example).
997  *
998  * Returns: the thread-local value
999  */
1000 gpointer
1001 g_private_get (GPrivate *key)
1002 {
1003   /* quote POSIX: No errors are returned from pthread_getspecific(). */
1004   return pthread_getspecific (*g_private_get_impl (key));
1005 }
1006
1007 /**
1008  * g_private_set:
1009  * @key: a #GPrivate
1010  * @value: the new value
1011  *
1012  * Sets the thread local variable @key to have the value @value in the
1013  * current thread.
1014  *
1015  * This function differs from g_private_replace() in the following way:
1016  * the #GDestroyNotify for @key is not called on the old value.
1017  */
1018 void
1019 g_private_set (GPrivate *key,
1020                gpointer  value)
1021 {
1022   gint status;
1023
1024   if G_UNLIKELY ((status = pthread_setspecific (*g_private_get_impl (key), value)) != 0)
1025     g_thread_abort (status, "pthread_setspecific");
1026 }
1027
1028 /**
1029  * g_private_replace:
1030  * @key: a #GPrivate
1031  * @value: the new value
1032  *
1033  * Sets the thread local variable @key to have the value @value in the
1034  * current thread.
1035  *
1036  * This function differs from g_private_set() in the following way: if
1037  * the previous value was non-%NULL then the #GDestroyNotify handler for
1038  * @key is run on it.
1039  *
1040  * Since: 2.32
1041  **/
1042 void
1043 g_private_replace (GPrivate *key,
1044                    gpointer  value)
1045 {
1046   pthread_key_t *impl = g_private_get_impl (key);
1047   gpointer old;
1048   gint status;
1049
1050   old = pthread_getspecific (*impl);
1051   if (old && key->notify)
1052     key->notify (old);
1053
1054   if G_UNLIKELY ((status = pthread_setspecific (*impl, value)) != 0)
1055     g_thread_abort (status, "pthread_setspecific");
1056 }
1057
1058 /* {{{1 GThread */
1059
1060 #define posix_check_err(err, name) G_STMT_START{                        \
1061   int error = (err);                                                    \
1062   if (error)                                                            \
1063     g_error ("file %s: line %d (%s): error '%s' during '%s'",           \
1064            __FILE__, __LINE__, G_STRFUNC,                               \
1065            g_strerror (error), name);                                   \
1066   }G_STMT_END
1067
1068 #define posix_check_cmd(cmd) posix_check_err (cmd, #cmd)
1069
1070 void
1071 g_system_thread_create (GThreadFunc       thread_func,
1072                         gpointer          arg,
1073                         gulong            stack_size,
1074                         gboolean          joinable,
1075                         gpointer          thread,
1076                         GError          **error)
1077 {
1078   pthread_attr_t attr;
1079   gint ret;
1080
1081   g_return_if_fail (thread_func);
1082
1083   posix_check_cmd (pthread_attr_init (&attr));
1084
1085 #ifdef HAVE_PTHREAD_ATTR_SETSTACKSIZE
1086   if (stack_size)
1087     {
1088 #ifdef _SC_THREAD_STACK_MIN
1089       stack_size = MAX (sysconf (_SC_THREAD_STACK_MIN), stack_size);
1090 #endif /* _SC_THREAD_STACK_MIN */
1091       /* No error check here, because some systems can't do it and
1092        * we simply don't want threads to fail because of that. */
1093       pthread_attr_setstacksize (&attr, stack_size);
1094     }
1095 #endif /* HAVE_PTHREAD_ATTR_SETSTACKSIZE */
1096
1097   posix_check_cmd (pthread_attr_setdetachstate (&attr,
1098           joinable ? PTHREAD_CREATE_JOINABLE : PTHREAD_CREATE_DETACHED));
1099
1100   ret = pthread_create (thread, &attr, (void* (*)(void*))thread_func, arg);
1101
1102   posix_check_cmd (pthread_attr_destroy (&attr));
1103
1104   if (ret == EAGAIN)
1105     {
1106       g_set_error (error, G_THREAD_ERROR, G_THREAD_ERROR_AGAIN, 
1107                    "Error creating thread: %s", g_strerror (ret));
1108       return;
1109     }
1110
1111   posix_check_err (ret, "pthread_create");
1112 }
1113
1114 /**
1115  * g_thread_yield:
1116  *
1117  * Gives way to other threads waiting to be scheduled.
1118  *
1119  * This function is often used as a method to make busy wait less evil.
1120  * But in most cases you will encounter, there are better methods to do
1121  * that. So in general you shouldn't use this function.
1122  */
1123 void
1124 g_thread_yield (void)
1125 {
1126   sched_yield ();
1127 }
1128
1129 void
1130 g_system_thread_join (gpointer thread)
1131 {
1132   gpointer ignore;
1133   posix_check_cmd (pthread_join (*(pthread_t*)thread, &ignore));
1134 }
1135
1136 void
1137 g_system_thread_exit (void)
1138 {
1139   pthread_exit (NULL);
1140 }
1141
1142 void
1143 g_system_thread_self (gpointer thread)
1144 {
1145   *(pthread_t*)thread = pthread_self();
1146 }
1147
1148 gboolean
1149 g_system_thread_equal (gpointer thread1,
1150                        gpointer thread2)
1151 {
1152   return (pthread_equal (*(pthread_t*)thread1, *(pthread_t*)thread2) != 0);
1153 }
1154
1155 void
1156 g_system_thread_set_name (const gchar *name)
1157 {
1158 #ifdef HAVE_SYS_PRCTL_H
1159   prctl (PR_SET_NAME, name, 0, 0, 0, 0);
1160 #endif
1161 }
1162
1163 /* {{{1 Epilogue */
1164 /* vim:set foldmethod=marker: */