515be1a548889bb57bd56ee493b0098b686897c9
[platform/upstream/glib.git] / glib / gthread.h
1 /* GLIB - Library of useful routines for C programming
2  * Copyright (C) 1995-1997  Peter Mattis, Spencer Kimball and Josh MacDonald
3  *
4  * This library is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU Lesser General Public
6  * License as published by the Free Software Foundation; either
7  * version 2 of the License, or (at your option) any later version.
8  *
9  * This library is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
12  * Lesser General Public License for more details.
13  *
14  * You should have received a copy of the GNU Lesser General Public
15  * License along with this library; if not, write to the
16  * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
17  * Boston, MA 02111-1307, USA.
18  */
19
20 /*
21  * Modified by the GLib Team and others 1997-2000.  See the AUTHORS
22  * file for a list of people on the GLib Team.  See the ChangeLog
23  * files for a list of changes.  These files are distributed with
24  * GLib at ftp://ftp.gtk.org/pub/gtk/. 
25  */
26
27 #ifndef __G_THREAD_H__
28 #define __G_THREAD_H__
29
30 #include <glib/gerror.h>
31 #include <glib/gtypes.h>
32 #include <glib/gutils.h>        /* for G_INLINE_FUNC */
33 #include <glib/gatomic.h>       /* for g_atomic_pointer_get */
34
35 G_BEGIN_DECLS
36
37 /* GLib Thread support
38  */
39
40 extern GQuark g_thread_error_quark (void);
41 #define G_THREAD_ERROR g_thread_error_quark ()
42
43 typedef enum
44 {
45   G_THREAD_ERROR_AGAIN /* Resource temporarily unavailable */
46 } GThreadError;
47
48 typedef gpointer (*GThreadFunc) (gpointer data);
49
50 typedef enum
51 {
52   G_THREAD_PRIORITY_LOW,
53   G_THREAD_PRIORITY_NORMAL,
54   G_THREAD_PRIORITY_HIGH,
55   G_THREAD_PRIORITY_URGENT
56 } GThreadPriority;
57
58 typedef struct _GThread         GThread;
59 struct  _GThread
60 {
61   /*< private >*/
62   GThreadFunc func;
63   gpointer data;
64   gboolean joinable;
65   GThreadPriority priority;
66 };
67
68 typedef struct _GMutex          GMutex;
69 typedef struct _GCond           GCond;
70 typedef struct _GPrivate        GPrivate;
71 typedef struct _GStaticPrivate  GStaticPrivate;
72
73 typedef struct _GThreadFunctions GThreadFunctions;
74 struct _GThreadFunctions
75 {
76   GMutex*  (*mutex_new)           (void);
77   void     (*mutex_lock)          (GMutex               *mutex);
78   gboolean (*mutex_trylock)       (GMutex               *mutex);
79   void     (*mutex_unlock)        (GMutex               *mutex);
80   void     (*mutex_free)          (GMutex               *mutex);
81   GCond*   (*cond_new)            (void);
82   void     (*cond_signal)         (GCond                *cond);
83   void     (*cond_broadcast)      (GCond                *cond);
84   void     (*cond_wait)           (GCond                *cond,
85                                    GMutex               *mutex);
86   gboolean (*cond_timed_wait)     (GCond                *cond,
87                                    GMutex               *mutex,
88                                    GTimeVal             *end_time);
89   void      (*cond_free)          (GCond                *cond);
90   GPrivate* (*private_new)        (GDestroyNotify        destructor);
91   gpointer  (*private_get)        (GPrivate             *private_key);
92   void      (*private_set)        (GPrivate             *private_key,
93                                    gpointer              data);
94   void      (*thread_create)      (GThreadFunc           func,
95                                    gpointer              data,
96                                    gulong                stack_size,
97                                    gboolean              joinable,
98                                    gboolean              bound,
99                                    GThreadPriority       priority,
100                                    gpointer              thread,
101                                    GError              **error);
102   void      (*thread_yield)       (void);
103   void      (*thread_join)        (gpointer              thread);
104   void      (*thread_exit)        (void);
105   void      (*thread_set_priority)(gpointer              thread,
106                                    GThreadPriority       priority);
107   void      (*thread_self)        (gpointer              thread);
108   gboolean  (*thread_equal)       (gpointer              thread1,
109                                    gpointer              thread2);
110 };
111
112 GLIB_VAR GThreadFunctions       g_thread_functions_for_glib_use;
113 GLIB_VAR gboolean               g_thread_use_default_impl;
114 GLIB_VAR gboolean               g_threads_got_initialized;
115
116 GLIB_VAR guint64   (*g_thread_gettime) (void);
117
118 /* initializes the mutex/cond/private implementation for glib, might
119  * only be called once, and must not be called directly or indirectly
120  * from another glib-function, e.g. as a callback.
121  */
122 void    g_thread_init   (GThreadFunctions       *vtable);
123
124 /* Errorcheck mutexes. If you define G_ERRORCHECK_MUTEXES, then all
125  * mutexes will check for re-locking and re-unlocking */
126
127 /* Initialize thread system with errorcheck mutexes. vtable must be
128  * NULL. Do not call directly. Use #define G_ERRORCHECK_MUTEXES
129  * instead.
130  */
131 void    g_thread_init_with_errorcheck_mutexes (GThreadFunctions* vtable);
132
133 /* A random number to recognize debug calls to g_mutex_... */
134 #define G_MUTEX_DEBUG_MAGIC 0xf8e18ad7
135
136 #ifdef G_ERRORCHECK_MUTEXES
137 #define g_thread_init(vtable) g_thread_init_with_errorcheck_mutexes (vtable)
138 #endif
139
140 /* internal function for fallback static mutex implementation */
141 GMutex* g_static_mutex_get_mutex_impl   (GMutex **mutex);
142
143 #ifdef __cplusplus
144 #define g_static_mutex_get_mutex_impl_shortcut(mutex) \
145   (g_atomic_pointer_get ((gpointer*)(void*)mutex) ? *(mutex) : \
146    g_static_mutex_get_mutex_impl (mutex))
147 #else
148 #define g_static_mutex_get_mutex_impl_shortcut(mutex) \
149   (g_atomic_pointer_get (mutex) ? *(mutex) : \
150    g_static_mutex_get_mutex_impl (mutex))
151 #endif
152
153 /* shorthands for conditional and unconditional function calls */
154
155 #define G_THREAD_UF(op, arglist)                                        \
156     (*g_thread_functions_for_glib_use . op) arglist
157 #define G_THREAD_CF(op, fail, arg)                                      \
158     (g_thread_supported () ? G_THREAD_UF (op, arg) : (fail))
159 #define G_THREAD_ECF(op, fail, mutex, type)                             \
160     (g_thread_supported () ?                                            \
161       ((type(*)(GMutex*, const gulong, gchar const*))                   \
162       (*g_thread_functions_for_glib_use . op))                          \
163      (mutex, G_MUTEX_DEBUG_MAGIC, G_STRLOC) : (fail))
164
165 #ifndef G_ERRORCHECK_MUTEXES
166 # define g_mutex_lock(mutex)                                            \
167     G_THREAD_CF (mutex_lock,     (void)0, (mutex))
168 # define g_mutex_trylock(mutex)                                         \
169     G_THREAD_CF (mutex_trylock,  TRUE,    (mutex))
170 # define g_mutex_unlock(mutex)                                          \
171     G_THREAD_CF (mutex_unlock,   (void)0, (mutex))
172 # define g_mutex_free(mutex)                                            \
173     G_THREAD_CF (mutex_free,     (void)0, (mutex))
174 # define g_cond_wait(cond, mutex)                                       \
175     G_THREAD_CF (cond_wait,      (void)0, (cond, mutex))
176 # define g_cond_timed_wait(cond, mutex, abs_time)                       \
177     G_THREAD_CF (cond_timed_wait, TRUE,   (cond, mutex, abs_time))
178 #else /* G_ERRORCHECK_MUTEXES */
179 # define g_mutex_lock(mutex)                                            \
180     G_THREAD_ECF (mutex_lock,    (void)0, (mutex), void)
181 # define g_mutex_trylock(mutex)                                         \
182     G_THREAD_ECF (mutex_trylock, TRUE,    (mutex), gboolean)
183 # define g_mutex_unlock(mutex)                                          \
184     G_THREAD_ECF (mutex_unlock,  (void)0, (mutex), void)
185 # define g_mutex_free(mutex)                                            \
186     G_THREAD_ECF (mutex_free,    (void)0, (mutex), void)
187 # define g_cond_wait(cond, mutex)                                       \
188     (g_thread_supported () ? ((void(*)(GCond*, GMutex*, gulong, gchar*))\
189       g_thread_functions_for_glib_use.cond_wait)                        \
190         (cond, mutex, G_MUTEX_DEBUG_MAGIC, G_STRLOC) : (void) 0)
191 # define g_cond_timed_wait(cond, mutex, abs_time)                       \
192     (g_thread_supported () ?                                            \
193       ((gboolean(*)(GCond*, GMutex*, GTimeVal*, gulong, gchar*))        \
194         g_thread_functions_for_glib_use.cond_timed_wait)                \
195           (cond, mutex, abs_time, G_MUTEX_DEBUG_MAGIC, G_STRLOC) : TRUE)
196 #endif /* G_ERRORCHECK_MUTEXES */
197
198 #define g_thread_supported()    (g_threads_got_initialized)
199 #define g_mutex_new()            G_THREAD_UF (mutex_new,      ())
200 #define g_cond_new()             G_THREAD_UF (cond_new,       ())
201 #define g_cond_signal(cond)      G_THREAD_CF (cond_signal,    (void)0, (cond))
202 #define g_cond_broadcast(cond)   G_THREAD_CF (cond_broadcast, (void)0, (cond))
203 #define g_cond_free(cond)        G_THREAD_CF (cond_free,      (void)0, (cond))
204 #define g_private_new(destructor) G_THREAD_UF (private_new, (destructor))
205 #define g_private_get(private_key) G_THREAD_CF (private_get, \
206                                                 ((gpointer)private_key), \
207                                                 (private_key))
208 #define g_private_set(private_key, value) G_THREAD_CF (private_set, \
209                                                        (void) (private_key = \
210                                                         (GPrivate*) (value)), \
211                                                        (private_key, value))
212 #define g_thread_yield()              G_THREAD_CF (thread_yield, (void)0, ())
213
214 #define g_thread_create(func, data, joinable, error)                    \
215   (g_thread_create_full (func, data, 0, joinable, FALSE,                \
216                          G_THREAD_PRIORITY_NORMAL, error))
217
218 GThread* g_thread_create_full  (GThreadFunc            func,
219                                 gpointer               data,
220                                 gulong                 stack_size,
221                                 gboolean               joinable,
222                                 gboolean               bound,
223                                 GThreadPriority        priority,
224                                 GError               **error);
225 GThread* g_thread_self         (void);
226 void     g_thread_exit         (gpointer               retval);
227 gpointer g_thread_join         (GThread               *thread);
228
229 void     g_thread_set_priority (GThread               *thread,
230                                 GThreadPriority        priority);
231
232 /* GStaticMutexes can be statically initialized with the value
233  * G_STATIC_MUTEX_INIT, and then they can directly be used, that is
234  * much easier, than having to explicitly allocate the mutex before
235  * use
236  */
237 #define g_static_mutex_lock(mutex) \
238     g_mutex_lock (g_static_mutex_get_mutex (mutex))
239 #define g_static_mutex_trylock(mutex) \
240     g_mutex_trylock (g_static_mutex_get_mutex (mutex))
241 #define g_static_mutex_unlock(mutex) \
242     g_mutex_unlock (g_static_mutex_get_mutex (mutex))
243 void g_static_mutex_init (GStaticMutex *mutex);
244 void g_static_mutex_free (GStaticMutex *mutex);
245
246 struct _GStaticPrivate
247 {
248   /*< private >*/
249   guint index;
250 };
251 #define G_STATIC_PRIVATE_INIT { 0 }
252 void     g_static_private_init           (GStaticPrivate   *private_key);
253 gpointer g_static_private_get            (GStaticPrivate   *private_key);
254 void     g_static_private_set            (GStaticPrivate   *private_key,
255                                           gpointer          data,
256                                           GDestroyNotify    notify);
257 void     g_static_private_free           (GStaticPrivate   *private_key);
258
259 typedef struct _GStaticRecMutex GStaticRecMutex;
260 struct _GStaticRecMutex
261 {
262   /*< private >*/
263   GStaticMutex mutex;
264   guint depth;
265   GSystemThread owner;
266 };
267
268 #define G_STATIC_REC_MUTEX_INIT { G_STATIC_MUTEX_INIT }
269 void     g_static_rec_mutex_init        (GStaticRecMutex *mutex);
270 void     g_static_rec_mutex_lock        (GStaticRecMutex *mutex);
271 gboolean g_static_rec_mutex_trylock     (GStaticRecMutex *mutex);
272 void     g_static_rec_mutex_unlock      (GStaticRecMutex *mutex);
273 void     g_static_rec_mutex_lock_full   (GStaticRecMutex *mutex,
274                                          guint            depth);
275 guint    g_static_rec_mutex_unlock_full (GStaticRecMutex *mutex);
276 void     g_static_rec_mutex_free        (GStaticRecMutex *mutex);
277
278 typedef struct _GStaticRWLock GStaticRWLock;
279 struct _GStaticRWLock
280 {
281   /*< private >*/
282   GStaticMutex mutex;
283   GCond *read_cond;
284   GCond *write_cond;
285   guint read_counter;
286   gboolean have_writer;
287   guint want_to_read;
288   guint want_to_write;
289 };
290
291 #define G_STATIC_RW_LOCK_INIT { G_STATIC_MUTEX_INIT, NULL, NULL, 0, FALSE, 0, 0 }
292
293 void      g_static_rw_lock_init           (GStaticRWLock* lock);
294 void      g_static_rw_lock_reader_lock    (GStaticRWLock* lock);
295 gboolean  g_static_rw_lock_reader_trylock (GStaticRWLock* lock);
296 void      g_static_rw_lock_reader_unlock  (GStaticRWLock* lock);
297 void      g_static_rw_lock_writer_lock    (GStaticRWLock* lock);
298 gboolean  g_static_rw_lock_writer_trylock (GStaticRWLock* lock);
299 void      g_static_rw_lock_writer_unlock  (GStaticRWLock* lock);
300 void      g_static_rw_lock_free           (GStaticRWLock* lock);
301
302 void      g_thread_foreach                (GFunc          thread_func,
303                                            gpointer       user_data);
304
305 typedef enum
306 {
307   G_ONCE_STATUS_NOTCALLED,
308   G_ONCE_STATUS_PROGRESS,
309   G_ONCE_STATUS_READY  
310 } GOnceStatus;
311
312 typedef struct _GOnce GOnce;
313 struct _GOnce
314 {
315   volatile GOnceStatus status;
316   volatile gpointer retval;
317 };
318
319 #define G_ONCE_INIT { G_ONCE_STATUS_NOTCALLED, NULL }
320
321 gpointer g_once_impl (GOnce *once, GThreadFunc func, gpointer arg);
322
323 #ifdef G_ATOMIC_OP_MEMORY_BARRIER_NEEDED
324 # define g_once(once, func, arg) g_once_impl ((once), (func), (arg))
325 #else /* !G_ATOMIC_OP_MEMORY_BARRIER_NEEDED*/
326 # define g_once(once, func, arg) \
327   (((once)->status == G_ONCE_STATUS_READY) ? \
328    (once)->retval : \
329    g_once_impl ((once), (func), (arg)))
330 #endif /* G_ATOMIC_OP_MEMORY_BARRIER_NEEDED */
331
332 /* initialize-once guards, keyed by value_location */
333 G_INLINE_FUNC gboolean  g_once_init_enter       (volatile gsize *value_location);
334 gboolean                g_once_init_enter_impl  (volatile gsize *value_location);
335 void                    g_once_init_leave       (volatile gsize *value_location,
336                                                  gsize           initialization_value);
337 #if defined (G_CAN_INLINE) || defined (__G_THREAD_C__)
338 G_INLINE_FUNC gboolean
339 g_once_init_enter (volatile gsize *value_location)
340 {
341   if G_LIKELY (g_atomic_pointer_get ((void*volatile*) value_location) != NULL)
342     return FALSE;
343   else
344     return g_once_init_enter_impl (value_location);
345 }
346 #endif /* G_CAN_INLINE || __G_THREAD_C__ */
347
348 /* these are some convenience macros that expand to nothing if GLib
349  * was configured with --disable-threads. for using StaticMutexes,
350  * you define them with G_LOCK_DEFINE_STATIC (name) or G_LOCK_DEFINE (name)
351  * if you need to export the mutex. With G_LOCK_EXTERN (name) you can
352  * declare such an globally defined lock. name is a unique identifier
353  * for the protected varibale or code portion. locking, testing and
354  * unlocking of such mutexes can be done with G_LOCK(), G_UNLOCK() and
355  * G_TRYLOCK() respectively.
356  */
357 extern void glib_dummy_decl (void);
358 #define G_LOCK_NAME(name)               g__ ## name ## _lock
359 #ifdef  G_THREADS_ENABLED
360 #  define G_LOCK_DEFINE_STATIC(name)    static G_LOCK_DEFINE (name)
361 #  define G_LOCK_DEFINE(name)           \
362     GStaticMutex G_LOCK_NAME (name) = G_STATIC_MUTEX_INIT
363 #  define G_LOCK_EXTERN(name)           extern GStaticMutex G_LOCK_NAME (name)
364
365 #  ifdef G_DEBUG_LOCKS
366 #    define G_LOCK(name)                G_STMT_START{             \
367         g_log (G_LOG_DOMAIN, G_LOG_LEVEL_DEBUG,                   \
368                "file %s: line %d (%s): locking: %s ",             \
369                __FILE__,        __LINE__, G_GNUC_PRETTY_FUNCTION, \
370                #name);                                            \
371         g_static_mutex_lock (&G_LOCK_NAME (name));                \
372      }G_STMT_END
373 #    define G_UNLOCK(name)              G_STMT_START{             \
374         g_log (G_LOG_DOMAIN, G_LOG_LEVEL_DEBUG,                   \
375                "file %s: line %d (%s): unlocking: %s ",           \
376                __FILE__,        __LINE__, G_GNUC_PRETTY_FUNCTION, \
377                #name);                                            \
378        g_static_mutex_unlock (&G_LOCK_NAME (name));               \
379      }G_STMT_END
380 #    define G_TRYLOCK(name)                                       \
381         (g_log (G_LOG_DOMAIN, G_LOG_LEVEL_DEBUG,                  \
382                "file %s: line %d (%s): try locking: %s ",         \
383                __FILE__,        __LINE__, G_GNUC_PRETTY_FUNCTION, \
384                #name), g_static_mutex_trylock (&G_LOCK_NAME (name)))
385 #  else  /* !G_DEBUG_LOCKS */
386 #    define G_LOCK(name) g_static_mutex_lock       (&G_LOCK_NAME (name))
387 #    define G_UNLOCK(name) g_static_mutex_unlock   (&G_LOCK_NAME (name))
388 #    define G_TRYLOCK(name) g_static_mutex_trylock (&G_LOCK_NAME (name))
389 #  endif /* !G_DEBUG_LOCKS */
390 #else   /* !G_THREADS_ENABLED */
391 #  define G_LOCK_DEFINE_STATIC(name)    extern void glib_dummy_decl (void)
392 #  define G_LOCK_DEFINE(name)           extern void glib_dummy_decl (void)
393 #  define G_LOCK_EXTERN(name)           extern void glib_dummy_decl (void)
394 #  define G_LOCK(name)
395 #  define G_UNLOCK(name)
396 #  define G_TRYLOCK(name)               (TRUE)
397 #endif  /* !G_THREADS_ENABLED */
398
399
400 G_END_DECLS
401
402 #endif /* __G_THREAD_H__ */