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