Add new thread creation API
[platform/upstream/glib.git] / glib / gmain.c
1 /* GLIB - Library of useful routines for C programming
2  * Copyright (C) 1995-1997  Peter Mattis, Spencer Kimball and Josh MacDonald
3  *
4  * gmain.c: Main loop abstraction, timeouts, and idle functions
5  * Copyright 1998 Owen Taylor
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 "config.h"
35 #include "glibconfig.h"
36
37 /* Uncomment the next line (and the corresponding line in gpoll.c) to
38  * enable debugging printouts if the environment variable
39  * G_MAIN_POLL_DEBUG is set to some value.
40  */
41 /* #define G_MAIN_POLL_DEBUG */
42
43 #ifdef _WIN32
44 /* Always enable debugging printout on Windows, as it is more often
45  * needed there...
46  */
47 #define G_MAIN_POLL_DEBUG
48 #endif
49
50 #ifdef G_OS_UNIX
51 #include "glib-unix.h"
52 #include <pthread.h>
53 #ifdef HAVE_EVENTFD
54 #include <sys/eventfd.h>
55 #endif
56 #endif
57
58 #include <signal.h>
59 #include <sys/types.h>
60 #include <time.h>
61 #include <stdlib.h>
62 #ifdef HAVE_SYS_TIME_H
63 #include <sys/time.h>
64 #endif /* HAVE_SYS_TIME_H */
65 #ifdef HAVE_UNISTD_H
66 #include <unistd.h>
67 #endif /* HAVE_UNISTD_H */
68 #include <errno.h>
69 #include <string.h>
70
71 #ifdef G_OS_WIN32
72 #define STRICT
73 #include <windows.h>
74 #endif /* G_OS_WIN32 */
75
76 #ifdef G_OS_BEOS
77 #include <sys/socket.h>
78 #include <sys/wait.h>
79 #endif /* G_OS_BEOS */
80
81 #include "gmain.h"
82
83 #include "garray.h"
84 #include "giochannel.h"
85 #include "ghash.h"
86 #include "ghook.h"
87 #include "gqueue.h"
88 #include "gstrfuncs.h"
89 #include "gtestutils.h"
90 #include "gthreadprivate.h"
91
92 #ifdef G_OS_WIN32
93 #include "gwin32.h"
94 #endif
95
96 #ifdef  G_MAIN_POLL_DEBUG
97 #include "gtimer.h"
98 #endif
99
100 #include "gwakeup.h"
101
102 #include "glib-private.h"
103
104 /**
105  * SECTION:main
106  * @title: The Main Event Loop
107  * @short_description: manages all available sources of events
108  *
109  * The main event loop manages all the available sources of events for
110  * GLib and GTK+ applications. These events can come from any number of
111  * different types of sources such as file descriptors (plain files,
112  * pipes or sockets) and timeouts. New types of event sources can also
113  * be added using g_source_attach().
114  *
115  * To allow multiple independent sets of sources to be handled in
116  * different threads, each source is associated with a #GMainContext.
117  * A GMainContext can only be running in a single thread, but
118  * sources can be added to it and removed from it from other threads.
119  *
120  * Each event source is assigned a priority. The default priority,
121  * #G_PRIORITY_DEFAULT, is 0. Values less than 0 denote higher priorities.
122  * Values greater than 0 denote lower priorities. Events from high priority
123  * sources are always processed before events from lower priority sources.
124  *
125  * Idle functions can also be added, and assigned a priority. These will
126  * be run whenever no events with a higher priority are ready to be processed.
127  *
128  * The #GMainLoop data type represents a main event loop. A GMainLoop is
129  * created with g_main_loop_new(). After adding the initial event sources,
130  * g_main_loop_run() is called. This continuously checks for new events from
131  * each of the event sources and dispatches them. Finally, the processing of
132  * an event from one of the sources leads to a call to g_main_loop_quit() to
133  * exit the main loop, and g_main_loop_run() returns.
134  *
135  * It is possible to create new instances of #GMainLoop recursively.
136  * This is often used in GTK+ applications when showing modal dialog
137  * boxes. Note that event sources are associated with a particular
138  * #GMainContext, and will be checked and dispatched for all main
139  * loops associated with that GMainContext.
140  *
141  * GTK+ contains wrappers of some of these functions, e.g. gtk_main(),
142  * gtk_main_quit() and gtk_events_pending().
143  *
144  * <refsect2><title>Creating new source types</title>
145  * <para>One of the unusual features of the #GMainLoop functionality
146  * is that new types of event source can be created and used in
147  * addition to the builtin type of event source. A new event source
148  * type is used for handling GDK events. A new source type is created
149  * by <firstterm>deriving</firstterm> from the #GSource structure.
150  * The derived type of source is represented by a structure that has
151  * the #GSource structure as a first element, and other elements specific
152  * to the new source type. To create an instance of the new source type,
153  * call g_source_new() passing in the size of the derived structure and
154  * a table of functions. These #GSourceFuncs determine the behavior of
155  * the new source type.</para>
156  * <para>New source types basically interact with the main context
157  * in two ways. Their prepare function in #GSourceFuncs can set a timeout
158  * to determine the maximum amount of time that the main loop will sleep
159  * before checking the source again. In addition, or as well, the source
160  * can add file descriptors to the set that the main context checks using
161  * g_source_add_poll().</para>
162  * </refsect2>
163  * <refsect2><title>Customizing the main loop iteration</title>
164  * <para>Single iterations of a #GMainContext can be run with
165  * g_main_context_iteration(). In some cases, more detailed control
166  * of exactly how the details of the main loop work is desired, for
167  * instance, when integrating the #GMainLoop with an external main loop.
168  * In such cases, you can call the component functions of
169  * g_main_context_iteration() directly. These functions are
170  * g_main_context_prepare(), g_main_context_query(),
171  * g_main_context_check() and g_main_context_dispatch().</para>
172  * <para>The operation of these functions can best be seen in terms
173  * of a state diagram, as shown in <xref linkend="mainloop-states"/>.</para>
174  * <figure id="mainloop-states"><title>States of a Main Context</title>
175  * <graphic fileref="mainloop-states.gif" format="GIF"></graphic>
176  * </figure>
177  * </refsect2>
178  *
179  * On Unix, the GLib mainloop is incompatible with fork().  Any program
180  * using the mainloop must either exec() or exit() from the child
181  * without returning to the mainloop.
182  */
183
184 /* Types */
185
186 typedef struct _GTimeoutSource GTimeoutSource;
187 typedef struct _GChildWatchSource GChildWatchSource;
188 typedef struct _GUnixSignalWatchSource GUnixSignalWatchSource;
189 typedef struct _GPollRec GPollRec;
190 typedef struct _GSourceCallback GSourceCallback;
191
192 typedef enum
193 {
194   G_SOURCE_READY = 1 << G_HOOK_FLAG_USER_SHIFT,
195   G_SOURCE_CAN_RECURSE = 1 << (G_HOOK_FLAG_USER_SHIFT + 1)
196 } GSourceFlags;
197
198 typedef struct _GMainWaiter GMainWaiter;
199
200 struct _GMainWaiter
201 {
202   GCond *cond;
203   GMutex *mutex;
204 };
205
206 typedef struct _GMainDispatch GMainDispatch;
207
208 struct _GMainDispatch
209 {
210   gint depth;
211   GSList *dispatching_sources; /* stack of current sources */
212 };
213
214 #ifdef G_MAIN_POLL_DEBUG
215 gboolean _g_main_poll_debug = FALSE;
216 #endif
217
218 struct _GMainContext
219 {
220   /* The following lock is used for both the list of sources
221    * and the list of poll records
222    */
223   GMutex mutex;
224   GCond *cond;
225   GThread *owner;
226   guint owner_count;
227   GSList *waiters;
228
229   gint ref_count;
230
231   GPtrArray *pending_dispatches;
232   gint timeout;                 /* Timeout for current iteration */
233
234   guint next_id;
235   GSource *source_list;
236   gint in_check_or_prepare;
237
238   GPollRec *poll_records, *poll_records_tail;
239   guint n_poll_records;
240   GPollFD *cached_poll_array;
241   guint cached_poll_array_size;
242
243   GWakeup *wakeup;
244
245   GPollFD wake_up_rec;
246
247 /* Flag indicating whether the set of fd's changed during a poll */
248   gboolean poll_changed;
249
250   GPollFunc poll_func;
251
252   gint64   time;
253   gboolean time_is_fresh;
254 };
255
256 struct _GSourceCallback
257 {
258   guint ref_count;
259   GSourceFunc func;
260   gpointer    data;
261   GDestroyNotify notify;
262 };
263
264 struct _GMainLoop
265 {
266   GMainContext *context;
267   gboolean is_running;
268   gint ref_count;
269 };
270
271 struct _GTimeoutSource
272 {
273   GSource     source;
274   gint64      expiration;
275   guint       interval;
276   gboolean    seconds;
277 };
278
279 struct _GChildWatchSource
280 {
281   GSource     source;
282   GPid        pid;
283   gint        child_status;
284 #ifdef G_OS_WIN32
285   GPollFD     poll;
286 #else /* G_OS_WIN32 */
287   gboolean    child_exited;
288 #endif /* G_OS_WIN32 */
289 };
290
291 struct _GUnixSignalWatchSource
292 {
293   GSource     source;
294   int         signum;
295   gboolean    pending;
296 };
297
298 struct _GPollRec
299 {
300   GPollFD *fd;
301   GPollRec *prev;
302   GPollRec *next;
303   gint priority;
304 };
305
306 struct _GSourcePrivate
307 {
308   GSList *child_sources;
309   GSource *parent_source;
310 };
311
312 #define LOCK_CONTEXT(context) g_mutex_lock (&context->mutex)
313 #define UNLOCK_CONTEXT(context) g_mutex_unlock (&context->mutex)
314 #define G_THREAD_SELF g_thread_self ()
315
316 #define SOURCE_DESTROYED(source) (((source)->flags & G_HOOK_FLAG_ACTIVE) == 0)
317 #define SOURCE_BLOCKED(source) (((source)->flags & G_HOOK_FLAG_IN_CALL) != 0 && \
318                                 ((source)->flags & G_SOURCE_CAN_RECURSE) == 0)
319
320 #define SOURCE_UNREF(source, context)                       \
321    G_STMT_START {                                           \
322     if ((source)->ref_count > 1)                            \
323       (source)->ref_count--;                                \
324     else                                                    \
325       g_source_unref_internal ((source), (context), TRUE);  \
326    } G_STMT_END
327
328
329 /* Forward declarations */
330
331 static void g_source_unref_internal             (GSource      *source,
332                                                  GMainContext *context,
333                                                  gboolean      have_lock);
334 static void g_source_destroy_internal           (GSource      *source,
335                                                  GMainContext *context,
336                                                  gboolean      have_lock);
337 static void g_source_set_priority_unlocked      (GSource      *source,
338                                                  GMainContext *context,
339                                                  gint          priority);
340 static void g_main_context_poll                 (GMainContext *context,
341                                                  gint          timeout,
342                                                  gint          priority,
343                                                  GPollFD      *fds,
344                                                  gint          n_fds);
345 static void g_main_context_add_poll_unlocked    (GMainContext *context,
346                                                  gint          priority,
347                                                  GPollFD      *fd);
348 static void g_main_context_remove_poll_unlocked (GMainContext *context,
349                                                  GPollFD      *fd);
350
351 static gboolean g_timeout_prepare  (GSource     *source,
352                                     gint        *timeout);
353 static gboolean g_timeout_check    (GSource     *source);
354 static gboolean g_timeout_dispatch (GSource     *source,
355                                     GSourceFunc  callback,
356                                     gpointer     user_data);
357 static gboolean g_child_watch_prepare  (GSource     *source,
358                                         gint        *timeout);
359 static gboolean g_child_watch_check    (GSource     *source);
360 static gboolean g_child_watch_dispatch (GSource     *source,
361                                         GSourceFunc  callback,
362                                         gpointer     user_data);
363 static void     g_child_watch_finalize (GSource     *source);
364 #ifdef G_OS_UNIX
365 static void g_unix_signal_handler (int signum);
366 static gboolean g_unix_signal_watch_prepare  (GSource     *source,
367                                               gint        *timeout);
368 static gboolean g_unix_signal_watch_check    (GSource     *source);
369 static gboolean g_unix_signal_watch_dispatch (GSource     *source,
370                                               GSourceFunc  callback,
371                                               gpointer     user_data);
372 static void     g_unix_signal_watch_finalize  (GSource     *source);
373 #endif
374 static gboolean g_idle_prepare     (GSource     *source,
375                                     gint        *timeout);
376 static gboolean g_idle_check       (GSource     *source);
377 static gboolean g_idle_dispatch    (GSource     *source,
378                                     GSourceFunc  callback,
379                                     gpointer     user_data);
380
381 static GMainContext *glib_worker_context;
382 static gboolean      g_main_context_fork_detected;
383
384 G_LOCK_DEFINE_STATIC (main_loop);
385 static GMainContext *default_main_context;
386
387 #ifndef G_OS_WIN32
388
389
390 /* UNIX signals work by marking one of these variables then waking the
391  * worker context to check on them and dispatch accordingly.
392  */
393 static volatile gchar unix_signal_pending[NSIG];
394 static volatile gboolean any_unix_signal_pending;
395
396 /* Guards all the data below */
397 G_LOCK_DEFINE_STATIC (unix_signal_lock);
398 static GSList *unix_signal_watches;
399 static GSList *unix_child_watches;
400
401 static GSourceFuncs g_unix_signal_funcs =
402 {
403   g_unix_signal_watch_prepare,
404   g_unix_signal_watch_check,
405   g_unix_signal_watch_dispatch,
406   g_unix_signal_watch_finalize
407 };
408 #endif /* !G_OS_WIN32 */
409 G_LOCK_DEFINE_STATIC (main_context_list);
410 static GSList *main_context_list = NULL;
411
412 GSourceFuncs g_timeout_funcs =
413 {
414   g_timeout_prepare,
415   g_timeout_check,
416   g_timeout_dispatch,
417   NULL
418 };
419
420 GSourceFuncs g_child_watch_funcs =
421 {
422   g_child_watch_prepare,
423   g_child_watch_check,
424   g_child_watch_dispatch,
425   g_child_watch_finalize
426 };
427
428 GSourceFuncs g_idle_funcs =
429 {
430   g_idle_prepare,
431   g_idle_check,
432   g_idle_dispatch,
433   NULL
434 };
435
436 /**
437  * g_main_context_ref:
438  * @context: a #GMainContext
439  * 
440  * Increases the reference count on a #GMainContext object by one.
441  *
442  * Returns: the @context that was passed in (since 2.6)
443  **/
444 GMainContext *
445 g_main_context_ref (GMainContext *context)
446 {
447   g_return_val_if_fail (context != NULL, NULL);
448   g_return_val_if_fail (g_atomic_int_get (&context->ref_count) > 0, NULL); 
449
450   g_atomic_int_inc (&context->ref_count);
451
452   return context;
453 }
454
455 static inline void
456 poll_rec_list_free (GMainContext *context,
457                     GPollRec     *list)
458 {
459   g_slice_free_chain (GPollRec, list, next);
460 }
461
462 /**
463  * g_main_context_unref:
464  * @context: a #GMainContext
465  * 
466  * Decreases the reference count on a #GMainContext object by one. If
467  * the result is zero, free the context and free all associated memory.
468  **/
469 void
470 g_main_context_unref (GMainContext *context)
471 {
472   GSource *source;
473   g_return_if_fail (context != NULL);
474   g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0); 
475
476   if (!g_atomic_int_dec_and_test (&context->ref_count))
477     return;
478
479   G_LOCK (main_context_list);
480   main_context_list = g_slist_remove (main_context_list, context);
481   G_UNLOCK (main_context_list);
482
483   source = context->source_list;
484   while (source)
485     {
486       GSource *next = source->next;
487       g_source_destroy_internal (source, context, FALSE);
488       source = next;
489     }
490
491   g_mutex_clear (&context->mutex);
492
493   g_ptr_array_free (context->pending_dispatches, TRUE);
494   g_free (context->cached_poll_array);
495
496   poll_rec_list_free (context, context->poll_records);
497
498   g_wakeup_free (context->wakeup);
499
500   if (context->cond != NULL)
501     g_cond_free (context->cond);
502
503   g_free (context);
504 }
505
506 #ifdef G_OS_UNIX
507 static void
508 g_main_context_forked (void)
509 {
510   g_main_context_fork_detected = TRUE;
511 }
512 #endif
513
514 /**
515  * g_main_context_new:
516  * 
517  * Creates a new #GMainContext structure.
518  * 
519  * Return value: the new #GMainContext
520  **/
521 GMainContext *
522 g_main_context_new (void)
523 {
524   static gsize initialised;
525   GMainContext *context;
526
527   g_thread_init_glib ();
528
529   if (g_once_init_enter (&initialised))
530     {
531 #ifdef G_MAIN_POLL_DEBUG
532       if (getenv ("G_MAIN_POLL_DEBUG") != NULL)
533         _g_main_poll_debug = TRUE;
534 #endif
535
536 #ifdef G_OS_UNIX
537       pthread_atfork (NULL, NULL, g_main_context_forked);
538 #endif
539
540       g_once_init_leave (&initialised, TRUE);
541     }
542
543   context = g_new0 (GMainContext, 1);
544
545   g_mutex_init (&context->mutex);
546
547   context->owner = NULL;
548   context->waiters = NULL;
549
550   context->ref_count = 1;
551
552   context->next_id = 1;
553   
554   context->source_list = NULL;
555   
556   context->poll_func = g_poll;
557   
558   context->cached_poll_array = NULL;
559   context->cached_poll_array_size = 0;
560   
561   context->pending_dispatches = g_ptr_array_new ();
562   
563   context->time_is_fresh = FALSE;
564   
565   context->wakeup = g_wakeup_new ();
566   g_wakeup_get_pollfd (context->wakeup, &context->wake_up_rec);
567   g_main_context_add_poll_unlocked (context, 0, &context->wake_up_rec);
568
569   G_LOCK (main_context_list);
570   main_context_list = g_slist_append (main_context_list, context);
571
572 #ifdef G_MAIN_POLL_DEBUG
573   if (_g_main_poll_debug)
574     g_print ("created context=%p\n", context);
575 #endif
576
577   G_UNLOCK (main_context_list);
578
579   return context;
580 }
581
582 /**
583  * g_main_context_default:
584  * 
585  * Returns the global default main context. This is the main context
586  * used for main loop functions when a main loop is not explicitly
587  * specified, and corresponds to the "main" main loop. See also
588  * g_main_context_get_thread_default().
589  * 
590  * Return value: (transfer none): the global default main context.
591  **/
592 GMainContext *
593 g_main_context_default (void)
594 {
595   /* Slow, but safe */
596   
597   G_LOCK (main_loop);
598
599   if (!default_main_context)
600     {
601       default_main_context = g_main_context_new ();
602 #ifdef G_MAIN_POLL_DEBUG
603       if (_g_main_poll_debug)
604         g_print ("default context=%p\n", default_main_context);
605 #endif
606     }
607
608   G_UNLOCK (main_loop);
609
610   return default_main_context;
611 }
612
613 static GStaticPrivate thread_context_stack = G_STATIC_PRIVATE_INIT;
614
615 static void
616 free_context_stack (gpointer data)
617 {
618   GQueue *stack = data;
619   GMainContext *context;
620
621   while (!g_queue_is_empty (stack))
622     {
623       context = g_queue_pop_head (stack);
624       g_main_context_release (context);
625       if (context)
626         g_main_context_unref (context);
627     }
628   g_queue_free (stack);
629 }
630
631 /**
632  * g_main_context_push_thread_default:
633  * @context: a #GMainContext, or %NULL for the global default context
634  *
635  * Acquires @context and sets it as the thread-default context for the
636  * current thread. This will cause certain asynchronous operations
637  * (such as most <link linkend="gio">gio</link>-based I/O) which are
638  * started in this thread to run under @context and deliver their
639  * results to its main loop, rather than running under the global
640  * default context in the main thread. Note that calling this function
641  * changes the context returned by
642  * g_main_context_get_thread_default(), <emphasis>not</emphasis> the
643  * one returned by g_main_context_default(), so it does not affect the
644  * context used by functions like g_idle_add().
645  *
646  * Normally you would call this function shortly after creating a new
647  * thread, passing it a #GMainContext which will be run by a
648  * #GMainLoop in that thread, to set a new default context for all
649  * async operations in that thread. (In this case, you don't need to
650  * ever call g_main_context_pop_thread_default().) In some cases
651  * however, you may want to schedule a single operation in a
652  * non-default context, or temporarily use a non-default context in
653  * the main thread. In that case, you can wrap the call to the
654  * asynchronous operation inside a
655  * g_main_context_push_thread_default() /
656  * g_main_context_pop_thread_default() pair, but it is up to you to
657  * ensure that no other asynchronous operations accidentally get
658  * started while the non-default context is active.
659  *
660  * Beware that libraries that predate this function may not correctly
661  * handle being used from a thread with a thread-default context. Eg,
662  * see g_file_supports_thread_contexts().
663  *
664  * Since: 2.22
665  **/
666 void
667 g_main_context_push_thread_default (GMainContext *context)
668 {
669   GQueue *stack;
670   gboolean acquired_context;
671
672   acquired_context = g_main_context_acquire (context);
673   g_return_if_fail (acquired_context);
674
675   if (context == g_main_context_default ())
676     context = NULL;
677   else if (context)
678     g_main_context_ref (context);
679
680   stack = g_static_private_get (&thread_context_stack);
681   if (!stack)
682     {
683       stack = g_queue_new ();
684       g_static_private_set (&thread_context_stack, stack,
685                             free_context_stack);
686     }
687
688   g_queue_push_head (stack, context);
689 }
690
691 /**
692  * g_main_context_pop_thread_default:
693  * @context: a #GMainContext object, or %NULL
694  *
695  * Pops @context off the thread-default context stack (verifying that
696  * it was on the top of the stack).
697  *
698  * Since: 2.22
699  **/
700 void
701 g_main_context_pop_thread_default (GMainContext *context)
702 {
703   GQueue *stack;
704
705   if (context == g_main_context_default ())
706     context = NULL;
707
708   stack = g_static_private_get (&thread_context_stack);
709
710   g_return_if_fail (stack != NULL);
711   g_return_if_fail (g_queue_peek_head (stack) == context);
712
713   g_queue_pop_head (stack);
714
715   g_main_context_release (context);
716   if (context)
717     g_main_context_unref (context);
718 }
719
720 /**
721  * g_main_context_get_thread_default:
722  *
723  * Gets the thread-default #GMainContext for this thread. Asynchronous
724  * operations that want to be able to be run in contexts other than
725  * the default one should call this method to get a #GMainContext to
726  * add their #GSource<!-- -->s to. (Note that even in single-threaded
727  * programs applications may sometimes want to temporarily push a
728  * non-default context, so it is not safe to assume that this will
729  * always return %NULL if threads are not initialized.)
730  *
731  * Returns: (transfer none): the thread-default #GMainContext, or
732  * %NULL if the thread-default context is the global default context.
733  *
734  * Since: 2.22
735  **/
736 GMainContext *
737 g_main_context_get_thread_default (void)
738 {
739   GQueue *stack;
740
741   stack = g_static_private_get (&thread_context_stack);
742   if (stack)
743     return g_queue_peek_head (stack);
744   else
745     return NULL;
746 }
747
748 /* Hooks for adding to the main loop */
749
750 /**
751  * g_source_new:
752  * @source_funcs: structure containing functions that implement
753  *                the sources behavior.
754  * @struct_size: size of the #GSource structure to create.
755  * 
756  * Creates a new #GSource structure. The size is specified to
757  * allow creating structures derived from #GSource that contain
758  * additional data. The size passed in must be at least
759  * <literal>sizeof (GSource)</literal>.
760  * 
761  * The source will not initially be associated with any #GMainContext
762  * and must be added to one with g_source_attach() before it will be
763  * executed.
764  * 
765  * Return value: the newly-created #GSource.
766  **/
767 GSource *
768 g_source_new (GSourceFuncs *source_funcs,
769               guint         struct_size)
770 {
771   GSource *source;
772
773   g_return_val_if_fail (source_funcs != NULL, NULL);
774   g_return_val_if_fail (struct_size >= sizeof (GSource), NULL);
775   
776   source = (GSource*) g_malloc0 (struct_size);
777
778   source->source_funcs = source_funcs;
779   source->ref_count = 1;
780   
781   source->priority = G_PRIORITY_DEFAULT;
782
783   source->flags = G_HOOK_FLAG_ACTIVE;
784
785   /* NULL/0 initialization for all other fields */
786   
787   return source;
788 }
789
790 /* Holds context's lock
791  */
792 static void
793 g_source_list_add (GSource      *source,
794                    GMainContext *context)
795 {
796   GSource *tmp_source, *last_source;
797   
798   if (source->priv && source->priv->parent_source)
799     {
800       /* Put the source immediately before its parent */
801       tmp_source = source->priv->parent_source;
802       last_source = source->priv->parent_source->prev;
803     }
804   else
805     {
806       last_source = NULL;
807       tmp_source = context->source_list;
808       while (tmp_source && tmp_source->priority <= source->priority)
809         {
810           last_source = tmp_source;
811           tmp_source = tmp_source->next;
812         }
813     }
814
815   source->next = tmp_source;
816   if (tmp_source)
817     tmp_source->prev = source;
818   
819   source->prev = last_source;
820   if (last_source)
821     last_source->next = source;
822   else
823     context->source_list = source;
824 }
825
826 /* Holds context's lock
827  */
828 static void
829 g_source_list_remove (GSource      *source,
830                       GMainContext *context)
831 {
832   if (source->prev)
833     source->prev->next = source->next;
834   else
835     context->source_list = source->next;
836
837   if (source->next)
838     source->next->prev = source->prev;
839
840   source->prev = NULL;
841   source->next = NULL;
842 }
843
844 static guint
845 g_source_attach_unlocked (GSource      *source,
846                           GMainContext *context)
847 {
848   guint result = 0;
849   GSList *tmp_list;
850
851   source->context = context;
852   result = source->source_id = context->next_id++;
853
854   source->ref_count++;
855   g_source_list_add (source, context);
856
857   tmp_list = source->poll_fds;
858   while (tmp_list)
859     {
860       g_main_context_add_poll_unlocked (context, source->priority, tmp_list->data);
861       tmp_list = tmp_list->next;
862     }
863
864   if (source->priv)
865     {
866       tmp_list = source->priv->child_sources;
867       while (tmp_list)
868         {
869           g_source_attach_unlocked (tmp_list->data, context);
870           tmp_list = tmp_list->next;
871         }
872     }
873
874   return result;
875 }
876
877 /**
878  * g_source_attach:
879  * @source: a #GSource
880  * @context: a #GMainContext (if %NULL, the default context will be used)
881  * 
882  * Adds a #GSource to a @context so that it will be executed within
883  * that context. Remove it by calling g_source_destroy().
884  *
885  * Return value: the ID (greater than 0) for the source within the 
886  *   #GMainContext. 
887  **/
888 guint
889 g_source_attach (GSource      *source,
890                  GMainContext *context)
891 {
892   guint result = 0;
893
894   g_return_val_if_fail (source->context == NULL, 0);
895   g_return_val_if_fail (!SOURCE_DESTROYED (source), 0);
896   
897   if (!context)
898     context = g_main_context_default ();
899
900   LOCK_CONTEXT (context);
901
902   result = g_source_attach_unlocked (source, context);
903
904   /* If another thread has acquired the context, wake it up since it
905    * might be in poll() right now.
906    */
907   if (context->owner && context->owner != G_THREAD_SELF)
908     g_wakeup_signal (context->wakeup);
909
910   UNLOCK_CONTEXT (context);
911
912   return result;
913 }
914
915 static void
916 g_source_destroy_internal (GSource      *source,
917                            GMainContext *context,
918                            gboolean      have_lock)
919 {
920   if (!have_lock)
921     LOCK_CONTEXT (context);
922   
923   if (!SOURCE_DESTROYED (source))
924     {
925       GSList *tmp_list;
926       gpointer old_cb_data;
927       GSourceCallbackFuncs *old_cb_funcs;
928       
929       source->flags &= ~G_HOOK_FLAG_ACTIVE;
930
931       old_cb_data = source->callback_data;
932       old_cb_funcs = source->callback_funcs;
933
934       source->callback_data = NULL;
935       source->callback_funcs = NULL;
936
937       if (old_cb_funcs)
938         {
939           UNLOCK_CONTEXT (context);
940           old_cb_funcs->unref (old_cb_data);
941           LOCK_CONTEXT (context);
942         }
943
944       if (!SOURCE_BLOCKED (source))
945         {
946           tmp_list = source->poll_fds;
947           while (tmp_list)
948             {
949               g_main_context_remove_poll_unlocked (context, tmp_list->data);
950               tmp_list = tmp_list->next;
951             }
952         }
953
954       if (source->priv && source->priv->child_sources)
955         {
956           /* This is safe because even if a child_source finalizer or
957            * closure notify tried to modify source->priv->child_sources
958            * from outside the lock, it would fail since
959            * SOURCE_DESTROYED(source) is now TRUE.
960            */
961           tmp_list = source->priv->child_sources;
962           while (tmp_list)
963             {
964               g_source_destroy_internal (tmp_list->data, context, TRUE);
965               g_source_unref_internal (tmp_list->data, context, TRUE);
966               tmp_list = tmp_list->next;
967             }
968           g_slist_free (source->priv->child_sources);
969           source->priv->child_sources = NULL;
970         }
971           
972       g_source_unref_internal (source, context, TRUE);
973     }
974
975   if (!have_lock)
976     UNLOCK_CONTEXT (context);
977 }
978
979 /**
980  * g_source_destroy:
981  * @source: a #GSource
982  * 
983  * Removes a source from its #GMainContext, if any, and mark it as
984  * destroyed.  The source cannot be subsequently added to another
985  * context.
986  **/
987 void
988 g_source_destroy (GSource *source)
989 {
990   GMainContext *context;
991   
992   g_return_if_fail (source != NULL);
993   
994   context = source->context;
995   
996   if (context)
997     g_source_destroy_internal (source, context, FALSE);
998   else
999     source->flags &= ~G_HOOK_FLAG_ACTIVE;
1000 }
1001
1002 /**
1003  * g_source_get_id:
1004  * @source: a #GSource
1005  * 
1006  * Returns the numeric ID for a particular source. The ID of a source
1007  * is a positive integer which is unique within a particular main loop 
1008  * context. The reverse
1009  * mapping from ID to source is done by g_main_context_find_source_by_id().
1010  *
1011  * Return value: the ID (greater than 0) for the source
1012  **/
1013 guint
1014 g_source_get_id (GSource *source)
1015 {
1016   guint result;
1017   
1018   g_return_val_if_fail (source != NULL, 0);
1019   g_return_val_if_fail (source->context != NULL, 0);
1020
1021   LOCK_CONTEXT (source->context);
1022   result = source->source_id;
1023   UNLOCK_CONTEXT (source->context);
1024   
1025   return result;
1026 }
1027
1028 /**
1029  * g_source_get_context:
1030  * @source: a #GSource
1031  * 
1032  * Gets the #GMainContext with which the source is associated.
1033  * Calling this function on a destroyed source is an error.
1034  * 
1035  * Return value: (transfer none): the #GMainContext with which the
1036  *               source is associated, or %NULL if the context has not
1037  *               yet been added to a source.
1038  **/
1039 GMainContext *
1040 g_source_get_context (GSource *source)
1041 {
1042   g_return_val_if_fail (!SOURCE_DESTROYED (source), NULL);
1043
1044   return source->context;
1045 }
1046
1047 /**
1048  * g_source_add_poll:
1049  * @source:a #GSource 
1050  * @fd: a #GPollFD structure holding information about a file
1051  *      descriptor to watch.
1052  * 
1053  * Adds a file descriptor to the set of file descriptors polled for
1054  * this source. This is usually combined with g_source_new() to add an
1055  * event source. The event source's check function will typically test
1056  * the @revents field in the #GPollFD struct and return %TRUE if events need
1057  * to be processed.
1058  **/
1059 void
1060 g_source_add_poll (GSource *source,
1061                    GPollFD *fd)
1062 {
1063   GMainContext *context;
1064   
1065   g_return_if_fail (source != NULL);
1066   g_return_if_fail (fd != NULL);
1067   g_return_if_fail (!SOURCE_DESTROYED (source));
1068   
1069   context = source->context;
1070
1071   if (context)
1072     LOCK_CONTEXT (context);
1073   
1074   source->poll_fds = g_slist_prepend (source->poll_fds, fd);
1075
1076   if (context)
1077     {
1078       if (!SOURCE_BLOCKED (source))
1079         g_main_context_add_poll_unlocked (context, source->priority, fd);
1080       UNLOCK_CONTEXT (context);
1081     }
1082 }
1083
1084 /**
1085  * g_source_remove_poll:
1086  * @source:a #GSource 
1087  * @fd: a #GPollFD structure previously passed to g_source_add_poll().
1088  * 
1089  * Removes a file descriptor from the set of file descriptors polled for
1090  * this source. 
1091  **/
1092 void
1093 g_source_remove_poll (GSource *source,
1094                       GPollFD *fd)
1095 {
1096   GMainContext *context;
1097   
1098   g_return_if_fail (source != NULL);
1099   g_return_if_fail (fd != NULL);
1100   g_return_if_fail (!SOURCE_DESTROYED (source));
1101   
1102   context = source->context;
1103
1104   if (context)
1105     LOCK_CONTEXT (context);
1106   
1107   source->poll_fds = g_slist_remove (source->poll_fds, fd);
1108
1109   if (context)
1110     {
1111       if (!SOURCE_BLOCKED (source))
1112         g_main_context_remove_poll_unlocked (context, fd);
1113       UNLOCK_CONTEXT (context);
1114     }
1115 }
1116
1117 /**
1118  * g_source_add_child_source:
1119  * @source:a #GSource
1120  * @child_source: a second #GSource that @source should "poll"
1121  *
1122  * Adds @child_source to @source as a "polled" source; when @source is
1123  * added to a #GMainContext, @child_source will be automatically added
1124  * with the same priority, when @child_source is triggered, it will
1125  * cause @source to dispatch (in addition to calling its own
1126  * callback), and when @source is destroyed, it will destroy
1127  * @child_source as well. (@source will also still be dispatched if
1128  * its own prepare/check functions indicate that it is ready.)
1129  *
1130  * If you don't need @child_source to do anything on its own when it
1131  * triggers, you can call g_source_set_dummy_callback() on it to set a
1132  * callback that does nothing (except return %TRUE if appropriate).
1133  *
1134  * @source will hold a reference on @child_source while @child_source
1135  * is attached to it.
1136  *
1137  * Since: 2.28
1138  **/
1139 void
1140 g_source_add_child_source (GSource *source,
1141                            GSource *child_source)
1142 {
1143   GMainContext *context;
1144
1145   g_return_if_fail (source != NULL);
1146   g_return_if_fail (child_source != NULL);
1147   g_return_if_fail (!SOURCE_DESTROYED (source));
1148   g_return_if_fail (!SOURCE_DESTROYED (child_source));
1149   g_return_if_fail (child_source->context == NULL);
1150   g_return_if_fail (child_source->priv == NULL || child_source->priv->parent_source == NULL);
1151
1152   context = source->context;
1153
1154   if (context)
1155     LOCK_CONTEXT (context);
1156
1157   if (!source->priv)
1158     source->priv = g_slice_new0 (GSourcePrivate);
1159   if (!child_source->priv)
1160     child_source->priv = g_slice_new0 (GSourcePrivate);
1161
1162   source->priv->child_sources = g_slist_prepend (source->priv->child_sources,
1163                                                  g_source_ref (child_source));
1164   child_source->priv->parent_source = source;
1165   g_source_set_priority_unlocked (child_source, context, source->priority);
1166
1167   if (context)
1168     {
1169       UNLOCK_CONTEXT (context);
1170       g_source_attach (child_source, context);
1171     }
1172 }
1173
1174 /**
1175  * g_source_remove_child_source:
1176  * @source:a #GSource
1177  * @child_source: a #GSource previously passed to
1178  *     g_source_add_child_source().
1179  *
1180  * Detaches @child_source from @source and destroys it.
1181  *
1182  * Since: 2.28
1183  **/
1184 void
1185 g_source_remove_child_source (GSource *source,
1186                               GSource *child_source)
1187 {
1188   GMainContext *context;
1189
1190   g_return_if_fail (source != NULL);
1191   g_return_if_fail (child_source != NULL);
1192   g_return_if_fail (child_source->priv != NULL && child_source->priv->parent_source == source);
1193   g_return_if_fail (!SOURCE_DESTROYED (source));
1194   g_return_if_fail (!SOURCE_DESTROYED (child_source));
1195
1196   context = source->context;
1197
1198   if (context)
1199     LOCK_CONTEXT (context);
1200
1201   source->priv->child_sources = g_slist_remove (source->priv->child_sources, child_source);
1202   g_source_destroy_internal (child_source, context, TRUE);
1203   g_source_unref_internal (child_source, context, TRUE);
1204
1205   if (context)
1206     UNLOCK_CONTEXT (context);
1207 }
1208
1209 /**
1210  * g_source_set_callback_indirect:
1211  * @source: the source
1212  * @callback_data: pointer to callback data "object"
1213  * @callback_funcs: functions for reference counting @callback_data
1214  *                  and getting the callback and data
1215  * 
1216  * Sets the callback function storing the data as a refcounted callback
1217  * "object". This is used internally. Note that calling 
1218  * g_source_set_callback_indirect() assumes
1219  * an initial reference count on @callback_data, and thus
1220  * @callback_funcs->unref will eventually be called once more
1221  * than @callback_funcs->ref.
1222  **/
1223 void
1224 g_source_set_callback_indirect (GSource              *source,
1225                                 gpointer              callback_data,
1226                                 GSourceCallbackFuncs *callback_funcs)
1227 {
1228   GMainContext *context;
1229   gpointer old_cb_data;
1230   GSourceCallbackFuncs *old_cb_funcs;
1231   
1232   g_return_if_fail (source != NULL);
1233   g_return_if_fail (callback_funcs != NULL || callback_data == NULL);
1234
1235   context = source->context;
1236
1237   if (context)
1238     LOCK_CONTEXT (context);
1239
1240   old_cb_data = source->callback_data;
1241   old_cb_funcs = source->callback_funcs;
1242
1243   source->callback_data = callback_data;
1244   source->callback_funcs = callback_funcs;
1245   
1246   if (context)
1247     UNLOCK_CONTEXT (context);
1248   
1249   if (old_cb_funcs)
1250     old_cb_funcs->unref (old_cb_data);
1251 }
1252
1253 static void
1254 g_source_callback_ref (gpointer cb_data)
1255 {
1256   GSourceCallback *callback = cb_data;
1257
1258   callback->ref_count++;
1259 }
1260
1261
1262 static void
1263 g_source_callback_unref (gpointer cb_data)
1264 {
1265   GSourceCallback *callback = cb_data;
1266
1267   callback->ref_count--;
1268   if (callback->ref_count == 0)
1269     {
1270       if (callback->notify)
1271         callback->notify (callback->data);
1272       g_free (callback);
1273     }
1274 }
1275
1276 static void
1277 g_source_callback_get (gpointer     cb_data,
1278                        GSource     *source, 
1279                        GSourceFunc *func,
1280                        gpointer    *data)
1281 {
1282   GSourceCallback *callback = cb_data;
1283
1284   *func = callback->func;
1285   *data = callback->data;
1286 }
1287
1288 static GSourceCallbackFuncs g_source_callback_funcs = {
1289   g_source_callback_ref,
1290   g_source_callback_unref,
1291   g_source_callback_get,
1292 };
1293
1294 /**
1295  * g_source_set_callback:
1296  * @source: the source
1297  * @func: a callback function
1298  * @data: the data to pass to callback function
1299  * @notify: a function to call when @data is no longer in use, or %NULL.
1300  * 
1301  * Sets the callback function for a source. The callback for a source is
1302  * called from the source's dispatch function.
1303  *
1304  * The exact type of @func depends on the type of source; ie. you
1305  * should not count on @func being called with @data as its first
1306  * parameter.
1307  * 
1308  * Typically, you won't use this function. Instead use functions specific
1309  * to the type of source you are using.
1310  **/
1311 void
1312 g_source_set_callback (GSource        *source,
1313                        GSourceFunc     func,
1314                        gpointer        data,
1315                        GDestroyNotify  notify)
1316 {
1317   GSourceCallback *new_callback;
1318
1319   g_return_if_fail (source != NULL);
1320
1321   new_callback = g_new (GSourceCallback, 1);
1322
1323   new_callback->ref_count = 1;
1324   new_callback->func = func;
1325   new_callback->data = data;
1326   new_callback->notify = notify;
1327
1328   g_source_set_callback_indirect (source, new_callback, &g_source_callback_funcs);
1329 }
1330
1331
1332 /**
1333  * g_source_set_funcs:
1334  * @source: a #GSource
1335  * @funcs: the new #GSourceFuncs
1336  * 
1337  * Sets the source functions (can be used to override 
1338  * default implementations) of an unattached source.
1339  * 
1340  * Since: 2.12
1341  */
1342 void
1343 g_source_set_funcs (GSource     *source,
1344                    GSourceFuncs *funcs)
1345 {
1346   g_return_if_fail (source != NULL);
1347   g_return_if_fail (source->context == NULL);
1348   g_return_if_fail (source->ref_count > 0);
1349   g_return_if_fail (funcs != NULL);
1350
1351   source->source_funcs = funcs;
1352 }
1353
1354 static void
1355 g_source_set_priority_unlocked (GSource      *source,
1356                                 GMainContext *context,
1357                                 gint          priority)
1358 {
1359   GSList *tmp_list;
1360   
1361   source->priority = priority;
1362
1363   if (context)
1364     {
1365       /* Remove the source from the context's source and then
1366        * add it back so it is sorted in the correct place
1367        */
1368       g_source_list_remove (source, source->context);
1369       g_source_list_add (source, source->context);
1370
1371       if (!SOURCE_BLOCKED (source))
1372         {
1373           tmp_list = source->poll_fds;
1374           while (tmp_list)
1375             {
1376               g_main_context_remove_poll_unlocked (context, tmp_list->data);
1377               g_main_context_add_poll_unlocked (context, priority, tmp_list->data);
1378               
1379               tmp_list = tmp_list->next;
1380             }
1381         }
1382     }
1383
1384   if (source->priv && source->priv->child_sources)
1385     {
1386       tmp_list = source->priv->child_sources;
1387       while (tmp_list)
1388         {
1389           g_source_set_priority_unlocked (tmp_list->data, context, priority);
1390           tmp_list = tmp_list->next;
1391         }
1392     }
1393 }
1394
1395 /**
1396  * g_source_set_priority:
1397  * @source: a #GSource
1398  * @priority: the new priority.
1399  *
1400  * Sets the priority of a source. While the main loop is being run, a
1401  * source will be dispatched if it is ready to be dispatched and no
1402  * sources at a higher (numerically smaller) priority are ready to be
1403  * dispatched.
1404  **/
1405 void
1406 g_source_set_priority (GSource  *source,
1407                        gint      priority)
1408 {
1409   GMainContext *context;
1410
1411   g_return_if_fail (source != NULL);
1412
1413   context = source->context;
1414
1415   if (context)
1416     LOCK_CONTEXT (context);
1417   g_source_set_priority_unlocked (source, context, priority);
1418   if (context)
1419     UNLOCK_CONTEXT (source->context);
1420 }
1421
1422 /**
1423  * g_source_get_priority:
1424  * @source: a #GSource
1425  * 
1426  * Gets the priority of a source.
1427  * 
1428  * Return value: the priority of the source
1429  **/
1430 gint
1431 g_source_get_priority (GSource *source)
1432 {
1433   g_return_val_if_fail (source != NULL, 0);
1434
1435   return source->priority;
1436 }
1437
1438 /**
1439  * g_source_set_can_recurse:
1440  * @source: a #GSource
1441  * @can_recurse: whether recursion is allowed for this source
1442  * 
1443  * Sets whether a source can be called recursively. If @can_recurse is
1444  * %TRUE, then while the source is being dispatched then this source
1445  * will be processed normally. Otherwise, all processing of this
1446  * source is blocked until the dispatch function returns.
1447  **/
1448 void
1449 g_source_set_can_recurse (GSource  *source,
1450                           gboolean  can_recurse)
1451 {
1452   GMainContext *context;
1453   
1454   g_return_if_fail (source != NULL);
1455
1456   context = source->context;
1457
1458   if (context)
1459     LOCK_CONTEXT (context);
1460   
1461   if (can_recurse)
1462     source->flags |= G_SOURCE_CAN_RECURSE;
1463   else
1464     source->flags &= ~G_SOURCE_CAN_RECURSE;
1465
1466   if (context)
1467     UNLOCK_CONTEXT (context);
1468 }
1469
1470 /**
1471  * g_source_get_can_recurse:
1472  * @source: a #GSource
1473  * 
1474  * Checks whether a source is allowed to be called recursively.
1475  * see g_source_set_can_recurse().
1476  * 
1477  * Return value: whether recursion is allowed.
1478  **/
1479 gboolean
1480 g_source_get_can_recurse (GSource  *source)
1481 {
1482   g_return_val_if_fail (source != NULL, FALSE);
1483   
1484   return (source->flags & G_SOURCE_CAN_RECURSE) != 0;
1485 }
1486
1487
1488 /**
1489  * g_source_set_name:
1490  * @source: a #GSource
1491  * @name: debug name for the source
1492  *
1493  * Sets a name for the source, used in debugging and profiling.
1494  * The name defaults to #NULL.
1495  *
1496  * The source name should describe in a human-readable way
1497  * what the source does. For example, "X11 event queue"
1498  * or "GTK+ repaint idle handler" or whatever it is.
1499  *
1500  * It is permitted to call this function multiple times, but is not
1501  * recommended due to the potential performance impact.  For example,
1502  * one could change the name in the "check" function of a #GSourceFuncs 
1503  * to include details like the event type in the source name.
1504  *
1505  * Since: 2.26
1506  **/
1507 void
1508 g_source_set_name (GSource    *source,
1509                    const char *name)
1510 {
1511   g_return_if_fail (source != NULL);
1512
1513   /* setting back to NULL is allowed, just because it's
1514    * weird if get_name can return NULL but you can't
1515    * set that.
1516    */
1517
1518   g_free (source->name);
1519   source->name = g_strdup (name);
1520 }
1521
1522 /**
1523  * g_source_get_name:
1524  * @source: a #GSource
1525  *
1526  * Gets a name for the source, used in debugging and profiling.
1527  * The name may be #NULL if it has never been set with
1528  * g_source_set_name().
1529  *
1530  * Return value: the name of the source
1531  * Since: 2.26
1532  **/
1533 const char *
1534 g_source_get_name (GSource *source)
1535 {
1536   g_return_val_if_fail (source != NULL, NULL);
1537
1538   return source->name;
1539 }
1540
1541 /**
1542  * g_source_set_name_by_id:
1543  * @tag: a #GSource ID
1544  * @name: debug name for the source
1545  *
1546  * Sets the name of a source using its ID.
1547  *
1548  * This is a convenience utility to set source names from the return
1549  * value of g_idle_add(), g_timeout_add(), etc.
1550  *
1551  * Since: 2.26
1552  **/
1553 void
1554 g_source_set_name_by_id (guint           tag,
1555                          const char     *name)
1556 {
1557   GSource *source;
1558
1559   g_return_if_fail (tag > 0);
1560
1561   source = g_main_context_find_source_by_id (NULL, tag);
1562   if (source == NULL)
1563     return;
1564
1565   g_source_set_name (source, name);
1566 }
1567
1568
1569 /**
1570  * g_source_ref:
1571  * @source: a #GSource
1572  * 
1573  * Increases the reference count on a source by one.
1574  * 
1575  * Return value: @source
1576  **/
1577 GSource *
1578 g_source_ref (GSource *source)
1579 {
1580   GMainContext *context;
1581   
1582   g_return_val_if_fail (source != NULL, NULL);
1583
1584   context = source->context;
1585
1586   if (context)
1587     LOCK_CONTEXT (context);
1588
1589   source->ref_count++;
1590
1591   if (context)
1592     UNLOCK_CONTEXT (context);
1593
1594   return source;
1595 }
1596
1597 /* g_source_unref() but possible to call within context lock
1598  */
1599 static void
1600 g_source_unref_internal (GSource      *source,
1601                          GMainContext *context,
1602                          gboolean      have_lock)
1603 {
1604   gpointer old_cb_data = NULL;
1605   GSourceCallbackFuncs *old_cb_funcs = NULL;
1606
1607   g_return_if_fail (source != NULL);
1608   
1609   if (!have_lock && context)
1610     LOCK_CONTEXT (context);
1611
1612   source->ref_count--;
1613   if (source->ref_count == 0)
1614     {
1615       old_cb_data = source->callback_data;
1616       old_cb_funcs = source->callback_funcs;
1617
1618       source->callback_data = NULL;
1619       source->callback_funcs = NULL;
1620
1621       if (context)
1622         {
1623           if (!SOURCE_DESTROYED (source))
1624             g_warning (G_STRLOC ": ref_count == 0, but source was still attached to a context!");
1625           g_source_list_remove (source, context);
1626         }
1627
1628       if (source->source_funcs->finalize)
1629         {
1630           if (context)
1631             UNLOCK_CONTEXT (context);
1632           source->source_funcs->finalize (source);
1633           if (context)
1634             LOCK_CONTEXT (context);
1635         }
1636
1637       g_free (source->name);
1638       source->name = NULL;
1639
1640       g_slist_free (source->poll_fds);
1641       source->poll_fds = NULL;
1642
1643       if (source->priv)
1644         {
1645           g_slice_free (GSourcePrivate, source->priv);
1646           source->priv = NULL;
1647         }
1648
1649       g_free (source);
1650     }
1651   
1652   if (!have_lock && context)
1653     UNLOCK_CONTEXT (context);
1654
1655   if (old_cb_funcs)
1656     {
1657       if (have_lock)
1658         UNLOCK_CONTEXT (context);
1659       
1660       old_cb_funcs->unref (old_cb_data);
1661
1662       if (have_lock)
1663         LOCK_CONTEXT (context);
1664     }
1665 }
1666
1667 /**
1668  * g_source_unref:
1669  * @source: a #GSource
1670  * 
1671  * Decreases the reference count of a source by one. If the
1672  * resulting reference count is zero the source and associated
1673  * memory will be destroyed. 
1674  **/
1675 void
1676 g_source_unref (GSource *source)
1677 {
1678   g_return_if_fail (source != NULL);
1679
1680   g_source_unref_internal (source, source->context, FALSE);
1681 }
1682
1683 /**
1684  * g_main_context_find_source_by_id:
1685  * @context: a #GMainContext (if %NULL, the default context will be used)
1686  * @source_id: the source ID, as returned by g_source_get_id(). 
1687  * 
1688  * Finds a #GSource given a pair of context and ID.
1689  * 
1690  * Return value: (transfer none): the #GSource if found, otherwise, %NULL
1691  **/
1692 GSource *
1693 g_main_context_find_source_by_id (GMainContext *context,
1694                                   guint         source_id)
1695 {
1696   GSource *source;
1697   
1698   g_return_val_if_fail (source_id > 0, NULL);
1699
1700   if (context == NULL)
1701     context = g_main_context_default ();
1702   
1703   LOCK_CONTEXT (context);
1704   
1705   source = context->source_list;
1706   while (source)
1707     {
1708       if (!SOURCE_DESTROYED (source) &&
1709           source->source_id == source_id)
1710         break;
1711       source = source->next;
1712     }
1713
1714   UNLOCK_CONTEXT (context);
1715
1716   return source;
1717 }
1718
1719 /**
1720  * g_main_context_find_source_by_funcs_user_data:
1721  * @context: a #GMainContext (if %NULL, the default context will be used).
1722  * @funcs: the @source_funcs passed to g_source_new().
1723  * @user_data: the user data from the callback.
1724  * 
1725  * Finds a source with the given source functions and user data.  If
1726  * multiple sources exist with the same source function and user data,
1727  * the first one found will be returned.
1728  * 
1729  * Return value: (transfer none): the source, if one was found, otherwise %NULL
1730  **/
1731 GSource *
1732 g_main_context_find_source_by_funcs_user_data (GMainContext *context,
1733                                                GSourceFuncs *funcs,
1734                                                gpointer      user_data)
1735 {
1736   GSource *source;
1737   
1738   g_return_val_if_fail (funcs != NULL, NULL);
1739
1740   if (context == NULL)
1741     context = g_main_context_default ();
1742   
1743   LOCK_CONTEXT (context);
1744
1745   source = context->source_list;
1746   while (source)
1747     {
1748       if (!SOURCE_DESTROYED (source) &&
1749           source->source_funcs == funcs &&
1750           source->callback_funcs)
1751         {
1752           GSourceFunc callback;
1753           gpointer callback_data;
1754
1755           source->callback_funcs->get (source->callback_data, source, &callback, &callback_data);
1756           
1757           if (callback_data == user_data)
1758             break;
1759         }
1760       source = source->next;
1761     }
1762
1763   UNLOCK_CONTEXT (context);
1764
1765   return source;
1766 }
1767
1768 /**
1769  * g_main_context_find_source_by_user_data:
1770  * @context: a #GMainContext
1771  * @user_data: the user_data for the callback.
1772  * 
1773  * Finds a source with the given user data for the callback.  If
1774  * multiple sources exist with the same user data, the first
1775  * one found will be returned.
1776  * 
1777  * Return value: (transfer none): the source, if one was found, otherwise %NULL
1778  **/
1779 GSource *
1780 g_main_context_find_source_by_user_data (GMainContext *context,
1781                                          gpointer      user_data)
1782 {
1783   GSource *source;
1784   
1785   if (context == NULL)
1786     context = g_main_context_default ();
1787   
1788   LOCK_CONTEXT (context);
1789
1790   source = context->source_list;
1791   while (source)
1792     {
1793       if (!SOURCE_DESTROYED (source) &&
1794           source->callback_funcs)
1795         {
1796           GSourceFunc callback;
1797           gpointer callback_data = NULL;
1798
1799           source->callback_funcs->get (source->callback_data, source, &callback, &callback_data);
1800
1801           if (callback_data == user_data)
1802             break;
1803         }
1804       source = source->next;
1805     }
1806
1807   UNLOCK_CONTEXT (context);
1808
1809   return source;
1810 }
1811
1812 /**
1813  * g_source_remove:
1814  * @tag: the ID of the source to remove.
1815  * 
1816  * Removes the source with the given id from the default main context. 
1817  * The id of
1818  * a #GSource is given by g_source_get_id(), or will be returned by the
1819  * functions g_source_attach(), g_idle_add(), g_idle_add_full(),
1820  * g_timeout_add(), g_timeout_add_full(), g_child_watch_add(),
1821  * g_child_watch_add_full(), g_io_add_watch(), and g_io_add_watch_full().
1822  *
1823  * See also g_source_destroy(). You must use g_source_destroy() for sources
1824  * added to a non-default main context.
1825  *
1826  * Return value: %TRUE if the source was found and removed.
1827  **/
1828 gboolean
1829 g_source_remove (guint tag)
1830 {
1831   GSource *source;
1832   
1833   g_return_val_if_fail (tag > 0, FALSE);
1834
1835   source = g_main_context_find_source_by_id (NULL, tag);
1836   if (source)
1837     g_source_destroy (source);
1838
1839   return source != NULL;
1840 }
1841
1842 /**
1843  * g_source_remove_by_user_data:
1844  * @user_data: the user_data for the callback.
1845  * 
1846  * Removes a source from the default main loop context given the user
1847  * data for the callback. If multiple sources exist with the same user
1848  * data, only one will be destroyed.
1849  * 
1850  * Return value: %TRUE if a source was found and removed. 
1851  **/
1852 gboolean
1853 g_source_remove_by_user_data (gpointer user_data)
1854 {
1855   GSource *source;
1856   
1857   source = g_main_context_find_source_by_user_data (NULL, user_data);
1858   if (source)
1859     {
1860       g_source_destroy (source);
1861       return TRUE;
1862     }
1863   else
1864     return FALSE;
1865 }
1866
1867 /**
1868  * g_source_remove_by_funcs_user_data:
1869  * @funcs: The @source_funcs passed to g_source_new()
1870  * @user_data: the user data for the callback
1871  * 
1872  * Removes a source from the default main loop context given the
1873  * source functions and user data. If multiple sources exist with the
1874  * same source functions and user data, only one will be destroyed.
1875  * 
1876  * Return value: %TRUE if a source was found and removed. 
1877  **/
1878 gboolean
1879 g_source_remove_by_funcs_user_data (GSourceFuncs *funcs,
1880                                     gpointer      user_data)
1881 {
1882   GSource *source;
1883
1884   g_return_val_if_fail (funcs != NULL, FALSE);
1885
1886   source = g_main_context_find_source_by_funcs_user_data (NULL, funcs, user_data);
1887   if (source)
1888     {
1889       g_source_destroy (source);
1890       return TRUE;
1891     }
1892   else
1893     return FALSE;
1894 }
1895
1896 /**
1897  * g_get_current_time:
1898  * @result: #GTimeVal structure in which to store current time.
1899  *
1900  * Equivalent to the UNIX gettimeofday() function, but portable.
1901  *
1902  * You may find g_get_real_time() to be more convenient.
1903  **/
1904 void
1905 g_get_current_time (GTimeVal *result)
1906 {
1907 #ifndef G_OS_WIN32
1908   struct timeval r;
1909
1910   g_return_if_fail (result != NULL);
1911
1912   /*this is required on alpha, there the timeval structs are int's
1913     not longs and a cast only would fail horribly*/
1914   gettimeofday (&r, NULL);
1915   result->tv_sec = r.tv_sec;
1916   result->tv_usec = r.tv_usec;
1917 #else
1918   FILETIME ft;
1919   guint64 time64;
1920
1921   g_return_if_fail (result != NULL);
1922
1923   GetSystemTimeAsFileTime (&ft);
1924   memmove (&time64, &ft, sizeof (FILETIME));
1925
1926   /* Convert from 100s of nanoseconds since 1601-01-01
1927    * to Unix epoch. Yes, this is Y2038 unsafe.
1928    */
1929   time64 -= G_GINT64_CONSTANT (116444736000000000);
1930   time64 /= 10;
1931
1932   result->tv_sec = time64 / 1000000;
1933   result->tv_usec = time64 % 1000000;
1934 #endif
1935 }
1936
1937 /**
1938  * g_get_real_time:
1939  *
1940  * Queries the system wall-clock time.
1941  *
1942  * This call is functionally equivalent to g_get_current_time() except
1943  * that the return value is often more convenient than dealing with a
1944  * #GTimeVal.
1945  *
1946  * You should only use this call if you are actually interested in the real
1947  * wall-clock time.  g_get_monotonic_time() is probably more useful for
1948  * measuring intervals.
1949  *
1950  * Returns: the number of microseconds since January 1, 1970 UTC.
1951  *
1952  * Since: 2.28
1953  **/
1954 gint64
1955 g_get_real_time (void)
1956 {
1957   GTimeVal tv;
1958
1959   g_get_current_time (&tv);
1960
1961   return (((gint64) tv.tv_sec) * 1000000) + tv.tv_usec;
1962 }
1963
1964 /**
1965  * g_get_monotonic_time:
1966  *
1967  * Queries the system monotonic time, if available.
1968  *
1969  * On POSIX systems with clock_gettime() and %CLOCK_MONOTONIC this call
1970  * is a very shallow wrapper for that.  Otherwise, we make a best effort
1971  * that probably involves returning the wall clock time (with at least
1972  * microsecond accuracy, subject to the limitations of the OS kernel).
1973  *
1974  * It's important to note that POSIX %CLOCK_MONOTONIC does not count
1975  * time spent while the machine is suspended.
1976  *
1977  * On Windows, "limitations of the OS kernel" is a rather substantial
1978  * statement.  Depending on the configuration of the system, the wall
1979  * clock time is updated as infrequently as 64 times a second (which
1980  * is approximately every 16ms).
1981  *
1982  * Returns: the monotonic time, in microseconds
1983  *
1984  * Since: 2.28
1985  **/
1986 gint64
1987 g_get_monotonic_time (void)
1988 {
1989 #ifdef HAVE_CLOCK_GETTIME
1990   /* librt clock_gettime() is our first choice */
1991   {
1992 #ifdef HAVE_MONOTONIC_CLOCK
1993     static volatile gsize clockid = 0;
1994 #else
1995     static clockid_t clockid = CLOCK_REALTIME;
1996 #endif
1997     struct timespec ts;
1998
1999 #ifdef HAVE_MONOTONIC_CLOCK
2000     if (g_once_init_enter (&clockid))
2001       {
2002         clockid_t best_clockid;
2003
2004         if (sysconf (_SC_MONOTONIC_CLOCK) >= 0)
2005           best_clockid = CLOCK_MONOTONIC;
2006         else
2007           best_clockid = CLOCK_REALTIME;
2008         g_once_init_leave (&clockid, (gsize)best_clockid);
2009       }
2010 #endif
2011
2012     clock_gettime (clockid, &ts);
2013
2014     /* In theory monotonic time can have any epoch.
2015      *
2016      * glib presently assumes the following:
2017      *
2018      *   1) The epoch comes some time after the birth of Jesus of Nazareth, but
2019      *      not more than 10000 years later.
2020      *
2021      *   2) The current time also falls sometime within this range.
2022      *
2023      * These two reasonable assumptions leave us with a maximum deviation from
2024      * the epoch of 10000 years, or 315569520000000000 seconds.
2025      *
2026      * If we restrict ourselves to this range then the number of microseconds
2027      * will always fit well inside the constraints of a int64 (by a factor of
2028      * about 29).
2029      *
2030      * If you actually hit the following assertion, probably you should file a
2031      * bug against your operating system for being excessively silly.
2032      **/
2033     g_assert (G_GINT64_CONSTANT (-315569520000000000) < ts.tv_sec &&
2034               ts.tv_sec < G_GINT64_CONSTANT (315569520000000000));
2035
2036     return (((gint64) ts.tv_sec) * 1000000) + (ts.tv_nsec / 1000);
2037   }
2038 #else
2039   /* It may look like we are discarding accuracy on Windows (since its
2040    * current time is expressed in 100s of nanoseconds) but according to
2041    * many sources, the time is only updated 64 times per second, so
2042    * microsecond accuracy is more than enough.
2043    */
2044   {
2045     GTimeVal tv;
2046
2047     g_get_current_time (&tv);
2048
2049     return (((gint64) tv.tv_sec) * 1000000) + tv.tv_usec;
2050   }
2051 #endif
2052 }
2053
2054 static void
2055 g_main_dispatch_free (gpointer dispatch)
2056 {
2057   g_slice_free (GMainDispatch, dispatch);
2058 }
2059
2060 /* Running the main loop */
2061
2062 static GMainDispatch *
2063 get_dispatch (void)
2064 {
2065   static GStaticPrivate depth_private = G_STATIC_PRIVATE_INIT;
2066   GMainDispatch *dispatch = g_static_private_get (&depth_private);
2067   if (!dispatch)
2068     {
2069       dispatch = g_slice_new0 (GMainDispatch);
2070       g_static_private_set (&depth_private, dispatch, g_main_dispatch_free);
2071     }
2072
2073   return dispatch;
2074 }
2075
2076 /**
2077  * g_main_depth:
2078  *
2079  * Returns the depth of the stack of calls to
2080  * g_main_context_dispatch() on any #GMainContext in the current thread.
2081  *  That is, when called from the toplevel, it gives 0. When
2082  * called from within a callback from g_main_context_iteration()
2083  * (or g_main_loop_run(), etc.) it returns 1. When called from within 
2084  * a callback to a recursive call to g_main_context_iteration(),
2085  * it returns 2. And so forth.
2086  *
2087  * This function is useful in a situation like the following:
2088  * Imagine an extremely simple "garbage collected" system.
2089  *
2090  * |[
2091  * static GList *free_list;
2092  * 
2093  * gpointer
2094  * allocate_memory (gsize size)
2095  * { 
2096  *   gpointer result = g_malloc (size);
2097  *   free_list = g_list_prepend (free_list, result);
2098  *   return result;
2099  * }
2100  * 
2101  * void
2102  * free_allocated_memory (void)
2103  * {
2104  *   GList *l;
2105  *   for (l = free_list; l; l = l->next);
2106  *     g_free (l->data);
2107  *   g_list_free (free_list);
2108  *   free_list = NULL;
2109  *  }
2110  * 
2111  * [...]
2112  * 
2113  * while (TRUE); 
2114  *  {
2115  *    g_main_context_iteration (NULL, TRUE);
2116  *    free_allocated_memory();
2117  *   }
2118  * ]|
2119  *
2120  * This works from an application, however, if you want to do the same
2121  * thing from a library, it gets more difficult, since you no longer
2122  * control the main loop. You might think you can simply use an idle
2123  * function to make the call to free_allocated_memory(), but that
2124  * doesn't work, since the idle function could be called from a
2125  * recursive callback. This can be fixed by using g_main_depth()
2126  *
2127  * |[
2128  * gpointer
2129  * allocate_memory (gsize size)
2130  * { 
2131  *   FreeListBlock *block = g_new (FreeListBlock, 1);
2132  *   block->mem = g_malloc (size);
2133  *   block->depth = g_main_depth ();   
2134  *   free_list = g_list_prepend (free_list, block);
2135  *   return block->mem;
2136  * }
2137  * 
2138  * void
2139  * free_allocated_memory (void)
2140  * {
2141  *   GList *l;
2142  *   
2143  *   int depth = g_main_depth ();
2144  *   for (l = free_list; l; );
2145  *     {
2146  *       GList *next = l->next;
2147  *       FreeListBlock *block = l->data;
2148  *       if (block->depth > depth)
2149  *         {
2150  *           g_free (block->mem);
2151  *           g_free (block);
2152  *           free_list = g_list_delete_link (free_list, l);
2153  *         }
2154  *               
2155  *       l = next;
2156  *     }
2157  *   }
2158  * ]|
2159  *
2160  * There is a temptation to use g_main_depth() to solve
2161  * problems with reentrancy. For instance, while waiting for data
2162  * to be received from the network in response to a menu item,
2163  * the menu item might be selected again. It might seem that
2164  * one could make the menu item's callback return immediately
2165  * and do nothing if g_main_depth() returns a value greater than 1.
2166  * However, this should be avoided since the user then sees selecting
2167  * the menu item do nothing. Furthermore, you'll find yourself adding
2168  * these checks all over your code, since there are doubtless many,
2169  * many things that the user could do. Instead, you can use the
2170  * following techniques:
2171  *
2172  * <orderedlist>
2173  *  <listitem>
2174  *   <para>
2175  *     Use gtk_widget_set_sensitive() or modal dialogs to prevent
2176  *     the user from interacting with elements while the main
2177  *     loop is recursing.
2178  *   </para>
2179  *  </listitem>
2180  *  <listitem>
2181  *   <para>
2182  *     Avoid main loop recursion in situations where you can't handle
2183  *     arbitrary  callbacks. Instead, structure your code so that you
2184  *     simply return to the main loop and then get called again when
2185  *     there is more work to do.
2186  *   </para>
2187  *  </listitem>
2188  * </orderedlist>
2189  * 
2190  * Return value: The main loop recursion level in the current thread
2191  **/
2192 int
2193 g_main_depth (void)
2194 {
2195   GMainDispatch *dispatch = get_dispatch ();
2196   return dispatch->depth;
2197 }
2198
2199 /**
2200  * g_main_current_source:
2201  *
2202  * Returns the currently firing source for this thread.
2203  * 
2204  * Return value: (transfer none): The currently firing source or %NULL.
2205  *
2206  * Since: 2.12
2207  */
2208 GSource *
2209 g_main_current_source (void)
2210 {
2211   GMainDispatch *dispatch = get_dispatch ();
2212   return dispatch->dispatching_sources ? dispatch->dispatching_sources->data : NULL;
2213 }
2214
2215 /**
2216  * g_source_is_destroyed:
2217  * @source: a #GSource
2218  *
2219  * Returns whether @source has been destroyed.
2220  *
2221  * This is important when you operate upon your objects 
2222  * from within idle handlers, but may have freed the object 
2223  * before the dispatch of your idle handler.
2224  *
2225  * |[
2226  * static gboolean 
2227  * idle_callback (gpointer data)
2228  * {
2229  *   SomeWidget *self = data;
2230  *    
2231  *   GDK_THREADS_ENTER (<!-- -->);
2232  *   /<!-- -->* do stuff with self *<!-- -->/
2233  *   self->idle_id = 0;
2234  *   GDK_THREADS_LEAVE (<!-- -->);
2235  *    
2236  *   return FALSE;
2237  * }
2238  *  
2239  * static void 
2240  * some_widget_do_stuff_later (SomeWidget *self)
2241  * {
2242  *   self->idle_id = g_idle_add (idle_callback, self);
2243  * }
2244  *  
2245  * static void 
2246  * some_widget_finalize (GObject *object)
2247  * {
2248  *   SomeWidget *self = SOME_WIDGET (object);
2249  *    
2250  *   if (self->idle_id)
2251  *     g_source_remove (self->idle_id);
2252  *    
2253  *   G_OBJECT_CLASS (parent_class)->finalize (object);
2254  * }
2255  * ]|
2256  *
2257  * This will fail in a multi-threaded application if the 
2258  * widget is destroyed before the idle handler fires due 
2259  * to the use after free in the callback. A solution, to 
2260  * this particular problem, is to check to if the source
2261  * has already been destroy within the callback.
2262  *
2263  * |[
2264  * static gboolean 
2265  * idle_callback (gpointer data)
2266  * {
2267  *   SomeWidget *self = data;
2268  *   
2269  *   GDK_THREADS_ENTER ();
2270  *   if (!g_source_is_destroyed (g_main_current_source ()))
2271  *     {
2272  *       /<!-- -->* do stuff with self *<!-- -->/
2273  *     }
2274  *   GDK_THREADS_LEAVE ();
2275  *   
2276  *   return FALSE;
2277  * }
2278  * ]|
2279  *
2280  * Return value: %TRUE if the source has been destroyed
2281  *
2282  * Since: 2.12
2283  */
2284 gboolean
2285 g_source_is_destroyed (GSource *source)
2286 {
2287   return SOURCE_DESTROYED (source);
2288 }
2289
2290 /* Temporarily remove all this source's file descriptors from the
2291  * poll(), so that if data comes available for one of the file descriptors
2292  * we don't continually spin in the poll()
2293  */
2294 /* HOLDS: source->context's lock */
2295 static void
2296 block_source (GSource *source)
2297 {
2298   GSList *tmp_list;
2299
2300   g_return_if_fail (!SOURCE_BLOCKED (source));
2301
2302   tmp_list = source->poll_fds;
2303   while (tmp_list)
2304     {
2305       g_main_context_remove_poll_unlocked (source->context, tmp_list->data);
2306       tmp_list = tmp_list->next;
2307     }
2308 }
2309
2310 /* HOLDS: source->context's lock */
2311 static void
2312 unblock_source (GSource *source)
2313 {
2314   GSList *tmp_list;
2315   
2316   g_return_if_fail (!SOURCE_BLOCKED (source)); /* Source already unblocked */
2317   g_return_if_fail (!SOURCE_DESTROYED (source));
2318   
2319   tmp_list = source->poll_fds;
2320   while (tmp_list)
2321     {
2322       g_main_context_add_poll_unlocked (source->context, source->priority, tmp_list->data);
2323       tmp_list = tmp_list->next;
2324     }
2325 }
2326
2327 /* HOLDS: context's lock */
2328 static void
2329 g_main_dispatch (GMainContext *context)
2330 {
2331   GMainDispatch *current = get_dispatch ();
2332   guint i;
2333
2334   for (i = 0; i < context->pending_dispatches->len; i++)
2335     {
2336       GSource *source = context->pending_dispatches->pdata[i];
2337
2338       context->pending_dispatches->pdata[i] = NULL;
2339       g_assert (source);
2340
2341       source->flags &= ~G_SOURCE_READY;
2342
2343       if (!SOURCE_DESTROYED (source))
2344         {
2345           gboolean was_in_call;
2346           gpointer user_data = NULL;
2347           GSourceFunc callback = NULL;
2348           GSourceCallbackFuncs *cb_funcs;
2349           gpointer cb_data;
2350           gboolean need_destroy;
2351
2352           gboolean (*dispatch) (GSource *,
2353                                 GSourceFunc,
2354                                 gpointer);
2355           GSList current_source_link;
2356
2357           dispatch = source->source_funcs->dispatch;
2358           cb_funcs = source->callback_funcs;
2359           cb_data = source->callback_data;
2360
2361           if (cb_funcs)
2362             cb_funcs->ref (cb_data);
2363           
2364           if ((source->flags & G_SOURCE_CAN_RECURSE) == 0)
2365             block_source (source);
2366           
2367           was_in_call = source->flags & G_HOOK_FLAG_IN_CALL;
2368           source->flags |= G_HOOK_FLAG_IN_CALL;
2369
2370           if (cb_funcs)
2371             cb_funcs->get (cb_data, source, &callback, &user_data);
2372
2373           UNLOCK_CONTEXT (context);
2374
2375           current->depth++;
2376           /* The on-stack allocation of the GSList is unconventional, but
2377            * we know that the lifetime of the link is bounded to this
2378            * function as the link is kept in a thread specific list and
2379            * not manipulated outside of this function and its descendants.
2380            * Avoiding the overhead of a g_slist_alloc() is useful as many
2381            * applications do little more than dispatch events.
2382            *
2383            * This is a performance hack - do not revert to g_slist_prepend()!
2384            */
2385           current_source_link.data = source;
2386           current_source_link.next = current->dispatching_sources;
2387           current->dispatching_sources = &current_source_link;
2388           need_destroy = ! dispatch (source,
2389                                      callback,
2390                                      user_data);
2391           g_assert (current->dispatching_sources == &current_source_link);
2392           current->dispatching_sources = current_source_link.next;
2393           current->depth--;
2394           
2395           if (cb_funcs)
2396             cb_funcs->unref (cb_data);
2397
2398           LOCK_CONTEXT (context);
2399           
2400           if (!was_in_call)
2401             source->flags &= ~G_HOOK_FLAG_IN_CALL;
2402
2403           if ((source->flags & G_SOURCE_CAN_RECURSE) == 0 &&
2404               !SOURCE_DESTROYED (source))
2405             unblock_source (source);
2406           
2407           /* Note: this depends on the fact that we can't switch
2408            * sources from one main context to another
2409            */
2410           if (need_destroy && !SOURCE_DESTROYED (source))
2411             {
2412               g_assert (source->context == context);
2413               g_source_destroy_internal (source, context, TRUE);
2414             }
2415         }
2416       
2417       SOURCE_UNREF (source, context);
2418     }
2419
2420   g_ptr_array_set_size (context->pending_dispatches, 0);
2421 }
2422
2423 /* Holds context's lock */
2424 static inline GSource *
2425 next_valid_source (GMainContext *context,
2426                    GSource      *source)
2427 {
2428   GSource *new_source = source ? source->next : context->source_list;
2429
2430   while (new_source)
2431     {
2432       if (!SOURCE_DESTROYED (new_source))
2433         {
2434           new_source->ref_count++;
2435           break;
2436         }
2437       
2438       new_source = new_source->next;
2439     }
2440
2441   if (source)
2442     SOURCE_UNREF (source, context);
2443           
2444   return new_source;
2445 }
2446
2447 /**
2448  * g_main_context_acquire:
2449  * @context: a #GMainContext
2450  * 
2451  * Tries to become the owner of the specified context.
2452  * If some other thread is the owner of the context,
2453  * returns %FALSE immediately. Ownership is properly
2454  * recursive: the owner can require ownership again
2455  * and will release ownership when g_main_context_release()
2456  * is called as many times as g_main_context_acquire().
2457  *
2458  * You must be the owner of a context before you
2459  * can call g_main_context_prepare(), g_main_context_query(),
2460  * g_main_context_check(), g_main_context_dispatch().
2461  * 
2462  * Return value: %TRUE if the operation succeeded, and
2463  *   this thread is now the owner of @context.
2464  **/
2465 gboolean 
2466 g_main_context_acquire (GMainContext *context)
2467 {
2468   gboolean result = FALSE;
2469   GThread *self = G_THREAD_SELF;
2470
2471   if (context == NULL)
2472     context = g_main_context_default ();
2473   
2474   LOCK_CONTEXT (context);
2475
2476   if (!context->owner)
2477     {
2478       context->owner = self;
2479       g_assert (context->owner_count == 0);
2480     }
2481
2482   if (context->owner == self)
2483     {
2484       context->owner_count++;
2485       result = TRUE;
2486     }
2487
2488   UNLOCK_CONTEXT (context); 
2489   
2490   return result;
2491 }
2492
2493 /**
2494  * g_main_context_release:
2495  * @context: a #GMainContext
2496  * 
2497  * Releases ownership of a context previously acquired by this thread
2498  * with g_main_context_acquire(). If the context was acquired multiple
2499  * times, the ownership will be released only when g_main_context_release()
2500  * is called as many times as it was acquired.
2501  **/
2502 void
2503 g_main_context_release (GMainContext *context)
2504 {
2505   if (context == NULL)
2506     context = g_main_context_default ();
2507   
2508   LOCK_CONTEXT (context);
2509
2510   context->owner_count--;
2511   if (context->owner_count == 0)
2512     {
2513       context->owner = NULL;
2514
2515       if (context->waiters)
2516         {
2517           GMainWaiter *waiter = context->waiters->data;
2518           gboolean loop_internal_waiter = (waiter->mutex == &context->mutex);
2519           context->waiters = g_slist_delete_link (context->waiters,
2520                                                   context->waiters);
2521           if (!loop_internal_waiter)
2522             g_mutex_lock (waiter->mutex);
2523           
2524           g_cond_signal (waiter->cond);
2525           
2526           if (!loop_internal_waiter)
2527             g_mutex_unlock (waiter->mutex);
2528         }
2529     }
2530
2531   UNLOCK_CONTEXT (context); 
2532 }
2533
2534 /**
2535  * g_main_context_wait:
2536  * @context: a #GMainContext
2537  * @cond: a condition variable
2538  * @mutex: a mutex, currently held
2539  * 
2540  * Tries to become the owner of the specified context,
2541  * as with g_main_context_acquire(). But if another thread
2542  * is the owner, atomically drop @mutex and wait on @cond until 
2543  * that owner releases ownership or until @cond is signaled, then
2544  * try again (once) to become the owner.
2545  * 
2546  * Return value: %TRUE if the operation succeeded, and
2547  *   this thread is now the owner of @context.
2548  **/
2549 gboolean
2550 g_main_context_wait (GMainContext *context,
2551                      GCond        *cond,
2552                      GMutex       *mutex)
2553 {
2554   gboolean result = FALSE;
2555   GThread *self = G_THREAD_SELF;
2556   gboolean loop_internal_waiter;
2557   
2558   if (context == NULL)
2559     context = g_main_context_default ();
2560
2561   loop_internal_waiter = (mutex == &context->mutex);
2562   
2563   if (!loop_internal_waiter)
2564     LOCK_CONTEXT (context);
2565
2566   if (context->owner && context->owner != self)
2567     {
2568       GMainWaiter waiter;
2569
2570       waiter.cond = cond;
2571       waiter.mutex = mutex;
2572
2573       context->waiters = g_slist_append (context->waiters, &waiter);
2574       
2575       if (!loop_internal_waiter)
2576         UNLOCK_CONTEXT (context);
2577       g_cond_wait (cond, mutex);
2578       if (!loop_internal_waiter)      
2579         LOCK_CONTEXT (context);
2580
2581       context->waiters = g_slist_remove (context->waiters, &waiter);
2582     }
2583
2584   if (!context->owner)
2585     {
2586       context->owner = self;
2587       g_assert (context->owner_count == 0);
2588     }
2589
2590   if (context->owner == self)
2591     {
2592       context->owner_count++;
2593       result = TRUE;
2594     }
2595
2596   if (!loop_internal_waiter)
2597     UNLOCK_CONTEXT (context); 
2598   
2599   return result;
2600 }
2601
2602 /**
2603  * g_main_context_prepare:
2604  * @context: a #GMainContext
2605  * @priority: location to store priority of highest priority
2606  *            source already ready.
2607  * 
2608  * Prepares to poll sources within a main loop. The resulting information
2609  * for polling is determined by calling g_main_context_query ().
2610  * 
2611  * Return value: %TRUE if some source is ready to be dispatched
2612  *               prior to polling.
2613  **/
2614 gboolean
2615 g_main_context_prepare (GMainContext *context,
2616                         gint         *priority)
2617 {
2618   gint i;
2619   gint n_ready = 0;
2620   gint current_priority = G_MAXINT;
2621   GSource *source;
2622
2623   if (context == NULL)
2624     context = g_main_context_default ();
2625   
2626   LOCK_CONTEXT (context);
2627
2628   context->time_is_fresh = FALSE;
2629
2630   if (context->in_check_or_prepare)
2631     {
2632       g_warning ("g_main_context_prepare() called recursively from within a source's check() or "
2633                  "prepare() member.");
2634       UNLOCK_CONTEXT (context);
2635       return FALSE;
2636     }
2637
2638 #if 0
2639   /* If recursing, finish up current dispatch, before starting over */
2640   if (context->pending_dispatches)
2641     {
2642       if (dispatch)
2643         g_main_dispatch (context, &current_time);
2644       
2645       UNLOCK_CONTEXT (context);
2646       return TRUE;
2647     }
2648 #endif
2649
2650   /* If recursing, clear list of pending dispatches */
2651
2652   for (i = 0; i < context->pending_dispatches->len; i++)
2653     {
2654       if (context->pending_dispatches->pdata[i])
2655         SOURCE_UNREF ((GSource *)context->pending_dispatches->pdata[i], context);
2656     }
2657   g_ptr_array_set_size (context->pending_dispatches, 0);
2658   
2659   /* Prepare all sources */
2660
2661   context->timeout = -1;
2662   
2663   source = next_valid_source (context, NULL);
2664   while (source)
2665     {
2666       gint source_timeout = -1;
2667
2668       if ((n_ready > 0) && (source->priority > current_priority))
2669         {
2670           SOURCE_UNREF (source, context);
2671           break;
2672         }
2673       if (SOURCE_BLOCKED (source))
2674         goto next;
2675
2676       if (!(source->flags & G_SOURCE_READY))
2677         {
2678           gboolean result;
2679           gboolean (*prepare)  (GSource  *source, 
2680                                 gint     *timeout);
2681
2682           prepare = source->source_funcs->prepare;
2683           context->in_check_or_prepare++;
2684           UNLOCK_CONTEXT (context);
2685
2686           result = (*prepare) (source, &source_timeout);
2687
2688           LOCK_CONTEXT (context);
2689           context->in_check_or_prepare--;
2690
2691           if (result)
2692             {
2693               GSource *ready_source = source;
2694
2695               while (ready_source)
2696                 {
2697                   ready_source->flags |= G_SOURCE_READY;
2698                   ready_source = ready_source->priv ? ready_source->priv->parent_source : NULL;
2699                 }
2700             }
2701         }
2702
2703       if (source->flags & G_SOURCE_READY)
2704         {
2705           n_ready++;
2706           current_priority = source->priority;
2707           context->timeout = 0;
2708         }
2709       
2710       if (source_timeout >= 0)
2711         {
2712           if (context->timeout < 0)
2713             context->timeout = source_timeout;
2714           else
2715             context->timeout = MIN (context->timeout, source_timeout);
2716         }
2717
2718     next:
2719       source = next_valid_source (context, source);
2720     }
2721
2722   UNLOCK_CONTEXT (context);
2723   
2724   if (priority)
2725     *priority = current_priority;
2726   
2727   return (n_ready > 0);
2728 }
2729
2730 /**
2731  * g_main_context_query:
2732  * @context: a #GMainContext
2733  * @max_priority: maximum priority source to check
2734  * @timeout_: (out): location to store timeout to be used in polling
2735  * @fds: (out caller-allocates) (array length=n_fds): location to
2736  *       store #GPollFD records that need to be polled.
2737  * @n_fds: length of @fds.
2738  * 
2739  * Determines information necessary to poll this main loop.
2740  * 
2741  * Return value: the number of records actually stored in @fds,
2742  *   or, if more than @n_fds records need to be stored, the number
2743  *   of records that need to be stored.
2744  **/
2745 gint
2746 g_main_context_query (GMainContext *context,
2747                       gint          max_priority,
2748                       gint         *timeout,
2749                       GPollFD      *fds,
2750                       gint          n_fds)
2751 {
2752   gint n_poll;
2753   GPollRec *pollrec;
2754   
2755   LOCK_CONTEXT (context);
2756
2757   pollrec = context->poll_records;
2758   n_poll = 0;
2759   while (pollrec && max_priority >= pollrec->priority)
2760     {
2761       /* We need to include entries with fd->events == 0 in the array because
2762        * otherwise if the application changes fd->events behind our back and 
2763        * makes it non-zero, we'll be out of sync when we check the fds[] array.
2764        * (Changing fd->events after adding an FD wasn't an anticipated use of 
2765        * this API, but it occurs in practice.) */
2766       if (n_poll < n_fds)
2767         {
2768           fds[n_poll].fd = pollrec->fd->fd;
2769           /* In direct contradiction to the Unix98 spec, IRIX runs into
2770            * difficulty if you pass in POLLERR, POLLHUP or POLLNVAL
2771            * flags in the events field of the pollfd while it should
2772            * just ignoring them. So we mask them out here.
2773            */
2774           fds[n_poll].events = pollrec->fd->events & ~(G_IO_ERR|G_IO_HUP|G_IO_NVAL);
2775           fds[n_poll].revents = 0;
2776         }
2777
2778       pollrec = pollrec->next;
2779       n_poll++;
2780     }
2781
2782   context->poll_changed = FALSE;
2783   
2784   if (timeout)
2785     {
2786       *timeout = context->timeout;
2787       if (*timeout != 0)
2788         context->time_is_fresh = FALSE;
2789     }
2790   
2791   UNLOCK_CONTEXT (context);
2792
2793   return n_poll;
2794 }
2795
2796 /**
2797  * g_main_context_check:
2798  * @context: a #GMainContext
2799  * @max_priority: the maximum numerical priority of sources to check
2800  * @fds: (array length=n_fds): array of #GPollFD's that was passed to
2801  *       the last call to g_main_context_query()
2802  * @n_fds: return value of g_main_context_query()
2803  * 
2804  * Passes the results of polling back to the main loop.
2805  * 
2806  * Return value: %TRUE if some sources are ready to be dispatched.
2807  **/
2808 gboolean
2809 g_main_context_check (GMainContext *context,
2810                       gint          max_priority,
2811                       GPollFD      *fds,
2812                       gint          n_fds)
2813 {
2814   GSource *source;
2815   GPollRec *pollrec;
2816   gint n_ready = 0;
2817   gint i;
2818    
2819   LOCK_CONTEXT (context);
2820
2821   if (context->in_check_or_prepare)
2822     {
2823       g_warning ("g_main_context_check() called recursively from within a source's check() or "
2824                  "prepare() member.");
2825       UNLOCK_CONTEXT (context);
2826       return FALSE;
2827     }
2828
2829   if (context->wake_up_rec.events)
2830     g_wakeup_acknowledge (context->wakeup);
2831
2832   /* If the set of poll file descriptors changed, bail out
2833    * and let the main loop rerun
2834    */
2835   if (context->poll_changed)
2836     {
2837       UNLOCK_CONTEXT (context);
2838       return FALSE;
2839     }
2840   
2841   pollrec = context->poll_records;
2842   i = 0;
2843   while (i < n_fds)
2844     {
2845       if (pollrec->fd->events)
2846         pollrec->fd->revents = fds[i].revents;
2847
2848       pollrec = pollrec->next;
2849       i++;
2850     }
2851
2852   source = next_valid_source (context, NULL);
2853   while (source)
2854     {
2855       if ((n_ready > 0) && (source->priority > max_priority))
2856         {
2857           SOURCE_UNREF (source, context);
2858           break;
2859         }
2860       if (SOURCE_BLOCKED (source))
2861         goto next;
2862
2863       if (!(source->flags & G_SOURCE_READY))
2864         {
2865           gboolean result;
2866           gboolean (*check) (GSource  *source);
2867
2868           check = source->source_funcs->check;
2869           
2870           context->in_check_or_prepare++;
2871           UNLOCK_CONTEXT (context);
2872           
2873           result = (*check) (source);
2874           
2875           LOCK_CONTEXT (context);
2876           context->in_check_or_prepare--;
2877           
2878           if (result)
2879             {
2880               GSource *ready_source = source;
2881
2882               while (ready_source)
2883                 {
2884                   ready_source->flags |= G_SOURCE_READY;
2885                   ready_source = ready_source->priv ? ready_source->priv->parent_source : NULL;
2886                 }
2887             }
2888         }
2889
2890       if (source->flags & G_SOURCE_READY)
2891         {
2892           source->ref_count++;
2893           g_ptr_array_add (context->pending_dispatches, source);
2894
2895           n_ready++;
2896
2897           /* never dispatch sources with less priority than the first
2898            * one we choose to dispatch
2899            */
2900           max_priority = source->priority;
2901         }
2902
2903     next:
2904       source = next_valid_source (context, source);
2905     }
2906
2907   UNLOCK_CONTEXT (context);
2908
2909   return n_ready > 0;
2910 }
2911
2912 /**
2913  * g_main_context_dispatch:
2914  * @context: a #GMainContext
2915  * 
2916  * Dispatches all pending sources.
2917  **/
2918 void
2919 g_main_context_dispatch (GMainContext *context)
2920 {
2921   LOCK_CONTEXT (context);
2922
2923   if (context->pending_dispatches->len > 0)
2924     {
2925       g_main_dispatch (context);
2926     }
2927
2928   UNLOCK_CONTEXT (context);
2929 }
2930
2931 /* HOLDS context lock */
2932 static gboolean
2933 g_main_context_iterate (GMainContext *context,
2934                         gboolean      block,
2935                         gboolean      dispatch,
2936                         GThread      *self)
2937 {
2938   gint max_priority;
2939   gint timeout;
2940   gboolean some_ready;
2941   gint nfds, allocated_nfds;
2942   GPollFD *fds = NULL;
2943
2944   UNLOCK_CONTEXT (context);
2945
2946   if (!g_main_context_acquire (context))
2947     {
2948       gboolean got_ownership;
2949
2950       LOCK_CONTEXT (context);
2951
2952       if (!block)
2953         return FALSE;
2954
2955       if (!context->cond)
2956         context->cond = g_cond_new ();
2957
2958       got_ownership = g_main_context_wait (context,
2959                                            context->cond,
2960                                            &context->mutex);
2961
2962       if (!got_ownership)
2963         return FALSE;
2964     }
2965   else
2966     LOCK_CONTEXT (context);
2967   
2968   if (!context->cached_poll_array)
2969     {
2970       context->cached_poll_array_size = context->n_poll_records;
2971       context->cached_poll_array = g_new (GPollFD, context->n_poll_records);
2972     }
2973
2974   allocated_nfds = context->cached_poll_array_size;
2975   fds = context->cached_poll_array;
2976   
2977   UNLOCK_CONTEXT (context);
2978
2979   g_main_context_prepare (context, &max_priority); 
2980   
2981   while ((nfds = g_main_context_query (context, max_priority, &timeout, fds, 
2982                                        allocated_nfds)) > allocated_nfds)
2983     {
2984       LOCK_CONTEXT (context);
2985       g_free (fds);
2986       context->cached_poll_array_size = allocated_nfds = nfds;
2987       context->cached_poll_array = fds = g_new (GPollFD, nfds);
2988       UNLOCK_CONTEXT (context);
2989     }
2990
2991   if (!block)
2992     timeout = 0;
2993   
2994   g_assert (!g_main_context_fork_detected);
2995   g_main_context_poll (context, timeout, max_priority, fds, nfds);
2996   
2997   some_ready = g_main_context_check (context, max_priority, fds, nfds);
2998   
2999   if (dispatch)
3000     g_main_context_dispatch (context);
3001   
3002   g_main_context_release (context);
3003
3004   LOCK_CONTEXT (context);
3005
3006   return some_ready;
3007 }
3008
3009 /**
3010  * g_main_context_pending:
3011  * @context: a #GMainContext (if %NULL, the default context will be used)
3012  *
3013  * Checks if any sources have pending events for the given context.
3014  * 
3015  * Return value: %TRUE if events are pending.
3016  **/
3017 gboolean 
3018 g_main_context_pending (GMainContext *context)
3019 {
3020   gboolean retval;
3021
3022   if (!context)
3023     context = g_main_context_default();
3024
3025   LOCK_CONTEXT (context);
3026   retval = g_main_context_iterate (context, FALSE, FALSE, G_THREAD_SELF);
3027   UNLOCK_CONTEXT (context);
3028   
3029   return retval;
3030 }
3031
3032 /**
3033  * g_main_context_iteration:
3034  * @context: a #GMainContext (if %NULL, the default context will be used) 
3035  * @may_block: whether the call may block.
3036  * 
3037  * Runs a single iteration for the given main loop. This involves
3038  * checking to see if any event sources are ready to be processed,
3039  * then if no events sources are ready and @may_block is %TRUE, waiting
3040  * for a source to become ready, then dispatching the highest priority
3041  * events sources that are ready. Otherwise, if @may_block is %FALSE 
3042  * sources are not waited to become ready, only those highest priority 
3043  * events sources will be dispatched (if any), that are ready at this 
3044  * given moment without further waiting.
3045  *
3046  * Note that even when @may_block is %TRUE, it is still possible for 
3047  * g_main_context_iteration() to return %FALSE, since the the wait may 
3048  * be interrupted for other reasons than an event source becoming ready.
3049  * 
3050  * Return value: %TRUE if events were dispatched.
3051  **/
3052 gboolean
3053 g_main_context_iteration (GMainContext *context, gboolean may_block)
3054 {
3055   gboolean retval;
3056
3057   if (!context)
3058     context = g_main_context_default();
3059   
3060   LOCK_CONTEXT (context);
3061   retval = g_main_context_iterate (context, may_block, TRUE, G_THREAD_SELF);
3062   UNLOCK_CONTEXT (context);
3063   
3064   return retval;
3065 }
3066
3067 /**
3068  * g_main_loop_new:
3069  * @context: (allow-none): a #GMainContext  (if %NULL, the default context will be used).
3070  * @is_running: set to %TRUE to indicate that the loop is running. This
3071  * is not very important since calling g_main_loop_run() will set this to
3072  * %TRUE anyway.
3073  * 
3074  * Creates a new #GMainLoop structure.
3075  * 
3076  * Return value: a new #GMainLoop.
3077  **/
3078 GMainLoop *
3079 g_main_loop_new (GMainContext *context,
3080                  gboolean      is_running)
3081 {
3082   GMainLoop *loop;
3083
3084   if (!context)
3085     context = g_main_context_default();
3086   
3087   g_main_context_ref (context);
3088
3089   loop = g_new0 (GMainLoop, 1);
3090   loop->context = context;
3091   loop->is_running = is_running != FALSE;
3092   loop->ref_count = 1;
3093   
3094   return loop;
3095 }
3096
3097 /**
3098  * g_main_loop_ref:
3099  * @loop: a #GMainLoop
3100  * 
3101  * Increases the reference count on a #GMainLoop object by one.
3102  * 
3103  * Return value: @loop
3104  **/
3105 GMainLoop *
3106 g_main_loop_ref (GMainLoop *loop)
3107 {
3108   g_return_val_if_fail (loop != NULL, NULL);
3109   g_return_val_if_fail (g_atomic_int_get (&loop->ref_count) > 0, NULL);
3110
3111   g_atomic_int_inc (&loop->ref_count);
3112
3113   return loop;
3114 }
3115
3116 /**
3117  * g_main_loop_unref:
3118  * @loop: a #GMainLoop
3119  * 
3120  * Decreases the reference count on a #GMainLoop object by one. If
3121  * the result is zero, free the loop and free all associated memory.
3122  **/
3123 void
3124 g_main_loop_unref (GMainLoop *loop)
3125 {
3126   g_return_if_fail (loop != NULL);
3127   g_return_if_fail (g_atomic_int_get (&loop->ref_count) > 0);
3128
3129   if (!g_atomic_int_dec_and_test (&loop->ref_count))
3130     return;
3131
3132   g_main_context_unref (loop->context);
3133   g_free (loop);
3134 }
3135
3136 /**
3137  * g_main_loop_run:
3138  * @loop: a #GMainLoop
3139  * 
3140  * Runs a main loop until g_main_loop_quit() is called on the loop.
3141  * If this is called for the thread of the loop's #GMainContext,
3142  * it will process events from the loop, otherwise it will
3143  * simply wait.
3144  **/
3145 void 
3146 g_main_loop_run (GMainLoop *loop)
3147 {
3148   GThread *self = G_THREAD_SELF;
3149
3150   g_return_if_fail (loop != NULL);
3151   g_return_if_fail (g_atomic_int_get (&loop->ref_count) > 0);
3152
3153   if (!g_main_context_acquire (loop->context))
3154     {
3155       gboolean got_ownership = FALSE;
3156       
3157       /* Another thread owns this context */
3158       LOCK_CONTEXT (loop->context);
3159
3160       g_atomic_int_inc (&loop->ref_count);
3161
3162       if (!loop->is_running)
3163         loop->is_running = TRUE;
3164
3165       if (!loop->context->cond)
3166         loop->context->cond = g_cond_new ();
3167           
3168       while (loop->is_running && !got_ownership)
3169         got_ownership = g_main_context_wait (loop->context,
3170                                              loop->context->cond,
3171                                              &loop->context->mutex);
3172       
3173       if (!loop->is_running)
3174         {
3175           UNLOCK_CONTEXT (loop->context);
3176           if (got_ownership)
3177             g_main_context_release (loop->context);
3178           g_main_loop_unref (loop);
3179           return;
3180         }
3181
3182       g_assert (got_ownership);
3183     }
3184   else
3185     LOCK_CONTEXT (loop->context);
3186
3187   if (loop->context->in_check_or_prepare)
3188     {
3189       g_warning ("g_main_loop_run(): called recursively from within a source's "
3190                  "check() or prepare() member, iteration not possible.");
3191       return;
3192     }
3193
3194   g_atomic_int_inc (&loop->ref_count);
3195   loop->is_running = TRUE;
3196   while (loop->is_running)
3197     g_main_context_iterate (loop->context, TRUE, TRUE, self);
3198
3199   UNLOCK_CONTEXT (loop->context);
3200   
3201   g_main_context_release (loop->context);
3202   
3203   g_main_loop_unref (loop);
3204 }
3205
3206 /**
3207  * g_main_loop_quit:
3208  * @loop: a #GMainLoop
3209  * 
3210  * Stops a #GMainLoop from running. Any calls to g_main_loop_run()
3211  * for the loop will return. 
3212  *
3213  * Note that sources that have already been dispatched when 
3214  * g_main_loop_quit() is called will still be executed.
3215  **/
3216 void 
3217 g_main_loop_quit (GMainLoop *loop)
3218 {
3219   g_return_if_fail (loop != NULL);
3220   g_return_if_fail (g_atomic_int_get (&loop->ref_count) > 0);
3221
3222   LOCK_CONTEXT (loop->context);
3223   loop->is_running = FALSE;
3224   g_wakeup_signal (loop->context->wakeup);
3225
3226   if (loop->context->cond)
3227     g_cond_broadcast (loop->context->cond);
3228
3229   UNLOCK_CONTEXT (loop->context);
3230 }
3231
3232 /**
3233  * g_main_loop_is_running:
3234  * @loop: a #GMainLoop.
3235  * 
3236  * Checks to see if the main loop is currently being run via g_main_loop_run().
3237  * 
3238  * Return value: %TRUE if the mainloop is currently being run.
3239  **/
3240 gboolean
3241 g_main_loop_is_running (GMainLoop *loop)
3242 {
3243   g_return_val_if_fail (loop != NULL, FALSE);
3244   g_return_val_if_fail (g_atomic_int_get (&loop->ref_count) > 0, FALSE);
3245
3246   return loop->is_running;
3247 }
3248
3249 /**
3250  * g_main_loop_get_context:
3251  * @loop: a #GMainLoop.
3252  * 
3253  * Returns the #GMainContext of @loop.
3254  * 
3255  * Return value: (transfer none): the #GMainContext of @loop
3256  **/
3257 GMainContext *
3258 g_main_loop_get_context (GMainLoop *loop)
3259 {
3260   g_return_val_if_fail (loop != NULL, NULL);
3261   g_return_val_if_fail (g_atomic_int_get (&loop->ref_count) > 0, NULL);
3262  
3263   return loop->context;
3264 }
3265
3266 /* HOLDS: context's lock */
3267 static void
3268 g_main_context_poll (GMainContext *context,
3269                      gint          timeout,
3270                      gint          priority,
3271                      GPollFD      *fds,
3272                      gint          n_fds)
3273 {
3274 #ifdef  G_MAIN_POLL_DEBUG
3275   GTimer *poll_timer;
3276   GPollRec *pollrec;
3277   gint i;
3278 #endif
3279
3280   GPollFunc poll_func;
3281
3282   if (n_fds || timeout != 0)
3283     {
3284 #ifdef  G_MAIN_POLL_DEBUG
3285       if (_g_main_poll_debug)
3286         {
3287           g_print ("polling context=%p n=%d timeout=%d\n",
3288                    context, n_fds, timeout);
3289           poll_timer = g_timer_new ();
3290         }
3291 #endif
3292
3293       LOCK_CONTEXT (context);
3294
3295       poll_func = context->poll_func;
3296       
3297       UNLOCK_CONTEXT (context);
3298       if ((*poll_func) (fds, n_fds, timeout) < 0 && errno != EINTR)
3299         {
3300 #ifndef G_OS_WIN32
3301           g_warning ("poll(2) failed due to: %s.",
3302                      g_strerror (errno));
3303 #else
3304           /* If g_poll () returns -1, it has already called g_warning() */
3305 #endif
3306         }
3307       
3308 #ifdef  G_MAIN_POLL_DEBUG
3309       if (_g_main_poll_debug)
3310         {
3311           LOCK_CONTEXT (context);
3312
3313           g_print ("g_main_poll(%d) timeout: %d - elapsed %12.10f seconds",
3314                    n_fds,
3315                    timeout,
3316                    g_timer_elapsed (poll_timer, NULL));
3317           g_timer_destroy (poll_timer);
3318           pollrec = context->poll_records;
3319
3320           while (pollrec != NULL)
3321             {
3322               i = 0;
3323               while (i < n_fds)
3324                 {
3325                   if (fds[i].fd == pollrec->fd->fd &&
3326                       pollrec->fd->events &&
3327                       fds[i].revents)
3328                     {
3329                       g_print (" [" G_POLLFD_FORMAT " :", fds[i].fd);
3330                       if (fds[i].revents & G_IO_IN)
3331                         g_print ("i");
3332                       if (fds[i].revents & G_IO_OUT)
3333                         g_print ("o");
3334                       if (fds[i].revents & G_IO_PRI)
3335                         g_print ("p");
3336                       if (fds[i].revents & G_IO_ERR)
3337                         g_print ("e");
3338                       if (fds[i].revents & G_IO_HUP)
3339                         g_print ("h");
3340                       if (fds[i].revents & G_IO_NVAL)
3341                         g_print ("n");
3342                       g_print ("]");
3343                     }
3344                   i++;
3345                 }
3346               pollrec = pollrec->next;
3347             }
3348           g_print ("\n");
3349
3350           UNLOCK_CONTEXT (context);
3351         }
3352 #endif
3353     } /* if (n_fds || timeout != 0) */
3354 }
3355
3356 /**
3357  * g_main_context_add_poll:
3358  * @context: a #GMainContext (or %NULL for the default context)
3359  * @fd: a #GPollFD structure holding information about a file
3360  *      descriptor to watch.
3361  * @priority: the priority for this file descriptor which should be
3362  *      the same as the priority used for g_source_attach() to ensure that the
3363  *      file descriptor is polled whenever the results may be needed.
3364  * 
3365  * Adds a file descriptor to the set of file descriptors polled for
3366  * this context. This will very seldom be used directly. Instead
3367  * a typical event source will use g_source_add_poll() instead.
3368  **/
3369 void
3370 g_main_context_add_poll (GMainContext *context,
3371                          GPollFD      *fd,
3372                          gint          priority)
3373 {
3374   if (!context)
3375     context = g_main_context_default ();
3376   
3377   g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
3378   g_return_if_fail (fd);
3379
3380   LOCK_CONTEXT (context);
3381   g_main_context_add_poll_unlocked (context, priority, fd);
3382   UNLOCK_CONTEXT (context);
3383 }
3384
3385 /* HOLDS: main_loop_lock */
3386 static void 
3387 g_main_context_add_poll_unlocked (GMainContext *context,
3388                                   gint          priority,
3389                                   GPollFD      *fd)
3390 {
3391   GPollRec *prevrec, *nextrec;
3392   GPollRec *newrec = g_slice_new (GPollRec);
3393
3394   /* This file descriptor may be checked before we ever poll */
3395   fd->revents = 0;
3396   newrec->fd = fd;
3397   newrec->priority = priority;
3398
3399   prevrec = context->poll_records_tail;
3400   nextrec = NULL;
3401   while (prevrec && priority < prevrec->priority)
3402     {
3403       nextrec = prevrec;
3404       prevrec = prevrec->prev;
3405     }
3406
3407   if (prevrec)
3408     prevrec->next = newrec;
3409   else
3410     context->poll_records = newrec;
3411
3412   newrec->prev = prevrec;
3413   newrec->next = nextrec;
3414
3415   if (nextrec)
3416     nextrec->prev = newrec;
3417   else 
3418     context->poll_records_tail = newrec;
3419
3420   context->n_poll_records++;
3421
3422   context->poll_changed = TRUE;
3423
3424   /* Now wake up the main loop if it is waiting in the poll() */
3425   g_wakeup_signal (context->wakeup);
3426 }
3427
3428 /**
3429  * g_main_context_remove_poll:
3430  * @context:a #GMainContext 
3431  * @fd: a #GPollFD descriptor previously added with g_main_context_add_poll()
3432  * 
3433  * Removes file descriptor from the set of file descriptors to be
3434  * polled for a particular context.
3435  **/
3436 void
3437 g_main_context_remove_poll (GMainContext *context,
3438                             GPollFD      *fd)
3439 {
3440   if (!context)
3441     context = g_main_context_default ();
3442   
3443   g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
3444   g_return_if_fail (fd);
3445
3446   LOCK_CONTEXT (context);
3447   g_main_context_remove_poll_unlocked (context, fd);
3448   UNLOCK_CONTEXT (context);
3449 }
3450
3451 static void
3452 g_main_context_remove_poll_unlocked (GMainContext *context,
3453                                      GPollFD      *fd)
3454 {
3455   GPollRec *pollrec, *prevrec, *nextrec;
3456
3457   prevrec = NULL;
3458   pollrec = context->poll_records;
3459
3460   while (pollrec)
3461     {
3462       nextrec = pollrec->next;
3463       if (pollrec->fd == fd)
3464         {
3465           if (prevrec != NULL)
3466             prevrec->next = nextrec;
3467           else
3468             context->poll_records = nextrec;
3469
3470           if (nextrec != NULL)
3471             nextrec->prev = prevrec;
3472           else
3473             context->poll_records_tail = prevrec;
3474
3475           g_slice_free (GPollRec, pollrec);
3476
3477           context->n_poll_records--;
3478           break;
3479         }
3480       prevrec = pollrec;
3481       pollrec = nextrec;
3482     }
3483
3484   context->poll_changed = TRUE;
3485   
3486   /* Now wake up the main loop if it is waiting in the poll() */
3487   g_wakeup_signal (context->wakeup);
3488 }
3489
3490 /**
3491  * g_source_get_current_time:
3492  * @source:  a #GSource
3493  * @timeval: #GTimeVal structure in which to store current time.
3494  *
3495  * This function ignores @source and is otherwise the same as
3496  * g_get_current_time().
3497  *
3498  * Deprecated: 2.28: use g_source_get_time() instead
3499  **/
3500 void
3501 g_source_get_current_time (GSource  *source,
3502                            GTimeVal *timeval)
3503 {
3504   g_get_current_time (timeval);
3505 }
3506
3507 /**
3508  * g_source_get_time:
3509  * @source: a #GSource
3510  *
3511  * Gets the time to be used when checking this source. The advantage of
3512  * calling this function over calling g_get_monotonic_time() directly is
3513  * that when checking multiple sources, GLib can cache a single value
3514  * instead of having to repeatedly get the system monotonic time.
3515  *
3516  * The time here is the system monotonic time, if available, or some
3517  * other reasonable alternative otherwise.  See g_get_monotonic_time().
3518  *
3519  * Returns: the monotonic time in microseconds
3520  *
3521  * Since: 2.28
3522  **/
3523 gint64
3524 g_source_get_time (GSource *source)
3525 {
3526   GMainContext *context;
3527   gint64 result;
3528
3529   g_return_val_if_fail (source->context != NULL, 0);
3530
3531   context = source->context;
3532
3533   LOCK_CONTEXT (context);
3534
3535   if (!context->time_is_fresh)
3536     {
3537       context->time = g_get_monotonic_time ();
3538       context->time_is_fresh = TRUE;
3539     }
3540
3541   result = context->time;
3542
3543   UNLOCK_CONTEXT (context);
3544
3545   return result;
3546 }
3547
3548 /**
3549  * g_main_context_set_poll_func:
3550  * @context: a #GMainContext
3551  * @func: the function to call to poll all file descriptors
3552  * 
3553  * Sets the function to use to handle polling of file descriptors. It
3554  * will be used instead of the poll() system call 
3555  * (or GLib's replacement function, which is used where 
3556  * poll() isn't available).
3557  *
3558  * This function could possibly be used to integrate the GLib event
3559  * loop with an external event loop.
3560  **/
3561 void
3562 g_main_context_set_poll_func (GMainContext *context,
3563                               GPollFunc     func)
3564 {
3565   if (!context)
3566     context = g_main_context_default ();
3567   
3568   g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
3569
3570   LOCK_CONTEXT (context);
3571   
3572   if (func)
3573     context->poll_func = func;
3574   else
3575     context->poll_func = g_poll;
3576
3577   UNLOCK_CONTEXT (context);
3578 }
3579
3580 /**
3581  * g_main_context_get_poll_func:
3582  * @context: a #GMainContext
3583  * 
3584  * Gets the poll function set by g_main_context_set_poll_func().
3585  * 
3586  * Return value: the poll function
3587  **/
3588 GPollFunc
3589 g_main_context_get_poll_func (GMainContext *context)
3590 {
3591   GPollFunc result;
3592   
3593   if (!context)
3594     context = g_main_context_default ();
3595   
3596   g_return_val_if_fail (g_atomic_int_get (&context->ref_count) > 0, NULL);
3597
3598   LOCK_CONTEXT (context);
3599   result = context->poll_func;
3600   UNLOCK_CONTEXT (context);
3601
3602   return result;
3603 }
3604
3605 /**
3606  * g_main_context_wakeup:
3607  * @context: a #GMainContext
3608  * 
3609  * If @context is currently waiting in a poll(), interrupt
3610  * the poll(), and continue the iteration process.
3611  **/
3612 void
3613 g_main_context_wakeup (GMainContext *context)
3614 {
3615   if (!context)
3616     context = g_main_context_default ();
3617
3618   g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
3619
3620   g_wakeup_signal (context->wakeup);
3621 }
3622
3623 /**
3624  * g_main_context_is_owner:
3625  * @context: a #GMainContext
3626  * 
3627  * Determines whether this thread holds the (recursive)
3628  * ownership of this #GMainContext. This is useful to
3629  * know before waiting on another thread that may be
3630  * blocking to get ownership of @context.
3631  *
3632  * Returns: %TRUE if current thread is owner of @context.
3633  *
3634  * Since: 2.10
3635  **/
3636 gboolean
3637 g_main_context_is_owner (GMainContext *context)
3638 {
3639   gboolean is_owner;
3640
3641   if (!context)
3642     context = g_main_context_default ();
3643
3644   LOCK_CONTEXT (context);
3645   is_owner = context->owner == G_THREAD_SELF;
3646   UNLOCK_CONTEXT (context);
3647
3648   return is_owner;
3649 }
3650
3651 /* Timeouts */
3652
3653 static void
3654 g_timeout_set_expiration (GTimeoutSource *timeout_source,
3655                           gint64          current_time)
3656 {
3657   timeout_source->expiration = current_time +
3658                                (guint64) timeout_source->interval * 1000;
3659
3660   if (timeout_source->seconds)
3661     {
3662       gint64 remainder;
3663       static gint timer_perturb = -1;
3664
3665       if (timer_perturb == -1)
3666         {
3667           /*
3668            * we want a per machine/session unique 'random' value; try the dbus
3669            * address first, that has a UUID in it. If there is no dbus, use the
3670            * hostname for hashing.
3671            */
3672           const char *session_bus_address = g_getenv ("DBUS_SESSION_BUS_ADDRESS");
3673           if (!session_bus_address)
3674             session_bus_address = g_getenv ("HOSTNAME");
3675           if (session_bus_address)
3676             timer_perturb = ABS ((gint) g_str_hash (session_bus_address)) % 1000000;
3677           else
3678             timer_perturb = 0;
3679         }
3680
3681       /* We want the microseconds part of the timeout to land on the
3682        * 'timer_perturb' mark, but we need to make sure we don't try to
3683        * set the timeout in the past.  We do this by ensuring that we
3684        * always only *increase* the expiration time by adding a full
3685        * second in the case that the microsecond portion decreases.
3686        */
3687       timeout_source->expiration -= timer_perturb;
3688
3689       remainder = timeout_source->expiration % 1000000;
3690       if (remainder >= 1000000/4)
3691         timeout_source->expiration += 1000000;
3692
3693       timeout_source->expiration -= remainder;
3694       timeout_source->expiration += timer_perturb;
3695     }
3696 }
3697
3698 static gboolean
3699 g_timeout_prepare (GSource *source,
3700                    gint    *timeout)
3701 {
3702   GTimeoutSource *timeout_source = (GTimeoutSource *) source;
3703   gint64 now = g_source_get_time (source);
3704
3705   if (now < timeout_source->expiration)
3706     {
3707       /* Round up to ensure that we don't try again too early */
3708       *timeout = (timeout_source->expiration - now + 999) / 1000;
3709       return FALSE;
3710     }
3711
3712   *timeout = 0;
3713   return TRUE;
3714 }
3715
3716 static gboolean 
3717 g_timeout_check (GSource *source)
3718 {
3719   GTimeoutSource *timeout_source = (GTimeoutSource *) source;
3720   gint64 now = g_source_get_time (source);
3721
3722   return timeout_source->expiration <= now;
3723 }
3724
3725 static gboolean
3726 g_timeout_dispatch (GSource     *source,
3727                     GSourceFunc  callback,
3728                     gpointer     user_data)
3729 {
3730   GTimeoutSource *timeout_source = (GTimeoutSource *)source;
3731   gboolean again;
3732
3733   if (!callback)
3734     {
3735       g_warning ("Timeout source dispatched without callback\n"
3736                  "You must call g_source_set_callback().");
3737       return FALSE;
3738     }
3739
3740   again = callback (user_data);
3741
3742   if (again)
3743     g_timeout_set_expiration (timeout_source, g_source_get_time (source));
3744
3745   return again;
3746 }
3747
3748 /**
3749  * g_timeout_source_new:
3750  * @interval: the timeout interval in milliseconds.
3751  * 
3752  * Creates a new timeout source.
3753  *
3754  * The source will not initially be associated with any #GMainContext
3755  * and must be added to one with g_source_attach() before it will be
3756  * executed.
3757  *
3758  * The interval given is in terms of monotonic time, not wall clock
3759  * time.  See g_get_monotonic_time().
3760  * 
3761  * Return value: the newly-created timeout source
3762  **/
3763 GSource *
3764 g_timeout_source_new (guint interval)
3765 {
3766   GSource *source = g_source_new (&g_timeout_funcs, sizeof (GTimeoutSource));
3767   GTimeoutSource *timeout_source = (GTimeoutSource *)source;
3768
3769   timeout_source->interval = interval;
3770   g_timeout_set_expiration (timeout_source, g_get_monotonic_time ());
3771
3772   return source;
3773 }
3774
3775 /**
3776  * g_timeout_source_new_seconds:
3777  * @interval: the timeout interval in seconds
3778  *
3779  * Creates a new timeout source.
3780  *
3781  * The source will not initially be associated with any #GMainContext
3782  * and must be added to one with g_source_attach() before it will be
3783  * executed.
3784  *
3785  * The scheduling granularity/accuracy of this timeout source will be
3786  * in seconds.
3787  *
3788  * The interval given in terms of monotonic time, not wall clock time.
3789  * See g_get_monotonic_time().
3790  *
3791  * Return value: the newly-created timeout source
3792  *
3793  * Since: 2.14  
3794  **/
3795 GSource *
3796 g_timeout_source_new_seconds (guint interval)
3797 {
3798   GSource *source = g_source_new (&g_timeout_funcs, sizeof (GTimeoutSource));
3799   GTimeoutSource *timeout_source = (GTimeoutSource *)source;
3800
3801   timeout_source->interval = 1000 * interval;
3802   timeout_source->seconds = TRUE;
3803
3804   g_timeout_set_expiration (timeout_source, g_get_monotonic_time ());
3805
3806   return source;
3807 }
3808
3809
3810 /**
3811  * g_timeout_add_full:
3812  * @priority: the priority of the timeout source. Typically this will be in
3813  *            the range between #G_PRIORITY_DEFAULT and #G_PRIORITY_HIGH.
3814  * @interval: the time between calls to the function, in milliseconds
3815  *             (1/1000ths of a second)
3816  * @function: function to call
3817  * @data:     data to pass to @function
3818  * @notify:   function to call when the timeout is removed, or %NULL
3819  * 
3820  * Sets a function to be called at regular intervals, with the given
3821  * priority.  The function is called repeatedly until it returns
3822  * %FALSE, at which point the timeout is automatically destroyed and
3823  * the function will not be called again.  The @notify function is
3824  * called when the timeout is destroyed.  The first call to the
3825  * function will be at the end of the first @interval.
3826  *
3827  * Note that timeout functions may be delayed, due to the processing of other
3828  * event sources. Thus they should not be relied on for precise timing.
3829  * After each call to the timeout function, the time of the next
3830  * timeout is recalculated based on the current time and the given interval
3831  * (it does not try to 'catch up' time lost in delays).
3832  *
3833  * This internally creates a main loop source using g_timeout_source_new()
3834  * and attaches it to the main loop context using g_source_attach(). You can
3835  * do these steps manually if you need greater control.
3836  *
3837  * The interval given in terms of monotonic time, not wall clock time.
3838  * See g_get_monotonic_time().
3839  * 
3840  * Return value: the ID (greater than 0) of the event source.
3841  * Rename to: g_timeout_add
3842  **/
3843 guint
3844 g_timeout_add_full (gint           priority,
3845                     guint          interval,
3846                     GSourceFunc    function,
3847                     gpointer       data,
3848                     GDestroyNotify notify)
3849 {
3850   GSource *source;
3851   guint id;
3852   
3853   g_return_val_if_fail (function != NULL, 0);
3854
3855   source = g_timeout_source_new (interval);
3856
3857   if (priority != G_PRIORITY_DEFAULT)
3858     g_source_set_priority (source, priority);
3859
3860   g_source_set_callback (source, function, data, notify);
3861   id = g_source_attach (source, NULL);
3862   g_source_unref (source);
3863
3864   return id;
3865 }
3866
3867 /**
3868  * g_timeout_add:
3869  * @interval: the time between calls to the function, in milliseconds
3870  *             (1/1000ths of a second)
3871  * @function: function to call
3872  * @data:     data to pass to @function
3873  * 
3874  * Sets a function to be called at regular intervals, with the default
3875  * priority, #G_PRIORITY_DEFAULT.  The function is called repeatedly
3876  * until it returns %FALSE, at which point the timeout is automatically
3877  * destroyed and the function will not be called again.  The first call
3878  * to the function will be at the end of the first @interval.
3879  *
3880  * Note that timeout functions may be delayed, due to the processing of other
3881  * event sources. Thus they should not be relied on for precise timing.
3882  * After each call to the timeout function, the time of the next
3883  * timeout is recalculated based on the current time and the given interval
3884  * (it does not try to 'catch up' time lost in delays).
3885  *
3886  * If you want to have a timer in the "seconds" range and do not care
3887  * about the exact time of the first call of the timer, use the
3888  * g_timeout_add_seconds() function; this function allows for more
3889  * optimizations and more efficient system power usage.
3890  *
3891  * This internally creates a main loop source using g_timeout_source_new()
3892  * and attaches it to the main loop context using g_source_attach(). You can
3893  * do these steps manually if you need greater control.
3894  * 
3895  * The interval given is in terms of monotonic time, not wall clock
3896  * time.  See g_get_monotonic_time().
3897  * 
3898  * Return value: the ID (greater than 0) of the event source.
3899  **/
3900 guint
3901 g_timeout_add (guint32        interval,
3902                GSourceFunc    function,
3903                gpointer       data)
3904 {
3905   return g_timeout_add_full (G_PRIORITY_DEFAULT, 
3906                              interval, function, data, NULL);
3907 }
3908
3909 /**
3910  * g_timeout_add_seconds_full:
3911  * @priority: the priority of the timeout source. Typically this will be in
3912  *            the range between #G_PRIORITY_DEFAULT and #G_PRIORITY_HIGH.
3913  * @interval: the time between calls to the function, in seconds
3914  * @function: function to call
3915  * @data:     data to pass to @function
3916  * @notify:   function to call when the timeout is removed, or %NULL
3917  *
3918  * Sets a function to be called at regular intervals, with @priority.
3919  * The function is called repeatedly until it returns %FALSE, at which
3920  * point the timeout is automatically destroyed and the function will
3921  * not be called again.
3922  *
3923  * Unlike g_timeout_add(), this function operates at whole second granularity.
3924  * The initial starting point of the timer is determined by the implementation
3925  * and the implementation is expected to group multiple timers together so that
3926  * they fire all at the same time.
3927  * To allow this grouping, the @interval to the first timer is rounded
3928  * and can deviate up to one second from the specified interval.
3929  * Subsequent timer iterations will generally run at the specified interval.
3930  *
3931  * Note that timeout functions may be delayed, due to the processing of other
3932  * event sources. Thus they should not be relied on for precise timing.
3933  * After each call to the timeout function, the time of the next
3934  * timeout is recalculated based on the current time and the given @interval
3935  *
3936  * If you want timing more precise than whole seconds, use g_timeout_add()
3937  * instead.
3938  *
3939  * The grouping of timers to fire at the same time results in a more power
3940  * and CPU efficient behavior so if your timer is in multiples of seconds
3941  * and you don't require the first timer exactly one second from now, the
3942  * use of g_timeout_add_seconds() is preferred over g_timeout_add().
3943  *
3944  * This internally creates a main loop source using 
3945  * g_timeout_source_new_seconds() and attaches it to the main loop context 
3946  * using g_source_attach(). You can do these steps manually if you need 
3947  * greater control.
3948  * 
3949  * The interval given is in terms of monotonic time, not wall clock
3950  * time.  See g_get_monotonic_time().
3951  * 
3952  * Return value: the ID (greater than 0) of the event source.
3953  *
3954  * Rename to: g_timeout_add_seconds
3955  * Since: 2.14
3956  **/
3957 guint
3958 g_timeout_add_seconds_full (gint           priority,
3959                             guint32        interval,
3960                             GSourceFunc    function,
3961                             gpointer       data,
3962                             GDestroyNotify notify)
3963 {
3964   GSource *source;
3965   guint id;
3966
3967   g_return_val_if_fail (function != NULL, 0);
3968
3969   source = g_timeout_source_new_seconds (interval);
3970
3971   if (priority != G_PRIORITY_DEFAULT)
3972     g_source_set_priority (source, priority);
3973
3974   g_source_set_callback (source, function, data, notify);
3975   id = g_source_attach (source, NULL);
3976   g_source_unref (source);
3977
3978   return id;
3979 }
3980
3981 /**
3982  * g_timeout_add_seconds:
3983  * @interval: the time between calls to the function, in seconds
3984  * @function: function to call
3985  * @data: data to pass to @function
3986  *
3987  * Sets a function to be called at regular intervals with the default
3988  * priority, #G_PRIORITY_DEFAULT. The function is called repeatedly until
3989  * it returns %FALSE, at which point the timeout is automatically destroyed
3990  * and the function will not be called again.
3991  *
3992  * This internally creates a main loop source using
3993  * g_timeout_source_new_seconds() and attaches it to the main loop context
3994  * using g_source_attach(). You can do these steps manually if you need
3995  * greater control. Also see g_timeout_add_seconds_full().
3996  *
3997  * Note that the first call of the timer may not be precise for timeouts
3998  * of one second. If you need finer precision and have such a timeout,
3999  * you may want to use g_timeout_add() instead.
4000  *
4001  * The interval given is in terms of monotonic time, not wall clock
4002  * time.  See g_get_monotonic_time().
4003  * 
4004  * Return value: the ID (greater than 0) of the event source.
4005  *
4006  * Since: 2.14
4007  **/
4008 guint
4009 g_timeout_add_seconds (guint       interval,
4010                        GSourceFunc function,
4011                        gpointer    data)
4012 {
4013   g_return_val_if_fail (function != NULL, 0);
4014
4015   return g_timeout_add_seconds_full (G_PRIORITY_DEFAULT, interval, function, data, NULL);
4016 }
4017
4018 /* Child watch functions */
4019
4020 #ifdef G_OS_WIN32
4021
4022 static gboolean
4023 g_child_watch_prepare (GSource *source,
4024                        gint    *timeout)
4025 {
4026   *timeout = -1;
4027   return FALSE;
4028 }
4029
4030 static gboolean 
4031 g_child_watch_check (GSource  *source)
4032 {
4033   GChildWatchSource *child_watch_source;
4034   gboolean child_exited;
4035
4036   child_watch_source = (GChildWatchSource *) source;
4037
4038   child_exited = child_watch_source->poll.revents & G_IO_IN;
4039
4040   if (child_exited)
4041     {
4042       DWORD child_status;
4043
4044       /*
4045        * Note: We do _not_ check for the special value of STILL_ACTIVE
4046        * since we know that the process has exited and doing so runs into
4047        * problems if the child process "happens to return STILL_ACTIVE(259)"
4048        * as Microsoft's Platform SDK puts it.
4049        */
4050       if (!GetExitCodeProcess (child_watch_source->pid, &child_status))
4051         {
4052           gchar *emsg = g_win32_error_message (GetLastError ());
4053           g_warning (G_STRLOC ": GetExitCodeProcess() failed: %s", emsg);
4054           g_free (emsg);
4055
4056           child_watch_source->child_status = -1;
4057         }
4058       else
4059         child_watch_source->child_status = child_status;
4060     }
4061
4062   return child_exited;
4063 }
4064
4065 static void
4066 g_child_watch_finalize (GSource *source)
4067 {
4068 }
4069
4070 #else /* G_OS_WIN32 */
4071
4072 static void
4073 wake_source (GSource *source)
4074 {
4075   GMainContext *context;
4076
4077   /* This should be thread-safe:
4078    *
4079    *  - if the source is currently being added to a context, that
4080    *    context will be woken up anyway
4081    *
4082    *  - if the source is currently being destroyed, we simply need not
4083    *    to crash:
4084    *
4085    *    - the memory for the source will remain valid until after the
4086    *      source finalize function was called (which would remove the
4087    *      source from the global list which we are currently holding the
4088    *      lock for)
4089    *
4090    *    - the GMainContext will either be NULL or point to a live
4091    *      GMainContext
4092    *
4093    *    - the GMainContext will remain valid since we hold the
4094    *      main_context_list lock
4095    *
4096    *  Since we are holding a lot of locks here, don't try to enter any
4097    *  more GMainContext functions for fear of dealock -- just hit the
4098    *  GWakeup and run.  Even if that's safe now, it could easily become
4099    *  unsafe with some very minor changes in the future, and signal
4100    *  handling is not the most well-tested codepath.
4101    */
4102   G_LOCK(main_context_list);
4103   context = source->context;
4104   if (context)
4105     g_wakeup_signal (context->wakeup);
4106   G_UNLOCK(main_context_list);
4107 }
4108
4109 static void
4110 dispatch_unix_signals (void)
4111 {
4112   GSList *node;
4113
4114   /* clear this first incase another one arrives while we're processing */
4115   any_unix_signal_pending = FALSE;
4116
4117   G_LOCK(unix_signal_lock);
4118
4119   /* handle GChildWatchSource instances */
4120   if (unix_signal_pending[SIGCHLD])
4121     {
4122       unix_signal_pending[SIGCHLD] = FALSE;
4123
4124       /* The only way we can do this is to scan all of the children.
4125        *
4126        * The docs promise that we will not reap children that we are not
4127        * explicitly watching, so that ties our hands from calling
4128        * waitpid(-1).  We also can't use siginfo's si_pid field since if
4129        * multiple SIGCHLD arrive at the same time, one of them can be
4130        * dropped (since a given UNIX signal can only be pending once).
4131        */
4132       for (node = unix_child_watches; node; node = node->next)
4133         {
4134           GChildWatchSource *source = node->data;
4135
4136           if (!source->child_exited)
4137             {
4138               if (waitpid (source->pid, &source->child_status, WNOHANG) > 0)
4139                 {
4140                   source->child_exited = TRUE;
4141
4142                   wake_source ((GSource *) source);
4143                 }
4144             }
4145         }
4146     }
4147
4148   /* handle GUnixSignalWatchSource instances */
4149   for (node = unix_signal_watches; node; node = node->next)
4150     {
4151       GUnixSignalWatchSource *source = node->data;
4152
4153       if (!source->pending)
4154         {
4155           if (unix_signal_pending[source->signum])
4156             {
4157               unix_signal_pending[source->signum] = FALSE;
4158               source->pending = TRUE;
4159
4160               wake_source ((GSource *) source);
4161             }
4162         }
4163     }
4164
4165   G_UNLOCK(unix_signal_lock);
4166 }
4167
4168 static gboolean
4169 g_child_watch_prepare (GSource *source,
4170                        gint    *timeout)
4171 {
4172   GChildWatchSource *child_watch_source;
4173
4174   child_watch_source = (GChildWatchSource *) source;
4175
4176   return child_watch_source->child_exited;
4177 }
4178
4179 static gboolean
4180 g_child_watch_check (GSource *source)
4181 {
4182   GChildWatchSource *child_watch_source;
4183
4184   child_watch_source = (GChildWatchSource *) source;
4185
4186   return child_watch_source->child_exited;
4187 }
4188
4189 static gboolean
4190 g_unix_signal_watch_prepare (GSource *source,
4191                              gint    *timeout)
4192 {
4193   GUnixSignalWatchSource *unix_signal_source;
4194
4195   unix_signal_source = (GUnixSignalWatchSource *) source;
4196
4197   return unix_signal_source->pending;
4198 }
4199
4200 static gboolean
4201 g_unix_signal_watch_check (GSource  *source)
4202 {
4203   GUnixSignalWatchSource *unix_signal_source;
4204
4205   unix_signal_source = (GUnixSignalWatchSource *) source;
4206
4207   return unix_signal_source->pending;
4208 }
4209
4210 static gboolean
4211 g_unix_signal_watch_dispatch (GSource    *source, 
4212                               GSourceFunc callback,
4213                               gpointer    user_data)
4214 {
4215   GUnixSignalWatchSource *unix_signal_source;
4216
4217   unix_signal_source = (GUnixSignalWatchSource *) source;
4218
4219   if (!callback)
4220     {
4221       g_warning ("Unix signal source dispatched without callback\n"
4222                  "You must call g_source_set_callback().");
4223       return FALSE;
4224     }
4225
4226   (callback) (user_data);
4227
4228   unix_signal_source->pending = FALSE;
4229
4230   return TRUE;
4231 }
4232
4233 static void
4234 ensure_unix_signal_handler_installed_unlocked (int signum)
4235 {
4236   static sigset_t installed_signal_mask;
4237   static gboolean initialized;
4238   struct sigaction action;
4239
4240   if (!initialized)
4241     {
4242       sigemptyset (&installed_signal_mask);
4243       g_get_worker_context ();
4244       initialized = TRUE;
4245     }
4246
4247   if (sigismember (&installed_signal_mask, signum))
4248     return;
4249
4250   sigaddset (&installed_signal_mask, signum);
4251
4252   action.sa_handler = g_unix_signal_handler;
4253   sigemptyset (&action.sa_mask);
4254   action.sa_flags = SA_RESTART | SA_NOCLDSTOP;
4255   sigaction (signum, &action, NULL);
4256 }
4257
4258 GSource *
4259 _g_main_create_unix_signal_watch (int signum)
4260 {
4261   GSource *source;
4262   GUnixSignalWatchSource *unix_signal_source;
4263
4264   source = g_source_new (&g_unix_signal_funcs, sizeof (GUnixSignalWatchSource));
4265   unix_signal_source = (GUnixSignalWatchSource *) source;
4266
4267   unix_signal_source->signum = signum;
4268   unix_signal_source->pending = FALSE;
4269
4270   G_LOCK (unix_signal_lock);
4271   ensure_unix_signal_handler_installed_unlocked (signum);
4272   unix_signal_watches = g_slist_prepend (unix_signal_watches, unix_signal_source);
4273   if (unix_signal_pending[signum])
4274     unix_signal_source->pending = TRUE;
4275   unix_signal_pending[signum] = FALSE;
4276   G_UNLOCK (unix_signal_lock);
4277
4278   return source;
4279 }
4280
4281 static void
4282 g_unix_signal_watch_finalize (GSource    *source)
4283 {
4284   G_LOCK (unix_signal_lock);
4285   unix_signal_watches = g_slist_remove (unix_signal_watches, source);
4286   G_UNLOCK (unix_signal_lock);
4287 }
4288
4289 static void
4290 g_child_watch_finalize (GSource *source)
4291 {
4292   G_LOCK (unix_signal_lock);
4293   unix_child_watches = g_slist_remove (unix_child_watches, source);
4294   G_UNLOCK (unix_signal_lock);
4295 }
4296
4297 #endif /* G_OS_WIN32 */
4298
4299 static gboolean
4300 g_child_watch_dispatch (GSource    *source, 
4301                         GSourceFunc callback,
4302                         gpointer    user_data)
4303 {
4304   GChildWatchSource *child_watch_source;
4305   GChildWatchFunc child_watch_callback = (GChildWatchFunc) callback;
4306
4307   child_watch_source = (GChildWatchSource *) source;
4308
4309   if (!callback)
4310     {
4311       g_warning ("Child watch source dispatched without callback\n"
4312                  "You must call g_source_set_callback().");
4313       return FALSE;
4314     }
4315
4316   (child_watch_callback) (child_watch_source->pid, child_watch_source->child_status, user_data);
4317
4318   /* We never keep a child watch source around as the child is gone */
4319   return FALSE;
4320 }
4321
4322 #ifndef G_OS_WIN32
4323
4324 static void
4325 g_unix_signal_handler (int signum)
4326 {
4327   unix_signal_pending[signum] = TRUE;
4328   any_unix_signal_pending = TRUE;
4329
4330   g_wakeup_signal (glib_worker_context->wakeup);
4331 }
4332
4333 #endif /* !G_OS_WIN32 */
4334
4335 /**
4336  * g_child_watch_source_new:
4337  * @pid: process to watch. On POSIX the pid of a child process. On
4338  * Windows a handle for a process (which doesn't have to be a child).
4339  * 
4340  * Creates a new child_watch source.
4341  *
4342  * The source will not initially be associated with any #GMainContext
4343  * and must be added to one with g_source_attach() before it will be
4344  * executed.
4345  * 
4346  * Note that child watch sources can only be used in conjunction with
4347  * <literal>g_spawn...</literal> when the %G_SPAWN_DO_NOT_REAP_CHILD
4348  * flag is used.
4349  *
4350  * Note that on platforms where #GPid must be explicitly closed
4351  * (see g_spawn_close_pid()) @pid must not be closed while the
4352  * source is still active. Typically, you will want to call
4353  * g_spawn_close_pid() in the callback function for the source.
4354  *
4355  * Note further that using g_child_watch_source_new() is not 
4356  * compatible with calling <literal>waitpid(-1)</literal> in 
4357  * the application. Calling waitpid() for individual pids will
4358  * still work fine. 
4359  * 
4360  * Return value: the newly-created child watch source
4361  *
4362  * Since: 2.4
4363  **/
4364 GSource *
4365 g_child_watch_source_new (GPid pid)
4366 {
4367   GSource *source = g_source_new (&g_child_watch_funcs, sizeof (GChildWatchSource));
4368   GChildWatchSource *child_watch_source = (GChildWatchSource *)source;
4369
4370   child_watch_source->pid = pid;
4371
4372 #ifdef G_OS_WIN32
4373   child_watch_source->poll.fd = (gintptr) pid;
4374   child_watch_source->poll.events = G_IO_IN;
4375
4376   g_source_add_poll (source, &child_watch_source->poll);
4377 #else /* G_OS_WIN32 */
4378   G_LOCK (unix_signal_lock);
4379   ensure_unix_signal_handler_installed_unlocked (SIGCHLD);
4380   unix_child_watches = g_slist_prepend (unix_child_watches, child_watch_source);
4381   if (waitpid (pid, &child_watch_source->child_status, WNOHANG) > 0)
4382     child_watch_source->child_exited = TRUE;
4383   G_UNLOCK (unix_signal_lock);
4384 #endif /* G_OS_WIN32 */
4385
4386   return source;
4387 }
4388
4389 /**
4390  * g_child_watch_add_full:
4391  * @priority: the priority of the idle source. Typically this will be in the
4392  *            range between #G_PRIORITY_DEFAULT_IDLE and #G_PRIORITY_HIGH_IDLE.
4393  * @pid:      process to watch. On POSIX the pid of a child process. On
4394  * Windows a handle for a process (which doesn't have to be a child).
4395  * @function: function to call
4396  * @data:     data to pass to @function
4397  * @notify:   function to call when the idle is removed, or %NULL
4398  * 
4399  * Sets a function to be called when the child indicated by @pid 
4400  * exits, at the priority @priority.
4401  *
4402  * If you obtain @pid from g_spawn_async() or g_spawn_async_with_pipes() 
4403  * you will need to pass #G_SPAWN_DO_NOT_REAP_CHILD as flag to 
4404  * the spawn function for the child watching to work.
4405  * 
4406  * Note that on platforms where #GPid must be explicitly closed
4407  * (see g_spawn_close_pid()) @pid must not be closed while the
4408  * source is still active. Typically, you will want to call
4409  * g_spawn_close_pid() in the callback function for the source.
4410  * 
4411  * GLib supports only a single callback per process id.
4412  *
4413  * This internally creates a main loop source using 
4414  * g_child_watch_source_new() and attaches it to the main loop context 
4415  * using g_source_attach(). You can do these steps manually if you 
4416  * need greater control.
4417  *
4418  * Return value: the ID (greater than 0) of the event source.
4419  *
4420  * Rename to: g_child_watch_add
4421  * Since: 2.4
4422  **/
4423 guint
4424 g_child_watch_add_full (gint            priority,
4425                         GPid            pid,
4426                         GChildWatchFunc function,
4427                         gpointer        data,
4428                         GDestroyNotify  notify)
4429 {
4430   GSource *source;
4431   guint id;
4432   
4433   g_return_val_if_fail (function != NULL, 0);
4434
4435   source = g_child_watch_source_new (pid);
4436
4437   if (priority != G_PRIORITY_DEFAULT)
4438     g_source_set_priority (source, priority);
4439
4440   g_source_set_callback (source, (GSourceFunc) function, data, notify);
4441   id = g_source_attach (source, NULL);
4442   g_source_unref (source);
4443
4444   return id;
4445 }
4446
4447 /**
4448  * g_child_watch_add:
4449  * @pid:      process id to watch. On POSIX the pid of a child process. On
4450  * Windows a handle for a process (which doesn't have to be a child).
4451  * @function: function to call
4452  * @data:     data to pass to @function
4453  * 
4454  * Sets a function to be called when the child indicated by @pid 
4455  * exits, at a default priority, #G_PRIORITY_DEFAULT.
4456  * 
4457  * If you obtain @pid from g_spawn_async() or g_spawn_async_with_pipes() 
4458  * you will need to pass #G_SPAWN_DO_NOT_REAP_CHILD as flag to 
4459  * the spawn function for the child watching to work.
4460  * 
4461  * Note that on platforms where #GPid must be explicitly closed
4462  * (see g_spawn_close_pid()) @pid must not be closed while the
4463  * source is still active. Typically, you will want to call
4464  * g_spawn_close_pid() in the callback function for the source.
4465  *
4466  * GLib supports only a single callback per process id.
4467  *
4468  * This internally creates a main loop source using 
4469  * g_child_watch_source_new() and attaches it to the main loop context 
4470  * using g_source_attach(). You can do these steps manually if you 
4471  * need greater control.
4472  *
4473  * Return value: the ID (greater than 0) of the event source.
4474  *
4475  * Since: 2.4
4476  **/
4477 guint 
4478 g_child_watch_add (GPid            pid,
4479                    GChildWatchFunc function,
4480                    gpointer        data)
4481 {
4482   return g_child_watch_add_full (G_PRIORITY_DEFAULT, pid, function, data, NULL);
4483 }
4484
4485
4486 /* Idle functions */
4487
4488 static gboolean 
4489 g_idle_prepare  (GSource  *source,
4490                  gint     *timeout)
4491 {
4492   *timeout = 0;
4493
4494   return TRUE;
4495 }
4496
4497 static gboolean 
4498 g_idle_check    (GSource  *source)
4499 {
4500   return TRUE;
4501 }
4502
4503 static gboolean
4504 g_idle_dispatch (GSource    *source, 
4505                  GSourceFunc callback,
4506                  gpointer    user_data)
4507 {
4508   if (!callback)
4509     {
4510       g_warning ("Idle source dispatched without callback\n"
4511                  "You must call g_source_set_callback().");
4512       return FALSE;
4513     }
4514   
4515   return callback (user_data);
4516 }
4517
4518 /**
4519  * g_idle_source_new:
4520  * 
4521  * Creates a new idle source.
4522  *
4523  * The source will not initially be associated with any #GMainContext
4524  * and must be added to one with g_source_attach() before it will be
4525  * executed. Note that the default priority for idle sources is
4526  * %G_PRIORITY_DEFAULT_IDLE, as compared to other sources which
4527  * have a default priority of %G_PRIORITY_DEFAULT.
4528  * 
4529  * Return value: the newly-created idle source
4530  **/
4531 GSource *
4532 g_idle_source_new (void)
4533 {
4534   GSource *source;
4535
4536   source = g_source_new (&g_idle_funcs, sizeof (GSource));
4537   g_source_set_priority (source, G_PRIORITY_DEFAULT_IDLE);
4538
4539   return source;
4540 }
4541
4542 /**
4543  * g_idle_add_full:
4544  * @priority: the priority of the idle source. Typically this will be in the
4545  *            range between #G_PRIORITY_DEFAULT_IDLE and #G_PRIORITY_HIGH_IDLE.
4546  * @function: function to call
4547  * @data:     data to pass to @function
4548  * @notify:   function to call when the idle is removed, or %NULL
4549  * 
4550  * Adds a function to be called whenever there are no higher priority
4551  * events pending.  If the function returns %FALSE it is automatically
4552  * removed from the list of event sources and will not be called again.
4553  * 
4554  * This internally creates a main loop source using g_idle_source_new()
4555  * and attaches it to the main loop context using g_source_attach(). 
4556  * You can do these steps manually if you need greater control.
4557  * 
4558  * Return value: the ID (greater than 0) of the event source.
4559  * Rename to: g_idle_add
4560  **/
4561 guint 
4562 g_idle_add_full (gint           priority,
4563                  GSourceFunc    function,
4564                  gpointer       data,
4565                  GDestroyNotify notify)
4566 {
4567   GSource *source;
4568   guint id;
4569   
4570   g_return_val_if_fail (function != NULL, 0);
4571
4572   source = g_idle_source_new ();
4573
4574   if (priority != G_PRIORITY_DEFAULT_IDLE)
4575     g_source_set_priority (source, priority);
4576
4577   g_source_set_callback (source, function, data, notify);
4578   id = g_source_attach (source, NULL);
4579   g_source_unref (source);
4580
4581   return id;
4582 }
4583
4584 /**
4585  * g_idle_add:
4586  * @function: function to call 
4587  * @data: data to pass to @function.
4588  * 
4589  * Adds a function to be called whenever there are no higher priority
4590  * events pending to the default main loop. The function is given the
4591  * default idle priority, #G_PRIORITY_DEFAULT_IDLE.  If the function
4592  * returns %FALSE it is automatically removed from the list of event
4593  * sources and will not be called again.
4594  * 
4595  * This internally creates a main loop source using g_idle_source_new()
4596  * and attaches it to the main loop context using g_source_attach(). 
4597  * You can do these steps manually if you need greater control.
4598  * 
4599  * Return value: the ID (greater than 0) of the event source.
4600  **/
4601 guint 
4602 g_idle_add (GSourceFunc    function,
4603             gpointer       data)
4604 {
4605   return g_idle_add_full (G_PRIORITY_DEFAULT_IDLE, function, data, NULL);
4606 }
4607
4608 /**
4609  * g_idle_remove_by_data:
4610  * @data: the data for the idle source's callback.
4611  * 
4612  * Removes the idle function with the given data.
4613  * 
4614  * Return value: %TRUE if an idle source was found and removed.
4615  **/
4616 gboolean
4617 g_idle_remove_by_data (gpointer data)
4618 {
4619   return g_source_remove_by_funcs_user_data (&g_idle_funcs, data);
4620 }
4621
4622 /**
4623  * g_main_context_invoke:
4624  * @context: (allow-none): a #GMainContext, or %NULL
4625  * @function: function to call
4626  * @data: data to pass to @function
4627  *
4628  * Invokes a function in such a way that @context is owned during the
4629  * invocation of @function.
4630  *
4631  * If @context is %NULL then the global default main context — as
4632  * returned by g_main_context_default() — is used.
4633  *
4634  * If @context is owned by the current thread, @function is called
4635  * directly.  Otherwise, if @context is the thread-default main context
4636  * of the current thread and g_main_context_acquire() succeeds, then
4637  * @function is called and g_main_context_release() is called
4638  * afterwards.
4639  *
4640  * In any other case, an idle source is created to call @function and
4641  * that source is attached to @context (presumably to be run in another
4642  * thread).  The idle source is attached with #G_PRIORITY_DEFAULT
4643  * priority.  If you want a different priority, use
4644  * g_main_context_invoke_full().
4645  *
4646  * Note that, as with normal idle functions, @function should probably
4647  * return %FALSE.  If it returns %TRUE, it will be continuously run in a
4648  * loop (and may prevent this call from returning).
4649  *
4650  * Since: 2.28
4651  **/
4652 void
4653 g_main_context_invoke (GMainContext *context,
4654                        GSourceFunc   function,
4655                        gpointer      data)
4656 {
4657   g_main_context_invoke_full (context,
4658                               G_PRIORITY_DEFAULT,
4659                               function, data, NULL);
4660 }
4661
4662 /**
4663  * g_main_context_invoke_full:
4664  * @context: (allow-none): a #GMainContext, or %NULL
4665  * @priority: the priority at which to run @function
4666  * @function: function to call
4667  * @data: data to pass to @function
4668  * @notify: a function to call when @data is no longer in use, or %NULL.
4669  *
4670  * Invokes a function in such a way that @context is owned during the
4671  * invocation of @function.
4672  *
4673  * This function is the same as g_main_context_invoke() except that it
4674  * lets you specify the priority incase @function ends up being
4675  * scheduled as an idle and also lets you give a #GDestroyNotify for @data.
4676  *
4677  * @notify should not assume that it is called from any particular
4678  * thread or with any particular context acquired.
4679  *
4680  * Since: 2.28
4681  **/
4682 void
4683 g_main_context_invoke_full (GMainContext   *context,
4684                             gint            priority,
4685                             GSourceFunc     function,
4686                             gpointer        data,
4687                             GDestroyNotify  notify)
4688 {
4689   g_return_if_fail (function != NULL);
4690
4691   if (!context)
4692     context = g_main_context_default ();
4693
4694   if (g_main_context_is_owner (context))
4695     {
4696       while (function (data));
4697       if (notify != NULL)
4698         notify (data);
4699     }
4700
4701   else
4702     {
4703       GMainContext *thread_default;
4704
4705       thread_default = g_main_context_get_thread_default ();
4706
4707       if (!thread_default)
4708         thread_default = g_main_context_default ();
4709
4710       if (thread_default == context && g_main_context_acquire (context))
4711         {
4712           while (function (data));
4713
4714           g_main_context_release (context);
4715
4716           if (notify != NULL)
4717             notify (data);
4718         }
4719       else
4720         {
4721           GSource *source;
4722
4723           source = g_idle_source_new ();
4724           g_source_set_priority (source, priority);
4725           g_source_set_callback (source, function, data, notify);
4726           g_source_attach (source, context);
4727           g_source_unref (source);
4728         }
4729     }
4730 }
4731
4732 static gpointer
4733 glib_worker_main (gpointer data)
4734 {
4735   while (TRUE)
4736     {
4737       g_main_context_iteration (glib_worker_context, TRUE);
4738
4739 #ifdef G_OS_UNIX
4740       if (any_unix_signal_pending)
4741         dispatch_unix_signals ();
4742 #endif
4743     }
4744
4745   return NULL; /* worst GCC warning message ever... */
4746 }
4747
4748 GMainContext *
4749 g_get_worker_context (void)
4750 {
4751   static gsize initialised;
4752
4753   g_thread_init_glib ();
4754
4755   if (g_once_init_enter (&initialised))
4756     {
4757       GError *error = NULL;
4758
4759       glib_worker_context = g_main_context_new ();
4760       if (g_thread_new ("gmain", glib_worker_main, NULL, FALSE, &error) == NULL)
4761         g_error ("Creating GLib worker thread failed: %s\n", error->message);
4762
4763       g_once_init_leave (&initialised, TRUE);
4764     }
4765
4766   return glib_worker_context;
4767 }