Clean up g_thread_yield implementation
[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
47 #include <pthread.h>
48 #include <stdlib.h>
49 #include <string.h>
50 #include <errno.h>
51 #include <stdio.h>
52
53 static void
54 g_thread_abort (gint         status,
55                 const gchar *function)
56 {
57   fprintf (stderr, "GLib (gthread-posix.c): Unexpected error from C library during '%s': %s.  Aborting.\n",
58            strerror (status), function);
59   abort ();
60 }
61
62 /* {{{1 GMutex */
63 void
64 g_mutex_init (GMutex *mutex)
65 {
66   gint status;
67
68   if G_UNLIKELY ((status = pthread_mutex_init (&mutex->impl, NULL)) != 0)
69     g_thread_abort (status, "pthread_mutex_init");
70 }
71
72 void
73 g_mutex_clear (GMutex *mutex)
74 {
75   gint status;
76
77   if G_UNLIKELY ((status = pthread_mutex_destroy (&mutex->impl)) != 0)
78     g_thread_abort (status, "pthread_mutex_destroy");
79 }
80
81 void
82 g_mutex_lock (GMutex *mutex)
83 {
84   gint status;
85
86   if G_UNLIKELY ((status = pthread_mutex_lock (&mutex->impl)) != 0)
87     g_thread_abort (status, "pthread_mutex_lock");
88 }
89
90 void
91 g_mutex_unlock (GMutex *mutex)
92 {
93   gint status;
94
95   if G_UNLIKELY ((status = pthread_mutex_unlock (&mutex->impl)) != 0)
96     g_thread_abort (status, "pthread_mutex_lock");
97 }
98
99 gboolean
100 g_mutex_trylock (GMutex *mutex)
101 {
102   gint status;
103
104   if G_LIKELY ((status = pthread_mutex_trylock (&mutex->impl)) == 0)
105     return TRUE;
106
107   if G_UNLIKELY (status != EBUSY)
108     g_thread_abort (status, "pthread_mutex_trylock");
109
110   return FALSE;
111 }
112
113 /* {{{1 GCond */
114
115 void
116 g_cond_init (GCond *cond)
117 {
118   gint status;
119
120   if G_UNLIKELY ((status = pthread_cond_init (&cond->impl, NULL)) != 0)
121     g_thread_abort (status, "pthread_cond_init");
122 }
123
124 void
125 g_cond_clear (GCond *cond)
126 {
127   gint status;
128
129   if G_UNLIKELY ((status = pthread_cond_destroy (&cond->impl)) != 0)
130     g_thread_abort (status, "pthread_cond_destroy");
131 }
132
133 void
134 g_cond_wait (GCond  *cond,
135              GMutex *mutex)
136 {
137   gint status;
138
139   if G_UNLIKELY ((status = pthread_cond_wait (&cond->impl, &mutex->impl)) != 0)
140     g_thread_abort (status, "pthread_cond_wait");
141 }
142
143 void
144 g_cond_signal (GCond *cond)
145 {
146   gint status;
147
148   if G_UNLIKELY ((status = pthread_cond_signal (&cond->impl)) != 0)
149     g_thread_abort (status, "pthread_cond_signal");
150 }
151
152 void
153 g_cond_broadcast (GCond *cond)
154 {
155   gint status;
156
157   if G_UNLIKELY ((status = pthread_cond_broadcast (&cond->impl)) != 0)
158     g_thread_abort (status, "pthread_cond_broadcast");
159 }
160
161 gboolean
162 g_cond_timed_wait (GCond    *cond,
163                    GMutex   *mutex,
164                    GTimeVal *abs_time)
165 {
166   struct timespec end_time;
167   gint status;
168
169   if (abs_time == NULL)
170     {
171       g_cond_wait (cond, mutex);
172       return TRUE;
173     }
174
175   end_time.tv_sec = abs_time->tv_sec;
176   end_time.tv_nsec = abs_time->tv_usec * 1000;
177
178   if ((status = pthread_cond_timedwait (&cond->impl, &mutex->impl, &end_time)) == 0)
179     return TRUE;
180
181   if G_UNLIKELY (status != ETIMEDOUT)
182     g_thread_abort (status, "pthread_cond_timedwait");
183
184   return FALSE;
185 }
186
187 gboolean
188 g_cond_timedwait (GCond  *cond,
189                   GMutex *mutex,
190                   gint64  abs_time)
191 {
192   struct timespec end_time;
193   gint status;
194
195   end_time.tv_sec = abs_time / 1000000;
196   end_time.tv_nsec = (abs_time % 1000000) * 1000;
197
198   if ((status = pthread_cond_timedwait (&cond->impl, &mutex->impl, &end_time)) == 0)
199     return TRUE;
200
201   if G_UNLIKELY (status != ETIMEDOUT)
202     g_thread_abort (status, "pthread_cond_timedwait");
203
204   return FALSE;
205 }
206
207 /* {{{1 GPrivate */
208
209 GPrivate *
210 g_private_new (GDestroyNotify notify)
211 {
212   GPrivate *key;
213
214   key = malloc (sizeof (GPrivate));
215   if G_UNLIKELY (key == NULL)
216     g_thread_abort (errno, "malloc");
217   g_private_init (key, notify);
218
219   return key;
220 }
221
222 void
223 g_private_init (GPrivate       *key,
224                 GDestroyNotify  notify)
225 {
226   pthread_key_create (&key->key, notify);
227   key->ready = TRUE;
228 }
229
230 gpointer
231 g_private_get (GPrivate *key)
232 {
233   if (!key->ready)
234     return key->single_value;
235
236   /* quote POSIX: No errors are returned from pthread_getspecific(). */
237   return pthread_getspecific (key->key);
238 }
239
240 void
241 g_private_set (GPrivate *key,
242                gpointer  value)
243 {
244   gint status;
245
246   if (!key->ready)
247     {
248       key->single_value = value;
249       return;
250     }
251
252   if G_UNLIKELY ((status = pthread_setspecific (key->key, value)) != 0)
253     g_thread_abort (status, "pthread_setspecific");
254 }
255
256 /* {{{1 GThread */
257
258 #include "glib.h"
259 #include "gthreadprivate.h"
260
261 #include <pthread.h>
262 #include <errno.h>
263 #include <stdlib.h>
264 #ifdef HAVE_SYS_TIME_H
265 # include <sys/time.h>
266 #endif
267 #ifdef HAVE_UNISTD_H
268 # include <unistd.h>
269 #endif
270
271 #ifdef HAVE_SCHED_H
272 #include <sched.h>
273 #endif
274
275 #define posix_check_err(err, name) G_STMT_START{                        \
276   int error = (err);                                                    \
277   if (error)                                                            \
278     g_error ("file %s: line %d (%s): error '%s' during '%s'",           \
279            __FILE__, __LINE__, G_STRFUNC,                               \
280            g_strerror (error), name);                                   \
281   }G_STMT_END
282
283 #define posix_check_cmd(cmd) posix_check_err (cmd, #cmd)
284
285 #ifdef G_ENABLE_DEBUG
286 static gboolean posix_check_cmd_prio_warned = FALSE;
287 # define posix_check_cmd_prio(cmd) G_STMT_START{                        \
288     int err = (cmd);                                                    \
289     if (err == EPERM)                                                   \
290       {                                                                 \
291         if (!posix_check_cmd_prio_warned)                               \
292           {                                                             \
293             posix_check_cmd_prio_warned = TRUE;                         \
294             g_warning ("Priorities can only be changed "                \
295                         "(resp. increased) by root.");                  \
296           }                                                             \
297       }                                                                 \
298     else                                                                \
299       posix_check_err (err, #cmd);                                      \
300      }G_STMT_END
301 #else /* G_ENABLE_DEBUG */
302 # define posix_check_cmd_prio(cmd) G_STMT_START{                        \
303     int err = (cmd);                                                    \
304     if (err != EPERM)                                                   \
305       posix_check_err (err, #cmd);                                      \
306      }G_STMT_END
307 #endif /* G_ENABLE_DEBUG */
308
309 #if defined (POSIX_MIN_PRIORITY) && defined (POSIX_MAX_PRIORITY)
310 # define HAVE_PRIORITIES 1
311 static gint priority_normal_value;
312 # ifdef __FreeBSD__
313    /* FreeBSD threads use different priority values from the POSIX_
314     * defines so we just set them here. The corresponding macros
315     * PTHREAD_MIN_PRIORITY and PTHREAD_MAX_PRIORITY are implied to be
316     * exported by the docs, but they aren't.
317     */
318 #  define PRIORITY_LOW_VALUE      0
319 #  define PRIORITY_URGENT_VALUE   31
320 # else /* !__FreeBSD__ */
321 #  define PRIORITY_LOW_VALUE      POSIX_MIN_PRIORITY
322 #  define PRIORITY_URGENT_VALUE   POSIX_MAX_PRIORITY
323 # endif /* !__FreeBSD__ */
324 # define PRIORITY_NORMAL_VALUE    priority_normal_value
325
326 # define PRIORITY_HIGH_VALUE \
327     ((PRIORITY_NORMAL_VALUE + PRIORITY_URGENT_VALUE * 2) / 3)
328
329 static gint
330 g_thread_priority_map (GThreadPriority priority)
331 {
332   switch (priority)
333     {
334     case G_THREAD_PRIORITY_LOW:
335       return PRIORITY_LOW_VALUE;
336
337     case G_THREAD_PRIORITY_NORMAL:
338       return PRIORITY_NORMAL_VALUE;
339
340     case G_THREAD_PRIORITY_HIGH:
341       return PRIORITY_HIGH_VALUE;
342
343     case G_THREAD_PRIORITY_URGENT:
344       return PRIORITY_URGENT_VALUE;
345
346     default:
347       g_assert_not_reached ();
348     }
349 }
350
351 #endif /* POSIX_MIN_PRIORITY && POSIX_MAX_PRIORITY */
352
353 static gulong g_thread_min_stack_size = 0;
354
355 #define G_MUTEX_SIZE (sizeof (pthread_mutex_t))
356
357 void
358 _g_thread_impl_init(void)
359 {
360 #ifdef _SC_THREAD_STACK_MIN
361   g_thread_min_stack_size = MAX (sysconf (_SC_THREAD_STACK_MIN), 0);
362 #endif /* _SC_THREAD_STACK_MIN */
363 #ifdef HAVE_PRIORITIES
364   {
365     struct sched_param sched;
366     int policy;
367     posix_check_cmd (pthread_getschedparam (pthread_self(), &policy, &sched));
368     priority_normal_value = sched.sched_priority;
369   }
370 #endif /* HAVE_PRIORITIES */
371 }
372
373 static void
374 g_thread_create_posix_impl (GThreadFunc thread_func,
375                             gpointer arg,
376                             gulong stack_size,
377                             gboolean joinable,
378                             gboolean bound,
379                             GThreadPriority priority,
380                             gpointer thread,
381                             GError **error)
382 {
383   pthread_attr_t attr;
384   gint ret;
385
386   g_return_if_fail (thread_func);
387   g_return_if_fail (priority >= G_THREAD_PRIORITY_LOW);
388   g_return_if_fail (priority <= G_THREAD_PRIORITY_URGENT);
389
390   posix_check_cmd (pthread_attr_init (&attr));
391
392 #ifdef HAVE_PTHREAD_ATTR_SETSTACKSIZE
393   if (stack_size)
394     {
395       stack_size = MAX (g_thread_min_stack_size, stack_size);
396       /* No error check here, because some systems can't do it and
397        * we simply don't want threads to fail because of that. */
398       pthread_attr_setstacksize (&attr, stack_size);
399     }
400 #endif /* HAVE_PTHREAD_ATTR_SETSTACKSIZE */
401
402 #ifdef PTHREAD_SCOPE_SYSTEM
403   if (bound)
404     /* No error check here, because some systems can't do it and we
405      * simply don't want threads to fail because of that. */
406     pthread_attr_setscope (&attr, PTHREAD_SCOPE_SYSTEM);
407 #endif /* PTHREAD_SCOPE_SYSTEM */
408
409   posix_check_cmd (pthread_attr_setdetachstate (&attr,
410           joinable ? PTHREAD_CREATE_JOINABLE : PTHREAD_CREATE_DETACHED));
411
412 #ifdef HAVE_PRIORITIES
413   {
414     struct sched_param sched;
415     posix_check_cmd (pthread_attr_getschedparam (&attr, &sched));
416     sched.sched_priority = g_thread_priority_map (priority);
417     posix_check_cmd_prio (pthread_attr_setschedparam (&attr, &sched));
418   }
419 #endif /* HAVE_PRIORITIES */
420   ret = pthread_create (thread, &attr, (void* (*)(void*))thread_func, arg);
421
422   posix_check_cmd (pthread_attr_destroy (&attr));
423
424   if (ret == EAGAIN)
425     {
426       g_set_error (error, G_THREAD_ERROR, G_THREAD_ERROR_AGAIN, 
427                    "Error creating thread: %s", g_strerror (ret));
428       return;
429     }
430
431   posix_check_err (ret, "pthread_create");
432 }
433
434 static void
435 g_thread_yield_posix_impl (void)
436 {
437   sched_yield ();
438 }
439
440 static void
441 g_thread_join_posix_impl (gpointer thread)
442 {
443   gpointer ignore;
444   posix_check_cmd (pthread_join (*(pthread_t*)thread, &ignore));
445 }
446
447 static void
448 g_thread_exit_posix_impl (void)
449 {
450   pthread_exit (NULL);
451 }
452
453 static void
454 g_thread_set_priority_posix_impl (gpointer thread, GThreadPriority priority)
455 {
456   g_return_if_fail (priority >= G_THREAD_PRIORITY_LOW);
457   g_return_if_fail (priority <= G_THREAD_PRIORITY_URGENT);
458 #ifdef HAVE_PRIORITIES
459   {
460     struct sched_param sched;
461     int policy;
462     posix_check_cmd (pthread_getschedparam (*(pthread_t*)thread, &policy,
463                                             &sched));
464     sched.sched_priority = g_thread_priority_map (priority);
465     posix_check_cmd_prio (pthread_setschedparam (*(pthread_t*)thread, policy,
466                                                  &sched));
467   }
468 #endif /* HAVE_PRIORITIES */
469 }
470
471 static void
472 g_thread_self_posix_impl (gpointer thread)
473 {
474   *(pthread_t*)thread = pthread_self();
475 }
476
477 static gboolean
478 g_thread_equal_posix_impl (gpointer thread1, gpointer thread2)
479 {
480   return (pthread_equal (*(pthread_t*)thread1, *(pthread_t*)thread2) != 0);
481 }
482
483 /* {{{1 Epilogue */
484 GThreadFunctions g_thread_functions_for_glib_use =
485 {
486   g_mutex_new,
487   g_mutex_lock,
488   g_mutex_trylock,
489   g_mutex_unlock,
490   g_mutex_free,
491   g_cond_new,
492   g_cond_signal,
493   g_cond_broadcast,
494   g_cond_wait,
495   g_cond_timed_wait,
496   g_cond_free,
497   g_private_new,
498   g_private_get,
499   g_private_set,
500   g_thread_create_posix_impl,
501   g_thread_yield_posix_impl,
502   g_thread_join_posix_impl,
503   g_thread_exit_posix_impl,
504   g_thread_set_priority_posix_impl,
505   g_thread_self_posix_impl,
506   g_thread_equal_posix_impl
507 };
508
509 /* vim:set foldmethod=marker: */