Port g_mutex_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 new/free API */
227
228 GCond *
229 g_cond_new (void)
230 {
231   GCond *cond;
232
233   /* malloc() is temporary until all libglib users are ported away */
234   cond = malloc (sizeof (GCond));
235   if G_UNLIKELY (cond == NULL)
236     g_thread_abort (errno, "malloc");
237   g_cond_init (cond);
238
239   return cond;
240 }
241
242 void
243 g_cond_free (GCond *cond)
244 {
245   g_cond_clear (cond);
246   free (cond);
247 }
248
249 /* {{{1 GPrivate */
250
251 #include "glib.h"
252 #include "gthreadprivate.h"
253
254 #include <pthread.h>
255 #include <errno.h>
256 #include <stdlib.h>
257 #ifdef HAVE_SYS_TIME_H
258 # include <sys/time.h>
259 #endif
260 #ifdef HAVE_UNISTD_H
261 # include <unistd.h>
262 #endif
263
264 #ifdef HAVE_SCHED_H
265 #include <sched.h>
266 #endif
267
268 #define posix_check_err(err, name) G_STMT_START{                        \
269   int error = (err);                                                    \
270   if (error)                                                            \
271     g_error ("file %s: line %d (%s): error '%s' during '%s'",           \
272            __FILE__, __LINE__, G_STRFUNC,                               \
273            g_strerror (error), name);                                   \
274   }G_STMT_END
275
276 #define posix_check_cmd(cmd) posix_check_err (cmd, #cmd)
277
278 #ifdef G_ENABLE_DEBUG
279 static gboolean posix_check_cmd_prio_warned = FALSE;
280 # define posix_check_cmd_prio(cmd) G_STMT_START{                        \
281     int err = (cmd);                                                    \
282     if (err == EPERM)                                                   \
283       {                                                                 \
284         if (!posix_check_cmd_prio_warned)                               \
285           {                                                             \
286             posix_check_cmd_prio_warned = TRUE;                         \
287             g_warning ("Priorities can only be changed "                \
288                         "(resp. increased) by root.");                  \
289           }                                                             \
290       }                                                                 \
291     else                                                                \
292       posix_check_err (err, #cmd);                                      \
293      }G_STMT_END
294 #else /* G_ENABLE_DEBUG */
295 # define posix_check_cmd_prio(cmd) G_STMT_START{                        \
296     int err = (cmd);                                                    \
297     if (err != EPERM)                                                   \
298       posix_check_err (err, #cmd);                                      \
299      }G_STMT_END
300 #endif /* G_ENABLE_DEBUG */
301
302 #if defined (POSIX_MIN_PRIORITY) && defined (POSIX_MAX_PRIORITY)
303 # define HAVE_PRIORITIES 1
304 static gint priority_normal_value;
305 # ifdef __FreeBSD__
306    /* FreeBSD threads use different priority values from the POSIX_
307     * defines so we just set them here. The corresponding macros
308     * PTHREAD_MIN_PRIORITY and PTHREAD_MAX_PRIORITY are implied to be
309     * exported by the docs, but they aren't.
310     */
311 #  define PRIORITY_LOW_VALUE      0
312 #  define PRIORITY_URGENT_VALUE   31
313 # else /* !__FreeBSD__ */
314 #  define PRIORITY_LOW_VALUE      POSIX_MIN_PRIORITY
315 #  define PRIORITY_URGENT_VALUE   POSIX_MAX_PRIORITY
316 # endif /* !__FreeBSD__ */
317 # define PRIORITY_NORMAL_VALUE    priority_normal_value
318
319 # define PRIORITY_HIGH_VALUE \
320     ((PRIORITY_NORMAL_VALUE + PRIORITY_URGENT_VALUE * 2) / 3)
321
322 static gint
323 g_thread_priority_map (GThreadPriority priority)
324 {
325   switch (priority)
326     {
327     case G_THREAD_PRIORITY_LOW:
328       return PRIORITY_LOW_VALUE;
329
330     case G_THREAD_PRIORITY_NORMAL:
331       return PRIORITY_NORMAL_VALUE;
332
333     case G_THREAD_PRIORITY_HIGH:
334       return PRIORITY_HIGH_VALUE;
335
336     case G_THREAD_PRIORITY_URGENT:
337       return PRIORITY_URGENT_VALUE;
338
339     default:
340       g_assert_not_reached ();
341     }
342 }
343
344 #endif /* POSIX_MIN_PRIORITY && POSIX_MAX_PRIORITY */
345
346 static gulong g_thread_min_stack_size = 0;
347
348 #define G_MUTEX_SIZE (sizeof (pthread_mutex_t))
349
350 void
351 _g_thread_impl_init(void)
352 {
353 #ifdef _SC_THREAD_STACK_MIN
354   g_thread_min_stack_size = MAX (sysconf (_SC_THREAD_STACK_MIN), 0);
355 #endif /* _SC_THREAD_STACK_MIN */
356 #ifdef HAVE_PRIORITIES
357   {
358     struct sched_param sched;
359     int policy;
360     posix_check_cmd (pthread_getschedparam (pthread_self(), &policy, &sched));
361     priority_normal_value = sched.sched_priority;
362   }
363 #endif /* HAVE_PRIORITIES */
364 }
365
366 static GPrivate *
367 g_private_new_posix_impl (GDestroyNotify destructor)
368 {
369   GPrivate *result = (GPrivate *) g_new (pthread_key_t, 1);
370   posix_check_cmd (pthread_key_create ((pthread_key_t *) result, destructor));
371   return result;
372 }
373
374 /* NOTE: the functions g_private_get and g_private_set may not use
375    functions from gmem.c and gmessages.c */
376
377 static void
378 g_private_set_posix_impl (GPrivate * private_key, gpointer value)
379 {
380   if (!private_key)
381     return;
382   pthread_setspecific (*(pthread_key_t *) private_key, value);
383 }
384
385 static gpointer
386 g_private_get_posix_impl (GPrivate * private_key)
387 {
388   if (!private_key)
389     return NULL;
390
391   return pthread_getspecific (*(pthread_key_t *) private_key);
392 }
393
394 /* {{{1 GThread */
395
396
397 static void
398 g_thread_create_posix_impl (GThreadFunc thread_func,
399                             gpointer arg,
400                             gulong stack_size,
401                             gboolean joinable,
402                             gboolean bound,
403                             GThreadPriority priority,
404                             gpointer thread,
405                             GError **error)
406 {
407   pthread_attr_t attr;
408   gint ret;
409
410   g_return_if_fail (thread_func);
411   g_return_if_fail (priority >= G_THREAD_PRIORITY_LOW);
412   g_return_if_fail (priority <= G_THREAD_PRIORITY_URGENT);
413
414   posix_check_cmd (pthread_attr_init (&attr));
415
416 #ifdef HAVE_PTHREAD_ATTR_SETSTACKSIZE
417   if (stack_size)
418     {
419       stack_size = MAX (g_thread_min_stack_size, stack_size);
420       /* No error check here, because some systems can't do it and
421        * we simply don't want threads to fail because of that. */
422       pthread_attr_setstacksize (&attr, stack_size);
423     }
424 #endif /* HAVE_PTHREAD_ATTR_SETSTACKSIZE */
425
426 #ifdef PTHREAD_SCOPE_SYSTEM
427   if (bound)
428     /* No error check here, because some systems can't do it and we
429      * simply don't want threads to fail because of that. */
430     pthread_attr_setscope (&attr, PTHREAD_SCOPE_SYSTEM);
431 #endif /* PTHREAD_SCOPE_SYSTEM */
432
433   posix_check_cmd (pthread_attr_setdetachstate (&attr,
434           joinable ? PTHREAD_CREATE_JOINABLE : PTHREAD_CREATE_DETACHED));
435
436 #ifdef HAVE_PRIORITIES
437   {
438     struct sched_param sched;
439     posix_check_cmd (pthread_attr_getschedparam (&attr, &sched));
440     sched.sched_priority = g_thread_priority_map (priority);
441     posix_check_cmd_prio (pthread_attr_setschedparam (&attr, &sched));
442   }
443 #endif /* HAVE_PRIORITIES */
444   ret = pthread_create (thread, &attr, (void* (*)(void*))thread_func, arg);
445
446   posix_check_cmd (pthread_attr_destroy (&attr));
447
448   if (ret == EAGAIN)
449     {
450       g_set_error (error, G_THREAD_ERROR, G_THREAD_ERROR_AGAIN, 
451                    "Error creating thread: %s", g_strerror (ret));
452       return;
453     }
454
455   posix_check_err (ret, "pthread_create");
456 }
457
458 static void
459 g_thread_yield_posix_impl (void)
460 {
461   POSIX_YIELD_FUNC;
462 }
463
464 static void
465 g_thread_join_posix_impl (gpointer thread)
466 {
467   gpointer ignore;
468   posix_check_cmd (pthread_join (*(pthread_t*)thread, &ignore));
469 }
470
471 static void
472 g_thread_exit_posix_impl (void)
473 {
474   pthread_exit (NULL);
475 }
476
477 static void
478 g_thread_set_priority_posix_impl (gpointer thread, GThreadPriority priority)
479 {
480   g_return_if_fail (priority >= G_THREAD_PRIORITY_LOW);
481   g_return_if_fail (priority <= G_THREAD_PRIORITY_URGENT);
482 #ifdef HAVE_PRIORITIES
483   {
484     struct sched_param sched;
485     int policy;
486     posix_check_cmd (pthread_getschedparam (*(pthread_t*)thread, &policy,
487                                             &sched));
488     sched.sched_priority = g_thread_priority_map (priority);
489     posix_check_cmd_prio (pthread_setschedparam (*(pthread_t*)thread, policy,
490                                                  &sched));
491   }
492 #endif /* HAVE_PRIORITIES */
493 }
494
495 static void
496 g_thread_self_posix_impl (gpointer thread)
497 {
498   *(pthread_t*)thread = pthread_self();
499 }
500
501 static gboolean
502 g_thread_equal_posix_impl (gpointer thread1, gpointer thread2)
503 {
504   return (pthread_equal (*(pthread_t*)thread1, *(pthread_t*)thread2) != 0);
505 }
506
507 /* {{{1 Epilogue */
508 GThreadFunctions g_thread_functions_for_glib_use =
509 {
510   g_mutex_new,
511   g_mutex_lock,
512   g_mutex_trylock,
513   g_mutex_unlock,
514   g_mutex_free,
515   g_cond_new,
516   g_cond_signal,
517   g_cond_broadcast,
518   g_cond_wait,
519   g_cond_timed_wait,
520   g_cond_free,
521   g_private_new_posix_impl,
522   g_private_get_posix_impl,
523   g_private_set_posix_impl,
524   g_thread_create_posix_impl,
525   g_thread_yield_posix_impl,
526   g_thread_join_posix_impl,
527   g_thread_exit_posix_impl,
528   g_thread_set_priority_posix_impl,
529   g_thread_self_posix_impl,
530   g_thread_equal_posix_impl
531 };
532
533 /* vim:set foldmethod=marker: */