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