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