633dcdbe99a2777ea168e2b6ddc10b87608f58f2
[platform/upstream/glib.git] / gthread / 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 /*
31  * MT safe
32  */
33
34 #include "config.h"
35
36 #include <pthread.h>
37 #include <errno.h>
38 #include <stdlib.h>
39 #ifdef HAVE_SYS_TIME_H
40 # include <sys/time.h>
41 #endif
42 #ifdef HAVE_UNISTD_H
43 # include <unistd.h>
44 #endif
45
46 #ifdef HAVE_SCHED_H
47 #include <sched.h>
48 #endif
49
50 #define posix_check_err(err, name) G_STMT_START{                        \
51   int error = (err);                                                    \
52   if (error)                                                            \
53     g_error ("file %s: line %d (%s): error '%s' during '%s'",           \
54            __FILE__, __LINE__, G_GNUC_PRETTY_FUNCTION,                  \
55            g_strerror (error), name);                                   \
56   }G_STMT_END
57
58 #define posix_check_cmd(cmd) posix_check_err (posix_error (cmd), #cmd)
59
60 #ifdef G_ENABLE_DEBUG
61 static gboolean posix_check_cmd_prio_warned = FALSE;
62 # define posix_check_cmd_prio(cmd) G_STMT_START{                        \
63     int err = posix_error (cmd);                                        \
64     if (err == EPERM)                                                   \
65       {                                                                 \
66         if (!posix_check_cmd_prio_warned)                               \
67           {                                                             \
68             posix_check_cmd_prio_warned = TRUE;                         \
69             g_warning ("Priorities can only be changed "                \
70                         "(resp. increased) by root.");                  \
71           }                                                             \
72       }                                                                 \
73     else                                                                \
74       posix_check_err (err, #cmd);                                      \
75      }G_STMT_END
76 #else /* G_ENABLE_DEBUG */
77 # define posix_check_cmd_prio(cmd) G_STMT_START{                        \
78     int err = posix_error (cmd);                                        \
79     if (err != EPERM)                                                   \
80       posix_check_err (err, #cmd);                                      \
81      }G_STMT_END
82 #endif /* G_ENABLE_DEBUG */
83
84 #if defined(G_THREADS_IMPL_POSIX)
85 # define posix_error(what) (what)
86 # define mutexattr_default NULL
87 # define condattr_default NULL
88 #elif defined(G_THREADS_IMPL_DCE)
89 # define posix_error(what) ((what) == -1 ? errno : 0)
90 # define pthread_key_create(a, b) pthread_keycreate (a, b)
91 # define pthread_attr_init(a) pthread_attr_create (a)
92 # define pthread_attr_destroy(a) pthread_attr_delete (a)
93 # define pthread_create(a, b, c, d) pthread_create (a, *b, c, d)
94 # define mutexattr_default (pthread_mutexattr_default)
95 # define condattr_default (pthread_condattr_default)
96 #else /* neither G_THREADS_IMPL_POSIX nor G_THREADS_IMPL_DCE are defined */
97 # error This should not happen. Contact the GLib team.
98 #endif
99
100 #if defined (POSIX_MIN_PRIORITY) && defined (POSIX_MAX_PRIORITY)
101 # define HAVE_PRIORITIES 1
102 static gint priority_normal_value;
103 # ifdef __FreeBSD__
104    /* FreeBSD threads use different priority values from the POSIX_
105     * defines so we just set them here. The corresponding macros
106     * PTHREAD_MIN_PRIORITY and PTHREAD_MAX_PRIORITY are implied to be
107     * exported by the docs, but they aren't.
108     */
109 #  define PRIORITY_LOW_VALUE      0
110 #  define PRIORITY_URGENT_VALUE   31
111 # else /* !__FreeBSD__ */
112 #  define PRIORITY_LOW_VALUE      POSIX_MIN_PRIORITY
113 #  define PRIORITY_URGENT_VALUE   POSIX_MAX_PRIORITY
114 # endif /* !__FreeBSD__ */
115 # define PRIORITY_NORMAL_VALUE    priority_normal_value
116 #endif /* POSIX_MIN_PRIORITY && POSIX_MAX_PRIORITY */
117
118 static gulong g_thread_min_stack_size = 0;
119
120 #define G_MUTEX_SIZE (sizeof (pthread_mutex_t))
121
122 #if defined(_SC_THREAD_STACK_MIN) || defined (HAVE_PRIORITIES)
123 #define HAVE_G_THREAD_IMPL_INIT
124 static void
125 g_thread_impl_init(void)
126 {
127 #ifdef _SC_THREAD_STACK_MIN
128   g_thread_min_stack_size = MAX (sysconf (_SC_THREAD_STACK_MIN), 0);
129 #endif /* _SC_THREAD_STACK_MIN */
130 #ifdef HAVE_PRIORITIES
131 # ifdef G_THREADS_IMPL_POSIX
132   {
133     struct sched_param sched;
134     int policy;
135     posix_check_cmd (pthread_getschedparam (pthread_self(), &policy, &sched));
136     priority_normal_value = sched.sched_priority;
137   }
138 # else /* G_THREADS_IMPL_DCE */
139   posix_check_cmd (priority_normal_value =
140                    pthread_getprio (*(pthread_t*)thread,
141                                     g_thread_priority_map [priority]));
142 # endif
143 #endif /* HAVE_PRIORITIES */
144
145 }
146 #endif /* _SC_THREAD_STACK_MIN || HAVE_PRIORITIES */
147
148 static GMutex *
149 g_mutex_new_posix_impl (void)
150 {
151   GMutex *result = (GMutex *) g_new (pthread_mutex_t, 1);
152   posix_check_cmd (pthread_mutex_init ((pthread_mutex_t *) result,
153                                        mutexattr_default));
154   return result;
155 }
156
157 static void
158 g_mutex_free_posix_impl (GMutex * mutex)
159 {
160   posix_check_cmd (pthread_mutex_destroy ((pthread_mutex_t *) mutex));
161   g_free (mutex);
162 }
163
164 /* NOTE: the functions g_mutex_lock and g_mutex_unlock may not use
165    functions from gmem.c and gmessages.c; */
166
167 /* pthread_mutex_lock, pthread_mutex_unlock can be taken directly, as
168    signature and semantic are right, but without error check then!!!!,
169    we might want to change this therefore. */
170
171 static gboolean
172 g_mutex_trylock_posix_impl (GMutex * mutex)
173 {
174   int result;
175
176   result = pthread_mutex_trylock ((pthread_mutex_t *) mutex);
177
178 #ifdef G_THREADS_IMPL_POSIX
179   if (result == EBUSY)
180     return FALSE;
181 #else /* G_THREADS_IMPL_DCE */
182   if (result == 0)
183     return FALSE;
184 #endif
185
186   posix_check_err (posix_error (result), "pthread_mutex_trylock");
187   return TRUE;
188 }
189
190 static GCond *
191 g_cond_new_posix_impl (void)
192 {
193   GCond *result = (GCond *) g_new (pthread_cond_t, 1);
194   posix_check_cmd (pthread_cond_init ((pthread_cond_t *) result,
195                                       condattr_default));
196   return result;
197 }
198
199 /* pthread_cond_signal, pthread_cond_broadcast and pthread_cond_wait
200    can be taken directly, as signature and semantic are right, but
201    without error check then!!!!, we might want to change this
202    therefore. */
203
204 #define G_NSEC_PER_SEC 1000000000
205
206 static gboolean
207 g_cond_timed_wait_posix_impl (GCond * cond,
208                               GMutex * entered_mutex,
209                               GTimeVal * abs_time)
210 {
211   int result;
212   struct timespec end_time;
213   gboolean timed_out;
214
215   g_return_val_if_fail (cond != NULL, FALSE);
216   g_return_val_if_fail (entered_mutex != NULL, FALSE);
217
218   if (!abs_time)
219     {
220       result = pthread_cond_wait ((pthread_cond_t *)cond,
221                                   (pthread_mutex_t *) entered_mutex);
222       timed_out = FALSE;
223     }
224   else
225     {
226       end_time.tv_sec = abs_time->tv_sec;
227       end_time.tv_nsec = abs_time->tv_usec * (G_NSEC_PER_SEC / G_USEC_PER_SEC);
228
229       g_return_val_if_fail (end_time.tv_nsec < G_NSEC_PER_SEC, TRUE);
230
231       result = pthread_cond_timedwait ((pthread_cond_t *) cond,
232                                        (pthread_mutex_t *) entered_mutex,
233                                        &end_time);
234 #ifdef G_THREADS_IMPL_POSIX
235       timed_out = (result == ETIMEDOUT);
236 #else /* G_THREADS_IMPL_DCE */
237       timed_out = (result == -1) && (errno == EAGAIN);
238 #endif
239     }
240
241   if (!timed_out)
242     posix_check_err (posix_error (result), "pthread_cond_timedwait");
243
244   return !timed_out;
245 }
246
247 static void
248 g_cond_free_posix_impl (GCond * cond)
249 {
250   posix_check_cmd (pthread_cond_destroy ((pthread_cond_t *) cond));
251   g_free (cond);
252 }
253
254 static GPrivate *
255 g_private_new_posix_impl (GDestroyNotify destructor)
256 {
257   GPrivate *result = (GPrivate *) g_new (pthread_key_t, 1);
258   posix_check_cmd (pthread_key_create ((pthread_key_t *) result, destructor));
259   return result;
260 }
261
262 /* NOTE: the functions g_private_get and g_private_set may not use
263    functions from gmem.c and gmessages.c */
264
265 static void
266 g_private_set_posix_impl (GPrivate * private_key, gpointer value)
267 {
268   if (!private_key)
269     return;
270   pthread_setspecific (*(pthread_key_t *) private_key, value);
271 }
272
273 static gpointer
274 g_private_get_posix_impl (GPrivate * private_key)
275 {
276   if (!private_key)
277     return NULL;
278 #ifdef G_THREADS_IMPL_POSIX
279   return pthread_getspecific (*(pthread_key_t *) private_key);
280 #else /* G_THREADS_IMPL_DCE */
281   {
282     void* data;
283     posix_check_cmd (pthread_getspecific (*(pthread_key_t *) private_key,
284                                           &data));
285     return data;
286   }
287 #endif
288 }
289
290 static void
291 g_thread_create_posix_impl (GThreadFunc thread_func,
292                             gpointer arg,
293                             gulong stack_size,
294                             gboolean joinable,
295                             gboolean bound,
296                             GThreadPriority priority,
297                             gpointer thread,
298                             GError **error)
299 {
300   pthread_attr_t attr;
301   gint ret;
302
303   g_return_if_fail (thread_func);
304   g_return_if_fail (priority >= G_THREAD_PRIORITY_LOW);
305   g_return_if_fail (priority <= G_THREAD_PRIORITY_URGENT);
306
307   posix_check_cmd (pthread_attr_init (&attr));
308
309 #ifdef HAVE_PTHREAD_ATTR_SETSTACKSIZE
310   if (stack_size)
311     {
312       stack_size = MAX (g_thread_min_stack_size, stack_size);
313       /* No error check here, because some systems can't do it and
314        * we simply don't want threads to fail because of that. */
315       pthread_attr_setstacksize (&attr, stack_size);
316     }
317 #endif /* HAVE_PTHREAD_ATTR_SETSTACKSIZE */
318
319 #ifdef PTHREAD_SCOPE_SYSTEM
320   if (bound)
321     /* No error check here, because some systems can't do it and we
322      * simply don't want threads to fail because of that. */
323     pthread_attr_setscope (&attr, PTHREAD_SCOPE_SYSTEM);
324 #endif /* PTHREAD_SCOPE_SYSTEM */
325
326 #ifdef G_THREADS_IMPL_POSIX
327   posix_check_cmd (pthread_attr_setdetachstate (&attr,
328           joinable ? PTHREAD_CREATE_JOINABLE : PTHREAD_CREATE_DETACHED));
329 #endif /* G_THREADS_IMPL_POSIX */
330
331 #ifdef HAVE_PRIORITIES
332 # ifdef G_THREADS_IMPL_POSIX
333   {
334     struct sched_param sched;
335     posix_check_cmd (pthread_attr_getschedparam (&attr, &sched));
336     sched.sched_priority = g_thread_priority_map [priority];
337     posix_check_cmd_prio (pthread_attr_setschedparam (&attr, &sched));
338   }
339 # else /* G_THREADS_IMPL_DCE */
340   posix_check_cmd_prio
341     (pthread_attr_setprio (&attr, g_thread_priority_map [priority]));
342 # endif /* G_THREADS_IMPL_DCE */
343 #endif /* HAVE_PRIORITIES */
344   ret = posix_error (pthread_create (thread, &attr,
345                                      (void* (*)(void*))thread_func, arg));
346
347   posix_check_cmd (pthread_attr_destroy (&attr));
348
349   if (ret == EAGAIN)
350     {
351       g_set_error (error, G_THREAD_ERROR, G_THREAD_ERROR_AGAIN, 
352                    "Error creating thread: %s", g_strerror (ret));
353       return;
354     }
355
356   posix_check_err (ret, "pthread_create");
357
358 #ifdef G_THREADS_IMPL_DCE
359   if (!joinable)
360     posix_check_cmd (pthread_detach (thread));
361 #endif /* G_THREADS_IMPL_DCE */
362 }
363
364 static void
365 g_thread_yield_posix_impl (void)
366 {
367   POSIX_YIELD_FUNC;
368 }
369
370 static void
371 g_thread_join_posix_impl (gpointer thread)
372 {
373   gpointer ignore;
374   posix_check_cmd (pthread_join (*(pthread_t*)thread, &ignore));
375 }
376
377 static void
378 g_thread_exit_posix_impl (void)
379 {
380   pthread_exit (NULL);
381 }
382
383 static void
384 g_thread_set_priority_posix_impl (gpointer thread, GThreadPriority priority)
385 {
386   g_return_if_fail (priority >= G_THREAD_PRIORITY_LOW);
387   g_return_if_fail (priority <= G_THREAD_PRIORITY_URGENT);
388 #ifdef HAVE_PRIORITIES
389 # ifdef G_THREADS_IMPL_POSIX
390   {
391     struct sched_param sched;
392     int policy;
393     posix_check_cmd (pthread_getschedparam (*(pthread_t*)thread, &policy,
394                                             &sched));
395     sched.sched_priority = g_thread_priority_map [priority];
396     posix_check_cmd_prio (pthread_setschedparam (*(pthread_t*)thread, policy,
397                                                  &sched));
398   }
399 # else /* G_THREADS_IMPL_DCE */
400   posix_check_cmd_prio (pthread_setprio (*(pthread_t*)thread,
401                                          g_thread_priority_map [priority]));
402 # endif
403 #endif /* HAVE_PRIORITIES */
404 }
405
406 static void
407 g_thread_self_posix_impl (gpointer thread)
408 {
409   *(pthread_t*)thread = pthread_self();
410 }
411
412 static gboolean
413 g_thread_equal_posix_impl (gpointer thread1, gpointer thread2)
414 {
415   return (pthread_equal (*(pthread_t*)thread1, *(pthread_t*)thread2) != 0);
416 }
417
418 static GThreadFunctions g_thread_functions_for_glib_use_default =
419 {
420   g_mutex_new_posix_impl,
421   (void (*)(GMutex *)) pthread_mutex_lock,
422   g_mutex_trylock_posix_impl,
423   (void (*)(GMutex *)) pthread_mutex_unlock,
424   g_mutex_free_posix_impl,
425   g_cond_new_posix_impl,
426   (void (*)(GCond *)) pthread_cond_signal,
427   (void (*)(GCond *)) pthread_cond_broadcast,
428   (void (*)(GCond *, GMutex *)) pthread_cond_wait,
429   g_cond_timed_wait_posix_impl,
430   g_cond_free_posix_impl,
431   g_private_new_posix_impl,
432   g_private_get_posix_impl,
433   g_private_set_posix_impl,
434   g_thread_create_posix_impl,
435   g_thread_yield_posix_impl,
436   g_thread_join_posix_impl,
437   g_thread_exit_posix_impl,
438   g_thread_set_priority_posix_impl,
439   g_thread_self_posix_impl,
440   g_thread_equal_posix_impl
441 };