1 /* GLIB - Library of useful routines for C programming
2 * Copyright (C) 1995-1997 Peter Mattis, Spencer Kimball and Josh MacDonald
4 * gmain.c: Main loop abstraction, timeouts, and idle functions
5 * Copyright 1998 Owen Taylor
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.
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.
17 * You should have received a copy of the GNU Lesser General Public
18 * License along with this library; if not, see <http://www.gnu.org/licenses/>.
22 * Modified by the GLib Team and others 1997-2000. See the AUTHORS
23 * file for a list of people on the GLib Team. See the ChangeLog
24 * files for a list of changes. These files are distributed with
25 * GLib at ftp://ftp.gtk.org/pub/gtk/.
33 #include "glibconfig.h"
35 /* Uncomment the next line (and the corresponding line in gpoll.c) to
36 * enable debugging printouts if the environment variable
37 * G_MAIN_POLL_DEBUG is set to some value.
39 /* #define G_MAIN_POLL_DEBUG */
42 /* Always enable debugging printout on Windows, as it is more often
45 #define G_MAIN_POLL_DEBUG
49 #include "glib-unix.h"
52 #include <sys/eventfd.h>
57 #include <sys/types.h>
60 #ifdef HAVE_SYS_TIME_H
62 #endif /* HAVE_SYS_TIME_H */
65 #endif /* G_OS_UNIX */
72 #endif /* G_OS_WIN32 */
74 #include "glib_trace.h"
79 #include "giochannel.h"
83 #include "gstrfuncs.h"
84 #include "gtestutils.h"
90 #ifdef G_MAIN_POLL_DEBUG
95 #include "gmain-internal.h"
96 #include "glib-init.h"
97 #include "glib-private.h"
101 * @title: The Main Event Loop
102 * @short_description: manages all available sources of events
104 * The main event loop manages all the available sources of events for
105 * GLib and GTK+ applications. These events can come from any number of
106 * different types of sources such as file descriptors (plain files,
107 * pipes or sockets) and timeouts. New types of event sources can also
108 * be added using g_source_attach().
110 * To allow multiple independent sets of sources to be handled in
111 * different threads, each source is associated with a #GMainContext.
112 * A GMainContext can only be running in a single thread, but
113 * sources can be added to it and removed from it from other threads.
115 * Each event source is assigned a priority. The default priority,
116 * #G_PRIORITY_DEFAULT, is 0. Values less than 0 denote higher priorities.
117 * Values greater than 0 denote lower priorities. Events from high priority
118 * sources are always processed before events from lower priority sources.
120 * Idle functions can also be added, and assigned a priority. These will
121 * be run whenever no events with a higher priority are ready to be processed.
123 * The #GMainLoop data type represents a main event loop. A GMainLoop is
124 * created with g_main_loop_new(). After adding the initial event sources,
125 * g_main_loop_run() is called. This continuously checks for new events from
126 * each of the event sources and dispatches them. Finally, the processing of
127 * an event from one of the sources leads to a call to g_main_loop_quit() to
128 * exit the main loop, and g_main_loop_run() returns.
130 * It is possible to create new instances of #GMainLoop recursively.
131 * This is often used in GTK+ applications when showing modal dialog
132 * boxes. Note that event sources are associated with a particular
133 * #GMainContext, and will be checked and dispatched for all main
134 * loops associated with that GMainContext.
136 * GTK+ contains wrappers of some of these functions, e.g. gtk_main(),
137 * gtk_main_quit() and gtk_events_pending().
139 * <refsect2><title>Creating new source types</title>
140 * <para>One of the unusual features of the #GMainLoop functionality
141 * is that new types of event source can be created and used in
142 * addition to the builtin type of event source. A new event source
143 * type is used for handling GDK events. A new source type is created
144 * by <firstterm>deriving</firstterm> from the #GSource structure.
145 * The derived type of source is represented by a structure that has
146 * the #GSource structure as a first element, and other elements specific
147 * to the new source type. To create an instance of the new source type,
148 * call g_source_new() passing in the size of the derived structure and
149 * a table of functions. These #GSourceFuncs determine the behavior of
150 * the new source type.</para>
151 * <para>New source types basically interact with the main context
152 * in two ways. Their prepare function in #GSourceFuncs can set a timeout
153 * to determine the maximum amount of time that the main loop will sleep
154 * before checking the source again. In addition, or as well, the source
155 * can add file descriptors to the set that the main context checks using
156 * g_source_add_poll().</para>
158 * <refsect2><title>Customizing the main loop iteration</title>
159 * <para>Single iterations of a #GMainContext can be run with
160 * g_main_context_iteration(). In some cases, more detailed control
161 * of exactly how the details of the main loop work is desired, for
162 * instance, when integrating the #GMainLoop with an external main loop.
163 * In such cases, you can call the component functions of
164 * g_main_context_iteration() directly. These functions are
165 * g_main_context_prepare(), g_main_context_query(),
166 * g_main_context_check() and g_main_context_dispatch().</para>
167 * <para>The operation of these functions can best be seen in terms
168 * of a state diagram, as shown in <xref linkend="mainloop-states"/>.</para>
169 * <figure id="mainloop-states"><title>States of a Main Context</title>
170 * <graphic fileref="mainloop-states.gif" format="GIF"></graphic>
174 * On Unix, the GLib mainloop is incompatible with fork(). Any program
175 * using the mainloop must either exec() or exit() from the child
176 * without returning to the mainloop.
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;
189 G_SOURCE_READY = 1 << G_HOOK_FLAG_USER_SHIFT,
190 G_SOURCE_CAN_RECURSE = 1 << (G_HOOK_FLAG_USER_SHIFT + 1),
191 G_SOURCE_BLOCKED = 1 << (G_HOOK_FLAG_USER_SHIFT + 2)
194 typedef struct _GSourceList GSourceList;
198 GSource *head, *tail;
202 typedef struct _GMainWaiter GMainWaiter;
210 typedef struct _GMainDispatch GMainDispatch;
212 struct _GMainDispatch
218 #ifdef G_MAIN_POLL_DEBUG
219 gboolean _g_main_poll_debug = FALSE;
224 /* The following lock is used for both the list of sources
225 * and the list of poll records
235 GPtrArray *pending_dispatches;
236 gint timeout; /* Timeout for current iteration */
239 GHashTable *overflow_used_source_ids; /* set<guint> */
241 gint in_check_or_prepare;
243 GPollRec *poll_records, *poll_records_tail;
244 guint n_poll_records;
245 GPollFD *cached_poll_array;
246 guint cached_poll_array_size;
252 /* Flag indicating whether the set of fd's changed during a poll */
253 gboolean poll_changed;
258 gboolean time_is_fresh;
261 struct _GSourceCallback
266 GDestroyNotify notify;
271 GMainContext *context;
276 struct _GTimeoutSource
283 struct _GChildWatchSource
290 #else /* G_OS_WIN32 */
291 gboolean child_exited;
292 #endif /* G_OS_WIN32 */
295 struct _GUnixSignalWatchSource
310 struct _GSourcePrivate
312 GSList *child_sources;
313 GSource *parent_source;
317 /* This is currently only used on UNIX, but we always declare it (and
318 * let it remain empty on Windows) to avoid #ifdef all over the place.
323 typedef struct _GSourceIter
325 GMainContext *context;
331 #define LOCK_CONTEXT(context) g_mutex_lock (&context->mutex)
332 #define UNLOCK_CONTEXT(context) g_mutex_unlock (&context->mutex)
333 #define G_THREAD_SELF g_thread_self ()
335 #define SOURCE_DESTROYED(source) (((source)->flags & G_HOOK_FLAG_ACTIVE) == 0)
336 #define SOURCE_BLOCKED(source) (((source)->flags & G_SOURCE_BLOCKED) != 0)
338 #define SOURCE_UNREF(source, context) \
340 if ((source)->ref_count > 1) \
341 (source)->ref_count--; \
343 g_source_unref_internal ((source), (context), TRUE); \
347 /* Forward declarations */
349 static void g_source_unref_internal (GSource *source,
350 GMainContext *context,
352 static void g_source_destroy_internal (GSource *source,
353 GMainContext *context,
355 static void g_source_set_priority_unlocked (GSource *source,
356 GMainContext *context,
358 static void g_child_source_remove_internal (GSource *child_source,
359 GMainContext *context);
361 static void g_main_context_poll (GMainContext *context,
366 static void g_main_context_add_poll_unlocked (GMainContext *context,
369 static void g_main_context_remove_poll_unlocked (GMainContext *context,
372 static void g_source_iter_init (GSourceIter *iter,
373 GMainContext *context,
374 gboolean may_modify);
375 static gboolean g_source_iter_next (GSourceIter *iter,
377 static void g_source_iter_clear (GSourceIter *iter);
379 static gboolean g_timeout_dispatch (GSource *source,
380 GSourceFunc callback,
382 static gboolean g_child_watch_prepare (GSource *source,
384 static gboolean g_child_watch_check (GSource *source);
385 static gboolean g_child_watch_dispatch (GSource *source,
386 GSourceFunc callback,
388 static void g_child_watch_finalize (GSource *source);
390 static void g_unix_signal_handler (int signum);
391 static gboolean g_unix_signal_watch_prepare (GSource *source,
393 static gboolean g_unix_signal_watch_check (GSource *source);
394 static gboolean g_unix_signal_watch_dispatch (GSource *source,
395 GSourceFunc callback,
397 static void g_unix_signal_watch_finalize (GSource *source);
399 static gboolean g_idle_prepare (GSource *source,
401 static gboolean g_idle_check (GSource *source);
402 static gboolean g_idle_dispatch (GSource *source,
403 GSourceFunc callback,
406 static void block_source (GSource *source);
408 static GMainContext *glib_worker_context;
410 G_LOCK_DEFINE_STATIC (main_loop);
411 static GMainContext *default_main_context;
416 /* UNIX signals work by marking one of these variables then waking the
417 * worker context to check on them and dispatch accordingly.
419 #ifdef HAVE_SIG_ATOMIC_T
420 static volatile sig_atomic_t unix_signal_pending[NSIG];
421 static volatile sig_atomic_t any_unix_signal_pending;
423 static volatile int unix_signal_pending[NSIG];
424 static volatile int any_unix_signal_pending;
426 static volatile guint unix_signal_refcount[NSIG];
428 /* Guards all the data below */
429 G_LOCK_DEFINE_STATIC (unix_signal_lock);
430 static GSList *unix_signal_watches;
431 static GSList *unix_child_watches;
433 GSourceFuncs g_unix_signal_funcs =
435 g_unix_signal_watch_prepare,
436 g_unix_signal_watch_check,
437 g_unix_signal_watch_dispatch,
438 g_unix_signal_watch_finalize
440 #endif /* !G_OS_WIN32 */
441 G_LOCK_DEFINE_STATIC (main_context_list);
442 static GSList *main_context_list = NULL;
444 GSourceFuncs g_timeout_funcs =
452 GSourceFuncs g_child_watch_funcs =
454 g_child_watch_prepare,
456 g_child_watch_dispatch,
457 g_child_watch_finalize
460 GSourceFuncs g_idle_funcs =
469 * g_main_context_ref:
470 * @context: a #GMainContext
472 * Increases the reference count on a #GMainContext object by one.
474 * Returns: the @context that was passed in (since 2.6)
477 g_main_context_ref (GMainContext *context)
479 g_return_val_if_fail (context != NULL, NULL);
480 g_return_val_if_fail (g_atomic_int_get (&context->ref_count) > 0, NULL);
482 g_atomic_int_inc (&context->ref_count);
488 poll_rec_list_free (GMainContext *context,
491 g_slice_free_chain (GPollRec, list, next);
495 * g_main_context_unref:
496 * @context: a #GMainContext
498 * Decreases the reference count on a #GMainContext object by one. If
499 * the result is zero, free the context and free all associated memory.
502 g_main_context_unref (GMainContext *context)
510 g_return_if_fail (context != NULL);
511 g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
513 if (!g_atomic_int_dec_and_test (&context->ref_count))
516 G_LOCK (main_context_list);
517 main_context_list = g_slist_remove (main_context_list, context);
518 G_UNLOCK (main_context_list);
520 /* Free pending dispatches */
521 for (i = 0; i < context->pending_dispatches->len; i++)
522 g_source_unref_internal (context->pending_dispatches->pdata[i], context, FALSE);
524 /* g_source_iter_next() assumes the context is locked. */
525 LOCK_CONTEXT (context);
526 g_source_iter_init (&iter, context, TRUE);
527 while (g_source_iter_next (&iter, &source))
529 source->context = NULL;
530 g_source_destroy_internal (source, context, TRUE);
532 UNLOCK_CONTEXT (context);
534 for (sl_iter = context->source_lists; sl_iter; sl_iter = sl_iter->next)
536 list = sl_iter->data;
537 g_slice_free (GSourceList, list);
539 g_list_free (context->source_lists);
541 if (context->overflow_used_source_ids)
542 g_hash_table_destroy (context->overflow_used_source_ids);
544 g_mutex_clear (&context->mutex);
546 g_ptr_array_free (context->pending_dispatches, TRUE);
547 g_free (context->cached_poll_array);
549 poll_rec_list_free (context, context->poll_records);
551 g_wakeup_free (context->wakeup);
552 g_cond_clear (&context->cond);
557 /* Helper function used by mainloop/overflow test.
560 g_main_context_new_with_next_id (guint next_id)
562 GMainContext *ret = g_main_context_new ();
564 ret->next_id = next_id;
570 * g_main_context_new:
572 * Creates a new #GMainContext structure.
574 * Return value: the new #GMainContext
577 g_main_context_new (void)
579 static gsize initialised;
580 GMainContext *context;
582 if (g_once_init_enter (&initialised))
584 #ifdef G_MAIN_POLL_DEBUG
585 if (getenv ("G_MAIN_POLL_DEBUG") != NULL)
586 _g_main_poll_debug = TRUE;
589 g_once_init_leave (&initialised, TRUE);
592 context = g_new0 (GMainContext, 1);
594 g_mutex_init (&context->mutex);
595 g_cond_init (&context->cond);
597 context->owner = NULL;
598 context->waiters = NULL;
600 context->ref_count = 1;
602 context->next_id = 1;
604 context->source_lists = NULL;
606 context->poll_func = g_poll;
608 context->cached_poll_array = NULL;
609 context->cached_poll_array_size = 0;
611 context->pending_dispatches = g_ptr_array_new ();
613 context->time_is_fresh = FALSE;
615 context->wakeup = g_wakeup_new ();
616 g_wakeup_get_pollfd (context->wakeup, &context->wake_up_rec);
617 g_main_context_add_poll_unlocked (context, 0, &context->wake_up_rec);
619 G_LOCK (main_context_list);
620 main_context_list = g_slist_append (main_context_list, context);
622 #ifdef G_MAIN_POLL_DEBUG
623 if (_g_main_poll_debug)
624 g_print ("created context=%p\n", context);
627 G_UNLOCK (main_context_list);
633 * g_main_context_default:
635 * Returns the global default main context. This is the main context
636 * used for main loop functions when a main loop is not explicitly
637 * specified, and corresponds to the "main" main loop. See also
638 * g_main_context_get_thread_default().
640 * Return value: (transfer none): the global default main context.
643 g_main_context_default (void)
649 if (!default_main_context)
651 default_main_context = g_main_context_new ();
652 #ifdef G_MAIN_POLL_DEBUG
653 if (_g_main_poll_debug)
654 g_print ("default context=%p\n", default_main_context);
658 G_UNLOCK (main_loop);
660 return default_main_context;
664 free_context (gpointer data)
666 GMainContext *context = data;
668 g_main_context_release (context);
670 g_main_context_unref (context);
674 free_context_stack (gpointer data)
676 g_queue_free_full((GQueue *) data, (GDestroyNotify) free_context);
679 static GPrivate thread_context_stack = G_PRIVATE_INIT (free_context_stack);
682 * g_main_context_push_thread_default:
683 * @context: (allow-none): a #GMainContext, or %NULL for the global default context
685 * Acquires @context and sets it as the thread-default context for the
686 * current thread. This will cause certain asynchronous operations
687 * (such as most <link linkend="gio">gio</link>-based I/O) which are
688 * started in this thread to run under @context and deliver their
689 * results to its main loop, rather than running under the global
690 * default context in the main thread. Note that calling this function
691 * changes the context returned by g_main_context_get_thread_default(),
692 * not the one returned by g_main_context_default(), so it does not affect
693 * the context used by functions like g_idle_add().
695 * Normally you would call this function shortly after creating a new
696 * thread, passing it a #GMainContext which will be run by a
697 * #GMainLoop in that thread, to set a new default context for all
698 * async operations in that thread. (In this case, you don't need to
699 * ever call g_main_context_pop_thread_default().) In some cases
700 * however, you may want to schedule a single operation in a
701 * non-default context, or temporarily use a non-default context in
702 * the main thread. In that case, you can wrap the call to the
703 * asynchronous operation inside a
704 * g_main_context_push_thread_default() /
705 * g_main_context_pop_thread_default() pair, but it is up to you to
706 * ensure that no other asynchronous operations accidentally get
707 * started while the non-default context is active.
709 * Beware that libraries that predate this function may not correctly
710 * handle being used from a thread with a thread-default context. Eg,
711 * see g_file_supports_thread_contexts().
716 g_main_context_push_thread_default (GMainContext *context)
719 gboolean acquired_context;
721 acquired_context = g_main_context_acquire (context);
722 g_return_if_fail (acquired_context);
724 if (context == g_main_context_default ())
727 g_main_context_ref (context);
729 stack = g_private_get (&thread_context_stack);
732 stack = g_queue_new ();
733 g_private_set (&thread_context_stack, stack);
736 g_queue_push_head (stack, context);
740 * g_main_context_pop_thread_default:
741 * @context: (allow-none): a #GMainContext object, or %NULL
743 * Pops @context off the thread-default context stack (verifying that
744 * it was on the top of the stack).
749 g_main_context_pop_thread_default (GMainContext *context)
753 if (context == g_main_context_default ())
756 stack = g_private_get (&thread_context_stack);
758 g_return_if_fail (stack != NULL);
759 g_return_if_fail (g_queue_peek_head (stack) == context);
761 g_queue_pop_head (stack);
763 g_main_context_release (context);
765 g_main_context_unref (context);
769 * g_main_context_get_thread_default:
771 * Gets the thread-default #GMainContext for this thread. Asynchronous
772 * operations that want to be able to be run in contexts other than
773 * the default one should call this method or
774 * g_main_context_ref_thread_default() to get a #GMainContext to add
775 * their #GSources to. (Note that even in single-threaded
776 * programs applications may sometimes want to temporarily push a
777 * non-default context, so it is not safe to assume that this will
778 * always return %NULL if you are running in the default thread.)
780 * If you need to hold a reference on the context, use
781 * g_main_context_ref_thread_default() instead.
783 * Returns: (transfer none): the thread-default #GMainContext, or
784 * %NULL if the thread-default context is the global default context.
789 g_main_context_get_thread_default (void)
793 stack = g_private_get (&thread_context_stack);
795 return g_queue_peek_head (stack);
801 * g_main_context_ref_thread_default:
803 * Gets the thread-default #GMainContext for this thread, as with
804 * g_main_context_get_thread_default(), but also adds a reference to
805 * it with g_main_context_ref(). In addition, unlike
806 * g_main_context_get_thread_default(), if the thread-default context
807 * is the global default context, this will return that #GMainContext
808 * (with a ref added to it) rather than returning %NULL.
810 * Returns: (transfer full): the thread-default #GMainContext. Unref
811 * with g_main_context_unref() when you are done with it.
816 g_main_context_ref_thread_default (void)
818 GMainContext *context;
820 context = g_main_context_get_thread_default ();
822 context = g_main_context_default ();
823 return g_main_context_ref (context);
826 /* Hooks for adding to the main loop */
830 * @source_funcs: structure containing functions that implement
831 * the sources behavior.
832 * @struct_size: size of the #GSource structure to create.
834 * Creates a new #GSource structure. The size is specified to
835 * allow creating structures derived from #GSource that contain
836 * additional data. The size passed in must be at least
837 * <literal>sizeof (GSource)</literal>.
839 * The source will not initially be associated with any #GMainContext
840 * and must be added to one with g_source_attach() before it will be
843 * Return value: the newly-created #GSource.
846 g_source_new (GSourceFuncs *source_funcs,
851 g_return_val_if_fail (source_funcs != NULL, NULL);
852 g_return_val_if_fail (struct_size >= sizeof (GSource), NULL);
854 source = (GSource*) g_malloc0 (struct_size);
855 source->priv = g_slice_new0 (GSourcePrivate);
856 source->source_funcs = source_funcs;
857 source->ref_count = 1;
859 source->priority = G_PRIORITY_DEFAULT;
861 source->flags = G_HOOK_FLAG_ACTIVE;
863 source->priv->ready_time = -1;
865 /* NULL/0 initialization for all other fields */
870 /* Holds context's lock */
872 g_source_iter_init (GSourceIter *iter,
873 GMainContext *context,
876 iter->context = context;
877 iter->current_list = NULL;
879 iter->may_modify = may_modify;
882 /* Holds context's lock */
884 g_source_iter_next (GSourceIter *iter, GSource **source)
886 GSource *next_source;
889 next_source = iter->source->next;
895 if (iter->current_list)
896 iter->current_list = iter->current_list->next;
898 iter->current_list = iter->context->source_lists;
900 if (iter->current_list)
902 GSourceList *source_list = iter->current_list->data;
904 next_source = source_list->head;
908 /* Note: unreffing iter->source could potentially cause its
909 * GSourceList to be removed from source_lists (if iter->source is
910 * the only source in its list, and it is destroyed), so we have to
911 * keep it reffed until after we advance iter->current_list, above.
914 if (iter->source && iter->may_modify)
915 SOURCE_UNREF (iter->source, iter->context);
916 iter->source = next_source;
917 if (iter->source && iter->may_modify)
918 iter->source->ref_count++;
920 *source = iter->source;
921 return *source != NULL;
924 /* Holds context's lock. Only necessary to call if you broke out of
925 * the g_source_iter_next() loop early.
928 g_source_iter_clear (GSourceIter *iter)
930 if (iter->source && iter->may_modify)
932 SOURCE_UNREF (iter->source, iter->context);
937 /* Holds context's lock
940 find_source_list_for_priority (GMainContext *context,
945 GSourceList *source_list;
948 for (iter = context->source_lists; iter != NULL; last = iter, iter = iter->next)
950 source_list = iter->data;
952 if (source_list->priority == priority)
955 if (source_list->priority > priority)
960 source_list = g_slice_new0 (GSourceList);
961 source_list->priority = priority;
962 context->source_lists = g_list_insert_before (context->source_lists,
972 source_list = g_slice_new0 (GSourceList);
973 source_list->priority = priority;
976 context->source_lists = g_list_append (NULL, source_list);
979 /* This just appends source_list to the end of
980 * context->source_lists without having to walk the list again.
982 last = g_list_append (last, source_list);
987 /* Holds context's lock
990 source_add_to_context (GSource *source,
991 GMainContext *context)
993 GSourceList *source_list;
994 GSource *prev, *next;
996 source_list = find_source_list_for_priority (context, source->priority, TRUE);
998 if (source->priv->parent_source)
1000 g_assert (source_list->head != NULL);
1002 /* Put the source immediately before its parent */
1003 prev = source->priv->parent_source->prev;
1004 next = source->priv->parent_source;
1008 prev = source_list->tail;
1012 source->next = next;
1014 next->prev = source;
1016 source_list->tail = source;
1018 source->prev = prev;
1020 prev->next = source;
1022 source_list->head = source;
1025 /* Holds context's lock
1028 source_remove_from_context (GSource *source,
1029 GMainContext *context)
1031 GSourceList *source_list;
1033 source_list = find_source_list_for_priority (context, source->priority, FALSE);
1034 g_return_if_fail (source_list != NULL);
1037 source->prev->next = source->next;
1039 source_list->head = source->next;
1042 source->next->prev = source->prev;
1044 source_list->tail = source->prev;
1046 source->prev = NULL;
1047 source->next = NULL;
1049 if (source_list->head == NULL)
1051 context->source_lists = g_list_remove (context->source_lists, source_list);
1052 g_slice_free (GSourceList, source_list);
1055 if (context->overflow_used_source_ids)
1056 g_hash_table_remove (context->overflow_used_source_ids,
1057 GUINT_TO_POINTER (source->source_id));
1062 assign_source_id_unlocked (GMainContext *context,
1067 /* Are we about to overflow back to 0?
1068 * See https://bugzilla.gnome.org/show_bug.cgi?id=687098
1070 if (G_UNLIKELY (context->next_id == G_MAXUINT &&
1071 context->overflow_used_source_ids == NULL))
1076 context->overflow_used_source_ids = g_hash_table_new (NULL, NULL);
1078 g_source_iter_init (&iter, context, FALSE);
1079 while (g_source_iter_next (&iter, &source))
1081 g_hash_table_add (context->overflow_used_source_ids,
1082 GUINT_TO_POINTER (source->source_id));
1085 g_hash_table_add (context->overflow_used_source_ids, GUINT_TO_POINTER (id));
1087 else if (context->overflow_used_source_ids == NULL)
1089 id = context->next_id++;
1094 * If we overran G_MAXUINT, we fall back to randomly probing the
1095 * source ids for the current context. This will be slower the more
1096 * sources there are, but we're mainly concerned right now about
1097 * correctness and code size. There's time for a more clever solution
1101 id = g_random_int ();
1103 g_hash_table_contains (context->overflow_used_source_ids,
1104 GUINT_TO_POINTER (id)));
1105 g_hash_table_add (context->overflow_used_source_ids, GUINT_TO_POINTER (id));
1108 source->source_id = id;
1112 g_source_attach_unlocked (GSource *source,
1113 GMainContext *context,
1118 source->context = context;
1119 assign_source_id_unlocked (context, source);
1120 source->ref_count++;
1121 source_add_to_context (source, context);
1123 if (!SOURCE_BLOCKED (source))
1125 tmp_list = source->poll_fds;
1128 g_main_context_add_poll_unlocked (context, source->priority, tmp_list->data);
1129 tmp_list = tmp_list->next;
1132 for (tmp_list = source->priv->fds; tmp_list; tmp_list = tmp_list->next)
1133 g_main_context_add_poll_unlocked (context, source->priority, tmp_list->data);
1136 tmp_list = source->priv->child_sources;
1139 g_source_attach_unlocked (tmp_list->data, context, FALSE);
1140 tmp_list = tmp_list->next;
1143 /* If another thread has acquired the context, wake it up since it
1144 * might be in poll() right now.
1146 if (do_wakeup && context->owner && context->owner != G_THREAD_SELF)
1147 g_wakeup_signal (context->wakeup);
1149 return source->source_id;
1154 * @source: a #GSource
1155 * @context: (allow-none): a #GMainContext (if %NULL, the default context will be used)
1157 * Adds a #GSource to a @context so that it will be executed within
1158 * that context. Remove it by calling g_source_destroy().
1160 * Return value: the ID (greater than 0) for the source within the
1164 g_source_attach (GSource *source,
1165 GMainContext *context)
1169 g_return_val_if_fail (source->context == NULL, 0);
1170 g_return_val_if_fail (!SOURCE_DESTROYED (source), 0);
1172 TRACE (GLIB_MAIN_SOURCE_ATTACH (g_source_get_name (source)));
1175 context = g_main_context_default ();
1177 LOCK_CONTEXT (context);
1179 result = g_source_attach_unlocked (source, context, TRUE);
1181 UNLOCK_CONTEXT (context);
1187 g_source_destroy_internal (GSource *source,
1188 GMainContext *context,
1191 TRACE (GLIB_MAIN_SOURCE_DESTROY (g_source_get_name (source)));
1194 LOCK_CONTEXT (context);
1196 if (!SOURCE_DESTROYED (source))
1199 gpointer old_cb_data;
1200 GSourceCallbackFuncs *old_cb_funcs;
1202 source->flags &= ~G_HOOK_FLAG_ACTIVE;
1204 old_cb_data = source->callback_data;
1205 old_cb_funcs = source->callback_funcs;
1207 source->callback_data = NULL;
1208 source->callback_funcs = NULL;
1212 UNLOCK_CONTEXT (context);
1213 old_cb_funcs->unref (old_cb_data);
1214 LOCK_CONTEXT (context);
1217 if (!SOURCE_BLOCKED (source))
1219 tmp_list = source->poll_fds;
1222 g_main_context_remove_poll_unlocked (context, tmp_list->data);
1223 tmp_list = tmp_list->next;
1226 for (tmp_list = source->priv->fds; tmp_list; tmp_list = tmp_list->next)
1227 g_main_context_remove_poll_unlocked (context, tmp_list->data);
1230 while (source->priv->child_sources)
1231 g_child_source_remove_internal (source->priv->child_sources->data, context);
1233 if (source->priv->parent_source)
1234 g_child_source_remove_internal (source, context);
1236 g_source_unref_internal (source, context, TRUE);
1240 UNLOCK_CONTEXT (context);
1245 * @source: a #GSource
1247 * Removes a source from its #GMainContext, if any, and mark it as
1248 * destroyed. The source cannot be subsequently added to another
1252 g_source_destroy (GSource *source)
1254 GMainContext *context;
1256 g_return_if_fail (source != NULL);
1258 context = source->context;
1261 g_source_destroy_internal (source, context, FALSE);
1263 source->flags &= ~G_HOOK_FLAG_ACTIVE;
1268 * @source: a #GSource
1270 * Returns the numeric ID for a particular source. The ID of a source
1271 * is a positive integer which is unique within a particular main loop
1272 * context. The reverse
1273 * mapping from ID to source is done by g_main_context_find_source_by_id().
1275 * Return value: the ID (greater than 0) for the source
1278 g_source_get_id (GSource *source)
1282 g_return_val_if_fail (source != NULL, 0);
1283 g_return_val_if_fail (source->context != NULL, 0);
1285 LOCK_CONTEXT (source->context);
1286 result = source->source_id;
1287 UNLOCK_CONTEXT (source->context);
1293 * g_source_get_context:
1294 * @source: a #GSource
1296 * Gets the #GMainContext with which the source is associated.
1298 * You can call this on a source that has been destroyed, provided
1299 * that the #GMainContext it was attached to still exists (in which
1300 * case it will return that #GMainContext). In particular, you can
1301 * always call this function on the source returned from
1302 * g_main_current_source(). But calling this function on a source
1303 * whose #GMainContext has been destroyed is an error.
1305 * Return value: (transfer none) (allow-none): the #GMainContext with which the
1306 * source is associated, or %NULL if the context has not
1307 * yet been added to a source.
1310 g_source_get_context (GSource *source)
1312 g_return_val_if_fail (source->context != NULL || !SOURCE_DESTROYED (source), NULL);
1314 return source->context;
1318 * g_source_add_poll:
1319 * @source:a #GSource
1320 * @fd: a #GPollFD structure holding information about a file
1321 * descriptor to watch.
1323 * Adds a file descriptor to the set of file descriptors polled for
1324 * this source. This is usually combined with g_source_new() to add an
1325 * event source. The event source's check function will typically test
1326 * the @revents field in the #GPollFD struct and return %TRUE if events need
1329 * Using this API forces the linear scanning of event sources on each
1330 * main loop iteration. Newly-written event sources should try to use
1331 * g_source_add_unix_fd() instead of this API.
1334 g_source_add_poll (GSource *source,
1337 GMainContext *context;
1339 g_return_if_fail (source != NULL);
1340 g_return_if_fail (fd != NULL);
1341 g_return_if_fail (!SOURCE_DESTROYED (source));
1343 context = source->context;
1346 LOCK_CONTEXT (context);
1348 source->poll_fds = g_slist_prepend (source->poll_fds, fd);
1352 if (!SOURCE_BLOCKED (source))
1353 g_main_context_add_poll_unlocked (context, source->priority, fd);
1354 UNLOCK_CONTEXT (context);
1359 * g_source_remove_poll:
1360 * @source:a #GSource
1361 * @fd: a #GPollFD structure previously passed to g_source_add_poll().
1363 * Removes a file descriptor from the set of file descriptors polled for
1367 g_source_remove_poll (GSource *source,
1370 GMainContext *context;
1372 g_return_if_fail (source != NULL);
1373 g_return_if_fail (fd != NULL);
1374 g_return_if_fail (!SOURCE_DESTROYED (source));
1376 context = source->context;
1379 LOCK_CONTEXT (context);
1381 source->poll_fds = g_slist_remove (source->poll_fds, fd);
1385 if (!SOURCE_BLOCKED (source))
1386 g_main_context_remove_poll_unlocked (context, fd);
1387 UNLOCK_CONTEXT (context);
1392 * g_source_add_child_source:
1393 * @source:a #GSource
1394 * @child_source: a second #GSource that @source should "poll"
1396 * Adds @child_source to @source as a "polled" source; when @source is
1397 * added to a #GMainContext, @child_source will be automatically added
1398 * with the same priority, when @child_source is triggered, it will
1399 * cause @source to dispatch (in addition to calling its own
1400 * callback), and when @source is destroyed, it will destroy
1401 * @child_source as well. (@source will also still be dispatched if
1402 * its own prepare/check functions indicate that it is ready.)
1404 * If you don't need @child_source to do anything on its own when it
1405 * triggers, you can call g_source_set_dummy_callback() on it to set a
1406 * callback that does nothing (except return %TRUE if appropriate).
1408 * @source will hold a reference on @child_source while @child_source
1409 * is attached to it.
1414 g_source_add_child_source (GSource *source,
1415 GSource *child_source)
1417 GMainContext *context;
1419 g_return_if_fail (source != NULL);
1420 g_return_if_fail (child_source != NULL);
1421 g_return_if_fail (!SOURCE_DESTROYED (source));
1422 g_return_if_fail (!SOURCE_DESTROYED (child_source));
1423 g_return_if_fail (child_source->context == NULL);
1424 g_return_if_fail (child_source->priv->parent_source == NULL);
1426 context = source->context;
1429 LOCK_CONTEXT (context);
1431 source->priv->child_sources = g_slist_prepend (source->priv->child_sources,
1432 g_source_ref (child_source));
1433 child_source->priv->parent_source = source;
1434 g_source_set_priority_unlocked (child_source, NULL, source->priority);
1435 if (SOURCE_BLOCKED (source))
1436 block_source (child_source);
1440 g_source_attach_unlocked (child_source, context, TRUE);
1441 UNLOCK_CONTEXT (context);
1446 g_child_source_remove_internal (GSource *child_source,
1447 GMainContext *context)
1449 GSource *parent_source = child_source->priv->parent_source;
1451 parent_source->priv->child_sources =
1452 g_slist_remove (parent_source->priv->child_sources, child_source);
1453 child_source->priv->parent_source = NULL;
1455 g_source_destroy_internal (child_source, context, TRUE);
1456 g_source_unref_internal (child_source, context, TRUE);
1460 * g_source_remove_child_source:
1461 * @source:a #GSource
1462 * @child_source: a #GSource previously passed to
1463 * g_source_add_child_source().
1465 * Detaches @child_source from @source and destroys it.
1470 g_source_remove_child_source (GSource *source,
1471 GSource *child_source)
1473 GMainContext *context;
1475 g_return_if_fail (source != NULL);
1476 g_return_if_fail (child_source != NULL);
1477 g_return_if_fail (child_source->priv->parent_source == source);
1478 g_return_if_fail (!SOURCE_DESTROYED (source));
1479 g_return_if_fail (!SOURCE_DESTROYED (child_source));
1481 context = source->context;
1484 LOCK_CONTEXT (context);
1486 g_child_source_remove_internal (child_source, context);
1489 UNLOCK_CONTEXT (context);
1493 * g_source_set_callback_indirect:
1494 * @source: the source
1495 * @callback_data: pointer to callback data "object"
1496 * @callback_funcs: functions for reference counting @callback_data
1497 * and getting the callback and data
1499 * Sets the callback function storing the data as a refcounted callback
1500 * "object". This is used internally. Note that calling
1501 * g_source_set_callback_indirect() assumes
1502 * an initial reference count on @callback_data, and thus
1503 * @callback_funcs->unref will eventually be called once more
1504 * than @callback_funcs->ref.
1507 g_source_set_callback_indirect (GSource *source,
1508 gpointer callback_data,
1509 GSourceCallbackFuncs *callback_funcs)
1511 GMainContext *context;
1512 gpointer old_cb_data;
1513 GSourceCallbackFuncs *old_cb_funcs;
1515 g_return_if_fail (source != NULL);
1516 g_return_if_fail (callback_funcs != NULL || callback_data == NULL);
1518 context = source->context;
1521 LOCK_CONTEXT (context);
1523 old_cb_data = source->callback_data;
1524 old_cb_funcs = source->callback_funcs;
1526 source->callback_data = callback_data;
1527 source->callback_funcs = callback_funcs;
1530 UNLOCK_CONTEXT (context);
1533 old_cb_funcs->unref (old_cb_data);
1537 g_source_callback_ref (gpointer cb_data)
1539 GSourceCallback *callback = cb_data;
1541 callback->ref_count++;
1546 g_source_callback_unref (gpointer cb_data)
1548 GSourceCallback *callback = cb_data;
1550 callback->ref_count--;
1551 if (callback->ref_count == 0)
1553 if (callback->notify)
1554 callback->notify (callback->data);
1560 g_source_callback_get (gpointer cb_data,
1565 GSourceCallback *callback = cb_data;
1567 *func = callback->func;
1568 *data = callback->data;
1571 static GSourceCallbackFuncs g_source_callback_funcs = {
1572 g_source_callback_ref,
1573 g_source_callback_unref,
1574 g_source_callback_get,
1578 * g_source_set_callback:
1579 * @source: the source
1580 * @func: a callback function
1581 * @data: the data to pass to callback function
1582 * @notify: (allow-none): a function to call when @data is no longer in use, or %NULL.
1584 * Sets the callback function for a source. The callback for a source is
1585 * called from the source's dispatch function.
1587 * The exact type of @func depends on the type of source; ie. you
1588 * should not count on @func being called with @data as its first
1591 * Typically, you won't use this function. Instead use functions specific
1592 * to the type of source you are using.
1595 g_source_set_callback (GSource *source,
1598 GDestroyNotify notify)
1600 GSourceCallback *new_callback;
1602 g_return_if_fail (source != NULL);
1604 new_callback = g_new (GSourceCallback, 1);
1606 new_callback->ref_count = 1;
1607 new_callback->func = func;
1608 new_callback->data = data;
1609 new_callback->notify = notify;
1611 g_source_set_callback_indirect (source, new_callback, &g_source_callback_funcs);
1616 * g_source_set_funcs:
1617 * @source: a #GSource
1618 * @funcs: the new #GSourceFuncs
1620 * Sets the source functions (can be used to override
1621 * default implementations) of an unattached source.
1626 g_source_set_funcs (GSource *source,
1627 GSourceFuncs *funcs)
1629 g_return_if_fail (source != NULL);
1630 g_return_if_fail (source->context == NULL);
1631 g_return_if_fail (source->ref_count > 0);
1632 g_return_if_fail (funcs != NULL);
1634 source->source_funcs = funcs;
1638 g_source_set_priority_unlocked (GSource *source,
1639 GMainContext *context,
1644 g_return_if_fail (source->priv->parent_source == NULL ||
1645 source->priv->parent_source->priority == priority);
1649 /* Remove the source from the context's source and then
1650 * add it back after so it is sorted in the correct place
1652 source_remove_from_context (source, source->context);
1655 source->priority = priority;
1659 source_add_to_context (source, source->context);
1661 if (!SOURCE_BLOCKED (source))
1663 tmp_list = source->poll_fds;
1666 g_main_context_remove_poll_unlocked (context, tmp_list->data);
1667 g_main_context_add_poll_unlocked (context, priority, tmp_list->data);
1669 tmp_list = tmp_list->next;
1672 for (tmp_list = source->priv->fds; tmp_list; tmp_list = tmp_list->next)
1674 g_main_context_remove_poll_unlocked (context, tmp_list->data);
1675 g_main_context_add_poll_unlocked (context, priority, tmp_list->data);
1680 if (source->priv->child_sources)
1682 tmp_list = source->priv->child_sources;
1685 g_source_set_priority_unlocked (tmp_list->data, context, priority);
1686 tmp_list = tmp_list->next;
1692 * g_source_set_priority:
1693 * @source: a #GSource
1694 * @priority: the new priority.
1696 * Sets the priority of a source. While the main loop is being run, a
1697 * source will be dispatched if it is ready to be dispatched and no
1698 * sources at a higher (numerically smaller) priority are ready to be
1702 g_source_set_priority (GSource *source,
1705 GMainContext *context;
1707 g_return_if_fail (source != NULL);
1709 context = source->context;
1712 LOCK_CONTEXT (context);
1713 g_source_set_priority_unlocked (source, context, priority);
1715 UNLOCK_CONTEXT (source->context);
1719 * g_source_get_priority:
1720 * @source: a #GSource
1722 * Gets the priority of a source.
1724 * Return value: the priority of the source
1727 g_source_get_priority (GSource *source)
1729 g_return_val_if_fail (source != NULL, 0);
1731 return source->priority;
1735 * g_source_set_ready_time:
1736 * @source: a #GSource
1737 * @ready_time: the monotonic time at which the source will be ready,
1738 * 0 for "immediately", -1 for "never"
1740 * Sets a #GSource to be dispatched when the given monotonic time is
1741 * reached (or passed). If the monotonic time is in the past (as it
1742 * always will be if @ready_time is 0) then the source will be
1743 * dispatched immediately.
1745 * If @ready_time is -1 then the source is never woken up on the basis
1746 * of the passage of time.
1748 * Dispatching the source does not reset the ready time. You should do
1749 * so yourself, from the source dispatch function.
1751 * Note that if you have a pair of sources where the ready time of one
1752 * suggests that it will be delivered first but the priority for the
1753 * other suggests that it would be delivered first, and the ready time
1754 * for both sources is reached during the same main context iteration
1755 * then the order of dispatch is undefined.
1760 g_source_set_ready_time (GSource *source,
1763 GMainContext *context;
1765 g_return_if_fail (source != NULL);
1766 g_return_if_fail (source->ref_count > 0);
1768 if (source->priv->ready_time == ready_time)
1771 context = source->context;
1774 LOCK_CONTEXT (context);
1776 source->priv->ready_time = ready_time;
1780 /* Quite likely that we need to change the timeout on the poll */
1781 if (!SOURCE_BLOCKED (source))
1782 g_wakeup_signal (context->wakeup);
1783 UNLOCK_CONTEXT (context);
1788 * g_source_get_ready_time:
1789 * @source: a #GSource
1791 * Gets the "ready time" of @source, as set by
1792 * g_source_set_ready_time().
1794 * Any time before the current monotonic time (including 0) is an
1795 * indication that the source will fire immediately.
1797 * Returns: the monotonic ready time, -1 for "never"
1800 g_source_get_ready_time (GSource *source)
1802 g_return_val_if_fail (source != NULL, -1);
1804 return source->priv->ready_time;
1808 * g_source_set_can_recurse:
1809 * @source: a #GSource
1810 * @can_recurse: whether recursion is allowed for this source
1812 * Sets whether a source can be called recursively. If @can_recurse is
1813 * %TRUE, then while the source is being dispatched then this source
1814 * will be processed normally. Otherwise, all processing of this
1815 * source is blocked until the dispatch function returns.
1818 g_source_set_can_recurse (GSource *source,
1819 gboolean can_recurse)
1821 GMainContext *context;
1823 g_return_if_fail (source != NULL);
1825 context = source->context;
1828 LOCK_CONTEXT (context);
1831 source->flags |= G_SOURCE_CAN_RECURSE;
1833 source->flags &= ~G_SOURCE_CAN_RECURSE;
1836 UNLOCK_CONTEXT (context);
1840 * g_source_get_can_recurse:
1841 * @source: a #GSource
1843 * Checks whether a source is allowed to be called recursively.
1844 * see g_source_set_can_recurse().
1846 * Return value: whether recursion is allowed.
1849 g_source_get_can_recurse (GSource *source)
1851 g_return_val_if_fail (source != NULL, FALSE);
1853 return (source->flags & G_SOURCE_CAN_RECURSE) != 0;
1858 * g_source_set_name:
1859 * @source: a #GSource
1860 * @name: debug name for the source
1862 * Sets a name for the source, used in debugging and profiling.
1863 * The name defaults to #NULL.
1865 * The source name should describe in a human-readable way
1866 * what the source does. For example, "X11 event queue"
1867 * or "GTK+ repaint idle handler" or whatever it is.
1869 * It is permitted to call this function multiple times, but is not
1870 * recommended due to the potential performance impact. For example,
1871 * one could change the name in the "check" function of a #GSourceFuncs
1872 * to include details like the event type in the source name.
1877 g_source_set_name (GSource *source,
1880 g_return_if_fail (source != NULL);
1882 /* setting back to NULL is allowed, just because it's
1883 * weird if get_name can return NULL but you can't
1887 g_free (source->name);
1888 source->name = g_strdup (name);
1892 * g_source_get_name:
1893 * @source: a #GSource
1895 * Gets a name for the source, used in debugging and profiling.
1896 * The name may be #NULL if it has never been set with
1897 * g_source_set_name().
1899 * Return value: the name of the source
1903 g_source_get_name (GSource *source)
1905 g_return_val_if_fail (source != NULL, NULL);
1907 return source->name;
1911 * g_source_set_name_by_id:
1912 * @tag: a #GSource ID
1913 * @name: debug name for the source
1915 * Sets the name of a source using its ID.
1917 * This is a convenience utility to set source names from the return
1918 * value of g_idle_add(), g_timeout_add(), etc.
1923 g_source_set_name_by_id (guint tag,
1928 g_return_if_fail (tag > 0);
1930 source = g_main_context_find_source_by_id (NULL, tag);
1934 g_source_set_name (source, name);
1940 * @source: a #GSource
1942 * Increases the reference count on a source by one.
1944 * Return value: @source
1947 g_source_ref (GSource *source)
1949 GMainContext *context;
1951 g_return_val_if_fail (source != NULL, NULL);
1953 context = source->context;
1956 LOCK_CONTEXT (context);
1958 source->ref_count++;
1961 UNLOCK_CONTEXT (context);
1966 /* g_source_unref() but possible to call within context lock
1969 g_source_unref_internal (GSource *source,
1970 GMainContext *context,
1973 gpointer old_cb_data = NULL;
1974 GSourceCallbackFuncs *old_cb_funcs = NULL;
1976 g_return_if_fail (source != NULL);
1978 if (!have_lock && context)
1979 LOCK_CONTEXT (context);
1981 source->ref_count--;
1982 if (source->ref_count == 0)
1984 old_cb_data = source->callback_data;
1985 old_cb_funcs = source->callback_funcs;
1987 source->callback_data = NULL;
1988 source->callback_funcs = NULL;
1992 if (!SOURCE_DESTROYED (source))
1993 g_warning (G_STRLOC ": ref_count == 0, but source was still attached to a context!");
1994 source_remove_from_context (source, context);
1997 if (source->source_funcs->finalize)
2000 UNLOCK_CONTEXT (context);
2001 source->source_funcs->finalize (source);
2003 LOCK_CONTEXT (context);
2006 g_free (source->name);
2007 source->name = NULL;
2009 g_slist_free (source->poll_fds);
2010 source->poll_fds = NULL;
2012 g_slist_free_full (source->priv->fds, g_free);
2014 g_slice_free (GSourcePrivate, source->priv);
2015 source->priv = NULL;
2020 if (!have_lock && context)
2021 UNLOCK_CONTEXT (context);
2026 UNLOCK_CONTEXT (context);
2028 old_cb_funcs->unref (old_cb_data);
2031 LOCK_CONTEXT (context);
2037 * @source: a #GSource
2039 * Decreases the reference count of a source by one. If the
2040 * resulting reference count is zero the source and associated
2041 * memory will be destroyed.
2044 g_source_unref (GSource *source)
2046 g_return_if_fail (source != NULL);
2048 g_source_unref_internal (source, source->context, FALSE);
2052 * g_main_context_find_source_by_id:
2053 * @context: (allow-none): a #GMainContext (if %NULL, the default context will be used)
2054 * @source_id: the source ID, as returned by g_source_get_id().
2056 * Finds a #GSource given a pair of context and ID.
2058 * Return value: (transfer none): the #GSource if found, otherwise, %NULL
2061 g_main_context_find_source_by_id (GMainContext *context,
2067 g_return_val_if_fail (source_id > 0, NULL);
2069 if (context == NULL)
2070 context = g_main_context_default ();
2072 LOCK_CONTEXT (context);
2074 g_source_iter_init (&iter, context, FALSE);
2075 while (g_source_iter_next (&iter, &source))
2077 if (!SOURCE_DESTROYED (source) &&
2078 source->source_id == source_id)
2081 g_source_iter_clear (&iter);
2083 UNLOCK_CONTEXT (context);
2089 * g_main_context_find_source_by_funcs_user_data:
2090 * @context: (allow-none): a #GMainContext (if %NULL, the default context will be used).
2091 * @funcs: the @source_funcs passed to g_source_new().
2092 * @user_data: the user data from the callback.
2094 * Finds a source with the given source functions and user data. If
2095 * multiple sources exist with the same source function and user data,
2096 * the first one found will be returned.
2098 * Return value: (transfer none): the source, if one was found, otherwise %NULL
2101 g_main_context_find_source_by_funcs_user_data (GMainContext *context,
2102 GSourceFuncs *funcs,
2108 g_return_val_if_fail (funcs != NULL, NULL);
2110 if (context == NULL)
2111 context = g_main_context_default ();
2113 LOCK_CONTEXT (context);
2115 g_source_iter_init (&iter, context, FALSE);
2116 while (g_source_iter_next (&iter, &source))
2118 if (!SOURCE_DESTROYED (source) &&
2119 source->source_funcs == funcs &&
2120 source->callback_funcs)
2122 GSourceFunc callback;
2123 gpointer callback_data;
2125 source->callback_funcs->get (source->callback_data, source, &callback, &callback_data);
2127 if (callback_data == user_data)
2131 g_source_iter_clear (&iter);
2133 UNLOCK_CONTEXT (context);
2139 * g_main_context_find_source_by_user_data:
2140 * @context: a #GMainContext
2141 * @user_data: the user_data for the callback.
2143 * Finds a source with the given user data for the callback. If
2144 * multiple sources exist with the same user data, the first
2145 * one found will be returned.
2147 * Return value: (transfer none): the source, if one was found, otherwise %NULL
2150 g_main_context_find_source_by_user_data (GMainContext *context,
2156 if (context == NULL)
2157 context = g_main_context_default ();
2159 LOCK_CONTEXT (context);
2161 g_source_iter_init (&iter, context, FALSE);
2162 while (g_source_iter_next (&iter, &source))
2164 if (!SOURCE_DESTROYED (source) &&
2165 source->callback_funcs)
2167 GSourceFunc callback;
2168 gpointer callback_data = NULL;
2170 source->callback_funcs->get (source->callback_data, source, &callback, &callback_data);
2172 if (callback_data == user_data)
2176 g_source_iter_clear (&iter);
2178 UNLOCK_CONTEXT (context);
2185 * @tag: the ID of the source to remove.
2187 * Removes the source with the given id from the default main context.
2189 * The id of a #GSource is given by g_source_get_id(), or will be
2190 * returned by the functions g_source_attach(), g_idle_add(),
2191 * g_idle_add_full(), g_timeout_add(), g_timeout_add_full(),
2192 * g_child_watch_add(), g_child_watch_add_full(), g_io_add_watch(), and
2193 * g_io_add_watch_full().
2195 * See also g_source_destroy(). You must use g_source_destroy() for sources
2196 * added to a non-default main context.
2198 * It is a programmer error to attempt to remove a non-existent source.
2200 * Return value: For historical reasons, this function always returns %TRUE
2203 g_source_remove (guint tag)
2207 g_return_val_if_fail (tag > 0, FALSE);
2209 source = g_main_context_find_source_by_id (NULL, tag);
2211 g_source_destroy (source);
2213 g_critical ("Source ID %u was not found when attempting to remove it", tag);
2215 return source != NULL;
2219 * g_source_remove_by_user_data:
2220 * @user_data: the user_data for the callback.
2222 * Removes a source from the default main loop context given the user
2223 * data for the callback. If multiple sources exist with the same user
2224 * data, only one will be destroyed.
2226 * Return value: %TRUE if a source was found and removed.
2229 g_source_remove_by_user_data (gpointer user_data)
2233 source = g_main_context_find_source_by_user_data (NULL, user_data);
2236 g_source_destroy (source);
2244 * g_source_remove_by_funcs_user_data:
2245 * @funcs: The @source_funcs passed to g_source_new()
2246 * @user_data: the user data for the callback
2248 * Removes a source from the default main loop context given the
2249 * source functions and user data. If multiple sources exist with the
2250 * same source functions and user data, only one will be destroyed.
2252 * Return value: %TRUE if a source was found and removed.
2255 g_source_remove_by_funcs_user_data (GSourceFuncs *funcs,
2260 g_return_val_if_fail (funcs != NULL, FALSE);
2262 source = g_main_context_find_source_by_funcs_user_data (NULL, funcs, user_data);
2265 g_source_destroy (source);
2274 * g_source_add_unix_fd:
2275 * @source: a #GSource
2276 * @fd: the fd to monitor
2277 * @events: an event mask
2279 * Monitors @fd for the IO events in @events.
2281 * The tag returned by this function can be used to remove or modify the
2282 * monitoring of the fd using g_source_remove_unix_fd() or
2283 * g_source_modify_unix_fd().
2285 * It is not necessary to remove the fd before destroying the source; it
2286 * will be cleaned up automatically.
2288 * As the name suggests, this function is not available on Windows.
2290 * Returns: an opaque tag
2295 g_source_add_unix_fd (GSource *source,
2297 GIOCondition events)
2299 GMainContext *context;
2302 g_return_val_if_fail (source != NULL, NULL);
2303 g_return_val_if_fail (!SOURCE_DESTROYED (source), NULL);
2305 poll_fd = g_new (GPollFD, 1);
2307 poll_fd->events = events;
2308 poll_fd->revents = 0;
2310 context = source->context;
2313 LOCK_CONTEXT (context);
2315 source->priv->fds = g_slist_prepend (source->priv->fds, poll_fd);
2319 if (!SOURCE_BLOCKED (source))
2320 g_main_context_add_poll_unlocked (context, source->priority, poll_fd);
2321 UNLOCK_CONTEXT (context);
2328 * g_source_modify_unix_fd:
2329 * @source: a #GSource
2330 * @tag: the tag from g_source_add_unix_fd()
2331 * @new_events: the new event mask to watch
2333 * Updates the event mask to watch for the fd identified by @tag.
2335 * @tag is the tag returned from g_source_add_unix_fd().
2337 * If you want to remove a fd, don't set its event mask to zero.
2338 * Instead, call g_source_remove_unix_fd().
2340 * As the name suggests, this function is not available on Windows.
2345 g_source_modify_unix_fd (GSource *source,
2347 GIOCondition new_events)
2349 GMainContext *context;
2352 g_return_if_fail (source != NULL);
2353 g_return_if_fail (g_slist_find (source->priv->fds, tag));
2355 context = source->context;
2358 poll_fd->events = new_events;
2361 g_main_context_wakeup (context);
2365 * g_source_remove_unix_fd:
2366 * @source: a #GSource
2367 * @tag: the tag from g_source_add_unix_fd()
2369 * Reverses the effect of a previous call to g_source_add_unix_fd().
2371 * You only need to call this if you want to remove an fd from being
2372 * watched while keeping the same source around. In the normal case you
2373 * will just want to destroy the source.
2375 * As the name suggests, this function is not available on Windows.
2380 g_source_remove_unix_fd (GSource *source,
2383 GMainContext *context;
2386 g_return_if_fail (source != NULL);
2387 g_return_if_fail (g_slist_find (source->priv->fds, tag));
2389 context = source->context;
2393 LOCK_CONTEXT (context);
2395 source->priv->fds = g_slist_remove (source->priv->fds, poll_fd);
2399 if (!SOURCE_BLOCKED (source))
2400 g_main_context_remove_poll_unlocked (context, poll_fd);
2402 UNLOCK_CONTEXT (context);
2409 * g_source_query_unix_fd:
2410 * @source: a #GSource
2411 * @tag: the tag from g_source_add_unix_fd()
2413 * Queries the events reported for the fd corresponding to @tag on
2414 * @source during the last poll.
2416 * The return value of this function is only defined when the function
2417 * is called from the check or dispatch functions for @source.
2419 * As the name suggests, this function is not available on Windows.
2421 * Returns: the conditions reported on the fd
2426 g_source_query_unix_fd (GSource *source,
2431 g_return_val_if_fail (source != NULL, 0);
2432 g_return_val_if_fail (g_slist_find (source->priv->fds, tag), 0);
2436 return poll_fd->revents;
2438 #endif /* G_OS_UNIX */
2441 * g_get_current_time:
2442 * @result: #GTimeVal structure in which to store current time.
2444 * Equivalent to the UNIX gettimeofday() function, but portable.
2446 * You may find g_get_real_time() to be more convenient.
2449 g_get_current_time (GTimeVal *result)
2454 g_return_if_fail (result != NULL);
2456 /*this is required on alpha, there the timeval structs are int's
2457 not longs and a cast only would fail horribly*/
2458 gettimeofday (&r, NULL);
2459 result->tv_sec = r.tv_sec;
2460 result->tv_usec = r.tv_usec;
2465 g_return_if_fail (result != NULL);
2467 GetSystemTimeAsFileTime (&ft);
2468 memmove (&time64, &ft, sizeof (FILETIME));
2470 /* Convert from 100s of nanoseconds since 1601-01-01
2471 * to Unix epoch. Yes, this is Y2038 unsafe.
2473 time64 -= G_GINT64_CONSTANT (116444736000000000);
2476 result->tv_sec = time64 / 1000000;
2477 result->tv_usec = time64 % 1000000;
2484 * Queries the system wall-clock time.
2486 * This call is functionally equivalent to g_get_current_time() except
2487 * that the return value is often more convenient than dealing with a
2490 * You should only use this call if you are actually interested in the real
2491 * wall-clock time. g_get_monotonic_time() is probably more useful for
2492 * measuring intervals.
2494 * Returns: the number of microseconds since January 1, 1970 UTC.
2499 g_get_real_time (void)
2503 g_get_current_time (&tv);
2505 return (((gint64) tv.tv_sec) * 1000000) + tv.tv_usec;
2509 static ULONGLONG (*g_GetTickCount64) (void) = NULL;
2510 static guint32 g_win32_tick_epoch = 0;
2513 g_clock_win32_init (void)
2517 g_GetTickCount64 = NULL;
2518 kernel32 = GetModuleHandle ("KERNEL32.DLL");
2519 if (kernel32 != NULL)
2520 g_GetTickCount64 = (void *) GetProcAddress (kernel32, "GetTickCount64");
2521 g_win32_tick_epoch = ((guint32)GetTickCount()) >> 31;
2526 * g_get_monotonic_time:
2528 * Queries the system monotonic time, if available.
2530 * On POSIX systems with clock_gettime() and <literal>CLOCK_MONOTONIC</literal> this call
2531 * is a very shallow wrapper for that. Otherwise, we make a best effort
2532 * that probably involves returning the wall clock time (with at least
2533 * microsecond accuracy, subject to the limitations of the OS kernel).
2535 * It's important to note that POSIX <literal>CLOCK_MONOTONIC</literal> does
2536 * not count time spent while the machine is suspended.
2538 * On Windows, "limitations of the OS kernel" is a rather substantial
2539 * statement. Depending on the configuration of the system, the wall
2540 * clock time is updated as infrequently as 64 times a second (which
2541 * is approximately every 16ms). Also, on XP (but not on Vista or later)
2542 * the monotonic clock is locally monotonic, but may differ in exact
2543 * value between processes due to timer wrap handling.
2545 * Returns: the monotonic time, in microseconds
2550 g_get_monotonic_time (void)
2552 #ifdef HAVE_CLOCK_GETTIME
2553 /* librt clock_gettime() is our first choice */
2556 #ifdef CLOCK_MONOTONIC
2557 clock_gettime (CLOCK_MONOTONIC, &ts);
2559 clock_gettime (CLOCK_REALTIME, &ts);
2562 /* In theory monotonic time can have any epoch.
2564 * glib presently assumes the following:
2566 * 1) The epoch comes some time after the birth of Jesus of Nazareth, but
2567 * not more than 10000 years later.
2569 * 2) The current time also falls sometime within this range.
2571 * These two reasonable assumptions leave us with a maximum deviation from
2572 * the epoch of 10000 years, or 315569520000000000 seconds.
2574 * If we restrict ourselves to this range then the number of microseconds
2575 * will always fit well inside the constraints of a int64 (by a factor of
2578 * If you actually hit the following assertion, probably you should file a
2579 * bug against your operating system for being excessively silly.
2581 g_assert (G_GINT64_CONSTANT (-315569520000000000) < ts.tv_sec &&
2582 ts.tv_sec < G_GINT64_CONSTANT (315569520000000000));
2584 return (((gint64) ts.tv_sec) * 1000000) + (ts.tv_nsec / 1000);
2586 #elif defined (G_OS_WIN32)
2590 /* There are four sources for the monotonic time on Windows:
2592 * Three are based on a (1 msec accuracy, but only read periodically) clock chip:
2593 * - GetTickCount (GTC)
2594 * 32bit msec counter, updated each ~15msec, wraps in ~50 days
2595 * - GetTickCount64 (GTC64)
2596 * Same as GetTickCount, but extended to 64bit, so no wrap
2597 * Only available in Vista or later
2598 * - timeGetTime (TGT)
2599 * similar to GetTickCount by default: 15msec, 50 day wrap.
2600 * available in winmm.dll (thus known as the multimedia timers)
2601 * However apps can raise the system timer clock frequency using timeBeginPeriod()
2602 * increasing the accuracy up to 1 msec, at a cost in general system performance
2605 * One is based on high precision clocks:
2606 * - QueryPrecisionCounter (QPC)
2607 * This has much higher accuracy, but is not guaranteed monotonic, and
2608 * has lots of complications like clock jumps and different times on different
2609 * CPUs. It also has lower long term accuracy (i.e. it will drift compared to
2610 * the low precision clocks.
2612 * Additionally, the precision available in the timer-based wakeup such as
2613 * MsgWaitForMultipleObjectsEx (which is what the mainloop is based on) is based
2614 * on the TGT resolution, so by default it is ~15msec, but can be increased by apps.
2616 * The QPC timer has too many issues to be used as is. The only way it could be used
2617 * is to use it to interpolate the lower precision clocks. Firefox does something like
2619 * https://bugzilla.mozilla.org/show_bug.cgi?id=363258
2621 * However this seems quite complicated, so we're not doing this right now.
2623 * The approach we take instead is to use the TGT timer, extending it to 64bit
2624 * either by using the GTC64 value, or if that is not available, a process local
2625 * time epoch that we increment when we detect a timer wrap (assumes that we read
2626 * the time at least once every 50 days).
2629 * - We have a globally consistent monotonic clock on Vista and later
2630 * - We have a locally monotonic clock on XP
2631 * - Apps that need higher precision in timeouts and clock reads can call
2632 * timeBeginPeriod() to increase it as much as they want
2635 if (g_GetTickCount64 != NULL)
2637 guint32 ticks_as_32bit;
2639 ticks = g_GetTickCount64 ();
2640 ticks32 = timeGetTime();
2642 /* GTC64 and TGT are sampled at different times, however they
2643 * have the same base and source (msecs since system boot).
2644 * They can differ by as much as -16 to +16 msecs.
2645 * We can't just inject the low bits into the 64bit counter
2646 * as one of the counters can have wrapped in 32bit space and
2647 * the other not. Instead we calculate the signed difference
2648 * in 32bit space and apply that difference to the 64bit counter.
2650 ticks_as_32bit = (guint32)ticks;
2652 /* We could do some 2's complement hack, but we play it safe */
2653 if (ticks32 - ticks_as_32bit <= G_MAXINT32)
2654 ticks += ticks32 - ticks_as_32bit;
2656 ticks -= ticks_as_32bit - ticks32;
2662 epoch = g_atomic_int_get (&g_win32_tick_epoch);
2664 /* Must read ticks after the epoch. Then we're guaranteed
2665 * that the ticks value we read is higher or equal to any
2666 * previous ones that lead to the writing of the epoch.
2668 ticks32 = timeGetTime();
2670 /* We store the MSB of the current time as the LSB
2671 * of the epoch. Comparing these bits lets us detect when
2672 * the 32bit counter has wrapped so we can increase the
2675 * This will work as long as this function is called at
2676 * least once every ~24 days, which is half the wrap time
2677 * of a 32bit msec counter. I think this is pretty likely.
2679 * Note that g_win32_tick_epoch is a process local state,
2680 * so the monotonic clock will not be the same between
2683 if ((ticks32 >> 31) != (epoch & 1))
2686 g_atomic_int_set (&g_win32_tick_epoch, epoch);
2690 ticks = (guint64)ticks32 | ((guint64)epoch) << 31;
2693 return ticks * 1000;
2695 #else /* !HAVE_CLOCK_GETTIME && ! G_OS_WIN32*/
2699 g_get_current_time (&tv);
2701 return (((gint64) tv.tv_sec) * 1000000) + tv.tv_usec;
2706 g_main_dispatch_free (gpointer dispatch)
2708 g_slice_free (GMainDispatch, dispatch);
2711 /* Running the main loop */
2713 static GMainDispatch *
2716 static GPrivate depth_private = G_PRIVATE_INIT (g_main_dispatch_free);
2717 GMainDispatch *dispatch;
2719 dispatch = g_private_get (&depth_private);
2723 dispatch = g_slice_new0 (GMainDispatch);
2724 g_private_set (&depth_private, dispatch);
2733 * Returns the depth of the stack of calls to
2734 * g_main_context_dispatch() on any #GMainContext in the current thread.
2735 * That is, when called from the toplevel, it gives 0. When
2736 * called from within a callback from g_main_context_iteration()
2737 * (or g_main_loop_run(), etc.) it returns 1. When called from within
2738 * a callback to a recursive call to g_main_context_iteration(),
2739 * it returns 2. And so forth.
2741 * This function is useful in a situation like the following:
2742 * Imagine an extremely simple "garbage collected" system.
2744 * |[<!-- language="C" -->
2745 * static GList *free_list;
2748 * allocate_memory (gsize size)
2750 * gpointer result = g_malloc (size);
2751 * free_list = g_list_prepend (free_list, result);
2756 * free_allocated_memory (void)
2759 * for (l = free_list; l; l = l->next);
2761 * g_list_free (free_list);
2769 * g_main_context_iteration (NULL, TRUE);
2770 * free_allocated_memory();
2774 * This works from an application, however, if you want to do the same
2775 * thing from a library, it gets more difficult, since you no longer
2776 * control the main loop. You might think you can simply use an idle
2777 * function to make the call to free_allocated_memory(), but that
2778 * doesn't work, since the idle function could be called from a
2779 * recursive callback. This can be fixed by using g_main_depth()
2781 * |[<!-- language="C" -->
2783 * allocate_memory (gsize size)
2785 * FreeListBlock *block = g_new (FreeListBlock, 1);
2786 * block->mem = g_malloc (size);
2787 * block->depth = g_main_depth ();
2788 * free_list = g_list_prepend (free_list, block);
2789 * return block->mem;
2793 * free_allocated_memory (void)
2797 * int depth = g_main_depth ();
2798 * for (l = free_list; l; );
2800 * GList *next = l->next;
2801 * FreeListBlock *block = l->data;
2802 * if (block->depth > depth)
2804 * g_free (block->mem);
2806 * free_list = g_list_delete_link (free_list, l);
2814 * There is a temptation to use g_main_depth() to solve
2815 * problems with reentrancy. For instance, while waiting for data
2816 * to be received from the network in response to a menu item,
2817 * the menu item might be selected again. It might seem that
2818 * one could make the menu item's callback return immediately
2819 * and do nothing if g_main_depth() returns a value greater than 1.
2820 * However, this should be avoided since the user then sees selecting
2821 * the menu item do nothing. Furthermore, you'll find yourself adding
2822 * these checks all over your code, since there are doubtless many,
2823 * many things that the user could do. Instead, you can use the
2824 * following techniques:
2826 * 1. Use gtk_widget_set_sensitive() or modal dialogs to prevent
2827 * the user from interacting with elements while the main
2828 * loop is recursing.
2830 * 2. Avoid main loop recursion in situations where you can't handle
2831 * arbitrary callbacks. Instead, structure your code so that you
2832 * simply return to the main loop and then get called again when
2833 * there is more work to do.
2835 * Return value: The main loop recursion level in the current thread
2840 GMainDispatch *dispatch = get_dispatch ();
2841 return dispatch->depth;
2845 * g_main_current_source:
2847 * Returns the currently firing source for this thread.
2849 * Return value: (transfer none): The currently firing source or %NULL.
2854 g_main_current_source (void)
2856 GMainDispatch *dispatch = get_dispatch ();
2857 return dispatch->source;
2861 * g_source_is_destroyed:
2862 * @source: a #GSource
2864 * Returns whether @source has been destroyed.
2866 * This is important when you operate upon your objects
2867 * from within idle handlers, but may have freed the object
2868 * before the dispatch of your idle handler.
2870 * |[<!-- language="C" -->
2872 * idle_callback (gpointer data)
2874 * SomeWidget *self = data;
2876 * GDK_THREADS_ENTER ();
2877 * /* do stuff with self */
2878 * self->idle_id = 0;
2879 * GDK_THREADS_LEAVE ();
2881 * return G_SOURCE_REMOVE;
2885 * some_widget_do_stuff_later (SomeWidget *self)
2887 * self->idle_id = g_idle_add (idle_callback, self);
2891 * some_widget_finalize (GObject *object)
2893 * SomeWidget *self = SOME_WIDGET (object);
2895 * if (self->idle_id)
2896 * g_source_remove (self->idle_id);
2898 * G_OBJECT_CLASS (parent_class)->finalize (object);
2902 * This will fail in a multi-threaded application if the
2903 * widget is destroyed before the idle handler fires due
2904 * to the use after free in the callback. A solution, to
2905 * this particular problem, is to check to if the source
2906 * has already been destroy within the callback.
2908 * |[<!-- language="C" -->
2910 * idle_callback (gpointer data)
2912 * SomeWidget *self = data;
2914 * GDK_THREADS_ENTER ();
2915 * if (!g_source_is_destroyed (g_main_current_source ()))
2917 * /* do stuff with self */
2919 * GDK_THREADS_LEAVE ();
2925 * Return value: %TRUE if the source has been destroyed
2930 g_source_is_destroyed (GSource *source)
2932 return SOURCE_DESTROYED (source);
2935 /* Temporarily remove all this source's file descriptors from the
2936 * poll(), so that if data comes available for one of the file descriptors
2937 * we don't continually spin in the poll()
2939 /* HOLDS: source->context's lock */
2941 block_source (GSource *source)
2945 g_return_if_fail (!SOURCE_BLOCKED (source));
2947 source->flags |= G_SOURCE_BLOCKED;
2949 if (source->context)
2951 tmp_list = source->poll_fds;
2954 g_main_context_remove_poll_unlocked (source->context, tmp_list->data);
2955 tmp_list = tmp_list->next;
2958 for (tmp_list = source->priv->fds; tmp_list; tmp_list = tmp_list->next)
2959 g_main_context_remove_poll_unlocked (source->context, tmp_list->data);
2962 if (source->priv && source->priv->child_sources)
2964 tmp_list = source->priv->child_sources;
2967 block_source (tmp_list->data);
2968 tmp_list = tmp_list->next;
2973 /* HOLDS: source->context's lock */
2975 unblock_source (GSource *source)
2979 g_return_if_fail (SOURCE_BLOCKED (source)); /* Source already unblocked */
2980 g_return_if_fail (!SOURCE_DESTROYED (source));
2982 source->flags &= ~G_SOURCE_BLOCKED;
2984 tmp_list = source->poll_fds;
2987 g_main_context_add_poll_unlocked (source->context, source->priority, tmp_list->data);
2988 tmp_list = tmp_list->next;
2991 for (tmp_list = source->priv->fds; tmp_list; tmp_list = tmp_list->next)
2992 g_main_context_add_poll_unlocked (source->context, source->priority, tmp_list->data);
2994 if (source->priv && source->priv->child_sources)
2996 tmp_list = source->priv->child_sources;
2999 unblock_source (tmp_list->data);
3000 tmp_list = tmp_list->next;
3005 /* HOLDS: context's lock */
3007 g_main_dispatch (GMainContext *context)
3009 GMainDispatch *current = get_dispatch ();
3012 for (i = 0; i < context->pending_dispatches->len; i++)
3014 GSource *source = context->pending_dispatches->pdata[i];
3016 context->pending_dispatches->pdata[i] = NULL;
3019 source->flags &= ~G_SOURCE_READY;
3021 if (!SOURCE_DESTROYED (source))
3023 gboolean was_in_call;
3024 gpointer user_data = NULL;
3025 GSourceFunc callback = NULL;
3026 GSourceCallbackFuncs *cb_funcs;
3028 gboolean need_destroy;
3030 gboolean (*dispatch) (GSource *,
3033 GSource *prev_source;
3035 dispatch = source->source_funcs->dispatch;
3036 cb_funcs = source->callback_funcs;
3037 cb_data = source->callback_data;
3040 cb_funcs->ref (cb_data);
3042 if ((source->flags & G_SOURCE_CAN_RECURSE) == 0)
3043 block_source (source);
3045 was_in_call = source->flags & G_HOOK_FLAG_IN_CALL;
3046 source->flags |= G_HOOK_FLAG_IN_CALL;
3049 cb_funcs->get (cb_data, source, &callback, &user_data);
3051 UNLOCK_CONTEXT (context);
3053 /* These operations are safe because 'current' is thread-local
3054 * and not modified from anywhere but this function.
3056 prev_source = current->source;
3057 current->source = source;
3060 TRACE( GLIB_MAIN_BEFORE_DISPATCH (g_source_get_name (source)));
3061 need_destroy = !(* dispatch) (source, callback, user_data);
3062 TRACE( GLIB_MAIN_AFTER_DISPATCH (g_source_get_name (source)));
3064 current->source = prev_source;
3068 cb_funcs->unref (cb_data);
3070 LOCK_CONTEXT (context);
3073 source->flags &= ~G_HOOK_FLAG_IN_CALL;
3075 if (SOURCE_BLOCKED (source) && !SOURCE_DESTROYED (source))
3076 unblock_source (source);
3078 /* Note: this depends on the fact that we can't switch
3079 * sources from one main context to another
3081 if (need_destroy && !SOURCE_DESTROYED (source))
3083 g_assert (source->context == context);
3084 g_source_destroy_internal (source, context, TRUE);
3088 SOURCE_UNREF (source, context);
3091 g_ptr_array_set_size (context->pending_dispatches, 0);
3095 * g_main_context_acquire:
3096 * @context: a #GMainContext
3098 * Tries to become the owner of the specified context.
3099 * If some other thread is the owner of the context,
3100 * returns %FALSE immediately. Ownership is properly
3101 * recursive: the owner can require ownership again
3102 * and will release ownership when g_main_context_release()
3103 * is called as many times as g_main_context_acquire().
3105 * You must be the owner of a context before you
3106 * can call g_main_context_prepare(), g_main_context_query(),
3107 * g_main_context_check(), g_main_context_dispatch().
3109 * Return value: %TRUE if the operation succeeded, and
3110 * this thread is now the owner of @context.
3113 g_main_context_acquire (GMainContext *context)
3115 gboolean result = FALSE;
3116 GThread *self = G_THREAD_SELF;
3118 if (context == NULL)
3119 context = g_main_context_default ();
3121 LOCK_CONTEXT (context);
3123 if (!context->owner)
3125 context->owner = self;
3126 g_assert (context->owner_count == 0);
3129 if (context->owner == self)
3131 context->owner_count++;
3135 UNLOCK_CONTEXT (context);
3141 * g_main_context_release:
3142 * @context: a #GMainContext
3144 * Releases ownership of a context previously acquired by this thread
3145 * with g_main_context_acquire(). If the context was acquired multiple
3146 * times, the ownership will be released only when g_main_context_release()
3147 * is called as many times as it was acquired.
3150 g_main_context_release (GMainContext *context)
3152 if (context == NULL)
3153 context = g_main_context_default ();
3155 LOCK_CONTEXT (context);
3157 context->owner_count--;
3158 if (context->owner_count == 0)
3160 context->owner = NULL;
3162 if (context->waiters)
3164 GMainWaiter *waiter = context->waiters->data;
3165 gboolean loop_internal_waiter = (waiter->mutex == &context->mutex);
3166 context->waiters = g_slist_delete_link (context->waiters,
3168 if (!loop_internal_waiter)
3169 g_mutex_lock (waiter->mutex);
3171 g_cond_signal (waiter->cond);
3173 if (!loop_internal_waiter)
3174 g_mutex_unlock (waiter->mutex);
3178 UNLOCK_CONTEXT (context);
3182 * g_main_context_wait:
3183 * @context: a #GMainContext
3184 * @cond: a condition variable
3185 * @mutex: a mutex, currently held
3187 * Tries to become the owner of the specified context,
3188 * as with g_main_context_acquire(). But if another thread
3189 * is the owner, atomically drop @mutex and wait on @cond until
3190 * that owner releases ownership or until @cond is signaled, then
3191 * try again (once) to become the owner.
3193 * Return value: %TRUE if the operation succeeded, and
3194 * this thread is now the owner of @context.
3197 g_main_context_wait (GMainContext *context,
3201 gboolean result = FALSE;
3202 GThread *self = G_THREAD_SELF;
3203 gboolean loop_internal_waiter;
3205 if (context == NULL)
3206 context = g_main_context_default ();
3208 loop_internal_waiter = (mutex == &context->mutex);
3210 if (!loop_internal_waiter)
3211 LOCK_CONTEXT (context);
3213 if (context->owner && context->owner != self)
3218 waiter.mutex = mutex;
3220 context->waiters = g_slist_append (context->waiters, &waiter);
3222 if (!loop_internal_waiter)
3223 UNLOCK_CONTEXT (context);
3224 g_cond_wait (cond, mutex);
3225 if (!loop_internal_waiter)
3226 LOCK_CONTEXT (context);
3228 context->waiters = g_slist_remove (context->waiters, &waiter);
3231 if (!context->owner)
3233 context->owner = self;
3234 g_assert (context->owner_count == 0);
3237 if (context->owner == self)
3239 context->owner_count++;
3243 if (!loop_internal_waiter)
3244 UNLOCK_CONTEXT (context);
3250 * g_main_context_prepare:
3251 * @context: a #GMainContext
3252 * @priority: location to store priority of highest priority
3253 * source already ready.
3255 * Prepares to poll sources within a main loop. The resulting information
3256 * for polling is determined by calling g_main_context_query ().
3258 * Return value: %TRUE if some source is ready to be dispatched
3262 g_main_context_prepare (GMainContext *context,
3267 gint current_priority = G_MAXINT;
3271 if (context == NULL)
3272 context = g_main_context_default ();
3274 LOCK_CONTEXT (context);
3276 context->time_is_fresh = FALSE;
3278 if (context->in_check_or_prepare)
3280 g_warning ("g_main_context_prepare() called recursively from within a source's check() or "
3281 "prepare() member.");
3282 UNLOCK_CONTEXT (context);
3287 /* If recursing, finish up current dispatch, before starting over */
3288 if (context->pending_dispatches)
3291 g_main_dispatch (context, ¤t_time);
3293 UNLOCK_CONTEXT (context);
3298 /* If recursing, clear list of pending dispatches */
3300 for (i = 0; i < context->pending_dispatches->len; i++)
3302 if (context->pending_dispatches->pdata[i])
3303 SOURCE_UNREF ((GSource *)context->pending_dispatches->pdata[i], context);
3305 g_ptr_array_set_size (context->pending_dispatches, 0);
3307 /* Prepare all sources */
3309 context->timeout = -1;
3311 g_source_iter_init (&iter, context, TRUE);
3312 while (g_source_iter_next (&iter, &source))
3314 gint source_timeout = -1;
3316 if (SOURCE_DESTROYED (source) || SOURCE_BLOCKED (source))
3318 if ((n_ready > 0) && (source->priority > current_priority))
3321 if (!(source->flags & G_SOURCE_READY))
3324 gboolean (* prepare) (GSource *source,
3327 prepare = source->source_funcs->prepare;
3331 context->in_check_or_prepare++;
3332 UNLOCK_CONTEXT (context);
3334 result = (* prepare) (source, &source_timeout);
3336 LOCK_CONTEXT (context);
3337 context->in_check_or_prepare--;
3341 source_timeout = -1;
3345 if (result == FALSE && source->priv->ready_time != -1)
3347 if (!context->time_is_fresh)
3349 context->time = g_get_monotonic_time ();
3350 context->time_is_fresh = TRUE;
3353 if (source->priv->ready_time <= context->time)
3362 /* rounding down will lead to spinning, so always round up */
3363 timeout = (source->priv->ready_time - context->time + 999) / 1000;
3365 if (source_timeout < 0 || timeout < source_timeout)
3366 source_timeout = timeout;
3372 GSource *ready_source = source;
3374 while (ready_source)
3376 ready_source->flags |= G_SOURCE_READY;
3377 ready_source = ready_source->priv->parent_source;
3382 if (source->flags & G_SOURCE_READY)
3385 current_priority = source->priority;
3386 context->timeout = 0;
3389 if (source_timeout >= 0)
3391 if (context->timeout < 0)
3392 context->timeout = source_timeout;
3394 context->timeout = MIN (context->timeout, source_timeout);
3397 g_source_iter_clear (&iter);
3399 UNLOCK_CONTEXT (context);
3402 *priority = current_priority;
3404 return (n_ready > 0);
3408 * g_main_context_query:
3409 * @context: a #GMainContext
3410 * @max_priority: maximum priority source to check
3411 * @timeout_: (out): location to store timeout to be used in polling
3412 * @fds: (out caller-allocates) (array length=n_fds): location to
3413 * store #GPollFD records that need to be polled.
3414 * @n_fds: length of @fds.
3416 * Determines information necessary to poll this main loop.
3418 * Return value: the number of records actually stored in @fds,
3419 * or, if more than @n_fds records need to be stored, the number
3420 * of records that need to be stored.
3423 g_main_context_query (GMainContext *context,
3432 LOCK_CONTEXT (context);
3434 pollrec = context->poll_records;
3436 while (pollrec && max_priority >= pollrec->priority)
3438 /* We need to include entries with fd->events == 0 in the array because
3439 * otherwise if the application changes fd->events behind our back and
3440 * makes it non-zero, we'll be out of sync when we check the fds[] array.
3441 * (Changing fd->events after adding an FD wasn't an anticipated use of
3442 * this API, but it occurs in practice.) */
3445 fds[n_poll].fd = pollrec->fd->fd;
3446 /* In direct contradiction to the Unix98 spec, IRIX runs into
3447 * difficulty if you pass in POLLERR, POLLHUP or POLLNVAL
3448 * flags in the events field of the pollfd while it should
3449 * just ignoring them. So we mask them out here.
3451 fds[n_poll].events = pollrec->fd->events & ~(G_IO_ERR|G_IO_HUP|G_IO_NVAL);
3452 fds[n_poll].revents = 0;
3455 pollrec = pollrec->next;
3459 context->poll_changed = FALSE;
3463 *timeout = context->timeout;
3465 context->time_is_fresh = FALSE;
3468 UNLOCK_CONTEXT (context);
3474 * g_main_context_check:
3475 * @context: a #GMainContext
3476 * @max_priority: the maximum numerical priority of sources to check
3477 * @fds: (array length=n_fds): array of #GPollFD's that was passed to
3478 * the last call to g_main_context_query()
3479 * @n_fds: return value of g_main_context_query()
3481 * Passes the results of polling back to the main loop.
3483 * Return value: %TRUE if some sources are ready to be dispatched.
3486 g_main_context_check (GMainContext *context,
3497 LOCK_CONTEXT (context);
3499 if (context->in_check_or_prepare)
3501 g_warning ("g_main_context_check() called recursively from within a source's check() or "
3502 "prepare() member.");
3503 UNLOCK_CONTEXT (context);
3507 if (context->wake_up_rec.revents)
3508 g_wakeup_acknowledge (context->wakeup);
3510 /* If the set of poll file descriptors changed, bail out
3511 * and let the main loop rerun
3513 if (context->poll_changed)
3515 UNLOCK_CONTEXT (context);
3519 pollrec = context->poll_records;
3523 if (pollrec->fd->events)
3524 pollrec->fd->revents = fds[i].revents;
3526 pollrec = pollrec->next;
3530 g_source_iter_init (&iter, context, TRUE);
3531 while (g_source_iter_next (&iter, &source))
3533 if (SOURCE_DESTROYED (source) || SOURCE_BLOCKED (source))
3535 if ((n_ready > 0) && (source->priority > max_priority))
3538 if (!(source->flags & G_SOURCE_READY))
3541 gboolean (* check) (GSource *source);
3543 check = source->source_funcs->check;
3547 /* If the check function is set, call it. */
3548 context->in_check_or_prepare++;
3549 UNLOCK_CONTEXT (context);
3551 result = (* check) (source);
3553 LOCK_CONTEXT (context);
3554 context->in_check_or_prepare--;
3559 if (result == FALSE)
3563 /* If not already explicitly flagged ready by ->check()
3564 * (or if we have no check) then we can still be ready if
3565 * any of our fds poll as ready.
3567 for (tmp_list = source->priv->fds; tmp_list; tmp_list = tmp_list->next)
3569 GPollFD *pollfd = tmp_list->data;
3571 if (pollfd->revents)
3579 if (result == FALSE && source->priv->ready_time != -1)
3581 if (!context->time_is_fresh)
3583 context->time = g_get_monotonic_time ();
3584 context->time_is_fresh = TRUE;
3587 if (source->priv->ready_time <= context->time)
3593 GSource *ready_source = source;
3595 while (ready_source)
3597 ready_source->flags |= G_SOURCE_READY;
3598 ready_source = ready_source->priv->parent_source;
3603 if (source->flags & G_SOURCE_READY)
3605 source->ref_count++;
3606 g_ptr_array_add (context->pending_dispatches, source);
3610 /* never dispatch sources with less priority than the first
3611 * one we choose to dispatch
3613 max_priority = source->priority;
3616 g_source_iter_clear (&iter);
3618 UNLOCK_CONTEXT (context);
3624 * g_main_context_dispatch:
3625 * @context: a #GMainContext
3627 * Dispatches all pending sources.
3630 g_main_context_dispatch (GMainContext *context)
3632 LOCK_CONTEXT (context);
3634 if (context->pending_dispatches->len > 0)
3636 g_main_dispatch (context);
3639 UNLOCK_CONTEXT (context);
3642 /* HOLDS context lock */
3644 g_main_context_iterate (GMainContext *context,
3651 gboolean some_ready;
3652 gint nfds, allocated_nfds;
3653 GPollFD *fds = NULL;
3655 UNLOCK_CONTEXT (context);
3657 if (!g_main_context_acquire (context))
3659 gboolean got_ownership;
3661 LOCK_CONTEXT (context);
3666 got_ownership = g_main_context_wait (context,
3674 LOCK_CONTEXT (context);
3676 if (!context->cached_poll_array)
3678 context->cached_poll_array_size = context->n_poll_records;
3679 context->cached_poll_array = g_new (GPollFD, context->n_poll_records);
3682 allocated_nfds = context->cached_poll_array_size;
3683 fds = context->cached_poll_array;
3685 UNLOCK_CONTEXT (context);
3687 g_main_context_prepare (context, &max_priority);
3689 while ((nfds = g_main_context_query (context, max_priority, &timeout, fds,
3690 allocated_nfds)) > allocated_nfds)
3692 LOCK_CONTEXT (context);
3694 context->cached_poll_array_size = allocated_nfds = nfds;
3695 context->cached_poll_array = fds = g_new (GPollFD, nfds);
3696 UNLOCK_CONTEXT (context);
3702 g_main_context_poll (context, timeout, max_priority, fds, nfds);
3704 some_ready = g_main_context_check (context, max_priority, fds, nfds);
3707 g_main_context_dispatch (context);
3709 g_main_context_release (context);
3711 LOCK_CONTEXT (context);
3717 * g_main_context_pending:
3718 * @context: (allow-none): a #GMainContext (if %NULL, the default context will be used)
3720 * Checks if any sources have pending events for the given context.
3722 * Return value: %TRUE if events are pending.
3725 g_main_context_pending (GMainContext *context)
3730 context = g_main_context_default();
3732 LOCK_CONTEXT (context);
3733 retval = g_main_context_iterate (context, FALSE, FALSE, G_THREAD_SELF);
3734 UNLOCK_CONTEXT (context);
3740 * g_main_context_iteration:
3741 * @context: (allow-none): a #GMainContext (if %NULL, the default context will be used)
3742 * @may_block: whether the call may block.
3744 * Runs a single iteration for the given main loop. This involves
3745 * checking to see if any event sources are ready to be processed,
3746 * then if no events sources are ready and @may_block is %TRUE, waiting
3747 * for a source to become ready, then dispatching the highest priority
3748 * events sources that are ready. Otherwise, if @may_block is %FALSE
3749 * sources are not waited to become ready, only those highest priority
3750 * events sources will be dispatched (if any), that are ready at this
3751 * given moment without further waiting.
3753 * Note that even when @may_block is %TRUE, it is still possible for
3754 * g_main_context_iteration() to return %FALSE, since the wait may
3755 * be interrupted for other reasons than an event source becoming ready.
3757 * Return value: %TRUE if events were dispatched.
3760 g_main_context_iteration (GMainContext *context, gboolean may_block)
3765 context = g_main_context_default();
3767 LOCK_CONTEXT (context);
3768 retval = g_main_context_iterate (context, may_block, TRUE, G_THREAD_SELF);
3769 UNLOCK_CONTEXT (context);
3776 * @context: (allow-none): a #GMainContext (if %NULL, the default context will be used).
3777 * @is_running: set to %TRUE to indicate that the loop is running. This
3778 * is not very important since calling g_main_loop_run() will set this to
3781 * Creates a new #GMainLoop structure.
3783 * Return value: a new #GMainLoop.
3786 g_main_loop_new (GMainContext *context,
3787 gboolean is_running)
3792 context = g_main_context_default();
3794 g_main_context_ref (context);
3796 loop = g_new0 (GMainLoop, 1);
3797 loop->context = context;
3798 loop->is_running = is_running != FALSE;
3799 loop->ref_count = 1;
3806 * @loop: a #GMainLoop
3808 * Increases the reference count on a #GMainLoop object by one.
3810 * Return value: @loop
3813 g_main_loop_ref (GMainLoop *loop)
3815 g_return_val_if_fail (loop != NULL, NULL);
3816 g_return_val_if_fail (g_atomic_int_get (&loop->ref_count) > 0, NULL);
3818 g_atomic_int_inc (&loop->ref_count);
3824 * g_main_loop_unref:
3825 * @loop: a #GMainLoop
3827 * Decreases the reference count on a #GMainLoop object by one. If
3828 * the result is zero, free the loop and free all associated memory.
3831 g_main_loop_unref (GMainLoop *loop)
3833 g_return_if_fail (loop != NULL);
3834 g_return_if_fail (g_atomic_int_get (&loop->ref_count) > 0);
3836 if (!g_atomic_int_dec_and_test (&loop->ref_count))
3839 g_main_context_unref (loop->context);
3845 * @loop: a #GMainLoop
3847 * Runs a main loop until g_main_loop_quit() is called on the loop.
3848 * If this is called for the thread of the loop's #GMainContext,
3849 * it will process events from the loop, otherwise it will
3853 g_main_loop_run (GMainLoop *loop)
3855 GThread *self = G_THREAD_SELF;
3857 g_return_if_fail (loop != NULL);
3858 g_return_if_fail (g_atomic_int_get (&loop->ref_count) > 0);
3860 if (!g_main_context_acquire (loop->context))
3862 gboolean got_ownership = FALSE;
3864 /* Another thread owns this context */
3865 LOCK_CONTEXT (loop->context);
3867 g_atomic_int_inc (&loop->ref_count);
3869 if (!loop->is_running)
3870 loop->is_running = TRUE;
3872 while (loop->is_running && !got_ownership)
3873 got_ownership = g_main_context_wait (loop->context,
3874 &loop->context->cond,
3875 &loop->context->mutex);
3877 if (!loop->is_running)
3879 UNLOCK_CONTEXT (loop->context);
3881 g_main_context_release (loop->context);
3882 g_main_loop_unref (loop);
3886 g_assert (got_ownership);
3889 LOCK_CONTEXT (loop->context);
3891 if (loop->context->in_check_or_prepare)
3893 g_warning ("g_main_loop_run(): called recursively from within a source's "
3894 "check() or prepare() member, iteration not possible.");
3898 g_atomic_int_inc (&loop->ref_count);
3899 loop->is_running = TRUE;
3900 while (loop->is_running)
3901 g_main_context_iterate (loop->context, TRUE, TRUE, self);
3903 UNLOCK_CONTEXT (loop->context);
3905 g_main_context_release (loop->context);
3907 g_main_loop_unref (loop);
3912 * @loop: a #GMainLoop
3914 * Stops a #GMainLoop from running. Any calls to g_main_loop_run()
3915 * for the loop will return.
3917 * Note that sources that have already been dispatched when
3918 * g_main_loop_quit() is called will still be executed.
3921 g_main_loop_quit (GMainLoop *loop)
3923 g_return_if_fail (loop != NULL);
3924 g_return_if_fail (g_atomic_int_get (&loop->ref_count) > 0);
3926 LOCK_CONTEXT (loop->context);
3927 loop->is_running = FALSE;
3928 g_wakeup_signal (loop->context->wakeup);
3930 g_cond_broadcast (&loop->context->cond);
3932 UNLOCK_CONTEXT (loop->context);
3936 * g_main_loop_is_running:
3937 * @loop: a #GMainLoop.
3939 * Checks to see if the main loop is currently being run via g_main_loop_run().
3941 * Return value: %TRUE if the mainloop is currently being run.
3944 g_main_loop_is_running (GMainLoop *loop)
3946 g_return_val_if_fail (loop != NULL, FALSE);
3947 g_return_val_if_fail (g_atomic_int_get (&loop->ref_count) > 0, FALSE);
3949 return loop->is_running;
3953 * g_main_loop_get_context:
3954 * @loop: a #GMainLoop.
3956 * Returns the #GMainContext of @loop.
3958 * Return value: (transfer none): the #GMainContext of @loop
3961 g_main_loop_get_context (GMainLoop *loop)
3963 g_return_val_if_fail (loop != NULL, NULL);
3964 g_return_val_if_fail (g_atomic_int_get (&loop->ref_count) > 0, NULL);
3966 return loop->context;
3969 /* HOLDS: context's lock */
3971 g_main_context_poll (GMainContext *context,
3977 #ifdef G_MAIN_POLL_DEBUG
3983 GPollFunc poll_func;
3985 if (n_fds || timeout != 0)
3987 #ifdef G_MAIN_POLL_DEBUG
3988 if (_g_main_poll_debug)
3990 g_print ("polling context=%p n=%d timeout=%d\n",
3991 context, n_fds, timeout);
3992 poll_timer = g_timer_new ();
3996 LOCK_CONTEXT (context);
3998 poll_func = context->poll_func;
4000 UNLOCK_CONTEXT (context);
4001 if ((*poll_func) (fds, n_fds, timeout) < 0 && errno != EINTR)
4004 g_warning ("poll(2) failed due to: %s.",
4005 g_strerror (errno));
4007 /* If g_poll () returns -1, it has already called g_warning() */
4011 #ifdef G_MAIN_POLL_DEBUG
4012 if (_g_main_poll_debug)
4014 LOCK_CONTEXT (context);
4016 g_print ("g_main_poll(%d) timeout: %d - elapsed %12.10f seconds",
4019 g_timer_elapsed (poll_timer, NULL));
4020 g_timer_destroy (poll_timer);
4021 pollrec = context->poll_records;
4023 while (pollrec != NULL)
4028 if (fds[i].fd == pollrec->fd->fd &&
4029 pollrec->fd->events &&
4032 g_print (" [" G_POLLFD_FORMAT " :", fds[i].fd);
4033 if (fds[i].revents & G_IO_IN)
4035 if (fds[i].revents & G_IO_OUT)
4037 if (fds[i].revents & G_IO_PRI)
4039 if (fds[i].revents & G_IO_ERR)
4041 if (fds[i].revents & G_IO_HUP)
4043 if (fds[i].revents & G_IO_NVAL)
4049 pollrec = pollrec->next;
4053 UNLOCK_CONTEXT (context);
4056 } /* if (n_fds || timeout != 0) */
4060 * g_main_context_add_poll:
4061 * @context: (allow-none): a #GMainContext (or %NULL for the default context)
4062 * @fd: a #GPollFD structure holding information about a file
4063 * descriptor to watch.
4064 * @priority: the priority for this file descriptor which should be
4065 * the same as the priority used for g_source_attach() to ensure that the
4066 * file descriptor is polled whenever the results may be needed.
4068 * Adds a file descriptor to the set of file descriptors polled for
4069 * this context. This will very seldom be used directly. Instead
4070 * a typical event source will use g_source_add_unix_fd() instead.
4073 g_main_context_add_poll (GMainContext *context,
4078 context = g_main_context_default ();
4080 g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
4081 g_return_if_fail (fd);
4083 LOCK_CONTEXT (context);
4084 g_main_context_add_poll_unlocked (context, priority, fd);
4085 UNLOCK_CONTEXT (context);
4088 /* HOLDS: main_loop_lock */
4090 g_main_context_add_poll_unlocked (GMainContext *context,
4094 GPollRec *prevrec, *nextrec;
4095 GPollRec *newrec = g_slice_new (GPollRec);
4097 /* This file descriptor may be checked before we ever poll */
4100 newrec->priority = priority;
4102 prevrec = context->poll_records_tail;
4104 while (prevrec && priority < prevrec->priority)
4107 prevrec = prevrec->prev;
4111 prevrec->next = newrec;
4113 context->poll_records = newrec;
4115 newrec->prev = prevrec;
4116 newrec->next = nextrec;
4119 nextrec->prev = newrec;
4121 context->poll_records_tail = newrec;
4123 context->n_poll_records++;
4125 context->poll_changed = TRUE;
4127 /* Now wake up the main loop if it is waiting in the poll() */
4128 g_wakeup_signal (context->wakeup);
4132 * g_main_context_remove_poll:
4133 * @context:a #GMainContext
4134 * @fd: a #GPollFD descriptor previously added with g_main_context_add_poll()
4136 * Removes file descriptor from the set of file descriptors to be
4137 * polled for a particular context.
4140 g_main_context_remove_poll (GMainContext *context,
4144 context = g_main_context_default ();
4146 g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
4147 g_return_if_fail (fd);
4149 LOCK_CONTEXT (context);
4150 g_main_context_remove_poll_unlocked (context, fd);
4151 UNLOCK_CONTEXT (context);
4155 g_main_context_remove_poll_unlocked (GMainContext *context,
4158 GPollRec *pollrec, *prevrec, *nextrec;
4161 pollrec = context->poll_records;
4165 nextrec = pollrec->next;
4166 if (pollrec->fd == fd)
4168 if (prevrec != NULL)
4169 prevrec->next = nextrec;
4171 context->poll_records = nextrec;
4173 if (nextrec != NULL)
4174 nextrec->prev = prevrec;
4176 context->poll_records_tail = prevrec;
4178 g_slice_free (GPollRec, pollrec);
4180 context->n_poll_records--;
4187 context->poll_changed = TRUE;
4189 /* Now wake up the main loop if it is waiting in the poll() */
4190 g_wakeup_signal (context->wakeup);
4194 * g_source_get_current_time:
4195 * @source: a #GSource
4196 * @timeval: #GTimeVal structure in which to store current time.
4198 * This function ignores @source and is otherwise the same as
4199 * g_get_current_time().
4201 * Deprecated: 2.28: use g_source_get_time() instead
4204 g_source_get_current_time (GSource *source,
4207 g_get_current_time (timeval);
4211 * g_source_get_time:
4212 * @source: a #GSource
4214 * Gets the time to be used when checking this source. The advantage of
4215 * calling this function over calling g_get_monotonic_time() directly is
4216 * that when checking multiple sources, GLib can cache a single value
4217 * instead of having to repeatedly get the system monotonic time.
4219 * The time here is the system monotonic time, if available, or some
4220 * other reasonable alternative otherwise. See g_get_monotonic_time().
4222 * Returns: the monotonic time in microseconds
4227 g_source_get_time (GSource *source)
4229 GMainContext *context;
4232 g_return_val_if_fail (source->context != NULL, 0);
4234 context = source->context;
4236 LOCK_CONTEXT (context);
4238 if (!context->time_is_fresh)
4240 context->time = g_get_monotonic_time ();
4241 context->time_is_fresh = TRUE;
4244 result = context->time;
4246 UNLOCK_CONTEXT (context);
4252 * g_main_context_set_poll_func:
4253 * @context: a #GMainContext
4254 * @func: the function to call to poll all file descriptors
4256 * Sets the function to use to handle polling of file descriptors. It
4257 * will be used instead of the poll() system call
4258 * (or GLib's replacement function, which is used where
4259 * poll() isn't available).
4261 * This function could possibly be used to integrate the GLib event
4262 * loop with an external event loop.
4265 g_main_context_set_poll_func (GMainContext *context,
4269 context = g_main_context_default ();
4271 g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
4273 LOCK_CONTEXT (context);
4276 context->poll_func = func;
4278 context->poll_func = g_poll;
4280 UNLOCK_CONTEXT (context);
4284 * g_main_context_get_poll_func:
4285 * @context: a #GMainContext
4287 * Gets the poll function set by g_main_context_set_poll_func().
4289 * Return value: the poll function
4292 g_main_context_get_poll_func (GMainContext *context)
4297 context = g_main_context_default ();
4299 g_return_val_if_fail (g_atomic_int_get (&context->ref_count) > 0, NULL);
4301 LOCK_CONTEXT (context);
4302 result = context->poll_func;
4303 UNLOCK_CONTEXT (context);
4309 * g_main_context_wakeup:
4310 * @context: a #GMainContext
4312 * If @context is currently blocking in g_main_context_iteration()
4313 * waiting for a source to become ready, cause it to stop blocking
4314 * and return. Otherwise, cause the next invocation of
4315 * g_main_context_iteration() to return without blocking.
4317 * This API is useful for low-level control over #GMainContext; for
4318 * example, integrating it with main loop implementations such as
4321 * Another related use for this function is when implementing a main
4322 * loop with a termination condition, computed from multiple threads:
4324 * |[<!-- language="C" -->
4325 * #define NUM_TASKS 10
4326 * static volatile gint tasks_remaining = NUM_TASKS;
4329 * while (g_atomic_int_get (&tasks_remaining) != 0)
4330 * g_main_context_iteration (NULL, TRUE);
4334 * |[<!-- language="C" -->
4337 * if (g_atomic_int_dec_and_test (&tasks_remaining))
4338 * g_main_context_wakeup (NULL);
4342 g_main_context_wakeup (GMainContext *context)
4345 context = g_main_context_default ();
4347 g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
4349 g_wakeup_signal (context->wakeup);
4353 * g_main_context_is_owner:
4354 * @context: a #GMainContext
4356 * Determines whether this thread holds the (recursive)
4357 * ownership of this #GMainContext. This is useful to
4358 * know before waiting on another thread that may be
4359 * blocking to get ownership of @context.
4361 * Returns: %TRUE if current thread is owner of @context.
4366 g_main_context_is_owner (GMainContext *context)
4371 context = g_main_context_default ();
4373 LOCK_CONTEXT (context);
4374 is_owner = context->owner == G_THREAD_SELF;
4375 UNLOCK_CONTEXT (context);
4383 g_timeout_set_expiration (GTimeoutSource *timeout_source,
4384 gint64 current_time)
4388 expiration = current_time + (guint64) timeout_source->interval * 1000;
4390 if (timeout_source->seconds)
4393 static gint timer_perturb = -1;
4395 if (timer_perturb == -1)
4398 * we want a per machine/session unique 'random' value; try the dbus
4399 * address first, that has a UUID in it. If there is no dbus, use the
4400 * hostname for hashing.
4402 const char *session_bus_address = g_getenv ("DBUS_SESSION_BUS_ADDRESS");
4403 if (!session_bus_address)
4404 session_bus_address = g_getenv ("HOSTNAME");
4405 if (session_bus_address)
4406 timer_perturb = ABS ((gint) g_str_hash (session_bus_address)) % 1000000;
4411 /* We want the microseconds part of the timeout to land on the
4412 * 'timer_perturb' mark, but we need to make sure we don't try to
4413 * set the timeout in the past. We do this by ensuring that we
4414 * always only *increase* the expiration time by adding a full
4415 * second in the case that the microsecond portion decreases.
4417 expiration -= timer_perturb;
4419 remainder = expiration % 1000000;
4420 if (remainder >= 1000000/4)
4421 expiration += 1000000;
4423 expiration -= remainder;
4424 expiration += timer_perturb;
4427 g_source_set_ready_time ((GSource *) timeout_source, expiration);
4431 g_timeout_dispatch (GSource *source,
4432 GSourceFunc callback,
4435 GTimeoutSource *timeout_source = (GTimeoutSource *)source;
4440 g_warning ("Timeout source dispatched without callback\n"
4441 "You must call g_source_set_callback().");
4445 again = callback (user_data);
4448 g_timeout_set_expiration (timeout_source, g_source_get_time (source));
4454 * g_timeout_source_new:
4455 * @interval: the timeout interval in milliseconds.
4457 * Creates a new timeout source.
4459 * The source will not initially be associated with any #GMainContext
4460 * and must be added to one with g_source_attach() before it will be
4463 * The interval given is in terms of monotonic time, not wall clock
4464 * time. See g_get_monotonic_time().
4466 * Return value: the newly-created timeout source
4469 g_timeout_source_new (guint interval)
4471 GSource *source = g_source_new (&g_timeout_funcs, sizeof (GTimeoutSource));
4472 GTimeoutSource *timeout_source = (GTimeoutSource *)source;
4474 timeout_source->interval = interval;
4475 g_timeout_set_expiration (timeout_source, g_get_monotonic_time ());
4481 * g_timeout_source_new_seconds:
4482 * @interval: the timeout interval in seconds
4484 * Creates a new timeout source.
4486 * The source will not initially be associated with any #GMainContext
4487 * and must be added to one with g_source_attach() before it will be
4490 * The scheduling granularity/accuracy of this timeout source will be
4493 * The interval given in terms of monotonic time, not wall clock time.
4494 * See g_get_monotonic_time().
4496 * Return value: the newly-created timeout source
4501 g_timeout_source_new_seconds (guint interval)
4503 GSource *source = g_source_new (&g_timeout_funcs, sizeof (GTimeoutSource));
4504 GTimeoutSource *timeout_source = (GTimeoutSource *)source;
4506 timeout_source->interval = 1000 * interval;
4507 timeout_source->seconds = TRUE;
4509 g_timeout_set_expiration (timeout_source, g_get_monotonic_time ());
4516 * g_timeout_add_full:
4517 * @priority: the priority of the timeout source. Typically this will be in
4518 * the range between #G_PRIORITY_DEFAULT and #G_PRIORITY_HIGH.
4519 * @interval: the time between calls to the function, in milliseconds
4520 * (1/1000ths of a second)
4521 * @function: function to call
4522 * @data: data to pass to @function
4523 * @notify: (allow-none): function to call when the timeout is removed, or %NULL
4525 * Sets a function to be called at regular intervals, with the given
4526 * priority. The function is called repeatedly until it returns
4527 * %FALSE, at which point the timeout is automatically destroyed and
4528 * the function will not be called again. The @notify function is
4529 * called when the timeout is destroyed. The first call to the
4530 * function will be at the end of the first @interval.
4532 * Note that timeout functions may be delayed, due to the processing of other
4533 * event sources. Thus they should not be relied on for precise timing.
4534 * After each call to the timeout function, the time of the next
4535 * timeout is recalculated based on the current time and the given interval
4536 * (it does not try to 'catch up' time lost in delays).
4538 * This internally creates a main loop source using g_timeout_source_new()
4539 * and attaches it to the main loop context using g_source_attach(). You can
4540 * do these steps manually if you need greater control.
4542 * The interval given in terms of monotonic time, not wall clock time.
4543 * See g_get_monotonic_time().
4545 * Return value: the ID (greater than 0) of the event source.
4546 * Rename to: g_timeout_add
4549 g_timeout_add_full (gint priority,
4551 GSourceFunc function,
4553 GDestroyNotify notify)
4558 g_return_val_if_fail (function != NULL, 0);
4560 source = g_timeout_source_new (interval);
4562 if (priority != G_PRIORITY_DEFAULT)
4563 g_source_set_priority (source, priority);
4565 g_source_set_callback (source, function, data, notify);
4566 id = g_source_attach (source, NULL);
4567 g_source_unref (source);
4574 * @interval: the time between calls to the function, in milliseconds
4575 * (1/1000ths of a second)
4576 * @function: function to call
4577 * @data: data to pass to @function
4579 * Sets a function to be called at regular intervals, with the default
4580 * priority, #G_PRIORITY_DEFAULT. The function is called repeatedly
4581 * until it returns %FALSE, at which point the timeout is automatically
4582 * destroyed and the function will not be called again. The first call
4583 * to the function will be at the end of the first @interval.
4585 * Note that timeout functions may be delayed, due to the processing of other
4586 * event sources. Thus they should not be relied on for precise timing.
4587 * After each call to the timeout function, the time of the next
4588 * timeout is recalculated based on the current time and the given interval
4589 * (it does not try to 'catch up' time lost in delays).
4591 * If you want to have a timer in the "seconds" range and do not care
4592 * about the exact time of the first call of the timer, use the
4593 * g_timeout_add_seconds() function; this function allows for more
4594 * optimizations and more efficient system power usage.
4596 * This internally creates a main loop source using g_timeout_source_new()
4597 * and attaches it to the main loop context using g_source_attach(). You can
4598 * do these steps manually if you need greater control.
4600 * The interval given is in terms of monotonic time, not wall clock
4601 * time. See g_get_monotonic_time().
4603 * Return value: the ID (greater than 0) of the event source.
4606 g_timeout_add (guint32 interval,
4607 GSourceFunc function,
4610 return g_timeout_add_full (G_PRIORITY_DEFAULT,
4611 interval, function, data, NULL);
4615 * g_timeout_add_seconds_full:
4616 * @priority: the priority of the timeout source. Typically this will be in
4617 * the range between #G_PRIORITY_DEFAULT and #G_PRIORITY_HIGH.
4618 * @interval: the time between calls to the function, in seconds
4619 * @function: function to call
4620 * @data: data to pass to @function
4621 * @notify: (allow-none): function to call when the timeout is removed, or %NULL
4623 * Sets a function to be called at regular intervals, with @priority.
4624 * The function is called repeatedly until it returns %FALSE, at which
4625 * point the timeout is automatically destroyed and the function will
4626 * not be called again.
4628 * Unlike g_timeout_add(), this function operates at whole second granularity.
4629 * The initial starting point of the timer is determined by the implementation
4630 * and the implementation is expected to group multiple timers together so that
4631 * they fire all at the same time.
4632 * To allow this grouping, the @interval to the first timer is rounded
4633 * and can deviate up to one second from the specified interval.
4634 * Subsequent timer iterations will generally run at the specified interval.
4636 * Note that timeout functions may be delayed, due to the processing of other
4637 * event sources. Thus they should not be relied on for precise timing.
4638 * After each call to the timeout function, the time of the next
4639 * timeout is recalculated based on the current time and the given @interval
4641 * If you want timing more precise than whole seconds, use g_timeout_add()
4644 * The grouping of timers to fire at the same time results in a more power
4645 * and CPU efficient behavior so if your timer is in multiples of seconds
4646 * and you don't require the first timer exactly one second from now, the
4647 * use of g_timeout_add_seconds() is preferred over g_timeout_add().
4649 * This internally creates a main loop source using
4650 * g_timeout_source_new_seconds() and attaches it to the main loop context
4651 * using g_source_attach(). You can do these steps manually if you need
4654 * The interval given is in terms of monotonic time, not wall clock
4655 * time. See g_get_monotonic_time().
4657 * Return value: the ID (greater than 0) of the event source.
4659 * Rename to: g_timeout_add_seconds
4663 g_timeout_add_seconds_full (gint priority,
4665 GSourceFunc function,
4667 GDestroyNotify notify)
4672 g_return_val_if_fail (function != NULL, 0);
4674 source = g_timeout_source_new_seconds (interval);
4676 if (priority != G_PRIORITY_DEFAULT)
4677 g_source_set_priority (source, priority);
4679 g_source_set_callback (source, function, data, notify);
4680 id = g_source_attach (source, NULL);
4681 g_source_unref (source);
4687 * g_timeout_add_seconds:
4688 * @interval: the time between calls to the function, in seconds
4689 * @function: function to call
4690 * @data: data to pass to @function
4692 * Sets a function to be called at regular intervals with the default
4693 * priority, #G_PRIORITY_DEFAULT. The function is called repeatedly until
4694 * it returns %FALSE, at which point the timeout is automatically destroyed
4695 * and the function will not be called again.
4697 * This internally creates a main loop source using
4698 * g_timeout_source_new_seconds() and attaches it to the main loop context
4699 * using g_source_attach(). You can do these steps manually if you need
4700 * greater control. Also see g_timeout_add_seconds_full().
4702 * Note that the first call of the timer may not be precise for timeouts
4703 * of one second. If you need finer precision and have such a timeout,
4704 * you may want to use g_timeout_add() instead.
4706 * The interval given is in terms of monotonic time, not wall clock
4707 * time. See g_get_monotonic_time().
4709 * Return value: the ID (greater than 0) of the event source.
4714 g_timeout_add_seconds (guint interval,
4715 GSourceFunc function,
4718 g_return_val_if_fail (function != NULL, 0);
4720 return g_timeout_add_seconds_full (G_PRIORITY_DEFAULT, interval, function, data, NULL);
4723 /* Child watch functions */
4728 g_child_watch_prepare (GSource *source,
4736 g_child_watch_check (GSource *source)
4738 GChildWatchSource *child_watch_source;
4739 gboolean child_exited;
4741 child_watch_source = (GChildWatchSource *) source;
4743 child_exited = child_watch_source->poll.revents & G_IO_IN;
4750 * Note: We do _not_ check for the special value of STILL_ACTIVE
4751 * since we know that the process has exited and doing so runs into
4752 * problems if the child process "happens to return STILL_ACTIVE(259)"
4753 * as Microsoft's Platform SDK puts it.
4755 if (!GetExitCodeProcess (child_watch_source->pid, &child_status))
4757 gchar *emsg = g_win32_error_message (GetLastError ());
4758 g_warning (G_STRLOC ": GetExitCodeProcess() failed: %s", emsg);
4761 child_watch_source->child_status = -1;
4764 child_watch_source->child_status = child_status;
4767 return child_exited;
4771 g_child_watch_finalize (GSource *source)
4775 #else /* G_OS_WIN32 */
4778 wake_source (GSource *source)
4780 GMainContext *context;
4782 /* This should be thread-safe:
4784 * - if the source is currently being added to a context, that
4785 * context will be woken up anyway
4787 * - if the source is currently being destroyed, we simply need not
4790 * - the memory for the source will remain valid until after the
4791 * source finalize function was called (which would remove the
4792 * source from the global list which we are currently holding the
4795 * - the GMainContext will either be NULL or point to a live
4798 * - the GMainContext will remain valid since we hold the
4799 * main_context_list lock
4801 * Since we are holding a lot of locks here, don't try to enter any
4802 * more GMainContext functions for fear of dealock -- just hit the
4803 * GWakeup and run. Even if that's safe now, it could easily become
4804 * unsafe with some very minor changes in the future, and signal
4805 * handling is not the most well-tested codepath.
4807 G_LOCK(main_context_list);
4808 context = source->context;
4810 g_wakeup_signal (context->wakeup);
4811 G_UNLOCK(main_context_list);
4815 dispatch_unix_signals_unlocked (void)
4817 gboolean pending[NSIG];
4821 /* clear this first incase another one arrives while we're processing */
4822 any_unix_signal_pending = FALSE;
4824 /* We atomically test/clear the bit from the global array in case
4825 * other signals arrive while we are dispatching.
4827 * We then can safely use our own array below without worrying about
4830 for (i = 0; i < NSIG; i++)
4832 /* Be very careful with (the volatile) unix_signal_pending.
4834 * We must ensure that it's not possible that we clear it without
4835 * handling the signal. We therefore must ensure that our pending
4836 * array has a field set (ie: we will do something about the
4837 * signal) before we clear the item in unix_signal_pending.
4839 * Note specifically: we must check _our_ array.
4841 pending[i] = unix_signal_pending[i];
4843 unix_signal_pending[i] = FALSE;
4846 /* handle GChildWatchSource instances */
4847 if (pending[SIGCHLD])
4849 /* The only way we can do this is to scan all of the children.
4851 * The docs promise that we will not reap children that we are not
4852 * explicitly watching, so that ties our hands from calling
4853 * waitpid(-1). We also can't use siginfo's si_pid field since if
4854 * multiple SIGCHLD arrive at the same time, one of them can be
4855 * dropped (since a given UNIX signal can only be pending once).
4857 for (node = unix_child_watches; node; node = node->next)
4859 GChildWatchSource *source = node->data;
4861 if (!source->child_exited)
4866 pid = waitpid (source->pid, &source->child_status, WNOHANG);
4869 source->child_exited = TRUE;
4870 wake_source ((GSource *) source);
4872 else if (pid == -1 && errno == ECHILD)
4874 g_warning ("GChildWatchSource: Exit status of a child process was requested but ECHILD was received by waitpid(). Most likely the process is ignoring SIGCHLD, or some other thread is invoking waitpid() with a nonpositive first argument; either behavior can break applications that use g_child_watch_add()/g_spawn_sync() either directly or indirectly.");
4875 source->child_exited = TRUE;
4876 source->child_status = 0;
4877 wake_source ((GSource *) source);
4880 while (pid == -1 && errno == EINTR);
4885 /* handle GUnixSignalWatchSource instances */
4886 for (node = unix_signal_watches; node; node = node->next)
4888 GUnixSignalWatchSource *source = node->data;
4890 if (!source->pending)
4892 if (pending[source->signum])
4894 source->pending = TRUE;
4896 wake_source ((GSource *) source);
4904 dispatch_unix_signals (void)
4906 G_LOCK(unix_signal_lock);
4907 dispatch_unix_signals_unlocked ();
4908 G_UNLOCK(unix_signal_lock);
4912 g_child_watch_prepare (GSource *source,
4915 GChildWatchSource *child_watch_source;
4917 child_watch_source = (GChildWatchSource *) source;
4919 return child_watch_source->child_exited;
4923 g_child_watch_check (GSource *source)
4925 GChildWatchSource *child_watch_source;
4927 child_watch_source = (GChildWatchSource *) source;
4929 return child_watch_source->child_exited;
4933 g_unix_signal_watch_prepare (GSource *source,
4936 GUnixSignalWatchSource *unix_signal_source;
4938 unix_signal_source = (GUnixSignalWatchSource *) source;
4940 return unix_signal_source->pending;
4944 g_unix_signal_watch_check (GSource *source)
4946 GUnixSignalWatchSource *unix_signal_source;
4948 unix_signal_source = (GUnixSignalWatchSource *) source;
4950 return unix_signal_source->pending;
4954 g_unix_signal_watch_dispatch (GSource *source,
4955 GSourceFunc callback,
4958 GUnixSignalWatchSource *unix_signal_source;
4961 unix_signal_source = (GUnixSignalWatchSource *) source;
4965 g_warning ("Unix signal source dispatched without callback\n"
4966 "You must call g_source_set_callback().");
4970 again = (callback) (user_data);
4972 unix_signal_source->pending = FALSE;
4978 ref_unix_signal_handler_unlocked (int signum)
4980 /* Ensure we have the worker context */
4981 g_get_worker_context ();
4982 unix_signal_refcount[signum]++;
4983 if (unix_signal_refcount[signum] == 1)
4985 struct sigaction action;
4986 action.sa_handler = g_unix_signal_handler;
4987 sigemptyset (&action.sa_mask);
4989 action.sa_flags = SA_RESTART | SA_NOCLDSTOP;
4991 action.sa_flags = SA_NOCLDSTOP;
4993 sigaction (signum, &action, NULL);
4998 unref_unix_signal_handler_unlocked (int signum)
5000 unix_signal_refcount[signum]--;
5001 if (unix_signal_refcount[signum] == 0)
5003 struct sigaction action;
5004 memset (&action, 0, sizeof (action));
5005 action.sa_handler = SIG_DFL;
5006 sigemptyset (&action.sa_mask);
5007 sigaction (signum, &action, NULL);
5012 _g_main_create_unix_signal_watch (int signum)
5015 GUnixSignalWatchSource *unix_signal_source;
5017 source = g_source_new (&g_unix_signal_funcs, sizeof (GUnixSignalWatchSource));
5018 unix_signal_source = (GUnixSignalWatchSource *) source;
5020 unix_signal_source->signum = signum;
5021 unix_signal_source->pending = FALSE;
5023 G_LOCK (unix_signal_lock);
5024 ref_unix_signal_handler_unlocked (signum);
5025 unix_signal_watches = g_slist_prepend (unix_signal_watches, unix_signal_source);
5026 dispatch_unix_signals_unlocked ();
5027 G_UNLOCK (unix_signal_lock);
5033 g_unix_signal_watch_finalize (GSource *source)
5035 GUnixSignalWatchSource *unix_signal_source;
5037 unix_signal_source = (GUnixSignalWatchSource *) source;
5039 G_LOCK (unix_signal_lock);
5040 unref_unix_signal_handler_unlocked (unix_signal_source->signum);
5041 unix_signal_watches = g_slist_remove (unix_signal_watches, source);
5042 G_UNLOCK (unix_signal_lock);
5046 g_child_watch_finalize (GSource *source)
5048 G_LOCK (unix_signal_lock);
5049 unix_child_watches = g_slist_remove (unix_child_watches, source);
5050 unref_unix_signal_handler_unlocked (SIGCHLD);
5051 G_UNLOCK (unix_signal_lock);
5054 #endif /* G_OS_WIN32 */
5057 g_child_watch_dispatch (GSource *source,
5058 GSourceFunc callback,
5061 GChildWatchSource *child_watch_source;
5062 GChildWatchFunc child_watch_callback = (GChildWatchFunc) callback;
5064 child_watch_source = (GChildWatchSource *) source;
5068 g_warning ("Child watch source dispatched without callback\n"
5069 "You must call g_source_set_callback().");
5073 (child_watch_callback) (child_watch_source->pid, child_watch_source->child_status, user_data);
5075 /* We never keep a child watch source around as the child is gone */
5082 g_unix_signal_handler (int signum)
5084 unix_signal_pending[signum] = TRUE;
5085 any_unix_signal_pending = TRUE;
5087 g_wakeup_signal (glib_worker_context->wakeup);
5090 #endif /* !G_OS_WIN32 */
5093 * g_child_watch_source_new:
5094 * @pid: process to watch. On POSIX the pid of a child process. On
5095 * Windows a handle for a process (which doesn't have to be a child).
5097 * Creates a new child_watch source.
5099 * The source will not initially be associated with any #GMainContext
5100 * and must be added to one with g_source_attach() before it will be
5103 * Note that child watch sources can only be used in conjunction with
5104 * <literal>g_spawn...</literal> when the %G_SPAWN_DO_NOT_REAP_CHILD
5107 * Note that on platforms where #GPid must be explicitly closed
5108 * (see g_spawn_close_pid()) @pid must not be closed while the
5109 * source is still active. Typically, you will want to call
5110 * g_spawn_close_pid() in the callback function for the source.
5112 * Note further that using g_child_watch_source_new() is not
5113 * compatible with calling <literal>waitpid</literal> with a
5114 * nonpositive first argument in the application. Calling waitpid()
5115 * for individual pids will still work fine.
5117 * Return value: the newly-created child watch source
5122 g_child_watch_source_new (GPid pid)
5124 GSource *source = g_source_new (&g_child_watch_funcs, sizeof (GChildWatchSource));
5125 GChildWatchSource *child_watch_source = (GChildWatchSource *)source;
5127 child_watch_source->pid = pid;
5130 child_watch_source->poll.fd = (gintptr) pid;
5131 child_watch_source->poll.events = G_IO_IN;
5133 g_source_add_poll (source, &child_watch_source->poll);
5134 #else /* G_OS_WIN32 */
5135 G_LOCK (unix_signal_lock);
5136 ref_unix_signal_handler_unlocked (SIGCHLD);
5137 unix_child_watches = g_slist_prepend (unix_child_watches, child_watch_source);
5138 if (waitpid (pid, &child_watch_source->child_status, WNOHANG) > 0)
5139 child_watch_source->child_exited = TRUE;
5140 G_UNLOCK (unix_signal_lock);
5141 #endif /* G_OS_WIN32 */
5147 * g_child_watch_add_full:
5148 * @priority: the priority of the idle source. Typically this will be in the
5149 * range between #G_PRIORITY_DEFAULT_IDLE and #G_PRIORITY_HIGH_IDLE.
5150 * @pid: process to watch. On POSIX the pid of a child process. On
5151 * Windows a handle for a process (which doesn't have to be a child).
5152 * @function: function to call
5153 * @data: data to pass to @function
5154 * @notify: (allow-none): function to call when the idle is removed, or %NULL
5156 * Sets a function to be called when the child indicated by @pid
5157 * exits, at the priority @priority.
5159 * If you obtain @pid from g_spawn_async() or g_spawn_async_with_pipes()
5160 * you will need to pass #G_SPAWN_DO_NOT_REAP_CHILD as flag to
5161 * the spawn function for the child watching to work.
5163 * In many programs, you will want to call g_spawn_check_exit_status()
5164 * in the callback to determine whether or not the child exited
5167 * Also, note that on platforms where #GPid must be explicitly closed
5168 * (see g_spawn_close_pid()) @pid must not be closed while the source
5169 * is still active. Typically, you should invoke g_spawn_close_pid()
5170 * in the callback function for the source.
5172 * GLib supports only a single callback per process id.
5174 * This internally creates a main loop source using
5175 * g_child_watch_source_new() and attaches it to the main loop context
5176 * using g_source_attach(). You can do these steps manually if you
5177 * need greater control.
5179 * Return value: the ID (greater than 0) of the event source.
5181 * Rename to: g_child_watch_add
5185 g_child_watch_add_full (gint priority,
5187 GChildWatchFunc function,
5189 GDestroyNotify notify)
5194 g_return_val_if_fail (function != NULL, 0);
5196 source = g_child_watch_source_new (pid);
5198 if (priority != G_PRIORITY_DEFAULT)
5199 g_source_set_priority (source, priority);
5201 g_source_set_callback (source, (GSourceFunc) function, data, notify);
5202 id = g_source_attach (source, NULL);
5203 g_source_unref (source);
5209 * g_child_watch_add:
5210 * @pid: process id to watch. On POSIX the pid of a child process. On
5211 * Windows a handle for a process (which doesn't have to be a child).
5212 * @function: function to call
5213 * @data: data to pass to @function
5215 * Sets a function to be called when the child indicated by @pid
5216 * exits, at a default priority, #G_PRIORITY_DEFAULT.
5218 * If you obtain @pid from g_spawn_async() or g_spawn_async_with_pipes()
5219 * you will need to pass #G_SPAWN_DO_NOT_REAP_CHILD as flag to
5220 * the spawn function for the child watching to work.
5222 * Note that on platforms where #GPid must be explicitly closed
5223 * (see g_spawn_close_pid()) @pid must not be closed while the
5224 * source is still active. Typically, you will want to call
5225 * g_spawn_close_pid() in the callback function for the source.
5227 * GLib supports only a single callback per process id.
5229 * This internally creates a main loop source using
5230 * g_child_watch_source_new() and attaches it to the main loop context
5231 * using g_source_attach(). You can do these steps manually if you
5232 * need greater control.
5234 * Return value: the ID (greater than 0) of the event source.
5239 g_child_watch_add (GPid pid,
5240 GChildWatchFunc function,
5243 return g_child_watch_add_full (G_PRIORITY_DEFAULT, pid, function, data, NULL);
5247 /* Idle functions */
5250 g_idle_prepare (GSource *source,
5259 g_idle_check (GSource *source)
5265 g_idle_dispatch (GSource *source,
5266 GSourceFunc callback,
5271 g_warning ("Idle source dispatched without callback\n"
5272 "You must call g_source_set_callback().");
5276 return callback (user_data);
5280 * g_idle_source_new:
5282 * Creates a new idle source.
5284 * The source will not initially be associated with any #GMainContext
5285 * and must be added to one with g_source_attach() before it will be
5286 * executed. Note that the default priority for idle sources is
5287 * %G_PRIORITY_DEFAULT_IDLE, as compared to other sources which
5288 * have a default priority of %G_PRIORITY_DEFAULT.
5290 * Return value: the newly-created idle source
5293 g_idle_source_new (void)
5297 source = g_source_new (&g_idle_funcs, sizeof (GSource));
5298 g_source_set_priority (source, G_PRIORITY_DEFAULT_IDLE);
5305 * @priority: the priority of the idle source. Typically this will be in the
5306 * range between #G_PRIORITY_DEFAULT_IDLE and #G_PRIORITY_HIGH_IDLE.
5307 * @function: function to call
5308 * @data: data to pass to @function
5309 * @notify: (allow-none): function to call when the idle is removed, or %NULL
5311 * Adds a function to be called whenever there are no higher priority
5312 * events pending. If the function returns %FALSE it is automatically
5313 * removed from the list of event sources and will not be called again.
5315 * This internally creates a main loop source using g_idle_source_new()
5316 * and attaches it to the main loop context using g_source_attach().
5317 * You can do these steps manually if you need greater control.
5319 * Return value: the ID (greater than 0) of the event source.
5320 * Rename to: g_idle_add
5323 g_idle_add_full (gint priority,
5324 GSourceFunc function,
5326 GDestroyNotify notify)
5331 g_return_val_if_fail (function != NULL, 0);
5333 source = g_idle_source_new ();
5335 if (priority != G_PRIORITY_DEFAULT_IDLE)
5336 g_source_set_priority (source, priority);
5338 g_source_set_callback (source, function, data, notify);
5339 id = g_source_attach (source, NULL);
5340 g_source_unref (source);
5347 * @function: function to call
5348 * @data: data to pass to @function.
5350 * Adds a function to be called whenever there are no higher priority
5351 * events pending to the default main loop. The function is given the
5352 * default idle priority, #G_PRIORITY_DEFAULT_IDLE. If the function
5353 * returns %FALSE it is automatically removed from the list of event
5354 * sources and will not be called again.
5356 * This internally creates a main loop source using g_idle_source_new()
5357 * and attaches it to the main loop context using g_source_attach().
5358 * You can do these steps manually if you need greater control.
5360 * Return value: the ID (greater than 0) of the event source.
5363 g_idle_add (GSourceFunc function,
5366 return g_idle_add_full (G_PRIORITY_DEFAULT_IDLE, function, data, NULL);
5370 * g_idle_remove_by_data:
5371 * @data: the data for the idle source's callback.
5373 * Removes the idle function with the given data.
5375 * Return value: %TRUE if an idle source was found and removed.
5378 g_idle_remove_by_data (gpointer data)
5380 return g_source_remove_by_funcs_user_data (&g_idle_funcs, data);
5384 * g_main_context_invoke:
5385 * @context: (allow-none): a #GMainContext, or %NULL
5386 * @function: function to call
5387 * @data: data to pass to @function
5389 * Invokes a function in such a way that @context is owned during the
5390 * invocation of @function.
5392 * If @context is %NULL then the global default main context — as
5393 * returned by g_main_context_default() — is used.
5395 * If @context is owned by the current thread, @function is called
5396 * directly. Otherwise, if @context is the thread-default main context
5397 * of the current thread and g_main_context_acquire() succeeds, then
5398 * @function is called and g_main_context_release() is called
5401 * In any other case, an idle source is created to call @function and
5402 * that source is attached to @context (presumably to be run in another
5403 * thread). The idle source is attached with #G_PRIORITY_DEFAULT
5404 * priority. If you want a different priority, use
5405 * g_main_context_invoke_full().
5407 * Note that, as with normal idle functions, @function should probably
5408 * return %FALSE. If it returns %TRUE, it will be continuously run in a
5409 * loop (and may prevent this call from returning).
5414 g_main_context_invoke (GMainContext *context,
5415 GSourceFunc function,
5418 g_main_context_invoke_full (context,
5420 function, data, NULL);
5424 * g_main_context_invoke_full:
5425 * @context: (allow-none): a #GMainContext, or %NULL
5426 * @priority: the priority at which to run @function
5427 * @function: function to call
5428 * @data: data to pass to @function
5429 * @notify: (allow-none): a function to call when @data is no longer in use, or %NULL.
5431 * Invokes a function in such a way that @context is owned during the
5432 * invocation of @function.
5434 * This function is the same as g_main_context_invoke() except that it
5435 * lets you specify the priority incase @function ends up being
5436 * scheduled as an idle and also lets you give a #GDestroyNotify for @data.
5438 * @notify should not assume that it is called from any particular
5439 * thread or with any particular context acquired.
5444 g_main_context_invoke_full (GMainContext *context,
5446 GSourceFunc function,
5448 GDestroyNotify notify)
5450 g_return_if_fail (function != NULL);
5453 context = g_main_context_default ();
5455 if (g_main_context_is_owner (context))
5457 while (function (data));
5464 GMainContext *thread_default;
5466 thread_default = g_main_context_get_thread_default ();
5468 if (!thread_default)
5469 thread_default = g_main_context_default ();
5471 if (thread_default == context && g_main_context_acquire (context))
5473 while (function (data));
5475 g_main_context_release (context);
5484 source = g_idle_source_new ();
5485 g_source_set_priority (source, priority);
5486 g_source_set_callback (source, function, data, notify);
5487 g_source_attach (source, context);
5488 g_source_unref (source);
5494 glib_worker_main (gpointer data)
5498 g_main_context_iteration (glib_worker_context, TRUE);
5501 if (any_unix_signal_pending)
5502 dispatch_unix_signals ();
5506 return NULL; /* worst GCC warning message ever... */
5510 g_get_worker_context (void)
5512 static gsize initialised;
5514 if (g_once_init_enter (&initialised))
5516 /* mask all signals in the worker thread */
5522 pthread_sigmask (SIG_SETMASK, &all, &prev_mask);
5524 glib_worker_context = g_main_context_new ();
5525 g_thread_new ("gmain", glib_worker_main, NULL);
5527 pthread_sigmask (SIG_SETMASK, &prev_mask, NULL);
5529 g_once_init_leave (&initialised, TRUE);
5532 return glib_worker_context;