G_OS_FOO #defines. I *think* I got the cygwin and beos stuff right, but
[platform/upstream/glib.git] / glib / gthread.c
1 /* GLIB - Library of useful routines for C programming
2  * Copyright (C) 1995-1997  Peter Mattis, Spencer Kimball and Josh MacDonald
3  *
4  * gmutex.c: MT safety related functions
5  * Copyright 1998 Sebastian Wilhelmi; University of Karlsruhe
6  *                Owen Taylor
7  *
8  * This library is free software; you can redistribute it and/or
9  * modify it under the terms of the GNU Library General Public
10  * License as published by the Free Software Foundation; either
11  * version 2 of the License, or (at your option) any later version.
12  *
13  * This library is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
16  * Library General Public License for more details.
17  *
18  * You should have received a copy of the GNU Library General Public
19  * License along with this library; if not, write to the
20  * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
21  * Boston, MA 02111-1307, USA.
22  */
23
24 /*
25  * Modified by the GLib Team and others 1997-1999.  See the AUTHORS
26  * file for a list of people on the GLib Team.  See the ChangeLog
27  * files for a list of changes.  These files are distributed with
28  * GLib at ftp://ftp.gtk.org/pub/gtk/. 
29  */
30
31 /* 
32  * MT safe
33  */
34
35 #include "config.h"
36 #include "glib.h"
37
38 #ifdef HAVE_UNISTD_H
39 #include <unistd.h>
40 #endif
41
42 typedef struct _GRealThread GRealThread;
43
44 struct  _GRealThread
45 {
46   GThread thread;
47   GThreadFunc func;
48   gpointer arg;
49   gpointer system_thread;
50   gpointer private_data;
51 };
52
53 typedef struct _GStaticPrivateNode GStaticPrivateNode;
54
55 struct _GStaticPrivateNode
56 {
57   gpointer       data;
58   GDestroyNotify destroy;
59 };
60
61 static void g_thread_cleanup (gpointer data);
62 static void g_thread_fail (void);
63
64 /* Global variables */
65
66 gboolean g_thread_use_default_impl = TRUE;
67 gboolean g_threads_got_initialized = FALSE;
68
69 #if defined(G_OS_WIN32) && defined(__GNUC__)
70 __declspec(dllexport)
71 #endif
72 GThreadFunctions g_thread_functions_for_glib_use = {
73   (GMutex*(*)())g_thread_fail,                 /* mutex_new */
74   NULL,                                        /* mutex_lock */
75   NULL,                                        /* mutex_trylock */
76   NULL,                                        /* mutex_unlock */
77   NULL,                                        /* mutex_free */
78   (GCond*(*)())g_thread_fail,                  /* cond_new */
79   NULL,                                        /* cond_signal */
80   NULL,                                        /* cond_broadcast */
81   NULL,                                        /* cond_wait */
82   NULL,                                        /* cond_timed_wait  */
83   NULL,                                        /* cond_free */
84   (GPrivate*(*)(GDestroyNotify))g_thread_fail, /* private_new */
85   NULL,                                        /* private_get */
86   NULL,                                        /* private_set */
87   (gpointer(*)(GThreadFunc, gpointer, gulong, 
88                gboolean, gboolean, 
89                GThreadPriority))g_thread_fail, /* thread_create */
90   NULL,                                        /* thread_yield */
91   NULL,                                        /* thread_join */
92   NULL,                                        /* thread_exit */
93   NULL,                                        /* thread_set_priority */
94   NULL                                         /* thread_self */
95 }; 
96
97 /* Local data */
98
99 static GMutex   *g_mutex_protect_static_mutex_allocation = NULL;
100 static GMutex   *g_thread_specific_mutex = NULL;
101 static GPrivate *g_thread_specific_private = NULL;
102
103 /* This must be called only once, before any threads are created.
104  * It will only be called from g_thread_init() in -lgthread.
105  */
106 void
107 g_mutex_init (void)
108 {
109   gpointer private_old;
110  
111   /* We let the main thread (the one that calls g_thread_init) inherit
112    * the data, that it set before calling g_thread_init
113    */
114   private_old = g_thread_specific_private;
115
116   g_thread_specific_private = g_private_new (g_thread_cleanup);
117
118   /* we can not use g_private_set here, as g_threads_got_initialized is not
119    * yet set TRUE, whereas the private_set function is already set.
120    */
121   g_thread_functions_for_glib_use.private_set (g_thread_specific_private, 
122                                                private_old);
123
124   g_mutex_protect_static_mutex_allocation = g_mutex_new();
125   g_thread_specific_mutex = g_mutex_new();
126   
127 }
128
129 GMutex *
130 g_static_mutex_get_mutex_impl (GMutex** mutex)
131 {
132   if (!g_thread_supported ())
133     return NULL;
134
135   g_assert (g_mutex_protect_static_mutex_allocation);
136
137   g_mutex_lock (g_mutex_protect_static_mutex_allocation);
138
139   if (!(*mutex)) 
140     *mutex = g_mutex_new(); 
141
142   g_mutex_unlock (g_mutex_protect_static_mutex_allocation);
143   
144   return *mutex;
145 }
146
147 #ifndef g_static_rec_mutex_lock
148 /* That means, that g_static_rec_mutex_lock is not defined to be 
149  * g_static_mutex_lock, we have to provide an implementation ourselves.
150  */
151 void
152 g_static_rec_mutex_lock (GStaticRecMutex* mutex)
153 {
154   guint counter = GPOINTER_TO_UINT (g_static_private_get (&mutex->counter));
155   if (counter == 0)
156     {
157       g_static_mutex_lock (&mutex->mutex);
158     }
159   counter++;
160   g_static_private_set (&mutex->counter, GUINT_TO_POINTER (counter), NULL);
161 }
162
163 gboolean
164 g_static_rec_mutex_trylock (GStaticRecMutex* mutex)
165 {
166   guint counter = GPOINTER_TO_UINT (g_static_private_get (&mutex->counter));
167   if (counter == 0)
168     {
169       if (!g_static_mutex_trylock (&mutex->mutex)) return FALSE;
170     }
171   counter++;
172   g_static_private_set (&mutex->counter, GUINT_TO_POINTER (counter), NULL);
173   return TRUE;
174 }
175
176 void
177 g_static_rec_mutex_unlock (GStaticRecMutex* mutex)
178 {
179   guint counter = GPOINTER_TO_UINT (g_static_private_get (&mutex->counter));
180   if (counter == 1)
181     {
182       g_static_mutex_unlock (&mutex->mutex);
183     }
184   counter--;
185   g_static_private_set (&mutex->counter, GUINT_TO_POINTER (counter), NULL);
186 }
187 #endif /* g_static_rec_mutex_lock */
188
189 gpointer
190 g_static_private_get (GStaticPrivate *private_key)
191 {
192   return g_static_private_get_for_thread (private_key, g_thread_self ());
193 }
194
195 gpointer
196 g_static_private_get_for_thread (GStaticPrivate *private_key,
197                                  GThread        *thread)
198 {
199   GArray *array;
200   GRealThread *self = (GRealThread*) thread;
201
202   g_return_val_if_fail (thread, NULL);
203
204   array = self->private_data;
205   if (!array)
206     return NULL;
207
208   if (!private_key->index)
209     return NULL;
210   else if (private_key->index <= array->len)
211     return g_array_index (array, GStaticPrivateNode, private_key->index - 1).data;
212   else
213     return NULL;
214 }
215
216 void
217 g_static_private_set (GStaticPrivate *private_key, 
218                       gpointer        data,
219                       GDestroyNotify  notify)
220 {
221   g_static_private_set_for_thread (private_key, g_thread_self (), 
222                                    data, notify);
223 }
224
225 void
226 g_static_private_set_for_thread (GStaticPrivate *private_key, 
227                                  GThread        *thread,
228                                  gpointer        data,
229                                  GDestroyNotify  notify)
230 {
231   GArray *array;
232   GRealThread *self =(GRealThread*) thread;
233   static guint next_index = 0;
234   GStaticPrivateNode *node;
235
236   g_return_if_fail (thread);
237   
238   array = self->private_data;
239   if (!array)
240     {
241       array = g_array_new (FALSE, TRUE, sizeof (GStaticPrivateNode));
242       self->private_data = array;
243     }
244
245   if (!private_key->index)
246     {
247       g_mutex_lock (g_thread_specific_mutex);
248
249       if (!private_key->index)
250         private_key->index = ++next_index;
251
252       g_mutex_unlock (g_thread_specific_mutex);
253     }
254
255   if (private_key->index > array->len)
256     g_array_set_size (array, private_key->index);
257
258   node = &g_array_index (array, GStaticPrivateNode, private_key->index - 1);
259   if (node->destroy)
260     {
261       gpointer ddata = node->data;
262       GDestroyNotify ddestroy = node->destroy;
263
264       node->data = data;
265       node->destroy = notify;
266
267       ddestroy (ddata);
268     }
269   else
270     {
271       node->data = data;
272       node->destroy = notify;
273     }
274 }
275
276 static void
277 g_thread_cleanup (gpointer data)
278 {
279   if (data)
280     {
281       GRealThread* thread = data;
282       if (thread->private_data)
283         {
284           GArray* array = thread->private_data;
285           guint i;
286           
287           for (i = 0; i < array->len; i++ )
288             {
289               GStaticPrivateNode *node = 
290                 &g_array_index (array, GStaticPrivateNode, i);
291               if (node->destroy)
292                 node->destroy (node->data);
293             }
294           g_array_free (array, TRUE);
295         }
296       /* We only free the thread structure, if it isn't joinable. If
297          it is, the structure is freed in g_thread_join */
298       if (!thread->thread.joinable)
299         {
300           /* Just to make sure, this isn't used any more */
301           thread->system_thread = NULL;
302           g_free (thread);
303         }
304     }
305 }
306
307 static void
308 g_thread_fail (void)
309 {
310   g_error ("The thread system is not yet initialized.");
311 }
312
313 G_LOCK_DEFINE_STATIC (g_thread_create);
314
315 static void 
316 g_thread_create_proxy (gpointer data)
317 {
318   GRealThread* thread = data;
319
320   g_assert (data);
321
322   /* the lock makes sure, that thread->system_thread is written,
323      before thread->func is called. See g_thread_create */
324
325   G_LOCK (g_thread_create);
326   g_private_set (g_thread_specific_private, data);
327   G_UNLOCK (g_thread_create);
328
329   thread->func (thread->arg);
330 }
331
332 GThread* 
333 g_thread_create (GThreadFunc             thread_func,
334                  gpointer                arg,
335                  gulong                  stack_size,
336                  gboolean                joinable,
337                  gboolean                bound,
338                  GThreadPriority         priority)
339 {
340   GRealThread* result = g_new0 (GRealThread,1);
341
342   g_return_val_if_fail (thread_func, NULL);
343   
344   result->thread.joinable = joinable;
345   result->thread.bound = bound;
346   result->thread.priority = priority;
347   result->func = thread_func;
348   result->arg = arg;
349   G_LOCK (g_thread_create);
350   result->system_thread = G_THREAD_UF (thread_create, (g_thread_create_proxy, 
351                                                        result, stack_size, 
352                                                        joinable, bound, 
353                                                        priority));
354   G_UNLOCK (g_thread_create);
355   return (GThread*) result;
356 }
357
358 void 
359 g_thread_join (GThread* thread)
360 {
361   GRealThread* real = (GRealThread*) thread;
362
363   g_return_if_fail (thread);
364   g_return_if_fail (thread->joinable);
365   g_return_if_fail (real->system_thread);
366
367   G_THREAD_UF (thread_join, (real->system_thread));
368
369   /* Just to make sure, this isn't used any more */
370   thread->joinable = 0;
371   real->system_thread = NULL;
372
373   /* the thread structure for non-joinable threads is freed upon
374      thread end. We free the memory here. This will leave loose end,
375      if a joinable thread is not joined. */
376
377   g_free (thread);
378 }
379
380 void
381 g_thread_set_priority (GThread* thread, 
382                        GThreadPriority priority)
383 {
384   GRealThread* real = (GRealThread*) thread;
385
386   g_return_if_fail (thread);
387   g_return_if_fail (real->system_thread);
388
389   thread->priority = priority;
390   G_THREAD_CF (thread_set_priority, (void)0, (real->system_thread, priority));
391 }
392
393 GThread*
394 g_thread_self()
395 {
396   GRealThread* thread = g_private_get (g_thread_specific_private);
397
398   if (!thread)
399     {  
400       /* If no thread data is available, provide and set one.  This
401          can happen for the main thread and for threads, that are not
402          created by glib. */
403       thread = g_new (GRealThread,1);
404       thread->thread.joinable = FALSE; /* This is a save guess */
405       thread->thread.bound = TRUE; /* This isn't important at all */
406       thread->thread.priority = G_THREAD_PRIORITY_NORMAL; /* This is
407                                                              just a guess */
408       thread->func = NULL;
409       thread->arg = NULL;
410       thread->system_thread = NULL;
411       thread->private_data = NULL;
412       g_private_set (g_thread_specific_private, thread);
413     }
414      
415   if (g_thread_supported () && !thread->system_thread)
416     {
417       thread->system_thread = g_thread_functions_for_glib_use.thread_self();
418     }
419
420   return (GThread*)thread;
421 }
422
423 static void inline g_static_rw_lock_wait (GCond** cond, GStaticMutex* mutex)
424 {
425   if (!*cond)
426       *cond = g_cond_new ();
427   g_cond_wait (*cond, g_static_mutex_get_mutex (mutex));
428 }
429
430 static void inline g_static_rw_lock_signal (GStaticRWLock* lock)
431 {
432   if (lock->want_to_write && lock->write_cond)
433     g_cond_signal (lock->write_cond);
434   else if (lock->read_cond)
435     g_cond_signal (lock->read_cond);
436 }
437
438 void g_static_rw_lock_reader_lock (GStaticRWLock* lock)
439 {
440   g_return_if_fail (lock);
441
442   if (!g_threads_got_initialized)
443     return;
444
445   g_static_mutex_lock (&lock->mutex);
446   while (lock->write || lock->want_to_write) 
447     g_static_rw_lock_wait (&lock->read_cond, &lock->mutex);
448   lock->read_counter++;
449   g_static_mutex_unlock (&lock->mutex);
450 }
451
452 gboolean g_static_rw_lock_reader_trylock (GStaticRWLock* lock)
453 {
454   gboolean ret_val = FALSE;
455
456   g_return_val_if_fail (lock, FALSE);
457
458   if (!g_threads_got_initialized)
459     return TRUE;
460
461   g_static_mutex_lock (&lock->mutex);
462   if (!lock->write && !lock->want_to_write)
463     {
464       lock->read_counter++;
465       ret_val = TRUE;
466     }
467   g_static_mutex_unlock (&lock->mutex);
468   return ret_val;
469 }
470
471 void g_static_rw_lock_reader_unlock  (GStaticRWLock* lock)
472 {
473   g_return_if_fail (lock);
474
475   if (!g_threads_got_initialized)
476     return;
477
478   g_static_mutex_lock (&lock->mutex);
479   lock->read_counter--;
480   g_static_rw_lock_signal (lock);
481   g_static_mutex_unlock (&lock->mutex);
482 }
483
484 void g_static_rw_lock_writer_lock (GStaticRWLock* lock)
485 {
486   g_return_if_fail (lock);
487
488   if (!g_threads_got_initialized)
489     return;
490
491   g_static_mutex_lock (&lock->mutex);
492   lock->want_to_write++;
493   while (lock->write || lock->read_counter)
494     g_static_rw_lock_wait (&lock->write_cond, &lock->mutex);
495   lock->want_to_write--;
496   lock->write = TRUE;
497   g_static_mutex_unlock (&lock->mutex);
498 }
499
500 gboolean g_static_rw_lock_writer_trylock (GStaticRWLock* lock)
501 {
502   gboolean ret_val = FALSE;
503
504   g_return_val_if_fail (lock, FALSE);
505   
506   if (!g_threads_got_initialized)
507     return TRUE;
508
509   g_static_mutex_lock (&lock->mutex);
510   if (!lock->write && !lock->read_counter)
511     {
512       lock->write = TRUE;
513       ret_val = TRUE;
514     }
515   g_static_mutex_unlock (&lock->mutex);
516   return ret_val;
517 }
518
519 void g_static_rw_lock_writer_unlock (GStaticRWLock* lock)
520 {
521   g_return_if_fail (lock);
522   
523   if (!g_threads_got_initialized)
524     return;
525
526   g_static_mutex_lock (&lock->mutex);
527   lock->write = FALSE; 
528   g_static_rw_lock_signal (lock);
529   g_static_mutex_unlock (&lock->mutex);
530 }
531
532 void g_static_rw_lock_free (GStaticRWLock* lock)
533 {
534   g_return_if_fail (lock);
535   
536   if (lock->read_cond)
537     g_cond_free (lock->read_cond);
538   if (lock->write_cond)
539     g_cond_free (lock->write_cond);
540   
541 }
542