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, write to the
19 * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
20 * Boston, MA 02111-1307, USA.
24 * Modified by the GLib Team and others 1997-2000. See the AUTHORS
25 * file for a list of people on the GLib Team. See the ChangeLog
26 * files for a list of changes. These files are distributed with
27 * GLib at ftp://ftp.gtk.org/pub/gtk/.
35 #include "glibconfig.h"
37 /* Uncomment the next line (and the corresponding line in gpoll.c) to
38 * enable debugging printouts if the environment variable
39 * G_MAIN_POLL_DEBUG is set to some value.
41 /* #define G_MAIN_POLL_DEBUG */
44 /* Always enable debugging printout on Windows, as it is more often
47 #define G_MAIN_POLL_DEBUG
51 #include "glib-unix.h"
54 #include <sys/eventfd.h>
59 #include <sys/types.h>
62 #ifdef HAVE_SYS_TIME_H
64 #endif /* HAVE_SYS_TIME_H */
67 #endif /* HAVE_UNISTD_H */
74 #endif /* G_OS_WIN32 */
77 #include <sys/socket.h>
79 #endif /* G_OS_BEOS */
84 #include "giochannel.h"
88 #include "gstrfuncs.h"
89 #include "gtestutils.h"
95 #ifdef G_MAIN_POLL_DEBUG
101 #include "glib-private.h"
105 * @title: The Main Event Loop
106 * @short_description: manages all available sources of events
108 * The main event loop manages all the available sources of events for
109 * GLib and GTK+ applications. These events can come from any number of
110 * different types of sources such as file descriptors (plain files,
111 * pipes or sockets) and timeouts. New types of event sources can also
112 * be added using g_source_attach().
114 * To allow multiple independent sets of sources to be handled in
115 * different threads, each source is associated with a #GMainContext.
116 * A GMainContext can only be running in a single thread, but
117 * sources can be added to it and removed from it from other threads.
119 * Each event source is assigned a priority. The default priority,
120 * #G_PRIORITY_DEFAULT, is 0. Values less than 0 denote higher priorities.
121 * Values greater than 0 denote lower priorities. Events from high priority
122 * sources are always processed before events from lower priority sources.
124 * Idle functions can also be added, and assigned a priority. These will
125 * be run whenever no events with a higher priority are ready to be processed.
127 * The #GMainLoop data type represents a main event loop. A GMainLoop is
128 * created with g_main_loop_new(). After adding the initial event sources,
129 * g_main_loop_run() is called. This continuously checks for new events from
130 * each of the event sources and dispatches them. Finally, the processing of
131 * an event from one of the sources leads to a call to g_main_loop_quit() to
132 * exit the main loop, and g_main_loop_run() returns.
134 * It is possible to create new instances of #GMainLoop recursively.
135 * This is often used in GTK+ applications when showing modal dialog
136 * boxes. Note that event sources are associated with a particular
137 * #GMainContext, and will be checked and dispatched for all main
138 * loops associated with that GMainContext.
140 * GTK+ contains wrappers of some of these functions, e.g. gtk_main(),
141 * gtk_main_quit() and gtk_events_pending().
143 * <refsect2><title>Creating new source types</title>
144 * <para>One of the unusual features of the #GMainLoop functionality
145 * is that new types of event source can be created and used in
146 * addition to the builtin type of event source. A new event source
147 * type is used for handling GDK events. A new source type is created
148 * by <firstterm>deriving</firstterm> from the #GSource structure.
149 * The derived type of source is represented by a structure that has
150 * the #GSource structure as a first element, and other elements specific
151 * to the new source type. To create an instance of the new source type,
152 * call g_source_new() passing in the size of the derived structure and
153 * a table of functions. These #GSourceFuncs determine the behavior of
154 * the new source type.</para>
155 * <para>New source types basically interact with the main context
156 * in two ways. Their prepare function in #GSourceFuncs can set a timeout
157 * to determine the maximum amount of time that the main loop will sleep
158 * before checking the source again. In addition, or as well, the source
159 * can add file descriptors to the set that the main context checks using
160 * g_source_add_poll().</para>
162 * <refsect2><title>Customizing the main loop iteration</title>
163 * <para>Single iterations of a #GMainContext can be run with
164 * g_main_context_iteration(). In some cases, more detailed control
165 * of exactly how the details of the main loop work is desired, for
166 * instance, when integrating the #GMainLoop with an external main loop.
167 * In such cases, you can call the component functions of
168 * g_main_context_iteration() directly. These functions are
169 * g_main_context_prepare(), g_main_context_query(),
170 * g_main_context_check() and g_main_context_dispatch().</para>
171 * <para>The operation of these functions can best be seen in terms
172 * of a state diagram, as shown in <xref linkend="mainloop-states"/>.</para>
173 * <figure id="mainloop-states"><title>States of a Main Context</title>
174 * <graphic fileref="mainloop-states.gif" format="GIF"></graphic>
178 * On Unix, the GLib mainloop is incompatible with fork(). Any program
179 * using the mainloop must either exec() or exit() from the child
180 * without returning to the mainloop.
185 typedef struct _GTimeoutSource GTimeoutSource;
186 typedef struct _GChildWatchSource GChildWatchSource;
187 typedef struct _GUnixSignalWatchSource GUnixSignalWatchSource;
188 typedef struct _GPollRec GPollRec;
189 typedef struct _GSourceCallback GSourceCallback;
193 G_SOURCE_READY = 1 << G_HOOK_FLAG_USER_SHIFT,
194 G_SOURCE_CAN_RECURSE = 1 << (G_HOOK_FLAG_USER_SHIFT + 1)
197 typedef struct _GMainWaiter GMainWaiter;
205 typedef struct _GMainDispatch GMainDispatch;
207 struct _GMainDispatch
210 GSList *dispatching_sources; /* stack of current sources */
213 #ifdef G_MAIN_POLL_DEBUG
214 gboolean _g_main_poll_debug = FALSE;
219 /* The following lock is used for both the list of sources
220 * and the list of poll records
230 GPtrArray *pending_dispatches;
231 gint timeout; /* Timeout for current iteration */
234 GSource *source_list;
235 gint in_check_or_prepare;
237 GPollRec *poll_records, *poll_records_tail;
238 guint n_poll_records;
239 GPollFD *cached_poll_array;
240 guint cached_poll_array_size;
246 /* Flag indicating whether the set of fd's changed during a poll */
247 gboolean poll_changed;
252 gboolean time_is_fresh;
255 struct _GSourceCallback
260 GDestroyNotify notify;
265 GMainContext *context;
270 struct _GTimeoutSource
278 struct _GChildWatchSource
285 #else /* G_OS_WIN32 */
286 gboolean child_exited;
287 #endif /* G_OS_WIN32 */
290 struct _GUnixSignalWatchSource
305 struct _GSourcePrivate
307 GSList *child_sources;
308 GSource *parent_source;
311 #define LOCK_CONTEXT(context) g_mutex_lock (&context->mutex)
312 #define UNLOCK_CONTEXT(context) g_mutex_unlock (&context->mutex)
313 #define G_THREAD_SELF g_thread_self ()
315 #define SOURCE_DESTROYED(source) (((source)->flags & G_HOOK_FLAG_ACTIVE) == 0)
316 #define SOURCE_BLOCKED(source) (((source)->flags & G_HOOK_FLAG_IN_CALL) != 0 && \
317 ((source)->flags & G_SOURCE_CAN_RECURSE) == 0)
319 #define SOURCE_UNREF(source, context) \
321 if ((source)->ref_count > 1) \
322 (source)->ref_count--; \
324 g_source_unref_internal ((source), (context), TRUE); \
328 /* Forward declarations */
330 static void g_source_unref_internal (GSource *source,
331 GMainContext *context,
333 static void g_source_destroy_internal (GSource *source,
334 GMainContext *context,
336 static void g_source_set_priority_unlocked (GSource *source,
337 GMainContext *context,
339 static void g_main_context_poll (GMainContext *context,
344 static void g_main_context_add_poll_unlocked (GMainContext *context,
347 static void g_main_context_remove_poll_unlocked (GMainContext *context,
350 static gboolean g_timeout_prepare (GSource *source,
352 static gboolean g_timeout_check (GSource *source);
353 static gboolean g_timeout_dispatch (GSource *source,
354 GSourceFunc callback,
356 static gboolean g_child_watch_prepare (GSource *source,
358 static gboolean g_child_watch_check (GSource *source);
359 static gboolean g_child_watch_dispatch (GSource *source,
360 GSourceFunc callback,
362 static void g_child_watch_finalize (GSource *source);
364 static void g_unix_signal_handler (int signum);
365 static gboolean g_unix_signal_watch_prepare (GSource *source,
367 static gboolean g_unix_signal_watch_check (GSource *source);
368 static gboolean g_unix_signal_watch_dispatch (GSource *source,
369 GSourceFunc callback,
371 static void g_unix_signal_watch_finalize (GSource *source);
373 static gboolean g_idle_prepare (GSource *source,
375 static gboolean g_idle_check (GSource *source);
376 static gboolean g_idle_dispatch (GSource *source,
377 GSourceFunc callback,
380 static GMainContext *glib_worker_context;
381 static gboolean g_main_context_fork_detected;
383 G_LOCK_DEFINE_STATIC (main_loop);
384 static GMainContext *default_main_context;
389 /* UNIX signals work by marking one of these variables then waking the
390 * worker context to check on them and dispatch accordingly.
392 static volatile gchar unix_signal_pending[NSIG];
393 static volatile gboolean any_unix_signal_pending;
395 /* Guards all the data below */
396 G_LOCK_DEFINE_STATIC (unix_signal_lock);
397 static GSList *unix_signal_watches;
398 static GSList *unix_child_watches;
400 static GSourceFuncs g_unix_signal_funcs =
402 g_unix_signal_watch_prepare,
403 g_unix_signal_watch_check,
404 g_unix_signal_watch_dispatch,
405 g_unix_signal_watch_finalize
407 #endif /* !G_OS_WIN32 */
408 G_LOCK_DEFINE_STATIC (main_context_list);
409 static GSList *main_context_list = NULL;
411 GSourceFuncs g_timeout_funcs =
419 GSourceFuncs g_child_watch_funcs =
421 g_child_watch_prepare,
423 g_child_watch_dispatch,
424 g_child_watch_finalize
427 GSourceFuncs g_idle_funcs =
436 * g_main_context_ref:
437 * @context: a #GMainContext
439 * Increases the reference count on a #GMainContext object by one.
441 * Returns: the @context that was passed in (since 2.6)
444 g_main_context_ref (GMainContext *context)
446 g_return_val_if_fail (context != NULL, NULL);
447 g_return_val_if_fail (g_atomic_int_get (&context->ref_count) > 0, NULL);
449 g_atomic_int_inc (&context->ref_count);
455 poll_rec_list_free (GMainContext *context,
458 g_slice_free_chain (GPollRec, list, next);
462 * g_main_context_unref:
463 * @context: a #GMainContext
465 * Decreases the reference count on a #GMainContext object by one. If
466 * the result is zero, free the context and free all associated memory.
469 g_main_context_unref (GMainContext *context)
472 g_return_if_fail (context != NULL);
473 g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
475 if (!g_atomic_int_dec_and_test (&context->ref_count))
478 G_LOCK (main_context_list);
479 main_context_list = g_slist_remove (main_context_list, context);
480 G_UNLOCK (main_context_list);
482 source = context->source_list;
485 GSource *next = source->next;
486 g_source_destroy_internal (source, context, FALSE);
490 g_mutex_clear (&context->mutex);
492 g_ptr_array_free (context->pending_dispatches, TRUE);
493 g_free (context->cached_poll_array);
495 poll_rec_list_free (context, context->poll_records);
497 g_wakeup_free (context->wakeup);
498 g_cond_clear (&context->cond);
505 g_main_context_forked (void)
507 g_main_context_fork_detected = TRUE;
512 * g_main_context_new:
514 * Creates a new #GMainContext structure.
516 * Return value: the new #GMainContext
519 g_main_context_new (void)
521 static gsize initialised;
522 GMainContext *context;
524 if (g_once_init_enter (&initialised))
526 #ifdef G_MAIN_POLL_DEBUG
527 if (getenv ("G_MAIN_POLL_DEBUG") != NULL)
528 _g_main_poll_debug = TRUE;
532 pthread_atfork (NULL, NULL, g_main_context_forked);
535 g_once_init_leave (&initialised, TRUE);
538 context = g_new0 (GMainContext, 1);
540 g_mutex_init (&context->mutex);
541 g_cond_init (&context->cond);
543 context->owner = NULL;
544 context->waiters = NULL;
546 context->ref_count = 1;
548 context->next_id = 1;
550 context->source_list = NULL;
552 context->poll_func = g_poll;
554 context->cached_poll_array = NULL;
555 context->cached_poll_array_size = 0;
557 context->pending_dispatches = g_ptr_array_new ();
559 context->time_is_fresh = FALSE;
561 context->wakeup = g_wakeup_new ();
562 g_wakeup_get_pollfd (context->wakeup, &context->wake_up_rec);
563 g_main_context_add_poll_unlocked (context, 0, &context->wake_up_rec);
565 G_LOCK (main_context_list);
566 main_context_list = g_slist_append (main_context_list, context);
568 #ifdef G_MAIN_POLL_DEBUG
569 if (_g_main_poll_debug)
570 g_print ("created context=%p\n", context);
573 G_UNLOCK (main_context_list);
579 * g_main_context_default:
581 * Returns the global default main context. This is the main context
582 * used for main loop functions when a main loop is not explicitly
583 * specified, and corresponds to the "main" main loop. See also
584 * g_main_context_get_thread_default().
586 * Return value: (transfer none): the global default main context.
589 g_main_context_default (void)
595 if (!default_main_context)
597 default_main_context = g_main_context_new ();
598 #ifdef G_MAIN_POLL_DEBUG
599 if (_g_main_poll_debug)
600 g_print ("default context=%p\n", default_main_context);
604 G_UNLOCK (main_loop);
606 return default_main_context;
610 free_context_stack (gpointer data)
612 GQueue *stack = data;
613 GMainContext *context;
615 while (!g_queue_is_empty (stack))
617 context = g_queue_pop_head (stack);
618 g_main_context_release (context);
620 g_main_context_unref (context);
622 g_queue_free (stack);
625 static GPrivate thread_context_stack = G_PRIVATE_INIT (free_context_stack);
628 * g_main_context_push_thread_default:
629 * @context: a #GMainContext, or %NULL for the global default context
631 * Acquires @context and sets it as the thread-default context for the
632 * current thread. This will cause certain asynchronous operations
633 * (such as most <link linkend="gio">gio</link>-based I/O) which are
634 * started in this thread to run under @context and deliver their
635 * results to its main loop, rather than running under the global
636 * default context in the main thread. Note that calling this function
637 * changes the context returned by
638 * g_main_context_get_thread_default(), <emphasis>not</emphasis> the
639 * one returned by g_main_context_default(), so it does not affect the
640 * context used by functions like g_idle_add().
642 * Normally you would call this function shortly after creating a new
643 * thread, passing it a #GMainContext which will be run by a
644 * #GMainLoop in that thread, to set a new default context for all
645 * async operations in that thread. (In this case, you don't need to
646 * ever call g_main_context_pop_thread_default().) In some cases
647 * however, you may want to schedule a single operation in a
648 * non-default context, or temporarily use a non-default context in
649 * the main thread. In that case, you can wrap the call to the
650 * asynchronous operation inside a
651 * g_main_context_push_thread_default() /
652 * g_main_context_pop_thread_default() pair, but it is up to you to
653 * ensure that no other asynchronous operations accidentally get
654 * started while the non-default context is active.
656 * Beware that libraries that predate this function may not correctly
657 * handle being used from a thread with a thread-default context. Eg,
658 * see g_file_supports_thread_contexts().
663 g_main_context_push_thread_default (GMainContext *context)
666 gboolean acquired_context;
668 acquired_context = g_main_context_acquire (context);
669 g_return_if_fail (acquired_context);
671 if (context == g_main_context_default ())
674 g_main_context_ref (context);
676 stack = g_private_get (&thread_context_stack);
679 stack = g_queue_new ();
680 g_private_set (&thread_context_stack, stack);
683 g_queue_push_head (stack, context);
687 * g_main_context_pop_thread_default:
688 * @context: a #GMainContext object, or %NULL
690 * Pops @context off the thread-default context stack (verifying that
691 * it was on the top of the stack).
696 g_main_context_pop_thread_default (GMainContext *context)
700 if (context == g_main_context_default ())
703 stack = g_private_get (&thread_context_stack);
705 g_return_if_fail (stack != NULL);
706 g_return_if_fail (g_queue_peek_head (stack) == context);
708 g_queue_pop_head (stack);
710 g_main_context_release (context);
712 g_main_context_unref (context);
716 * g_main_context_get_thread_default:
718 * Gets the thread-default #GMainContext for this thread. Asynchronous
719 * operations that want to be able to be run in contexts other than
720 * the default one should call this method or
721 * g_main_context_ref_thread_default() to get a #GMainContext to add
722 * their #GSource<!-- -->s to. (Note that even in single-threaded
723 * programs applications may sometimes want to temporarily push a
724 * non-default context, so it is not safe to assume that this will
725 * always return %NULL if you are running in the default thread.)
727 * If you need to hold a reference on the context, use
728 * g_main_context_ref_thread_default() instead.
730 * Returns: (transfer none): the thread-default #GMainContext, or
731 * %NULL if the thread-default context is the global default context.
736 g_main_context_get_thread_default (void)
740 stack = g_private_get (&thread_context_stack);
742 return g_queue_peek_head (stack);
748 * g_main_context_ref_thread_default:
750 * Gets the thread-default #GMainContext for this thread, as with
751 * g_main_context_get_thread_default(), but also adds a reference to
752 * it with g_main_context_ref(). In addition, unlike
753 * g_main_context_get_thread_default(), if the thread-default context
754 * is the global default context, this will return that #GMainContext
755 * (with a ref added to it) rather than returning %NULL.
757 * Returns: (transfer full): the thread-default #GMainContext. Unref
758 * with g_main_context_unref() when you are done with it.
763 g_main_context_ref_thread_default (void)
765 GMainContext *context;
767 context = g_main_context_get_thread_default ();
769 context = g_main_context_default ();
770 return g_main_context_ref (context);
773 /* Hooks for adding to the main loop */
777 * @source_funcs: structure containing functions that implement
778 * the sources behavior.
779 * @struct_size: size of the #GSource structure to create.
781 * Creates a new #GSource structure. The size is specified to
782 * allow creating structures derived from #GSource that contain
783 * additional data. The size passed in must be at least
784 * <literal>sizeof (GSource)</literal>.
786 * The source will not initially be associated with any #GMainContext
787 * and must be added to one with g_source_attach() before it will be
790 * Return value: the newly-created #GSource.
793 g_source_new (GSourceFuncs *source_funcs,
798 g_return_val_if_fail (source_funcs != NULL, NULL);
799 g_return_val_if_fail (struct_size >= sizeof (GSource), NULL);
801 source = (GSource*) g_malloc0 (struct_size);
803 source->source_funcs = source_funcs;
804 source->ref_count = 1;
806 source->priority = G_PRIORITY_DEFAULT;
808 source->flags = G_HOOK_FLAG_ACTIVE;
810 /* NULL/0 initialization for all other fields */
815 /* Holds context's lock
818 g_source_list_add (GSource *source,
819 GMainContext *context)
821 GSource *tmp_source, *last_source;
823 if (source->priv && source->priv->parent_source)
825 /* Put the source immediately before its parent */
826 tmp_source = source->priv->parent_source;
827 last_source = source->priv->parent_source->prev;
832 tmp_source = context->source_list;
833 while (tmp_source && tmp_source->priority <= source->priority)
835 last_source = tmp_source;
836 tmp_source = tmp_source->next;
840 source->next = tmp_source;
842 tmp_source->prev = source;
844 source->prev = last_source;
846 last_source->next = source;
848 context->source_list = source;
851 /* Holds context's lock
854 g_source_list_remove (GSource *source,
855 GMainContext *context)
858 source->prev->next = source->next;
860 context->source_list = source->next;
863 source->next->prev = source->prev;
870 g_source_attach_unlocked (GSource *source,
871 GMainContext *context)
876 source->context = context;
877 result = source->source_id = context->next_id++;
880 g_source_list_add (source, context);
882 tmp_list = source->poll_fds;
885 g_main_context_add_poll_unlocked (context, source->priority, tmp_list->data);
886 tmp_list = tmp_list->next;
891 tmp_list = source->priv->child_sources;
894 g_source_attach_unlocked (tmp_list->data, context);
895 tmp_list = tmp_list->next;
904 * @source: a #GSource
905 * @context: a #GMainContext (if %NULL, the default context will be used)
907 * Adds a #GSource to a @context so that it will be executed within
908 * that context. Remove it by calling g_source_destroy().
910 * Return value: the ID (greater than 0) for the source within the
914 g_source_attach (GSource *source,
915 GMainContext *context)
919 g_return_val_if_fail (source->context == NULL, 0);
920 g_return_val_if_fail (!SOURCE_DESTROYED (source), 0);
923 context = g_main_context_default ();
925 LOCK_CONTEXT (context);
927 result = g_source_attach_unlocked (source, context);
929 /* If another thread has acquired the context, wake it up since it
930 * might be in poll() right now.
932 if (context->owner && context->owner != G_THREAD_SELF)
933 g_wakeup_signal (context->wakeup);
935 UNLOCK_CONTEXT (context);
941 g_source_destroy_internal (GSource *source,
942 GMainContext *context,
946 LOCK_CONTEXT (context);
948 if (!SOURCE_DESTROYED (source))
951 gpointer old_cb_data;
952 GSourceCallbackFuncs *old_cb_funcs;
954 source->flags &= ~G_HOOK_FLAG_ACTIVE;
956 old_cb_data = source->callback_data;
957 old_cb_funcs = source->callback_funcs;
959 source->callback_data = NULL;
960 source->callback_funcs = NULL;
964 UNLOCK_CONTEXT (context);
965 old_cb_funcs->unref (old_cb_data);
966 LOCK_CONTEXT (context);
969 if (!SOURCE_BLOCKED (source))
971 tmp_list = source->poll_fds;
974 g_main_context_remove_poll_unlocked (context, tmp_list->data);
975 tmp_list = tmp_list->next;
979 if (source->priv && source->priv->child_sources)
981 /* This is safe because even if a child_source finalizer or
982 * closure notify tried to modify source->priv->child_sources
983 * from outside the lock, it would fail since
984 * SOURCE_DESTROYED(source) is now TRUE.
986 tmp_list = source->priv->child_sources;
989 g_source_destroy_internal (tmp_list->data, context, TRUE);
990 g_source_unref_internal (tmp_list->data, context, TRUE);
991 tmp_list = tmp_list->next;
993 g_slist_free (source->priv->child_sources);
994 source->priv->child_sources = NULL;
997 g_source_unref_internal (source, context, TRUE);
1001 UNLOCK_CONTEXT (context);
1006 * @source: a #GSource
1008 * Removes a source from its #GMainContext, if any, and mark it as
1009 * destroyed. The source cannot be subsequently added to another
1013 g_source_destroy (GSource *source)
1015 GMainContext *context;
1017 g_return_if_fail (source != NULL);
1019 context = source->context;
1022 g_source_destroy_internal (source, context, FALSE);
1024 source->flags &= ~G_HOOK_FLAG_ACTIVE;
1029 * @source: a #GSource
1031 * Returns the numeric ID for a particular source. The ID of a source
1032 * is a positive integer which is unique within a particular main loop
1033 * context. The reverse
1034 * mapping from ID to source is done by g_main_context_find_source_by_id().
1036 * Return value: the ID (greater than 0) for the source
1039 g_source_get_id (GSource *source)
1043 g_return_val_if_fail (source != NULL, 0);
1044 g_return_val_if_fail (source->context != NULL, 0);
1046 LOCK_CONTEXT (source->context);
1047 result = source->source_id;
1048 UNLOCK_CONTEXT (source->context);
1054 * g_source_get_context:
1055 * @source: a #GSource
1057 * Gets the #GMainContext with which the source is associated.
1058 * Calling this function on a destroyed source is an error.
1060 * Return value: (transfer none): the #GMainContext with which the
1061 * source is associated, or %NULL if the context has not
1062 * yet been added to a source.
1065 g_source_get_context (GSource *source)
1067 g_return_val_if_fail (!SOURCE_DESTROYED (source), NULL);
1069 return source->context;
1073 * g_source_add_poll:
1074 * @source:a #GSource
1075 * @fd: a #GPollFD structure holding information about a file
1076 * descriptor to watch.
1078 * Adds a file descriptor to the set of file descriptors polled for
1079 * this source. This is usually combined with g_source_new() to add an
1080 * event source. The event source's check function will typically test
1081 * the @revents field in the #GPollFD struct and return %TRUE if events need
1085 g_source_add_poll (GSource *source,
1088 GMainContext *context;
1090 g_return_if_fail (source != NULL);
1091 g_return_if_fail (fd != NULL);
1092 g_return_if_fail (!SOURCE_DESTROYED (source));
1094 context = source->context;
1097 LOCK_CONTEXT (context);
1099 source->poll_fds = g_slist_prepend (source->poll_fds, fd);
1103 if (!SOURCE_BLOCKED (source))
1104 g_main_context_add_poll_unlocked (context, source->priority, fd);
1105 UNLOCK_CONTEXT (context);
1110 * g_source_remove_poll:
1111 * @source:a #GSource
1112 * @fd: a #GPollFD structure previously passed to g_source_add_poll().
1114 * Removes a file descriptor from the set of file descriptors polled for
1118 g_source_remove_poll (GSource *source,
1121 GMainContext *context;
1123 g_return_if_fail (source != NULL);
1124 g_return_if_fail (fd != NULL);
1125 g_return_if_fail (!SOURCE_DESTROYED (source));
1127 context = source->context;
1130 LOCK_CONTEXT (context);
1132 source->poll_fds = g_slist_remove (source->poll_fds, fd);
1136 if (!SOURCE_BLOCKED (source))
1137 g_main_context_remove_poll_unlocked (context, fd);
1138 UNLOCK_CONTEXT (context);
1143 * g_source_add_child_source:
1144 * @source:a #GSource
1145 * @child_source: a second #GSource that @source should "poll"
1147 * Adds @child_source to @source as a "polled" source; when @source is
1148 * added to a #GMainContext, @child_source will be automatically added
1149 * with the same priority, when @child_source is triggered, it will
1150 * cause @source to dispatch (in addition to calling its own
1151 * callback), and when @source is destroyed, it will destroy
1152 * @child_source as well. (@source will also still be dispatched if
1153 * its own prepare/check functions indicate that it is ready.)
1155 * If you don't need @child_source to do anything on its own when it
1156 * triggers, you can call g_source_set_dummy_callback() on it to set a
1157 * callback that does nothing (except return %TRUE if appropriate).
1159 * @source will hold a reference on @child_source while @child_source
1160 * is attached to it.
1165 g_source_add_child_source (GSource *source,
1166 GSource *child_source)
1168 GMainContext *context;
1170 g_return_if_fail (source != NULL);
1171 g_return_if_fail (child_source != NULL);
1172 g_return_if_fail (!SOURCE_DESTROYED (source));
1173 g_return_if_fail (!SOURCE_DESTROYED (child_source));
1174 g_return_if_fail (child_source->context == NULL);
1175 g_return_if_fail (child_source->priv == NULL || child_source->priv->parent_source == NULL);
1177 context = source->context;
1180 LOCK_CONTEXT (context);
1183 source->priv = g_slice_new0 (GSourcePrivate);
1184 if (!child_source->priv)
1185 child_source->priv = g_slice_new0 (GSourcePrivate);
1187 source->priv->child_sources = g_slist_prepend (source->priv->child_sources,
1188 g_source_ref (child_source));
1189 child_source->priv->parent_source = source;
1190 g_source_set_priority_unlocked (child_source, context, source->priority);
1194 UNLOCK_CONTEXT (context);
1195 g_source_attach (child_source, context);
1200 * g_source_remove_child_source:
1201 * @source:a #GSource
1202 * @child_source: a #GSource previously passed to
1203 * g_source_add_child_source().
1205 * Detaches @child_source from @source and destroys it.
1210 g_source_remove_child_source (GSource *source,
1211 GSource *child_source)
1213 GMainContext *context;
1215 g_return_if_fail (source != NULL);
1216 g_return_if_fail (child_source != NULL);
1217 g_return_if_fail (child_source->priv != NULL && child_source->priv->parent_source == source);
1218 g_return_if_fail (!SOURCE_DESTROYED (source));
1219 g_return_if_fail (!SOURCE_DESTROYED (child_source));
1221 context = source->context;
1224 LOCK_CONTEXT (context);
1226 source->priv->child_sources = g_slist_remove (source->priv->child_sources, child_source);
1227 g_source_destroy_internal (child_source, context, TRUE);
1228 g_source_unref_internal (child_source, context, TRUE);
1231 UNLOCK_CONTEXT (context);
1235 * g_source_set_callback_indirect:
1236 * @source: the source
1237 * @callback_data: pointer to callback data "object"
1238 * @callback_funcs: functions for reference counting @callback_data
1239 * and getting the callback and data
1241 * Sets the callback function storing the data as a refcounted callback
1242 * "object". This is used internally. Note that calling
1243 * g_source_set_callback_indirect() assumes
1244 * an initial reference count on @callback_data, and thus
1245 * @callback_funcs->unref will eventually be called once more
1246 * than @callback_funcs->ref.
1249 g_source_set_callback_indirect (GSource *source,
1250 gpointer callback_data,
1251 GSourceCallbackFuncs *callback_funcs)
1253 GMainContext *context;
1254 gpointer old_cb_data;
1255 GSourceCallbackFuncs *old_cb_funcs;
1257 g_return_if_fail (source != NULL);
1258 g_return_if_fail (callback_funcs != NULL || callback_data == NULL);
1260 context = source->context;
1263 LOCK_CONTEXT (context);
1265 old_cb_data = source->callback_data;
1266 old_cb_funcs = source->callback_funcs;
1268 source->callback_data = callback_data;
1269 source->callback_funcs = callback_funcs;
1272 UNLOCK_CONTEXT (context);
1275 old_cb_funcs->unref (old_cb_data);
1279 g_source_callback_ref (gpointer cb_data)
1281 GSourceCallback *callback = cb_data;
1283 callback->ref_count++;
1288 g_source_callback_unref (gpointer cb_data)
1290 GSourceCallback *callback = cb_data;
1292 callback->ref_count--;
1293 if (callback->ref_count == 0)
1295 if (callback->notify)
1296 callback->notify (callback->data);
1302 g_source_callback_get (gpointer cb_data,
1307 GSourceCallback *callback = cb_data;
1309 *func = callback->func;
1310 *data = callback->data;
1313 static GSourceCallbackFuncs g_source_callback_funcs = {
1314 g_source_callback_ref,
1315 g_source_callback_unref,
1316 g_source_callback_get,
1320 * g_source_set_callback:
1321 * @source: the source
1322 * @func: a callback function
1323 * @data: the data to pass to callback function
1324 * @notify: a function to call when @data is no longer in use, or %NULL.
1326 * Sets the callback function for a source. The callback for a source is
1327 * called from the source's dispatch function.
1329 * The exact type of @func depends on the type of source; ie. you
1330 * should not count on @func being called with @data as its first
1333 * Typically, you won't use this function. Instead use functions specific
1334 * to the type of source you are using.
1337 g_source_set_callback (GSource *source,
1340 GDestroyNotify notify)
1342 GSourceCallback *new_callback;
1344 g_return_if_fail (source != NULL);
1346 new_callback = g_new (GSourceCallback, 1);
1348 new_callback->ref_count = 1;
1349 new_callback->func = func;
1350 new_callback->data = data;
1351 new_callback->notify = notify;
1353 g_source_set_callback_indirect (source, new_callback, &g_source_callback_funcs);
1358 * g_source_set_funcs:
1359 * @source: a #GSource
1360 * @funcs: the new #GSourceFuncs
1362 * Sets the source functions (can be used to override
1363 * default implementations) of an unattached source.
1368 g_source_set_funcs (GSource *source,
1369 GSourceFuncs *funcs)
1371 g_return_if_fail (source != NULL);
1372 g_return_if_fail (source->context == NULL);
1373 g_return_if_fail (source->ref_count > 0);
1374 g_return_if_fail (funcs != NULL);
1376 source->source_funcs = funcs;
1380 g_source_set_priority_unlocked (GSource *source,
1381 GMainContext *context,
1386 source->priority = priority;
1390 /* Remove the source from the context's source and then
1391 * add it back so it is sorted in the correct place
1393 g_source_list_remove (source, source->context);
1394 g_source_list_add (source, source->context);
1396 if (!SOURCE_BLOCKED (source))
1398 tmp_list = source->poll_fds;
1401 g_main_context_remove_poll_unlocked (context, tmp_list->data);
1402 g_main_context_add_poll_unlocked (context, priority, tmp_list->data);
1404 tmp_list = tmp_list->next;
1409 if (source->priv && source->priv->child_sources)
1411 tmp_list = source->priv->child_sources;
1414 g_source_set_priority_unlocked (tmp_list->data, context, priority);
1415 tmp_list = tmp_list->next;
1421 * g_source_set_priority:
1422 * @source: a #GSource
1423 * @priority: the new priority.
1425 * Sets the priority of a source. While the main loop is being run, a
1426 * source will be dispatched if it is ready to be dispatched and no
1427 * sources at a higher (numerically smaller) priority are ready to be
1431 g_source_set_priority (GSource *source,
1434 GMainContext *context;
1436 g_return_if_fail (source != NULL);
1438 context = source->context;
1441 LOCK_CONTEXT (context);
1442 g_source_set_priority_unlocked (source, context, priority);
1444 UNLOCK_CONTEXT (source->context);
1448 * g_source_get_priority:
1449 * @source: a #GSource
1451 * Gets the priority of a source.
1453 * Return value: the priority of the source
1456 g_source_get_priority (GSource *source)
1458 g_return_val_if_fail (source != NULL, 0);
1460 return source->priority;
1464 * g_source_set_can_recurse:
1465 * @source: a #GSource
1466 * @can_recurse: whether recursion is allowed for this source
1468 * Sets whether a source can be called recursively. If @can_recurse is
1469 * %TRUE, then while the source is being dispatched then this source
1470 * will be processed normally. Otherwise, all processing of this
1471 * source is blocked until the dispatch function returns.
1474 g_source_set_can_recurse (GSource *source,
1475 gboolean can_recurse)
1477 GMainContext *context;
1479 g_return_if_fail (source != NULL);
1481 context = source->context;
1484 LOCK_CONTEXT (context);
1487 source->flags |= G_SOURCE_CAN_RECURSE;
1489 source->flags &= ~G_SOURCE_CAN_RECURSE;
1492 UNLOCK_CONTEXT (context);
1496 * g_source_get_can_recurse:
1497 * @source: a #GSource
1499 * Checks whether a source is allowed to be called recursively.
1500 * see g_source_set_can_recurse().
1502 * Return value: whether recursion is allowed.
1505 g_source_get_can_recurse (GSource *source)
1507 g_return_val_if_fail (source != NULL, FALSE);
1509 return (source->flags & G_SOURCE_CAN_RECURSE) != 0;
1514 * g_source_set_name:
1515 * @source: a #GSource
1516 * @name: debug name for the source
1518 * Sets a name for the source, used in debugging and profiling.
1519 * The name defaults to #NULL.
1521 * The source name should describe in a human-readable way
1522 * what the source does. For example, "X11 event queue"
1523 * or "GTK+ repaint idle handler" or whatever it is.
1525 * It is permitted to call this function multiple times, but is not
1526 * recommended due to the potential performance impact. For example,
1527 * one could change the name in the "check" function of a #GSourceFuncs
1528 * to include details like the event type in the source name.
1533 g_source_set_name (GSource *source,
1536 g_return_if_fail (source != NULL);
1538 /* setting back to NULL is allowed, just because it's
1539 * weird if get_name can return NULL but you can't
1543 g_free (source->name);
1544 source->name = g_strdup (name);
1548 * g_source_get_name:
1549 * @source: a #GSource
1551 * Gets a name for the source, used in debugging and profiling.
1552 * The name may be #NULL if it has never been set with
1553 * g_source_set_name().
1555 * Return value: the name of the source
1559 g_source_get_name (GSource *source)
1561 g_return_val_if_fail (source != NULL, NULL);
1563 return source->name;
1567 * g_source_set_name_by_id:
1568 * @tag: a #GSource ID
1569 * @name: debug name for the source
1571 * Sets the name of a source using its ID.
1573 * This is a convenience utility to set source names from the return
1574 * value of g_idle_add(), g_timeout_add(), etc.
1579 g_source_set_name_by_id (guint tag,
1584 g_return_if_fail (tag > 0);
1586 source = g_main_context_find_source_by_id (NULL, tag);
1590 g_source_set_name (source, name);
1596 * @source: a #GSource
1598 * Increases the reference count on a source by one.
1600 * Return value: @source
1603 g_source_ref (GSource *source)
1605 GMainContext *context;
1607 g_return_val_if_fail (source != NULL, NULL);
1609 context = source->context;
1612 LOCK_CONTEXT (context);
1614 source->ref_count++;
1617 UNLOCK_CONTEXT (context);
1622 /* g_source_unref() but possible to call within context lock
1625 g_source_unref_internal (GSource *source,
1626 GMainContext *context,
1629 gpointer old_cb_data = NULL;
1630 GSourceCallbackFuncs *old_cb_funcs = NULL;
1632 g_return_if_fail (source != NULL);
1634 if (!have_lock && context)
1635 LOCK_CONTEXT (context);
1637 source->ref_count--;
1638 if (source->ref_count == 0)
1640 old_cb_data = source->callback_data;
1641 old_cb_funcs = source->callback_funcs;
1643 source->callback_data = NULL;
1644 source->callback_funcs = NULL;
1648 if (!SOURCE_DESTROYED (source))
1649 g_warning (G_STRLOC ": ref_count == 0, but source was still attached to a context!");
1650 g_source_list_remove (source, context);
1653 if (source->source_funcs->finalize)
1656 UNLOCK_CONTEXT (context);
1657 source->source_funcs->finalize (source);
1659 LOCK_CONTEXT (context);
1662 g_free (source->name);
1663 source->name = NULL;
1665 g_slist_free (source->poll_fds);
1666 source->poll_fds = NULL;
1670 g_slice_free (GSourcePrivate, source->priv);
1671 source->priv = NULL;
1677 if (!have_lock && context)
1678 UNLOCK_CONTEXT (context);
1683 UNLOCK_CONTEXT (context);
1685 old_cb_funcs->unref (old_cb_data);
1688 LOCK_CONTEXT (context);
1694 * @source: a #GSource
1696 * Decreases the reference count of a source by one. If the
1697 * resulting reference count is zero the source and associated
1698 * memory will be destroyed.
1701 g_source_unref (GSource *source)
1703 g_return_if_fail (source != NULL);
1705 g_source_unref_internal (source, source->context, FALSE);
1709 * g_main_context_find_source_by_id:
1710 * @context: a #GMainContext (if %NULL, the default context will be used)
1711 * @source_id: the source ID, as returned by g_source_get_id().
1713 * Finds a #GSource given a pair of context and ID.
1715 * Return value: (transfer none): the #GSource if found, otherwise, %NULL
1718 g_main_context_find_source_by_id (GMainContext *context,
1723 g_return_val_if_fail (source_id > 0, NULL);
1725 if (context == NULL)
1726 context = g_main_context_default ();
1728 LOCK_CONTEXT (context);
1730 source = context->source_list;
1733 if (!SOURCE_DESTROYED (source) &&
1734 source->source_id == source_id)
1736 source = source->next;
1739 UNLOCK_CONTEXT (context);
1745 * g_main_context_find_source_by_funcs_user_data:
1746 * @context: a #GMainContext (if %NULL, the default context will be used).
1747 * @funcs: the @source_funcs passed to g_source_new().
1748 * @user_data: the user data from the callback.
1750 * Finds a source with the given source functions and user data. If
1751 * multiple sources exist with the same source function and user data,
1752 * the first one found will be returned.
1754 * Return value: (transfer none): the source, if one was found, otherwise %NULL
1757 g_main_context_find_source_by_funcs_user_data (GMainContext *context,
1758 GSourceFuncs *funcs,
1763 g_return_val_if_fail (funcs != NULL, NULL);
1765 if (context == NULL)
1766 context = g_main_context_default ();
1768 LOCK_CONTEXT (context);
1770 source = context->source_list;
1773 if (!SOURCE_DESTROYED (source) &&
1774 source->source_funcs == funcs &&
1775 source->callback_funcs)
1777 GSourceFunc callback;
1778 gpointer callback_data;
1780 source->callback_funcs->get (source->callback_data, source, &callback, &callback_data);
1782 if (callback_data == user_data)
1785 source = source->next;
1788 UNLOCK_CONTEXT (context);
1794 * g_main_context_find_source_by_user_data:
1795 * @context: a #GMainContext
1796 * @user_data: the user_data for the callback.
1798 * Finds a source with the given user data for the callback. If
1799 * multiple sources exist with the same user data, the first
1800 * one found will be returned.
1802 * Return value: (transfer none): the source, if one was found, otherwise %NULL
1805 g_main_context_find_source_by_user_data (GMainContext *context,
1810 if (context == NULL)
1811 context = g_main_context_default ();
1813 LOCK_CONTEXT (context);
1815 source = context->source_list;
1818 if (!SOURCE_DESTROYED (source) &&
1819 source->callback_funcs)
1821 GSourceFunc callback;
1822 gpointer callback_data = NULL;
1824 source->callback_funcs->get (source->callback_data, source, &callback, &callback_data);
1826 if (callback_data == user_data)
1829 source = source->next;
1832 UNLOCK_CONTEXT (context);
1839 * @tag: the ID of the source to remove.
1841 * Removes the source with the given id from the default main context.
1843 * a #GSource is given by g_source_get_id(), or will be returned by the
1844 * functions g_source_attach(), g_idle_add(), g_idle_add_full(),
1845 * g_timeout_add(), g_timeout_add_full(), g_child_watch_add(),
1846 * g_child_watch_add_full(), g_io_add_watch(), and g_io_add_watch_full().
1848 * See also g_source_destroy(). You must use g_source_destroy() for sources
1849 * added to a non-default main context.
1851 * Return value: %TRUE if the source was found and removed.
1854 g_source_remove (guint tag)
1858 g_return_val_if_fail (tag > 0, FALSE);
1860 source = g_main_context_find_source_by_id (NULL, tag);
1862 g_source_destroy (source);
1864 return source != NULL;
1868 * g_source_remove_by_user_data:
1869 * @user_data: the user_data for the callback.
1871 * Removes a source from the default main loop context given the user
1872 * data for the callback. If multiple sources exist with the same user
1873 * data, only one will be destroyed.
1875 * Return value: %TRUE if a source was found and removed.
1878 g_source_remove_by_user_data (gpointer user_data)
1882 source = g_main_context_find_source_by_user_data (NULL, user_data);
1885 g_source_destroy (source);
1893 * g_source_remove_by_funcs_user_data:
1894 * @funcs: The @source_funcs passed to g_source_new()
1895 * @user_data: the user data for the callback
1897 * Removes a source from the default main loop context given the
1898 * source functions and user data. If multiple sources exist with the
1899 * same source functions and user data, only one will be destroyed.
1901 * Return value: %TRUE if a source was found and removed.
1904 g_source_remove_by_funcs_user_data (GSourceFuncs *funcs,
1909 g_return_val_if_fail (funcs != NULL, FALSE);
1911 source = g_main_context_find_source_by_funcs_user_data (NULL, funcs, user_data);
1914 g_source_destroy (source);
1922 * g_get_current_time:
1923 * @result: #GTimeVal structure in which to store current time.
1925 * Equivalent to the UNIX gettimeofday() function, but portable.
1927 * You may find g_get_real_time() to be more convenient.
1930 g_get_current_time (GTimeVal *result)
1935 g_return_if_fail (result != NULL);
1937 /*this is required on alpha, there the timeval structs are int's
1938 not longs and a cast only would fail horribly*/
1939 gettimeofday (&r, NULL);
1940 result->tv_sec = r.tv_sec;
1941 result->tv_usec = r.tv_usec;
1946 g_return_if_fail (result != NULL);
1948 GetSystemTimeAsFileTime (&ft);
1949 memmove (&time64, &ft, sizeof (FILETIME));
1951 /* Convert from 100s of nanoseconds since 1601-01-01
1952 * to Unix epoch. Yes, this is Y2038 unsafe.
1954 time64 -= G_GINT64_CONSTANT (116444736000000000);
1957 result->tv_sec = time64 / 1000000;
1958 result->tv_usec = time64 % 1000000;
1965 * Queries the system wall-clock time.
1967 * This call is functionally equivalent to g_get_current_time() except
1968 * that the return value is often more convenient than dealing with a
1971 * You should only use this call if you are actually interested in the real
1972 * wall-clock time. g_get_monotonic_time() is probably more useful for
1973 * measuring intervals.
1975 * Returns: the number of microseconds since January 1, 1970 UTC.
1980 g_get_real_time (void)
1984 g_get_current_time (&tv);
1986 return (((gint64) tv.tv_sec) * 1000000) + tv.tv_usec;
1990 * g_get_monotonic_time:
1992 * Queries the system monotonic time, if available.
1994 * On POSIX systems with clock_gettime() and %CLOCK_MONOTONIC this call
1995 * is a very shallow wrapper for that. Otherwise, we make a best effort
1996 * that probably involves returning the wall clock time (with at least
1997 * microsecond accuracy, subject to the limitations of the OS kernel).
1999 * It's important to note that POSIX %CLOCK_MONOTONIC does not count
2000 * time spent while the machine is suspended.
2002 * On Windows, "limitations of the OS kernel" is a rather substantial
2003 * statement. Depending on the configuration of the system, the wall
2004 * clock time is updated as infrequently as 64 times a second (which
2005 * is approximately every 16ms).
2007 * Returns: the monotonic time, in microseconds
2012 g_get_monotonic_time (void)
2014 #ifdef HAVE_CLOCK_GETTIME
2015 /* librt clock_gettime() is our first choice */
2017 #ifdef HAVE_MONOTONIC_CLOCK
2018 static volatile gsize clockid = 0;
2020 static clockid_t clockid = CLOCK_REALTIME;
2024 #ifdef HAVE_MONOTONIC_CLOCK
2025 if (g_once_init_enter (&clockid))
2027 clockid_t best_clockid;
2029 if (sysconf (_SC_MONOTONIC_CLOCK) >= 0)
2030 best_clockid = CLOCK_MONOTONIC;
2032 best_clockid = CLOCK_REALTIME;
2033 g_once_init_leave (&clockid, (gsize)best_clockid);
2037 clock_gettime (clockid, &ts);
2039 /* In theory monotonic time can have any epoch.
2041 * glib presently assumes the following:
2043 * 1) The epoch comes some time after the birth of Jesus of Nazareth, but
2044 * not more than 10000 years later.
2046 * 2) The current time also falls sometime within this range.
2048 * These two reasonable assumptions leave us with a maximum deviation from
2049 * the epoch of 10000 years, or 315569520000000000 seconds.
2051 * If we restrict ourselves to this range then the number of microseconds
2052 * will always fit well inside the constraints of a int64 (by a factor of
2055 * If you actually hit the following assertion, probably you should file a
2056 * bug against your operating system for being excessively silly.
2058 g_assert (G_GINT64_CONSTANT (-315569520000000000) < ts.tv_sec &&
2059 ts.tv_sec < G_GINT64_CONSTANT (315569520000000000));
2061 return (((gint64) ts.tv_sec) * 1000000) + (ts.tv_nsec / 1000);
2064 /* It may look like we are discarding accuracy on Windows (since its
2065 * current time is expressed in 100s of nanoseconds) but according to
2066 * many sources, the time is only updated 64 times per second, so
2067 * microsecond accuracy is more than enough.
2072 g_get_current_time (&tv);
2074 return (((gint64) tv.tv_sec) * 1000000) + tv.tv_usec;
2080 g_main_dispatch_free (gpointer dispatch)
2082 g_slice_free (GMainDispatch, dispatch);
2085 /* Running the main loop */
2087 static GMainDispatch *
2090 static GPrivate depth_private = G_PRIVATE_INIT (g_main_dispatch_free);
2091 GMainDispatch *dispatch;
2093 dispatch = g_private_get (&depth_private);
2097 dispatch = g_slice_new0 (GMainDispatch);
2098 g_private_set (&depth_private, dispatch);
2107 * Returns the depth of the stack of calls to
2108 * g_main_context_dispatch() on any #GMainContext in the current thread.
2109 * That is, when called from the toplevel, it gives 0. When
2110 * called from within a callback from g_main_context_iteration()
2111 * (or g_main_loop_run(), etc.) it returns 1. When called from within
2112 * a callback to a recursive call to g_main_context_iteration(),
2113 * it returns 2. And so forth.
2115 * This function is useful in a situation like the following:
2116 * Imagine an extremely simple "garbage collected" system.
2119 * static GList *free_list;
2122 * allocate_memory (gsize size)
2124 * gpointer result = g_malloc (size);
2125 * free_list = g_list_prepend (free_list, result);
2130 * free_allocated_memory (void)
2133 * for (l = free_list; l; l = l->next);
2135 * g_list_free (free_list);
2143 * g_main_context_iteration (NULL, TRUE);
2144 * free_allocated_memory();
2148 * This works from an application, however, if you want to do the same
2149 * thing from a library, it gets more difficult, since you no longer
2150 * control the main loop. You might think you can simply use an idle
2151 * function to make the call to free_allocated_memory(), but that
2152 * doesn't work, since the idle function could be called from a
2153 * recursive callback. This can be fixed by using g_main_depth()
2157 * allocate_memory (gsize size)
2159 * FreeListBlock *block = g_new (FreeListBlock, 1);
2160 * block->mem = g_malloc (size);
2161 * block->depth = g_main_depth ();
2162 * free_list = g_list_prepend (free_list, block);
2163 * return block->mem;
2167 * free_allocated_memory (void)
2171 * int depth = g_main_depth ();
2172 * for (l = free_list; l; );
2174 * GList *next = l->next;
2175 * FreeListBlock *block = l->data;
2176 * if (block->depth > depth)
2178 * g_free (block->mem);
2180 * free_list = g_list_delete_link (free_list, l);
2188 * There is a temptation to use g_main_depth() to solve
2189 * problems with reentrancy. For instance, while waiting for data
2190 * to be received from the network in response to a menu item,
2191 * the menu item might be selected again. It might seem that
2192 * one could make the menu item's callback return immediately
2193 * and do nothing if g_main_depth() returns a value greater than 1.
2194 * However, this should be avoided since the user then sees selecting
2195 * the menu item do nothing. Furthermore, you'll find yourself adding
2196 * these checks all over your code, since there are doubtless many,
2197 * many things that the user could do. Instead, you can use the
2198 * following techniques:
2203 * Use gtk_widget_set_sensitive() or modal dialogs to prevent
2204 * the user from interacting with elements while the main
2205 * loop is recursing.
2210 * Avoid main loop recursion in situations where you can't handle
2211 * arbitrary callbacks. Instead, structure your code so that you
2212 * simply return to the main loop and then get called again when
2213 * there is more work to do.
2218 * Return value: The main loop recursion level in the current thread
2223 GMainDispatch *dispatch = get_dispatch ();
2224 return dispatch->depth;
2228 * g_main_current_source:
2230 * Returns the currently firing source for this thread.
2232 * Return value: (transfer none): The currently firing source or %NULL.
2237 g_main_current_source (void)
2239 GMainDispatch *dispatch = get_dispatch ();
2240 return dispatch->dispatching_sources ? dispatch->dispatching_sources->data : NULL;
2244 * g_source_is_destroyed:
2245 * @source: a #GSource
2247 * Returns whether @source has been destroyed.
2249 * This is important when you operate upon your objects
2250 * from within idle handlers, but may have freed the object
2251 * before the dispatch of your idle handler.
2255 * idle_callback (gpointer data)
2257 * SomeWidget *self = data;
2259 * GDK_THREADS_ENTER (<!-- -->);
2260 * /<!-- -->* do stuff with self *<!-- -->/
2261 * self->idle_id = 0;
2262 * GDK_THREADS_LEAVE (<!-- -->);
2268 * some_widget_do_stuff_later (SomeWidget *self)
2270 * self->idle_id = g_idle_add (idle_callback, self);
2274 * some_widget_finalize (GObject *object)
2276 * SomeWidget *self = SOME_WIDGET (object);
2278 * if (self->idle_id)
2279 * g_source_remove (self->idle_id);
2281 * G_OBJECT_CLASS (parent_class)->finalize (object);
2285 * This will fail in a multi-threaded application if the
2286 * widget is destroyed before the idle handler fires due
2287 * to the use after free in the callback. A solution, to
2288 * this particular problem, is to check to if the source
2289 * has already been destroy within the callback.
2293 * idle_callback (gpointer data)
2295 * SomeWidget *self = data;
2297 * GDK_THREADS_ENTER ();
2298 * if (!g_source_is_destroyed (g_main_current_source ()))
2300 * /<!-- -->* do stuff with self *<!-- -->/
2302 * GDK_THREADS_LEAVE ();
2308 * Return value: %TRUE if the source has been destroyed
2313 g_source_is_destroyed (GSource *source)
2315 return SOURCE_DESTROYED (source);
2318 /* Temporarily remove all this source's file descriptors from the
2319 * poll(), so that if data comes available for one of the file descriptors
2320 * we don't continually spin in the poll()
2322 /* HOLDS: source->context's lock */
2324 block_source (GSource *source)
2328 g_return_if_fail (!SOURCE_BLOCKED (source));
2330 tmp_list = source->poll_fds;
2333 g_main_context_remove_poll_unlocked (source->context, tmp_list->data);
2334 tmp_list = tmp_list->next;
2338 /* HOLDS: source->context's lock */
2340 unblock_source (GSource *source)
2344 g_return_if_fail (!SOURCE_BLOCKED (source)); /* Source already unblocked */
2345 g_return_if_fail (!SOURCE_DESTROYED (source));
2347 tmp_list = source->poll_fds;
2350 g_main_context_add_poll_unlocked (source->context, source->priority, tmp_list->data);
2351 tmp_list = tmp_list->next;
2355 /* HOLDS: context's lock */
2357 g_main_dispatch (GMainContext *context)
2359 GMainDispatch *current = get_dispatch ();
2362 for (i = 0; i < context->pending_dispatches->len; i++)
2364 GSource *source = context->pending_dispatches->pdata[i];
2366 context->pending_dispatches->pdata[i] = NULL;
2369 source->flags &= ~G_SOURCE_READY;
2371 if (!SOURCE_DESTROYED (source))
2373 gboolean was_in_call;
2374 gpointer user_data = NULL;
2375 GSourceFunc callback = NULL;
2376 GSourceCallbackFuncs *cb_funcs;
2378 gboolean need_destroy;
2380 gboolean (*dispatch) (GSource *,
2383 GSList current_source_link;
2385 dispatch = source->source_funcs->dispatch;
2386 cb_funcs = source->callback_funcs;
2387 cb_data = source->callback_data;
2390 cb_funcs->ref (cb_data);
2392 if ((source->flags & G_SOURCE_CAN_RECURSE) == 0)
2393 block_source (source);
2395 was_in_call = source->flags & G_HOOK_FLAG_IN_CALL;
2396 source->flags |= G_HOOK_FLAG_IN_CALL;
2399 cb_funcs->get (cb_data, source, &callback, &user_data);
2401 UNLOCK_CONTEXT (context);
2404 /* The on-stack allocation of the GSList is unconventional, but
2405 * we know that the lifetime of the link is bounded to this
2406 * function as the link is kept in a thread specific list and
2407 * not manipulated outside of this function and its descendants.
2408 * Avoiding the overhead of a g_slist_alloc() is useful as many
2409 * applications do little more than dispatch events.
2411 * This is a performance hack - do not revert to g_slist_prepend()!
2413 current_source_link.data = source;
2414 current_source_link.next = current->dispatching_sources;
2415 current->dispatching_sources = ¤t_source_link;
2416 need_destroy = ! dispatch (source,
2419 g_assert (current->dispatching_sources == ¤t_source_link);
2420 current->dispatching_sources = current_source_link.next;
2424 cb_funcs->unref (cb_data);
2426 LOCK_CONTEXT (context);
2429 source->flags &= ~G_HOOK_FLAG_IN_CALL;
2431 if ((source->flags & G_SOURCE_CAN_RECURSE) == 0 &&
2432 !SOURCE_DESTROYED (source))
2433 unblock_source (source);
2435 /* Note: this depends on the fact that we can't switch
2436 * sources from one main context to another
2438 if (need_destroy && !SOURCE_DESTROYED (source))
2440 g_assert (source->context == context);
2441 g_source_destroy_internal (source, context, TRUE);
2445 SOURCE_UNREF (source, context);
2448 g_ptr_array_set_size (context->pending_dispatches, 0);
2451 /* Holds context's lock */
2452 static inline GSource *
2453 next_valid_source (GMainContext *context,
2456 GSource *new_source = source ? source->next : context->source_list;
2460 if (!SOURCE_DESTROYED (new_source))
2462 new_source->ref_count++;
2466 new_source = new_source->next;
2470 SOURCE_UNREF (source, context);
2476 * g_main_context_acquire:
2477 * @context: a #GMainContext
2479 * Tries to become the owner of the specified context.
2480 * If some other thread is the owner of the context,
2481 * returns %FALSE immediately. Ownership is properly
2482 * recursive: the owner can require ownership again
2483 * and will release ownership when g_main_context_release()
2484 * is called as many times as g_main_context_acquire().
2486 * You must be the owner of a context before you
2487 * can call g_main_context_prepare(), g_main_context_query(),
2488 * g_main_context_check(), g_main_context_dispatch().
2490 * Return value: %TRUE if the operation succeeded, and
2491 * this thread is now the owner of @context.
2494 g_main_context_acquire (GMainContext *context)
2496 gboolean result = FALSE;
2497 GThread *self = G_THREAD_SELF;
2499 if (context == NULL)
2500 context = g_main_context_default ();
2502 LOCK_CONTEXT (context);
2504 if (!context->owner)
2506 context->owner = self;
2507 g_assert (context->owner_count == 0);
2510 if (context->owner == self)
2512 context->owner_count++;
2516 UNLOCK_CONTEXT (context);
2522 * g_main_context_release:
2523 * @context: a #GMainContext
2525 * Releases ownership of a context previously acquired by this thread
2526 * with g_main_context_acquire(). If the context was acquired multiple
2527 * times, the ownership will be released only when g_main_context_release()
2528 * is called as many times as it was acquired.
2531 g_main_context_release (GMainContext *context)
2533 if (context == NULL)
2534 context = g_main_context_default ();
2536 LOCK_CONTEXT (context);
2538 context->owner_count--;
2539 if (context->owner_count == 0)
2541 context->owner = NULL;
2543 if (context->waiters)
2545 GMainWaiter *waiter = context->waiters->data;
2546 gboolean loop_internal_waiter = (waiter->mutex == &context->mutex);
2547 context->waiters = g_slist_delete_link (context->waiters,
2549 if (!loop_internal_waiter)
2550 g_mutex_lock (waiter->mutex);
2552 g_cond_signal (waiter->cond);
2554 if (!loop_internal_waiter)
2555 g_mutex_unlock (waiter->mutex);
2559 UNLOCK_CONTEXT (context);
2563 * g_main_context_wait:
2564 * @context: a #GMainContext
2565 * @cond: a condition variable
2566 * @mutex: a mutex, currently held
2568 * Tries to become the owner of the specified context,
2569 * as with g_main_context_acquire(). But if another thread
2570 * is the owner, atomically drop @mutex and wait on @cond until
2571 * that owner releases ownership or until @cond is signaled, then
2572 * try again (once) to become the owner.
2574 * Return value: %TRUE if the operation succeeded, and
2575 * this thread is now the owner of @context.
2578 g_main_context_wait (GMainContext *context,
2582 gboolean result = FALSE;
2583 GThread *self = G_THREAD_SELF;
2584 gboolean loop_internal_waiter;
2586 if (context == NULL)
2587 context = g_main_context_default ();
2589 loop_internal_waiter = (mutex == &context->mutex);
2591 if (!loop_internal_waiter)
2592 LOCK_CONTEXT (context);
2594 if (context->owner && context->owner != self)
2599 waiter.mutex = mutex;
2601 context->waiters = g_slist_append (context->waiters, &waiter);
2603 if (!loop_internal_waiter)
2604 UNLOCK_CONTEXT (context);
2605 g_cond_wait (cond, mutex);
2606 if (!loop_internal_waiter)
2607 LOCK_CONTEXT (context);
2609 context->waiters = g_slist_remove (context->waiters, &waiter);
2612 if (!context->owner)
2614 context->owner = self;
2615 g_assert (context->owner_count == 0);
2618 if (context->owner == self)
2620 context->owner_count++;
2624 if (!loop_internal_waiter)
2625 UNLOCK_CONTEXT (context);
2631 * g_main_context_prepare:
2632 * @context: a #GMainContext
2633 * @priority: location to store priority of highest priority
2634 * source already ready.
2636 * Prepares to poll sources within a main loop. The resulting information
2637 * for polling is determined by calling g_main_context_query ().
2639 * Return value: %TRUE if some source is ready to be dispatched
2643 g_main_context_prepare (GMainContext *context,
2648 gint current_priority = G_MAXINT;
2651 if (context == NULL)
2652 context = g_main_context_default ();
2654 LOCK_CONTEXT (context);
2656 context->time_is_fresh = FALSE;
2658 if (context->in_check_or_prepare)
2660 g_warning ("g_main_context_prepare() called recursively from within a source's check() or "
2661 "prepare() member.");
2662 UNLOCK_CONTEXT (context);
2667 /* If recursing, finish up current dispatch, before starting over */
2668 if (context->pending_dispatches)
2671 g_main_dispatch (context, ¤t_time);
2673 UNLOCK_CONTEXT (context);
2678 /* If recursing, clear list of pending dispatches */
2680 for (i = 0; i < context->pending_dispatches->len; i++)
2682 if (context->pending_dispatches->pdata[i])
2683 SOURCE_UNREF ((GSource *)context->pending_dispatches->pdata[i], context);
2685 g_ptr_array_set_size (context->pending_dispatches, 0);
2687 /* Prepare all sources */
2689 context->timeout = -1;
2691 source = next_valid_source (context, NULL);
2694 gint source_timeout = -1;
2696 if ((n_ready > 0) && (source->priority > current_priority))
2698 SOURCE_UNREF (source, context);
2701 if (SOURCE_BLOCKED (source))
2704 if (!(source->flags & G_SOURCE_READY))
2707 gboolean (*prepare) (GSource *source,
2710 prepare = source->source_funcs->prepare;
2711 context->in_check_or_prepare++;
2712 UNLOCK_CONTEXT (context);
2714 result = (*prepare) (source, &source_timeout);
2716 LOCK_CONTEXT (context);
2717 context->in_check_or_prepare--;
2721 GSource *ready_source = source;
2723 while (ready_source)
2725 ready_source->flags |= G_SOURCE_READY;
2726 ready_source = ready_source->priv ? ready_source->priv->parent_source : NULL;
2731 if (source->flags & G_SOURCE_READY)
2734 current_priority = source->priority;
2735 context->timeout = 0;
2738 if (source_timeout >= 0)
2740 if (context->timeout < 0)
2741 context->timeout = source_timeout;
2743 context->timeout = MIN (context->timeout, source_timeout);
2747 source = next_valid_source (context, source);
2750 UNLOCK_CONTEXT (context);
2753 *priority = current_priority;
2755 return (n_ready > 0);
2759 * g_main_context_query:
2760 * @context: a #GMainContext
2761 * @max_priority: maximum priority source to check
2762 * @timeout_: (out): location to store timeout to be used in polling
2763 * @fds: (out caller-allocates) (array length=n_fds): location to
2764 * store #GPollFD records that need to be polled.
2765 * @n_fds: length of @fds.
2767 * Determines information necessary to poll this main loop.
2769 * Return value: the number of records actually stored in @fds,
2770 * or, if more than @n_fds records need to be stored, the number
2771 * of records that need to be stored.
2774 g_main_context_query (GMainContext *context,
2783 LOCK_CONTEXT (context);
2785 pollrec = context->poll_records;
2787 while (pollrec && max_priority >= pollrec->priority)
2789 /* We need to include entries with fd->events == 0 in the array because
2790 * otherwise if the application changes fd->events behind our back and
2791 * makes it non-zero, we'll be out of sync when we check the fds[] array.
2792 * (Changing fd->events after adding an FD wasn't an anticipated use of
2793 * this API, but it occurs in practice.) */
2796 fds[n_poll].fd = pollrec->fd->fd;
2797 /* In direct contradiction to the Unix98 spec, IRIX runs into
2798 * difficulty if you pass in POLLERR, POLLHUP or POLLNVAL
2799 * flags in the events field of the pollfd while it should
2800 * just ignoring them. So we mask them out here.
2802 fds[n_poll].events = pollrec->fd->events & ~(G_IO_ERR|G_IO_HUP|G_IO_NVAL);
2803 fds[n_poll].revents = 0;
2806 pollrec = pollrec->next;
2810 context->poll_changed = FALSE;
2814 *timeout = context->timeout;
2816 context->time_is_fresh = FALSE;
2819 UNLOCK_CONTEXT (context);
2825 * g_main_context_check:
2826 * @context: a #GMainContext
2827 * @max_priority: the maximum numerical priority of sources to check
2828 * @fds: (array length=n_fds): array of #GPollFD's that was passed to
2829 * the last call to g_main_context_query()
2830 * @n_fds: return value of g_main_context_query()
2832 * Passes the results of polling back to the main loop.
2834 * Return value: %TRUE if some sources are ready to be dispatched.
2837 g_main_context_check (GMainContext *context,
2847 LOCK_CONTEXT (context);
2849 if (context->in_check_or_prepare)
2851 g_warning ("g_main_context_check() called recursively from within a source's check() or "
2852 "prepare() member.");
2853 UNLOCK_CONTEXT (context);
2857 if (context->wake_up_rec.events)
2858 g_wakeup_acknowledge (context->wakeup);
2860 /* If the set of poll file descriptors changed, bail out
2861 * and let the main loop rerun
2863 if (context->poll_changed)
2865 UNLOCK_CONTEXT (context);
2869 pollrec = context->poll_records;
2873 if (pollrec->fd->events)
2874 pollrec->fd->revents = fds[i].revents;
2876 pollrec = pollrec->next;
2880 source = next_valid_source (context, NULL);
2883 if ((n_ready > 0) && (source->priority > max_priority))
2885 SOURCE_UNREF (source, context);
2888 if (SOURCE_BLOCKED (source))
2891 if (!(source->flags & G_SOURCE_READY))
2894 gboolean (*check) (GSource *source);
2896 check = source->source_funcs->check;
2898 context->in_check_or_prepare++;
2899 UNLOCK_CONTEXT (context);
2901 result = (*check) (source);
2903 LOCK_CONTEXT (context);
2904 context->in_check_or_prepare--;
2908 GSource *ready_source = source;
2910 while (ready_source)
2912 ready_source->flags |= G_SOURCE_READY;
2913 ready_source = ready_source->priv ? ready_source->priv->parent_source : NULL;
2918 if (source->flags & G_SOURCE_READY)
2920 source->ref_count++;
2921 g_ptr_array_add (context->pending_dispatches, source);
2925 /* never dispatch sources with less priority than the first
2926 * one we choose to dispatch
2928 max_priority = source->priority;
2932 source = next_valid_source (context, source);
2935 UNLOCK_CONTEXT (context);
2941 * g_main_context_dispatch:
2942 * @context: a #GMainContext
2944 * Dispatches all pending sources.
2947 g_main_context_dispatch (GMainContext *context)
2949 LOCK_CONTEXT (context);
2951 if (context->pending_dispatches->len > 0)
2953 g_main_dispatch (context);
2956 UNLOCK_CONTEXT (context);
2959 /* HOLDS context lock */
2961 g_main_context_iterate (GMainContext *context,
2968 gboolean some_ready;
2969 gint nfds, allocated_nfds;
2970 GPollFD *fds = NULL;
2972 UNLOCK_CONTEXT (context);
2974 if (!g_main_context_acquire (context))
2976 gboolean got_ownership;
2978 LOCK_CONTEXT (context);
2983 got_ownership = g_main_context_wait (context,
2991 LOCK_CONTEXT (context);
2993 if (!context->cached_poll_array)
2995 context->cached_poll_array_size = context->n_poll_records;
2996 context->cached_poll_array = g_new (GPollFD, context->n_poll_records);
2999 allocated_nfds = context->cached_poll_array_size;
3000 fds = context->cached_poll_array;
3002 UNLOCK_CONTEXT (context);
3004 g_main_context_prepare (context, &max_priority);
3006 while ((nfds = g_main_context_query (context, max_priority, &timeout, fds,
3007 allocated_nfds)) > allocated_nfds)
3009 LOCK_CONTEXT (context);
3011 context->cached_poll_array_size = allocated_nfds = nfds;
3012 context->cached_poll_array = fds = g_new (GPollFD, nfds);
3013 UNLOCK_CONTEXT (context);
3019 g_assert (!g_main_context_fork_detected);
3020 g_main_context_poll (context, timeout, max_priority, fds, nfds);
3022 some_ready = g_main_context_check (context, max_priority, fds, nfds);
3025 g_main_context_dispatch (context);
3027 g_main_context_release (context);
3029 LOCK_CONTEXT (context);
3035 * g_main_context_pending:
3036 * @context: a #GMainContext (if %NULL, the default context will be used)
3038 * Checks if any sources have pending events for the given context.
3040 * Return value: %TRUE if events are pending.
3043 g_main_context_pending (GMainContext *context)
3048 context = g_main_context_default();
3050 LOCK_CONTEXT (context);
3051 retval = g_main_context_iterate (context, FALSE, FALSE, G_THREAD_SELF);
3052 UNLOCK_CONTEXT (context);
3058 * g_main_context_iteration:
3059 * @context: a #GMainContext (if %NULL, the default context will be used)
3060 * @may_block: whether the call may block.
3062 * Runs a single iteration for the given main loop. This involves
3063 * checking to see if any event sources are ready to be processed,
3064 * then if no events sources are ready and @may_block is %TRUE, waiting
3065 * for a source to become ready, then dispatching the highest priority
3066 * events sources that are ready. Otherwise, if @may_block is %FALSE
3067 * sources are not waited to become ready, only those highest priority
3068 * events sources will be dispatched (if any), that are ready at this
3069 * given moment without further waiting.
3071 * Note that even when @may_block is %TRUE, it is still possible for
3072 * g_main_context_iteration() to return %FALSE, since the the wait may
3073 * be interrupted for other reasons than an event source becoming ready.
3075 * Return value: %TRUE if events were dispatched.
3078 g_main_context_iteration (GMainContext *context, gboolean may_block)
3083 context = g_main_context_default();
3085 LOCK_CONTEXT (context);
3086 retval = g_main_context_iterate (context, may_block, TRUE, G_THREAD_SELF);
3087 UNLOCK_CONTEXT (context);
3094 * @context: (allow-none): a #GMainContext (if %NULL, the default context will be used).
3095 * @is_running: set to %TRUE to indicate that the loop is running. This
3096 * is not very important since calling g_main_loop_run() will set this to
3099 * Creates a new #GMainLoop structure.
3101 * Return value: a new #GMainLoop.
3104 g_main_loop_new (GMainContext *context,
3105 gboolean is_running)
3110 context = g_main_context_default();
3112 g_main_context_ref (context);
3114 loop = g_new0 (GMainLoop, 1);
3115 loop->context = context;
3116 loop->is_running = is_running != FALSE;
3117 loop->ref_count = 1;
3124 * @loop: a #GMainLoop
3126 * Increases the reference count on a #GMainLoop object by one.
3128 * Return value: @loop
3131 g_main_loop_ref (GMainLoop *loop)
3133 g_return_val_if_fail (loop != NULL, NULL);
3134 g_return_val_if_fail (g_atomic_int_get (&loop->ref_count) > 0, NULL);
3136 g_atomic_int_inc (&loop->ref_count);
3142 * g_main_loop_unref:
3143 * @loop: a #GMainLoop
3145 * Decreases the reference count on a #GMainLoop object by one. If
3146 * the result is zero, free the loop and free all associated memory.
3149 g_main_loop_unref (GMainLoop *loop)
3151 g_return_if_fail (loop != NULL);
3152 g_return_if_fail (g_atomic_int_get (&loop->ref_count) > 0);
3154 if (!g_atomic_int_dec_and_test (&loop->ref_count))
3157 g_main_context_unref (loop->context);
3163 * @loop: a #GMainLoop
3165 * Runs a main loop until g_main_loop_quit() is called on the loop.
3166 * If this is called for the thread of the loop's #GMainContext,
3167 * it will process events from the loop, otherwise it will
3171 g_main_loop_run (GMainLoop *loop)
3173 GThread *self = G_THREAD_SELF;
3175 g_return_if_fail (loop != NULL);
3176 g_return_if_fail (g_atomic_int_get (&loop->ref_count) > 0);
3178 if (!g_main_context_acquire (loop->context))
3180 gboolean got_ownership = FALSE;
3182 /* Another thread owns this context */
3183 LOCK_CONTEXT (loop->context);
3185 g_atomic_int_inc (&loop->ref_count);
3187 if (!loop->is_running)
3188 loop->is_running = TRUE;
3190 while (loop->is_running && !got_ownership)
3191 got_ownership = g_main_context_wait (loop->context,
3192 &loop->context->cond,
3193 &loop->context->mutex);
3195 if (!loop->is_running)
3197 UNLOCK_CONTEXT (loop->context);
3199 g_main_context_release (loop->context);
3200 g_main_loop_unref (loop);
3204 g_assert (got_ownership);
3207 LOCK_CONTEXT (loop->context);
3209 if (loop->context->in_check_or_prepare)
3211 g_warning ("g_main_loop_run(): called recursively from within a source's "
3212 "check() or prepare() member, iteration not possible.");
3216 g_atomic_int_inc (&loop->ref_count);
3217 loop->is_running = TRUE;
3218 while (loop->is_running)
3219 g_main_context_iterate (loop->context, TRUE, TRUE, self);
3221 UNLOCK_CONTEXT (loop->context);
3223 g_main_context_release (loop->context);
3225 g_main_loop_unref (loop);
3230 * @loop: a #GMainLoop
3232 * Stops a #GMainLoop from running. Any calls to g_main_loop_run()
3233 * for the loop will return.
3235 * Note that sources that have already been dispatched when
3236 * g_main_loop_quit() is called will still be executed.
3239 g_main_loop_quit (GMainLoop *loop)
3241 g_return_if_fail (loop != NULL);
3242 g_return_if_fail (g_atomic_int_get (&loop->ref_count) > 0);
3244 LOCK_CONTEXT (loop->context);
3245 loop->is_running = FALSE;
3246 g_wakeup_signal (loop->context->wakeup);
3248 g_cond_broadcast (&loop->context->cond);
3250 UNLOCK_CONTEXT (loop->context);
3254 * g_main_loop_is_running:
3255 * @loop: a #GMainLoop.
3257 * Checks to see if the main loop is currently being run via g_main_loop_run().
3259 * Return value: %TRUE if the mainloop is currently being run.
3262 g_main_loop_is_running (GMainLoop *loop)
3264 g_return_val_if_fail (loop != NULL, FALSE);
3265 g_return_val_if_fail (g_atomic_int_get (&loop->ref_count) > 0, FALSE);
3267 return loop->is_running;
3271 * g_main_loop_get_context:
3272 * @loop: a #GMainLoop.
3274 * Returns the #GMainContext of @loop.
3276 * Return value: (transfer none): the #GMainContext of @loop
3279 g_main_loop_get_context (GMainLoop *loop)
3281 g_return_val_if_fail (loop != NULL, NULL);
3282 g_return_val_if_fail (g_atomic_int_get (&loop->ref_count) > 0, NULL);
3284 return loop->context;
3287 /* HOLDS: context's lock */
3289 g_main_context_poll (GMainContext *context,
3295 #ifdef G_MAIN_POLL_DEBUG
3301 GPollFunc poll_func;
3303 if (n_fds || timeout != 0)
3305 #ifdef G_MAIN_POLL_DEBUG
3306 if (_g_main_poll_debug)
3308 g_print ("polling context=%p n=%d timeout=%d\n",
3309 context, n_fds, timeout);
3310 poll_timer = g_timer_new ();
3314 LOCK_CONTEXT (context);
3316 poll_func = context->poll_func;
3318 UNLOCK_CONTEXT (context);
3319 if ((*poll_func) (fds, n_fds, timeout) < 0 && errno != EINTR)
3322 g_warning ("poll(2) failed due to: %s.",
3323 g_strerror (errno));
3325 /* If g_poll () returns -1, it has already called g_warning() */
3329 #ifdef G_MAIN_POLL_DEBUG
3330 if (_g_main_poll_debug)
3332 LOCK_CONTEXT (context);
3334 g_print ("g_main_poll(%d) timeout: %d - elapsed %12.10f seconds",
3337 g_timer_elapsed (poll_timer, NULL));
3338 g_timer_destroy (poll_timer);
3339 pollrec = context->poll_records;
3341 while (pollrec != NULL)
3346 if (fds[i].fd == pollrec->fd->fd &&
3347 pollrec->fd->events &&
3350 g_print (" [" G_POLLFD_FORMAT " :", fds[i].fd);
3351 if (fds[i].revents & G_IO_IN)
3353 if (fds[i].revents & G_IO_OUT)
3355 if (fds[i].revents & G_IO_PRI)
3357 if (fds[i].revents & G_IO_ERR)
3359 if (fds[i].revents & G_IO_HUP)
3361 if (fds[i].revents & G_IO_NVAL)
3367 pollrec = pollrec->next;
3371 UNLOCK_CONTEXT (context);
3374 } /* if (n_fds || timeout != 0) */
3378 * g_main_context_add_poll:
3379 * @context: a #GMainContext (or %NULL for the default context)
3380 * @fd: a #GPollFD structure holding information about a file
3381 * descriptor to watch.
3382 * @priority: the priority for this file descriptor which should be
3383 * the same as the priority used for g_source_attach() to ensure that the
3384 * file descriptor is polled whenever the results may be needed.
3386 * Adds a file descriptor to the set of file descriptors polled for
3387 * this context. This will very seldom be used directly. Instead
3388 * a typical event source will use g_source_add_poll() instead.
3391 g_main_context_add_poll (GMainContext *context,
3396 context = g_main_context_default ();
3398 g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
3399 g_return_if_fail (fd);
3401 LOCK_CONTEXT (context);
3402 g_main_context_add_poll_unlocked (context, priority, fd);
3403 UNLOCK_CONTEXT (context);
3406 /* HOLDS: main_loop_lock */
3408 g_main_context_add_poll_unlocked (GMainContext *context,
3412 GPollRec *prevrec, *nextrec;
3413 GPollRec *newrec = g_slice_new (GPollRec);
3415 /* This file descriptor may be checked before we ever poll */
3418 newrec->priority = priority;
3420 prevrec = context->poll_records_tail;
3422 while (prevrec && priority < prevrec->priority)
3425 prevrec = prevrec->prev;
3429 prevrec->next = newrec;
3431 context->poll_records = newrec;
3433 newrec->prev = prevrec;
3434 newrec->next = nextrec;
3437 nextrec->prev = newrec;
3439 context->poll_records_tail = newrec;
3441 context->n_poll_records++;
3443 context->poll_changed = TRUE;
3445 /* Now wake up the main loop if it is waiting in the poll() */
3446 g_wakeup_signal (context->wakeup);
3450 * g_main_context_remove_poll:
3451 * @context:a #GMainContext
3452 * @fd: a #GPollFD descriptor previously added with g_main_context_add_poll()
3454 * Removes file descriptor from the set of file descriptors to be
3455 * polled for a particular context.
3458 g_main_context_remove_poll (GMainContext *context,
3462 context = g_main_context_default ();
3464 g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
3465 g_return_if_fail (fd);
3467 LOCK_CONTEXT (context);
3468 g_main_context_remove_poll_unlocked (context, fd);
3469 UNLOCK_CONTEXT (context);
3473 g_main_context_remove_poll_unlocked (GMainContext *context,
3476 GPollRec *pollrec, *prevrec, *nextrec;
3479 pollrec = context->poll_records;
3483 nextrec = pollrec->next;
3484 if (pollrec->fd == fd)
3486 if (prevrec != NULL)
3487 prevrec->next = nextrec;
3489 context->poll_records = nextrec;
3491 if (nextrec != NULL)
3492 nextrec->prev = prevrec;
3494 context->poll_records_tail = prevrec;
3496 g_slice_free (GPollRec, pollrec);
3498 context->n_poll_records--;
3505 context->poll_changed = TRUE;
3507 /* Now wake up the main loop if it is waiting in the poll() */
3508 g_wakeup_signal (context->wakeup);
3512 * g_source_get_current_time:
3513 * @source: a #GSource
3514 * @timeval: #GTimeVal structure in which to store current time.
3516 * This function ignores @source and is otherwise the same as
3517 * g_get_current_time().
3519 * Deprecated: 2.28: use g_source_get_time() instead
3522 g_source_get_current_time (GSource *source,
3525 g_get_current_time (timeval);
3529 * g_source_get_time:
3530 * @source: a #GSource
3532 * Gets the time to be used when checking this source. The advantage of
3533 * calling this function over calling g_get_monotonic_time() directly is
3534 * that when checking multiple sources, GLib can cache a single value
3535 * instead of having to repeatedly get the system monotonic time.
3537 * The time here is the system monotonic time, if available, or some
3538 * other reasonable alternative otherwise. See g_get_monotonic_time().
3540 * Returns: the monotonic time in microseconds
3545 g_source_get_time (GSource *source)
3547 GMainContext *context;
3550 g_return_val_if_fail (source->context != NULL, 0);
3552 context = source->context;
3554 LOCK_CONTEXT (context);
3556 if (!context->time_is_fresh)
3558 context->time = g_get_monotonic_time ();
3559 context->time_is_fresh = TRUE;
3562 result = context->time;
3564 UNLOCK_CONTEXT (context);
3570 * g_main_context_set_poll_func:
3571 * @context: a #GMainContext
3572 * @func: the function to call to poll all file descriptors
3574 * Sets the function to use to handle polling of file descriptors. It
3575 * will be used instead of the poll() system call
3576 * (or GLib's replacement function, which is used where
3577 * poll() isn't available).
3579 * This function could possibly be used to integrate the GLib event
3580 * loop with an external event loop.
3583 g_main_context_set_poll_func (GMainContext *context,
3587 context = g_main_context_default ();
3589 g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
3591 LOCK_CONTEXT (context);
3594 context->poll_func = func;
3596 context->poll_func = g_poll;
3598 UNLOCK_CONTEXT (context);
3602 * g_main_context_get_poll_func:
3603 * @context: a #GMainContext
3605 * Gets the poll function set by g_main_context_set_poll_func().
3607 * Return value: the poll function
3610 g_main_context_get_poll_func (GMainContext *context)
3615 context = g_main_context_default ();
3617 g_return_val_if_fail (g_atomic_int_get (&context->ref_count) > 0, NULL);
3619 LOCK_CONTEXT (context);
3620 result = context->poll_func;
3621 UNLOCK_CONTEXT (context);
3627 * g_main_context_wakeup:
3628 * @context: a #GMainContext
3630 * If @context is currently waiting in a poll(), interrupt
3631 * the poll(), and continue the iteration process.
3634 g_main_context_wakeup (GMainContext *context)
3637 context = g_main_context_default ();
3639 g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
3641 g_wakeup_signal (context->wakeup);
3645 * g_main_context_is_owner:
3646 * @context: a #GMainContext
3648 * Determines whether this thread holds the (recursive)
3649 * ownership of this #GMainContext. This is useful to
3650 * know before waiting on another thread that may be
3651 * blocking to get ownership of @context.
3653 * Returns: %TRUE if current thread is owner of @context.
3658 g_main_context_is_owner (GMainContext *context)
3663 context = g_main_context_default ();
3665 LOCK_CONTEXT (context);
3666 is_owner = context->owner == G_THREAD_SELF;
3667 UNLOCK_CONTEXT (context);
3675 g_timeout_set_expiration (GTimeoutSource *timeout_source,
3676 gint64 current_time)
3678 timeout_source->expiration = current_time +
3679 (guint64) timeout_source->interval * 1000;
3681 if (timeout_source->seconds)
3684 static gint timer_perturb = -1;
3686 if (timer_perturb == -1)
3689 * we want a per machine/session unique 'random' value; try the dbus
3690 * address first, that has a UUID in it. If there is no dbus, use the
3691 * hostname for hashing.
3693 const char *session_bus_address = g_getenv ("DBUS_SESSION_BUS_ADDRESS");
3694 if (!session_bus_address)
3695 session_bus_address = g_getenv ("HOSTNAME");
3696 if (session_bus_address)
3697 timer_perturb = ABS ((gint) g_str_hash (session_bus_address)) % 1000000;
3702 /* We want the microseconds part of the timeout to land on the
3703 * 'timer_perturb' mark, but we need to make sure we don't try to
3704 * set the timeout in the past. We do this by ensuring that we
3705 * always only *increase* the expiration time by adding a full
3706 * second in the case that the microsecond portion decreases.
3708 timeout_source->expiration -= timer_perturb;
3710 remainder = timeout_source->expiration % 1000000;
3711 if (remainder >= 1000000/4)
3712 timeout_source->expiration += 1000000;
3714 timeout_source->expiration -= remainder;
3715 timeout_source->expiration += timer_perturb;
3720 g_timeout_prepare (GSource *source,
3723 GTimeoutSource *timeout_source = (GTimeoutSource *) source;
3724 gint64 now = g_source_get_time (source);
3726 if (now < timeout_source->expiration)
3728 /* Round up to ensure that we don't try again too early */
3729 *timeout = (timeout_source->expiration - now + 999) / 1000;
3738 g_timeout_check (GSource *source)
3740 GTimeoutSource *timeout_source = (GTimeoutSource *) source;
3741 gint64 now = g_source_get_time (source);
3743 return timeout_source->expiration <= now;
3747 g_timeout_dispatch (GSource *source,
3748 GSourceFunc callback,
3751 GTimeoutSource *timeout_source = (GTimeoutSource *)source;
3756 g_warning ("Timeout source dispatched without callback\n"
3757 "You must call g_source_set_callback().");
3761 again = callback (user_data);
3764 g_timeout_set_expiration (timeout_source, g_source_get_time (source));
3770 * g_timeout_source_new:
3771 * @interval: the timeout interval in milliseconds.
3773 * Creates a new timeout source.
3775 * The source will not initially be associated with any #GMainContext
3776 * and must be added to one with g_source_attach() before it will be
3779 * The interval given is in terms of monotonic time, not wall clock
3780 * time. See g_get_monotonic_time().
3782 * Return value: the newly-created timeout source
3785 g_timeout_source_new (guint interval)
3787 GSource *source = g_source_new (&g_timeout_funcs, sizeof (GTimeoutSource));
3788 GTimeoutSource *timeout_source = (GTimeoutSource *)source;
3790 timeout_source->interval = interval;
3791 g_timeout_set_expiration (timeout_source, g_get_monotonic_time ());
3797 * g_timeout_source_new_seconds:
3798 * @interval: the timeout interval in seconds
3800 * Creates a new timeout source.
3802 * The source will not initially be associated with any #GMainContext
3803 * and must be added to one with g_source_attach() before it will be
3806 * The scheduling granularity/accuracy of this timeout source will be
3809 * The interval given in terms of monotonic time, not wall clock time.
3810 * See g_get_monotonic_time().
3812 * Return value: the newly-created timeout source
3817 g_timeout_source_new_seconds (guint interval)
3819 GSource *source = g_source_new (&g_timeout_funcs, sizeof (GTimeoutSource));
3820 GTimeoutSource *timeout_source = (GTimeoutSource *)source;
3822 timeout_source->interval = 1000 * interval;
3823 timeout_source->seconds = TRUE;
3825 g_timeout_set_expiration (timeout_source, g_get_monotonic_time ());
3832 * g_timeout_add_full:
3833 * @priority: the priority of the timeout source. Typically this will be in
3834 * the range between #G_PRIORITY_DEFAULT and #G_PRIORITY_HIGH.
3835 * @interval: the time between calls to the function, in milliseconds
3836 * (1/1000ths of a second)
3837 * @function: function to call
3838 * @data: data to pass to @function
3839 * @notify: function to call when the timeout is removed, or %NULL
3841 * Sets a function to be called at regular intervals, with the given
3842 * priority. The function is called repeatedly until it returns
3843 * %FALSE, at which point the timeout is automatically destroyed and
3844 * the function will not be called again. The @notify function is
3845 * called when the timeout is destroyed. The first call to the
3846 * function will be at the end of the first @interval.
3848 * Note that timeout functions may be delayed, due to the processing of other
3849 * event sources. Thus they should not be relied on for precise timing.
3850 * After each call to the timeout function, the time of the next
3851 * timeout is recalculated based on the current time and the given interval
3852 * (it does not try to 'catch up' time lost in delays).
3854 * This internally creates a main loop source using g_timeout_source_new()
3855 * and attaches it to the main loop context using g_source_attach(). You can
3856 * do these steps manually if you need greater control.
3858 * The interval given in terms of monotonic time, not wall clock time.
3859 * See g_get_monotonic_time().
3861 * Return value: the ID (greater than 0) of the event source.
3862 * Rename to: g_timeout_add
3865 g_timeout_add_full (gint priority,
3867 GSourceFunc function,
3869 GDestroyNotify notify)
3874 g_return_val_if_fail (function != NULL, 0);
3876 source = g_timeout_source_new (interval);
3878 if (priority != G_PRIORITY_DEFAULT)
3879 g_source_set_priority (source, priority);
3881 g_source_set_callback (source, function, data, notify);
3882 id = g_source_attach (source, NULL);
3883 g_source_unref (source);
3890 * @interval: the time between calls to the function, in milliseconds
3891 * (1/1000ths of a second)
3892 * @function: function to call
3893 * @data: data to pass to @function
3895 * Sets a function to be called at regular intervals, with the default
3896 * priority, #G_PRIORITY_DEFAULT. The function is called repeatedly
3897 * until it returns %FALSE, at which point the timeout is automatically
3898 * destroyed and the function will not be called again. The first call
3899 * to the function will be at the end of the first @interval.
3901 * Note that timeout functions may be delayed, due to the processing of other
3902 * event sources. Thus they should not be relied on for precise timing.
3903 * After each call to the timeout function, the time of the next
3904 * timeout is recalculated based on the current time and the given interval
3905 * (it does not try to 'catch up' time lost in delays).
3907 * If you want to have a timer in the "seconds" range and do not care
3908 * about the exact time of the first call of the timer, use the
3909 * g_timeout_add_seconds() function; this function allows for more
3910 * optimizations and more efficient system power usage.
3912 * This internally creates a main loop source using g_timeout_source_new()
3913 * and attaches it to the main loop context using g_source_attach(). You can
3914 * do these steps manually if you need greater control.
3916 * The interval given is in terms of monotonic time, not wall clock
3917 * time. See g_get_monotonic_time().
3919 * Return value: the ID (greater than 0) of the event source.
3922 g_timeout_add (guint32 interval,
3923 GSourceFunc function,
3926 return g_timeout_add_full (G_PRIORITY_DEFAULT,
3927 interval, function, data, NULL);
3931 * g_timeout_add_seconds_full:
3932 * @priority: the priority of the timeout source. Typically this will be in
3933 * the range between #G_PRIORITY_DEFAULT and #G_PRIORITY_HIGH.
3934 * @interval: the time between calls to the function, in seconds
3935 * @function: function to call
3936 * @data: data to pass to @function
3937 * @notify: function to call when the timeout is removed, or %NULL
3939 * Sets a function to be called at regular intervals, with @priority.
3940 * The function is called repeatedly until it returns %FALSE, at which
3941 * point the timeout is automatically destroyed and the function will
3942 * not be called again.
3944 * Unlike g_timeout_add(), this function operates at whole second granularity.
3945 * The initial starting point of the timer is determined by the implementation
3946 * and the implementation is expected to group multiple timers together so that
3947 * they fire all at the same time.
3948 * To allow this grouping, the @interval to the first timer is rounded
3949 * and can deviate up to one second from the specified interval.
3950 * Subsequent timer iterations will generally run at the specified interval.
3952 * Note that timeout functions may be delayed, due to the processing of other
3953 * event sources. Thus they should not be relied on for precise timing.
3954 * After each call to the timeout function, the time of the next
3955 * timeout is recalculated based on the current time and the given @interval
3957 * If you want timing more precise than whole seconds, use g_timeout_add()
3960 * The grouping of timers to fire at the same time results in a more power
3961 * and CPU efficient behavior so if your timer is in multiples of seconds
3962 * and you don't require the first timer exactly one second from now, the
3963 * use of g_timeout_add_seconds() is preferred over g_timeout_add().
3965 * This internally creates a main loop source using
3966 * g_timeout_source_new_seconds() and attaches it to the main loop context
3967 * using g_source_attach(). You can do these steps manually if you need
3970 * The interval given is in terms of monotonic time, not wall clock
3971 * time. See g_get_monotonic_time().
3973 * Return value: the ID (greater than 0) of the event source.
3975 * Rename to: g_timeout_add_seconds
3979 g_timeout_add_seconds_full (gint priority,
3981 GSourceFunc function,
3983 GDestroyNotify notify)
3988 g_return_val_if_fail (function != NULL, 0);
3990 source = g_timeout_source_new_seconds (interval);
3992 if (priority != G_PRIORITY_DEFAULT)
3993 g_source_set_priority (source, priority);
3995 g_source_set_callback (source, function, data, notify);
3996 id = g_source_attach (source, NULL);
3997 g_source_unref (source);
4003 * g_timeout_add_seconds:
4004 * @interval: the time between calls to the function, in seconds
4005 * @function: function to call
4006 * @data: data to pass to @function
4008 * Sets a function to be called at regular intervals with the default
4009 * priority, #G_PRIORITY_DEFAULT. The function is called repeatedly until
4010 * it returns %FALSE, at which point the timeout is automatically destroyed
4011 * and the function will not be called again.
4013 * This internally creates a main loop source using
4014 * g_timeout_source_new_seconds() and attaches it to the main loop context
4015 * using g_source_attach(). You can do these steps manually if you need
4016 * greater control. Also see g_timeout_add_seconds_full().
4018 * Note that the first call of the timer may not be precise for timeouts
4019 * of one second. If you need finer precision and have such a timeout,
4020 * you may want to use g_timeout_add() instead.
4022 * The interval given is in terms of monotonic time, not wall clock
4023 * time. See g_get_monotonic_time().
4025 * Return value: the ID (greater than 0) of the event source.
4030 g_timeout_add_seconds (guint interval,
4031 GSourceFunc function,
4034 g_return_val_if_fail (function != NULL, 0);
4036 return g_timeout_add_seconds_full (G_PRIORITY_DEFAULT, interval, function, data, NULL);
4039 /* Child watch functions */
4044 g_child_watch_prepare (GSource *source,
4052 g_child_watch_check (GSource *source)
4054 GChildWatchSource *child_watch_source;
4055 gboolean child_exited;
4057 child_watch_source = (GChildWatchSource *) source;
4059 child_exited = child_watch_source->poll.revents & G_IO_IN;
4066 * Note: We do _not_ check for the special value of STILL_ACTIVE
4067 * since we know that the process has exited and doing so runs into
4068 * problems if the child process "happens to return STILL_ACTIVE(259)"
4069 * as Microsoft's Platform SDK puts it.
4071 if (!GetExitCodeProcess (child_watch_source->pid, &child_status))
4073 gchar *emsg = g_win32_error_message (GetLastError ());
4074 g_warning (G_STRLOC ": GetExitCodeProcess() failed: %s", emsg);
4077 child_watch_source->child_status = -1;
4080 child_watch_source->child_status = child_status;
4083 return child_exited;
4087 g_child_watch_finalize (GSource *source)
4091 #else /* G_OS_WIN32 */
4094 wake_source (GSource *source)
4096 GMainContext *context;
4098 /* This should be thread-safe:
4100 * - if the source is currently being added to a context, that
4101 * context will be woken up anyway
4103 * - if the source is currently being destroyed, we simply need not
4106 * - the memory for the source will remain valid until after the
4107 * source finalize function was called (which would remove the
4108 * source from the global list which we are currently holding the
4111 * - the GMainContext will either be NULL or point to a live
4114 * - the GMainContext will remain valid since we hold the
4115 * main_context_list lock
4117 * Since we are holding a lot of locks here, don't try to enter any
4118 * more GMainContext functions for fear of dealock -- just hit the
4119 * GWakeup and run. Even if that's safe now, it could easily become
4120 * unsafe with some very minor changes in the future, and signal
4121 * handling is not the most well-tested codepath.
4123 G_LOCK(main_context_list);
4124 context = source->context;
4126 g_wakeup_signal (context->wakeup);
4127 G_UNLOCK(main_context_list);
4131 dispatch_unix_signals (void)
4135 /* clear this first incase another one arrives while we're processing */
4136 any_unix_signal_pending = FALSE;
4138 G_LOCK(unix_signal_lock);
4140 /* handle GChildWatchSource instances */
4141 if (unix_signal_pending[SIGCHLD])
4143 unix_signal_pending[SIGCHLD] = FALSE;
4145 /* The only way we can do this is to scan all of the children.
4147 * The docs promise that we will not reap children that we are not
4148 * explicitly watching, so that ties our hands from calling
4149 * waitpid(-1). We also can't use siginfo's si_pid field since if
4150 * multiple SIGCHLD arrive at the same time, one of them can be
4151 * dropped (since a given UNIX signal can only be pending once).
4153 for (node = unix_child_watches; node; node = node->next)
4155 GChildWatchSource *source = node->data;
4157 if (!source->child_exited)
4159 if (waitpid (source->pid, &source->child_status, WNOHANG) > 0)
4161 source->child_exited = TRUE;
4163 wake_source ((GSource *) source);
4169 /* handle GUnixSignalWatchSource instances */
4170 for (node = unix_signal_watches; node; node = node->next)
4172 GUnixSignalWatchSource *source = node->data;
4174 if (!source->pending)
4176 if (unix_signal_pending[source->signum])
4178 unix_signal_pending[source->signum] = FALSE;
4179 source->pending = TRUE;
4181 wake_source ((GSource *) source);
4186 G_UNLOCK(unix_signal_lock);
4190 g_child_watch_prepare (GSource *source,
4193 GChildWatchSource *child_watch_source;
4195 child_watch_source = (GChildWatchSource *) source;
4197 return child_watch_source->child_exited;
4201 g_child_watch_check (GSource *source)
4203 GChildWatchSource *child_watch_source;
4205 child_watch_source = (GChildWatchSource *) source;
4207 return child_watch_source->child_exited;
4211 g_unix_signal_watch_prepare (GSource *source,
4214 GUnixSignalWatchSource *unix_signal_source;
4216 unix_signal_source = (GUnixSignalWatchSource *) source;
4218 return unix_signal_source->pending;
4222 g_unix_signal_watch_check (GSource *source)
4224 GUnixSignalWatchSource *unix_signal_source;
4226 unix_signal_source = (GUnixSignalWatchSource *) source;
4228 return unix_signal_source->pending;
4232 g_unix_signal_watch_dispatch (GSource *source,
4233 GSourceFunc callback,
4236 GUnixSignalWatchSource *unix_signal_source;
4238 unix_signal_source = (GUnixSignalWatchSource *) source;
4242 g_warning ("Unix signal source dispatched without callback\n"
4243 "You must call g_source_set_callback().");
4247 (callback) (user_data);
4249 unix_signal_source->pending = FALSE;
4255 ensure_unix_signal_handler_installed_unlocked (int signum)
4257 static sigset_t installed_signal_mask;
4258 static gboolean initialized;
4259 struct sigaction action;
4263 sigemptyset (&installed_signal_mask);
4264 g_get_worker_context ();
4268 if (sigismember (&installed_signal_mask, signum))
4271 sigaddset (&installed_signal_mask, signum);
4273 action.sa_handler = g_unix_signal_handler;
4274 sigemptyset (&action.sa_mask);
4275 action.sa_flags = SA_RESTART | SA_NOCLDSTOP;
4276 sigaction (signum, &action, NULL);
4280 _g_main_create_unix_signal_watch (int signum)
4283 GUnixSignalWatchSource *unix_signal_source;
4285 source = g_source_new (&g_unix_signal_funcs, sizeof (GUnixSignalWatchSource));
4286 unix_signal_source = (GUnixSignalWatchSource *) source;
4288 unix_signal_source->signum = signum;
4289 unix_signal_source->pending = FALSE;
4291 G_LOCK (unix_signal_lock);
4292 ensure_unix_signal_handler_installed_unlocked (signum);
4293 unix_signal_watches = g_slist_prepend (unix_signal_watches, unix_signal_source);
4294 if (unix_signal_pending[signum])
4295 unix_signal_source->pending = TRUE;
4296 unix_signal_pending[signum] = FALSE;
4297 G_UNLOCK (unix_signal_lock);
4303 g_unix_signal_watch_finalize (GSource *source)
4305 G_LOCK (unix_signal_lock);
4306 unix_signal_watches = g_slist_remove (unix_signal_watches, source);
4307 G_UNLOCK (unix_signal_lock);
4311 g_child_watch_finalize (GSource *source)
4313 G_LOCK (unix_signal_lock);
4314 unix_child_watches = g_slist_remove (unix_child_watches, source);
4315 G_UNLOCK (unix_signal_lock);
4318 #endif /* G_OS_WIN32 */
4321 g_child_watch_dispatch (GSource *source,
4322 GSourceFunc callback,
4325 GChildWatchSource *child_watch_source;
4326 GChildWatchFunc child_watch_callback = (GChildWatchFunc) callback;
4328 child_watch_source = (GChildWatchSource *) source;
4332 g_warning ("Child watch source dispatched without callback\n"
4333 "You must call g_source_set_callback().");
4337 (child_watch_callback) (child_watch_source->pid, child_watch_source->child_status, user_data);
4339 /* We never keep a child watch source around as the child is gone */
4346 g_unix_signal_handler (int signum)
4348 unix_signal_pending[signum] = TRUE;
4349 any_unix_signal_pending = TRUE;
4351 g_wakeup_signal (glib_worker_context->wakeup);
4354 #endif /* !G_OS_WIN32 */
4357 * g_child_watch_source_new:
4358 * @pid: process to watch. On POSIX the pid of a child process. On
4359 * Windows a handle for a process (which doesn't have to be a child).
4361 * Creates a new child_watch source.
4363 * The source will not initially be associated with any #GMainContext
4364 * and must be added to one with g_source_attach() before it will be
4367 * Note that child watch sources can only be used in conjunction with
4368 * <literal>g_spawn...</literal> when the %G_SPAWN_DO_NOT_REAP_CHILD
4371 * Note that on platforms where #GPid must be explicitly closed
4372 * (see g_spawn_close_pid()) @pid must not be closed while the
4373 * source is still active. Typically, you will want to call
4374 * g_spawn_close_pid() in the callback function for the source.
4376 * Note further that using g_child_watch_source_new() is not
4377 * compatible with calling <literal>waitpid(-1)</literal> in
4378 * the application. Calling waitpid() for individual pids will
4381 * Return value: the newly-created child watch source
4386 g_child_watch_source_new (GPid pid)
4388 GSource *source = g_source_new (&g_child_watch_funcs, sizeof (GChildWatchSource));
4389 GChildWatchSource *child_watch_source = (GChildWatchSource *)source;
4391 child_watch_source->pid = pid;
4394 child_watch_source->poll.fd = (gintptr) pid;
4395 child_watch_source->poll.events = G_IO_IN;
4397 g_source_add_poll (source, &child_watch_source->poll);
4398 #else /* G_OS_WIN32 */
4399 G_LOCK (unix_signal_lock);
4400 ensure_unix_signal_handler_installed_unlocked (SIGCHLD);
4401 unix_child_watches = g_slist_prepend (unix_child_watches, child_watch_source);
4402 if (waitpid (pid, &child_watch_source->child_status, WNOHANG) > 0)
4403 child_watch_source->child_exited = TRUE;
4404 G_UNLOCK (unix_signal_lock);
4405 #endif /* G_OS_WIN32 */
4411 * g_child_watch_add_full:
4412 * @priority: the priority of the idle source. Typically this will be in the
4413 * range between #G_PRIORITY_DEFAULT_IDLE and #G_PRIORITY_HIGH_IDLE.
4414 * @pid: process to watch. On POSIX the pid of a child process. On
4415 * Windows a handle for a process (which doesn't have to be a child).
4416 * @function: function to call
4417 * @data: data to pass to @function
4418 * @notify: function to call when the idle is removed, or %NULL
4420 * Sets a function to be called when the child indicated by @pid
4421 * exits, at the priority @priority.
4423 * If you obtain @pid from g_spawn_async() or g_spawn_async_with_pipes()
4424 * you will need to pass #G_SPAWN_DO_NOT_REAP_CHILD as flag to
4425 * the spawn function for the child watching to work.
4427 * Note that on platforms where #GPid must be explicitly closed
4428 * (see g_spawn_close_pid()) @pid must not be closed while the
4429 * source is still active. Typically, you will want to call
4430 * g_spawn_close_pid() in the callback function for the source.
4432 * GLib supports only a single callback per process id.
4434 * This internally creates a main loop source using
4435 * g_child_watch_source_new() and attaches it to the main loop context
4436 * using g_source_attach(). You can do these steps manually if you
4437 * need greater control.
4439 * Return value: the ID (greater than 0) of the event source.
4441 * Rename to: g_child_watch_add
4445 g_child_watch_add_full (gint priority,
4447 GChildWatchFunc function,
4449 GDestroyNotify notify)
4454 g_return_val_if_fail (function != NULL, 0);
4456 source = g_child_watch_source_new (pid);
4458 if (priority != G_PRIORITY_DEFAULT)
4459 g_source_set_priority (source, priority);
4461 g_source_set_callback (source, (GSourceFunc) function, data, notify);
4462 id = g_source_attach (source, NULL);
4463 g_source_unref (source);
4469 * g_child_watch_add:
4470 * @pid: process id to watch. On POSIX the pid of a child process. On
4471 * Windows a handle for a process (which doesn't have to be a child).
4472 * @function: function to call
4473 * @data: data to pass to @function
4475 * Sets a function to be called when the child indicated by @pid
4476 * exits, at a default priority, #G_PRIORITY_DEFAULT.
4478 * If you obtain @pid from g_spawn_async() or g_spawn_async_with_pipes()
4479 * you will need to pass #G_SPAWN_DO_NOT_REAP_CHILD as flag to
4480 * the spawn function for the child watching to work.
4482 * Note that on platforms where #GPid must be explicitly closed
4483 * (see g_spawn_close_pid()) @pid must not be closed while the
4484 * source is still active. Typically, you will want to call
4485 * g_spawn_close_pid() in the callback function for the source.
4487 * GLib supports only a single callback per process id.
4489 * This internally creates a main loop source using
4490 * g_child_watch_source_new() and attaches it to the main loop context
4491 * using g_source_attach(). You can do these steps manually if you
4492 * need greater control.
4494 * Return value: the ID (greater than 0) of the event source.
4499 g_child_watch_add (GPid pid,
4500 GChildWatchFunc function,
4503 return g_child_watch_add_full (G_PRIORITY_DEFAULT, pid, function, data, NULL);
4507 /* Idle functions */
4510 g_idle_prepare (GSource *source,
4519 g_idle_check (GSource *source)
4525 g_idle_dispatch (GSource *source,
4526 GSourceFunc callback,
4531 g_warning ("Idle source dispatched without callback\n"
4532 "You must call g_source_set_callback().");
4536 return callback (user_data);
4540 * g_idle_source_new:
4542 * Creates a new idle source.
4544 * The source will not initially be associated with any #GMainContext
4545 * and must be added to one with g_source_attach() before it will be
4546 * executed. Note that the default priority for idle sources is
4547 * %G_PRIORITY_DEFAULT_IDLE, as compared to other sources which
4548 * have a default priority of %G_PRIORITY_DEFAULT.
4550 * Return value: the newly-created idle source
4553 g_idle_source_new (void)
4557 source = g_source_new (&g_idle_funcs, sizeof (GSource));
4558 g_source_set_priority (source, G_PRIORITY_DEFAULT_IDLE);
4565 * @priority: the priority of the idle source. Typically this will be in the
4566 * range between #G_PRIORITY_DEFAULT_IDLE and #G_PRIORITY_HIGH_IDLE.
4567 * @function: function to call
4568 * @data: data to pass to @function
4569 * @notify: function to call when the idle is removed, or %NULL
4571 * Adds a function to be called whenever there are no higher priority
4572 * events pending. If the function returns %FALSE it is automatically
4573 * removed from the list of event sources and will not be called again.
4575 * This internally creates a main loop source using g_idle_source_new()
4576 * and attaches it to the main loop context using g_source_attach().
4577 * You can do these steps manually if you need greater control.
4579 * Return value: the ID (greater than 0) of the event source.
4580 * Rename to: g_idle_add
4583 g_idle_add_full (gint priority,
4584 GSourceFunc function,
4586 GDestroyNotify notify)
4591 g_return_val_if_fail (function != NULL, 0);
4593 source = g_idle_source_new ();
4595 if (priority != G_PRIORITY_DEFAULT_IDLE)
4596 g_source_set_priority (source, priority);
4598 g_source_set_callback (source, function, data, notify);
4599 id = g_source_attach (source, NULL);
4600 g_source_unref (source);
4607 * @function: function to call
4608 * @data: data to pass to @function.
4610 * Adds a function to be called whenever there are no higher priority
4611 * events pending to the default main loop. The function is given the
4612 * default idle priority, #G_PRIORITY_DEFAULT_IDLE. If the function
4613 * returns %FALSE it is automatically removed from the list of event
4614 * sources and will not be called again.
4616 * This internally creates a main loop source using g_idle_source_new()
4617 * and attaches it to the main loop context using g_source_attach().
4618 * You can do these steps manually if you need greater control.
4620 * Return value: the ID (greater than 0) of the event source.
4623 g_idle_add (GSourceFunc function,
4626 return g_idle_add_full (G_PRIORITY_DEFAULT_IDLE, function, data, NULL);
4630 * g_idle_remove_by_data:
4631 * @data: the data for the idle source's callback.
4633 * Removes the idle function with the given data.
4635 * Return value: %TRUE if an idle source was found and removed.
4638 g_idle_remove_by_data (gpointer data)
4640 return g_source_remove_by_funcs_user_data (&g_idle_funcs, data);
4644 * g_main_context_invoke:
4645 * @context: (allow-none): a #GMainContext, or %NULL
4646 * @function: function to call
4647 * @data: data to pass to @function
4649 * Invokes a function in such a way that @context is owned during the
4650 * invocation of @function.
4652 * If @context is %NULL then the global default main context — as
4653 * returned by g_main_context_default() — is used.
4655 * If @context is owned by the current thread, @function is called
4656 * directly. Otherwise, if @context is the thread-default main context
4657 * of the current thread and g_main_context_acquire() succeeds, then
4658 * @function is called and g_main_context_release() is called
4661 * In any other case, an idle source is created to call @function and
4662 * that source is attached to @context (presumably to be run in another
4663 * thread). The idle source is attached with #G_PRIORITY_DEFAULT
4664 * priority. If you want a different priority, use
4665 * g_main_context_invoke_full().
4667 * Note that, as with normal idle functions, @function should probably
4668 * return %FALSE. If it returns %TRUE, it will be continuously run in a
4669 * loop (and may prevent this call from returning).
4674 g_main_context_invoke (GMainContext *context,
4675 GSourceFunc function,
4678 g_main_context_invoke_full (context,
4680 function, data, NULL);
4684 * g_main_context_invoke_full:
4685 * @context: (allow-none): a #GMainContext, or %NULL
4686 * @priority: the priority at which to run @function
4687 * @function: function to call
4688 * @data: data to pass to @function
4689 * @notify: a function to call when @data is no longer in use, or %NULL.
4691 * Invokes a function in such a way that @context is owned during the
4692 * invocation of @function.
4694 * This function is the same as g_main_context_invoke() except that it
4695 * lets you specify the priority incase @function ends up being
4696 * scheduled as an idle and also lets you give a #GDestroyNotify for @data.
4698 * @notify should not assume that it is called from any particular
4699 * thread or with any particular context acquired.
4704 g_main_context_invoke_full (GMainContext *context,
4706 GSourceFunc function,
4708 GDestroyNotify notify)
4710 g_return_if_fail (function != NULL);
4713 context = g_main_context_default ();
4715 if (g_main_context_is_owner (context))
4717 while (function (data));
4724 GMainContext *thread_default;
4726 thread_default = g_main_context_get_thread_default ();
4728 if (!thread_default)
4729 thread_default = g_main_context_default ();
4731 if (thread_default == context && g_main_context_acquire (context))
4733 while (function (data));
4735 g_main_context_release (context);
4744 source = g_idle_source_new ();
4745 g_source_set_priority (source, priority);
4746 g_source_set_callback (source, function, data, notify);
4747 g_source_attach (source, context);
4748 g_source_unref (source);
4754 glib_worker_main (gpointer data)
4758 g_main_context_iteration (glib_worker_context, TRUE);
4761 if (any_unix_signal_pending)
4762 dispatch_unix_signals ();
4766 return NULL; /* worst GCC warning message ever... */
4770 g_get_worker_context (void)
4772 static gsize initialised;
4774 if (g_once_init_enter (&initialised))
4776 GError *error = NULL;
4778 glib_worker_context = g_main_context_new ();
4779 if (g_thread_new ("gmain", glib_worker_main, NULL, FALSE, &error) == NULL)
4780 g_error ("Creating GLib worker thread failed: %s\n", error->message);
4782 g_once_init_leave (&initialised, TRUE);
4785 return glib_worker_context;