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