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