Do a comparison, not an assignment, stupid! Spotted by Daniel Elstner
[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 # ifdef __FreeBSD__
101    /* FreeBSD threads use different priority values from the POSIX_
102     * defines so we just set them here. The corresponding macros
103     * PTHREAD_MIN_PRIORITY and PTHREAD_MAX_PRIORITY are implied to be
104     * exported by the docs, but they aren't.
105     */
106 #  define PRIORITY_LOW_VALUE      0
107 #  define PRIORITY_URGENT_VALUE   31
108 # else /* !__FreeBSD__ */
109 #  define PRIORITY_LOW_VALUE POSIX_MIN_PRIORITY
110 #  define PRIORITY_URGENT_VALUE POSIX_MAX_PRIORITY
111 # endif /* !__FreeBSD__ */
112 #endif /* POSIX_MIN_PRIORITY && POSIX_MAX_PRIORITY */
113
114 static gulong g_thread_min_stack_size = 0;
115
116 #define G_MUTEX_SIZE (sizeof (pthread_mutex_t))
117
118 #ifdef _SC_THREAD_STACK_MIN
119 #define HAVE_G_THREAD_IMPL_INIT
120 static void 
121 g_thread_impl_init()
122 {
123   g_thread_min_stack_size = MAX (sysconf (_SC_THREAD_STACK_MIN), 0);
124 }
125 #endif /* _SC_THREAD_STACK_MIN */
126
127 static GMutex *
128 g_mutex_new_posix_impl (void)
129 {
130   GMutex *result = (GMutex *) g_new (pthread_mutex_t, 1);
131   posix_check_cmd (pthread_mutex_init ((pthread_mutex_t *) result, 
132                                        mutexattr_default));
133   return result;
134 }
135
136 static void
137 g_mutex_free_posix_impl (GMutex * mutex)
138 {
139   posix_check_cmd (pthread_mutex_destroy ((pthread_mutex_t *) mutex));
140   g_free (mutex);
141 }
142
143 /* NOTE: the functions g_mutex_lock and g_mutex_unlock may not use
144    functions from gmem.c and gmessages.c; */
145
146 /* pthread_mutex_lock, pthread_mutex_unlock can be taken directly, as
147    signature and semantic are right, but without error check then!!!!,
148    we might want to change this therefore. */
149
150 static gboolean
151 g_mutex_trylock_posix_impl (GMutex * mutex)
152 {
153   int result;
154
155   result = pthread_mutex_trylock ((pthread_mutex_t *) mutex);
156
157 #ifdef G_THREADS_IMPL_POSIX
158   if (result == EBUSY)
159     return FALSE;
160 #else /* G_THREADS_IMPL_DCE */
161   if (result == 0)
162     return FALSE;
163 #endif
164
165   posix_check_err (posix_error (result), "pthread_mutex_trylock");
166   return TRUE;
167 }
168
169 static GCond *
170 g_cond_new_posix_impl (void)
171 {
172   GCond *result = (GCond *) g_new (pthread_cond_t, 1);
173   posix_check_cmd (pthread_cond_init ((pthread_cond_t *) result, 
174                                       condattr_default));
175   return result;
176 }
177
178 /* pthread_cond_signal, pthread_cond_broadcast and pthread_cond_wait
179    can be taken directly, as signature and semantic are right, but
180    without error check then!!!!, we might want to change this
181    therfore. */
182
183 #define G_NSEC_PER_SEC 1000000000
184
185 static gboolean
186 g_cond_timed_wait_posix_impl (GCond * cond,
187                               GMutex * entered_mutex,
188                               GTimeVal * abs_time)
189 {
190   int result;
191   struct timespec end_time;
192   gboolean timed_out;
193
194   g_return_val_if_fail (cond != NULL, FALSE);
195   g_return_val_if_fail (entered_mutex != NULL, FALSE);
196
197   if (!abs_time)
198     {
199       g_cond_wait (cond, entered_mutex);
200       return TRUE;
201     }
202
203   end_time.tv_sec = abs_time->tv_sec;
204   end_time.tv_nsec = abs_time->tv_usec * (G_NSEC_PER_SEC / G_USEC_PER_SEC);
205
206   g_return_val_if_fail (end_time.tv_nsec < G_NSEC_PER_SEC, TRUE);
207
208   result = pthread_cond_timedwait ((pthread_cond_t *) cond,
209                                    (pthread_mutex_t *) entered_mutex,
210                                    &end_time);
211
212 #ifdef G_THREADS_IMPL_POSIX
213   timed_out = (result == ETIMEDOUT);
214 #else /* G_THREADS_IMPL_DCE */
215   timed_out = (result == -1) && (errno == EAGAIN);
216 #endif
217
218   if (!timed_out)
219     posix_check_err (posix_error (result), "pthread_cond_timedwait");
220   return !timed_out;
221 }
222
223 static void
224 g_cond_free_posix_impl (GCond * cond)
225 {
226   posix_check_cmd (pthread_cond_destroy ((pthread_cond_t *) cond));
227   g_free (cond);
228 }
229
230 static GPrivate *
231 g_private_new_posix_impl (GDestroyNotify destructor)
232 {
233   GPrivate *result = (GPrivate *) g_new (pthread_key_t, 1);
234   posix_check_cmd (pthread_key_create ((pthread_key_t *) result, destructor));
235   return result;
236 }
237
238 /* NOTE: the functions g_private_get and g_private_set may not use
239    functions from gmem.c and gmessages.c */
240
241 static void
242 g_private_set_posix_impl (GPrivate * private_key, gpointer value)
243 {
244   if (!private_key)
245     return;
246   pthread_setspecific (*(pthread_key_t *) private_key, value);
247 }
248
249 static gpointer
250 g_private_get_posix_impl (GPrivate * private_key)
251 {
252   if (!private_key)
253     return NULL;
254 #ifdef G_THREADS_IMPL_POSIX
255   return pthread_getspecific (*(pthread_key_t *) private_key);
256 #else /* G_THREADS_IMPL_DCE */
257   {
258     void* data;
259     posix_check_cmd (pthread_getspecific (*(pthread_key_t *) private_key, 
260                                           &data));
261     return data;
262   }
263 #endif
264 }
265
266 static void
267 g_thread_create_posix_impl (GThreadFunc thread_func, 
268                             gpointer arg, 
269                             gulong stack_size,
270                             gboolean joinable,
271                             gboolean bound,
272                             GThreadPriority priority,
273                             gpointer thread,
274                             GError **error)
275 {
276   pthread_attr_t attr;
277   gint ret;
278
279   g_return_if_fail (thread_func);
280   g_return_if_fail (priority >= G_THREAD_PRIORITY_LOW);
281   g_return_if_fail (priority <= G_THREAD_PRIORITY_URGENT);
282
283   posix_check_cmd (pthread_attr_init (&attr));
284   
285 #ifdef HAVE_PTHREAD_ATTR_SETSTACKSIZE
286   if (stack_size)
287     {
288       stack_size = MAX (g_thread_min_stack_size, stack_size);
289       posix_check_cmd (pthread_attr_setstacksize (&attr, stack_size));
290     }
291 #endif /* HAVE_PTHREAD_ATTR_SETSTACKSIZE */
292
293 #ifdef PTHREAD_SCOPE_SYSTEM
294   if (bound)
295     /* No error check here, because some systems can't do it and we
296      * simply don't want threads to fail because of that. */
297     pthread_attr_setscope (&attr, PTHREAD_SCOPE_SYSTEM);
298 #endif /* PTHREAD_SCOPE_SYSTEM */
299
300 #ifdef G_THREADS_IMPL_POSIX
301   posix_check_cmd (pthread_attr_setdetachstate (&attr,
302           joinable ? PTHREAD_CREATE_JOINABLE : PTHREAD_CREATE_DETACHED));
303 #endif /* G_THREADS_IMPL_POSIX */
304   
305 #ifdef HAVE_PRIORITIES
306 # ifdef G_THREADS_IMPL_POSIX
307   {
308     struct sched_param sched;
309     posix_check_cmd (pthread_attr_getschedparam (&attr, &sched));
310     sched.sched_priority = g_thread_priority_map [priority];
311     posix_check_cmd_prio (pthread_attr_setschedparam (&attr, &sched));
312   }
313 # else /* G_THREADS_IMPL_DCE */
314   posix_check_cmd_prio 
315     (pthread_attr_setprio (&attr, g_thread_priority_map [priority]));
316 # endif /* G_THREADS_IMPL_DCE */
317 #endif /* HAVE_PRIORITIES */
318   ret = posix_error (pthread_create (thread, &attr, 
319                                      (void* (*)(void*))thread_func, arg));
320
321   posix_check_cmd (pthread_attr_destroy (&attr));
322
323   if (ret == EAGAIN)
324     {
325       g_set_error (error, G_THREAD_ERROR, G_THREAD_ERROR_AGAIN, 
326                    "Error creating thread: %s", g_strerror (ret));
327       return;
328     }
329
330   posix_check_err (ret, "pthread_create");
331
332 #ifdef G_THREADS_IMPL_DCE
333   if (!joinable)
334     posix_check_cmd (pthread_detach (thread));
335 #endif /* G_THREADS_IMPL_DCE */
336 }
337
338 static void 
339 g_thread_yield_posix_impl (void)
340 {
341   POSIX_YIELD_FUNC;
342 }
343
344 static void
345 g_thread_join_posix_impl (gpointer thread)
346 {     
347   gpointer ignore;
348   posix_check_cmd (pthread_join (*(pthread_t*)thread, &ignore));
349 }
350
351 static void 
352 g_thread_exit_posix_impl (void) 
353 {
354   pthread_exit (NULL);
355 }
356
357 static void
358 g_thread_set_priority_posix_impl (gpointer thread, GThreadPriority priority)
359 {
360   g_return_if_fail (priority >= G_THREAD_PRIORITY_LOW);
361   g_return_if_fail (priority <= G_THREAD_PRIORITY_URGENT);
362 #ifdef HAVE_PRIORITIES
363 # ifdef G_THREADS_IMPL_POSIX
364   {
365     struct sched_param sched;
366     int policy;
367     posix_check_cmd (pthread_getschedparam (*(pthread_t*)thread, &policy, 
368                                             &sched));
369     sched.sched_priority = g_thread_priority_map [priority];
370     posix_check_cmd_prio (pthread_setschedparam (*(pthread_t*)thread, policy, 
371                                                  &sched));
372   }
373 # else /* G_THREADS_IMPL_DCE */
374   posix_check_cmd_prio (pthread_setprio (*(pthread_t*)thread, 
375                                          g_thread_priority_map [priority]));
376 # endif
377 #endif /* HAVE_PRIORITIES */
378 }
379
380 static void
381 g_thread_self_posix_impl (gpointer thread)
382 {
383   *(pthread_t*)thread = pthread_self();
384 }
385
386 static gboolean
387 g_thread_equal_posix_impl (gpointer thread1, gpointer thread2)
388 {
389   return (pthread_equal (*(pthread_t*)thread1, *(pthread_t*)thread2) != 0);
390 }
391
392 static GThreadFunctions g_thread_functions_for_glib_use_default =
393 {
394   g_mutex_new_posix_impl,
395   (void (*)(GMutex *)) pthread_mutex_lock,
396   g_mutex_trylock_posix_impl,
397   (void (*)(GMutex *)) pthread_mutex_unlock,
398   g_mutex_free_posix_impl,
399   g_cond_new_posix_impl,
400   (void (*)(GCond *)) pthread_cond_signal,
401   (void (*)(GCond *)) pthread_cond_broadcast,
402   (void (*)(GCond *, GMutex *)) pthread_cond_wait,
403   g_cond_timed_wait_posix_impl,
404   g_cond_free_posix_impl,
405   g_private_new_posix_impl,
406   g_private_get_posix_impl,
407   g_private_set_posix_impl,
408   g_thread_create_posix_impl,
409   g_thread_yield_posix_impl,
410   g_thread_join_posix_impl,
411   g_thread_exit_posix_impl,
412   g_thread_set_priority_posix_impl,
413   g_thread_self_posix_impl,
414   g_thread_equal_posix_impl
415 };