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"
90 #include "gthreadprivate.h"
96 #ifdef G_MAIN_POLL_DEBUG
102 #include "glib-private.h"
106 * @title: The Main Event Loop
107 * @short_description: manages all available sources of events
109 * The main event loop manages all the available sources of events for
110 * GLib and GTK+ applications. These events can come from any number of
111 * different types of sources such as file descriptors (plain files,
112 * pipes or sockets) and timeouts. New types of event sources can also
113 * be added using g_source_attach().
115 * To allow multiple independent sets of sources to be handled in
116 * different threads, each source is associated with a #GMainContext.
117 * A GMainContext can only be running in a single thread, but
118 * sources can be added to it and removed from it from other threads.
120 * Each event source is assigned a priority. The default priority,
121 * #G_PRIORITY_DEFAULT, is 0. Values less than 0 denote higher priorities.
122 * Values greater than 0 denote lower priorities. Events from high priority
123 * sources are always processed before events from lower priority sources.
125 * Idle functions can also be added, and assigned a priority. These will
126 * be run whenever no events with a higher priority are ready to be processed.
128 * The #GMainLoop data type represents a main event loop. A GMainLoop is
129 * created with g_main_loop_new(). After adding the initial event sources,
130 * g_main_loop_run() is called. This continuously checks for new events from
131 * each of the event sources and dispatches them. Finally, the processing of
132 * an event from one of the sources leads to a call to g_main_loop_quit() to
133 * exit the main loop, and g_main_loop_run() returns.
135 * It is possible to create new instances of #GMainLoop recursively.
136 * This is often used in GTK+ applications when showing modal dialog
137 * boxes. Note that event sources are associated with a particular
138 * #GMainContext, and will be checked and dispatched for all main
139 * loops associated with that GMainContext.
141 * GTK+ contains wrappers of some of these functions, e.g. gtk_main(),
142 * gtk_main_quit() and gtk_events_pending().
144 * <refsect2><title>Creating new source types</title>
145 * <para>One of the unusual features of the #GMainLoop functionality
146 * is that new types of event source can be created and used in
147 * addition to the builtin type of event source. A new event source
148 * type is used for handling GDK events. A new source type is created
149 * by <firstterm>deriving</firstterm> from the #GSource structure.
150 * The derived type of source is represented by a structure that has
151 * the #GSource structure as a first element, and other elements specific
152 * to the new source type. To create an instance of the new source type,
153 * call g_source_new() passing in the size of the derived structure and
154 * a table of functions. These #GSourceFuncs determine the behavior of
155 * the new source type.</para>
156 * <para>New source types basically interact with the main context
157 * in two ways. Their prepare function in #GSourceFuncs can set a timeout
158 * to determine the maximum amount of time that the main loop will sleep
159 * before checking the source again. In addition, or as well, the source
160 * can add file descriptors to the set that the main context checks using
161 * g_source_add_poll().</para>
163 * <refsect2><title>Customizing the main loop iteration</title>
164 * <para>Single iterations of a #GMainContext can be run with
165 * g_main_context_iteration(). In some cases, more detailed control
166 * of exactly how the details of the main loop work is desired, for
167 * instance, when integrating the #GMainLoop with an external main loop.
168 * In such cases, you can call the component functions of
169 * g_main_context_iteration() directly. These functions are
170 * g_main_context_prepare(), g_main_context_query(),
171 * g_main_context_check() and g_main_context_dispatch().</para>
172 * <para>The operation of these functions can best be seen in terms
173 * of a state diagram, as shown in <xref linkend="mainloop-states"/>.</para>
174 * <figure id="mainloop-states"><title>States of a Main Context</title>
175 * <graphic fileref="mainloop-states.gif" format="GIF"></graphic>
179 * On Unix, the GLib mainloop is incompatible with fork(). Any program
180 * using the mainloop must either exec() or exit() from the child
181 * without returning to the mainloop.
186 typedef struct _GTimeoutSource GTimeoutSource;
187 typedef struct _GChildWatchSource GChildWatchSource;
188 typedef struct _GUnixSignalWatchSource GUnixSignalWatchSource;
189 typedef struct _GPollRec GPollRec;
190 typedef struct _GSourceCallback GSourceCallback;
194 G_SOURCE_READY = 1 << G_HOOK_FLAG_USER_SHIFT,
195 G_SOURCE_CAN_RECURSE = 1 << (G_HOOK_FLAG_USER_SHIFT + 1)
198 typedef struct _GMainWaiter GMainWaiter;
206 typedef struct _GMainDispatch GMainDispatch;
208 struct _GMainDispatch
211 GSList *dispatching_sources; /* stack of current sources */
214 #ifdef G_MAIN_POLL_DEBUG
215 gboolean _g_main_poll_debug = FALSE;
220 /* The following lock is used for both the list of sources
221 * and the list of poll records
231 GPtrArray *pending_dispatches;
232 gint timeout; /* Timeout for current iteration */
235 GSource *source_list;
236 gint in_check_or_prepare;
238 GPollRec *poll_records, *poll_records_tail;
239 guint n_poll_records;
240 GPollFD *cached_poll_array;
241 guint cached_poll_array_size;
247 /* Flag indicating whether the set of fd's changed during a poll */
248 gboolean poll_changed;
253 gboolean time_is_fresh;
256 struct _GSourceCallback
261 GDestroyNotify notify;
266 GMainContext *context;
271 struct _GTimeoutSource
279 struct _GChildWatchSource
286 #else /* G_OS_WIN32 */
287 gboolean child_exited;
288 #endif /* G_OS_WIN32 */
291 struct _GUnixSignalWatchSource
306 struct _GSourcePrivate
308 GSList *child_sources;
309 GSource *parent_source;
312 #define LOCK_CONTEXT(context) g_mutex_lock (&context->mutex)
313 #define UNLOCK_CONTEXT(context) g_mutex_unlock (&context->mutex)
314 #define G_THREAD_SELF g_thread_self ()
316 #define SOURCE_DESTROYED(source) (((source)->flags & G_HOOK_FLAG_ACTIVE) == 0)
317 #define SOURCE_BLOCKED(source) (((source)->flags & G_HOOK_FLAG_IN_CALL) != 0 && \
318 ((source)->flags & G_SOURCE_CAN_RECURSE) == 0)
320 #define SOURCE_UNREF(source, context) \
322 if ((source)->ref_count > 1) \
323 (source)->ref_count--; \
325 g_source_unref_internal ((source), (context), TRUE); \
329 /* Forward declarations */
331 static void g_source_unref_internal (GSource *source,
332 GMainContext *context,
334 static void g_source_destroy_internal (GSource *source,
335 GMainContext *context,
337 static void g_source_set_priority_unlocked (GSource *source,
338 GMainContext *context,
340 static void g_main_context_poll (GMainContext *context,
345 static void g_main_context_add_poll_unlocked (GMainContext *context,
348 static void g_main_context_remove_poll_unlocked (GMainContext *context,
351 static gboolean g_timeout_prepare (GSource *source,
353 static gboolean g_timeout_check (GSource *source);
354 static gboolean g_timeout_dispatch (GSource *source,
355 GSourceFunc callback,
357 static gboolean g_child_watch_prepare (GSource *source,
359 static gboolean g_child_watch_check (GSource *source);
360 static gboolean g_child_watch_dispatch (GSource *source,
361 GSourceFunc callback,
363 static void g_child_watch_finalize (GSource *source);
365 static void g_unix_signal_handler (int signum);
366 static gboolean g_unix_signal_watch_prepare (GSource *source,
368 static gboolean g_unix_signal_watch_check (GSource *source);
369 static gboolean g_unix_signal_watch_dispatch (GSource *source,
370 GSourceFunc callback,
372 static void g_unix_signal_watch_finalize (GSource *source);
374 static gboolean g_idle_prepare (GSource *source,
376 static gboolean g_idle_check (GSource *source);
377 static gboolean g_idle_dispatch (GSource *source,
378 GSourceFunc callback,
381 static GMainContext *glib_worker_context;
382 static gboolean g_main_context_fork_detected;
384 G_LOCK_DEFINE_STATIC (main_loop);
385 static GMainContext *default_main_context;
390 /* UNIX signals work by marking one of these variables then waking the
391 * worker context to check on them and dispatch accordingly.
393 static volatile gchar unix_signal_pending[NSIG];
394 static volatile gboolean any_unix_signal_pending;
396 /* Guards all the data below */
397 G_LOCK_DEFINE_STATIC (unix_signal_lock);
398 static GSList *unix_signal_watches;
399 static GSList *unix_child_watches;
401 static GSourceFuncs g_unix_signal_funcs =
403 g_unix_signal_watch_prepare,
404 g_unix_signal_watch_check,
405 g_unix_signal_watch_dispatch,
406 g_unix_signal_watch_finalize
408 #endif /* !G_OS_WIN32 */
409 G_LOCK_DEFINE_STATIC (main_context_list);
410 static GSList *main_context_list = NULL;
412 GSourceFuncs g_timeout_funcs =
420 GSourceFuncs g_child_watch_funcs =
422 g_child_watch_prepare,
424 g_child_watch_dispatch,
425 g_child_watch_finalize
428 GSourceFuncs g_idle_funcs =
437 * g_main_context_ref:
438 * @context: a #GMainContext
440 * Increases the reference count on a #GMainContext object by one.
442 * Returns: the @context that was passed in (since 2.6)
445 g_main_context_ref (GMainContext *context)
447 g_return_val_if_fail (context != NULL, NULL);
448 g_return_val_if_fail (g_atomic_int_get (&context->ref_count) > 0, NULL);
450 g_atomic_int_inc (&context->ref_count);
456 poll_rec_list_free (GMainContext *context,
459 g_slice_free_chain (GPollRec, list, next);
463 * g_main_context_unref:
464 * @context: a #GMainContext
466 * Decreases the reference count on a #GMainContext object by one. If
467 * the result is zero, free the context and free all associated memory.
470 g_main_context_unref (GMainContext *context)
473 g_return_if_fail (context != NULL);
474 g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
476 if (!g_atomic_int_dec_and_test (&context->ref_count))
479 G_LOCK (main_context_list);
480 main_context_list = g_slist_remove (main_context_list, context);
481 G_UNLOCK (main_context_list);
483 source = context->source_list;
486 GSource *next = source->next;
487 g_source_destroy_internal (source, context, FALSE);
491 g_mutex_clear (&context->mutex);
493 g_ptr_array_free (context->pending_dispatches, TRUE);
494 g_free (context->cached_poll_array);
496 poll_rec_list_free (context, context->poll_records);
498 g_wakeup_free (context->wakeup);
499 g_cond_clear (&context->cond);
506 g_main_context_forked (void)
508 g_main_context_fork_detected = TRUE;
513 * g_main_context_new:
515 * Creates a new #GMainContext structure.
517 * Return value: the new #GMainContext
520 g_main_context_new (void)
522 static gsize initialised;
523 GMainContext *context;
525 if (g_once_init_enter (&initialised))
527 #ifdef G_MAIN_POLL_DEBUG
528 if (getenv ("G_MAIN_POLL_DEBUG") != NULL)
529 _g_main_poll_debug = TRUE;
533 pthread_atfork (NULL, NULL, g_main_context_forked);
536 g_once_init_leave (&initialised, TRUE);
539 context = g_new0 (GMainContext, 1);
541 g_mutex_init (&context->mutex);
542 g_cond_init (&context->cond);
544 context->owner = NULL;
545 context->waiters = NULL;
547 context->ref_count = 1;
549 context->next_id = 1;
551 context->source_list = NULL;
553 context->poll_func = g_poll;
555 context->cached_poll_array = NULL;
556 context->cached_poll_array_size = 0;
558 context->pending_dispatches = g_ptr_array_new ();
560 context->time_is_fresh = FALSE;
562 context->wakeup = g_wakeup_new ();
563 g_wakeup_get_pollfd (context->wakeup, &context->wake_up_rec);
564 g_main_context_add_poll_unlocked (context, 0, &context->wake_up_rec);
566 G_LOCK (main_context_list);
567 main_context_list = g_slist_append (main_context_list, context);
569 #ifdef G_MAIN_POLL_DEBUG
570 if (_g_main_poll_debug)
571 g_print ("created context=%p\n", context);
574 G_UNLOCK (main_context_list);
580 * g_main_context_default:
582 * Returns the global default main context. This is the main context
583 * used for main loop functions when a main loop is not explicitly
584 * specified, and corresponds to the "main" main loop. See also
585 * g_main_context_get_thread_default().
587 * Return value: (transfer none): the global default main context.
590 g_main_context_default (void)
596 if (!default_main_context)
598 default_main_context = g_main_context_new ();
599 #ifdef G_MAIN_POLL_DEBUG
600 if (_g_main_poll_debug)
601 g_print ("default context=%p\n", default_main_context);
605 G_UNLOCK (main_loop);
607 return default_main_context;
610 static GStaticPrivate thread_context_stack = G_STATIC_PRIVATE_INIT;
613 free_context_stack (gpointer data)
615 GQueue *stack = data;
616 GMainContext *context;
618 while (!g_queue_is_empty (stack))
620 context = g_queue_pop_head (stack);
621 g_main_context_release (context);
623 g_main_context_unref (context);
625 g_queue_free (stack);
629 * g_main_context_push_thread_default:
630 * @context: a #GMainContext, or %NULL for the global default context
632 * Acquires @context and sets it as the thread-default context for the
633 * current thread. This will cause certain asynchronous operations
634 * (such as most <link linkend="gio">gio</link>-based I/O) which are
635 * started in this thread to run under @context and deliver their
636 * results to its main loop, rather than running under the global
637 * default context in the main thread. Note that calling this function
638 * changes the context returned by
639 * g_main_context_get_thread_default(), <emphasis>not</emphasis> the
640 * one returned by g_main_context_default(), so it does not affect the
641 * context used by functions like g_idle_add().
643 * Normally you would call this function shortly after creating a new
644 * thread, passing it a #GMainContext which will be run by a
645 * #GMainLoop in that thread, to set a new default context for all
646 * async operations in that thread. (In this case, you don't need to
647 * ever call g_main_context_pop_thread_default().) In some cases
648 * however, you may want to schedule a single operation in a
649 * non-default context, or temporarily use a non-default context in
650 * the main thread. In that case, you can wrap the call to the
651 * asynchronous operation inside a
652 * g_main_context_push_thread_default() /
653 * g_main_context_pop_thread_default() pair, but it is up to you to
654 * ensure that no other asynchronous operations accidentally get
655 * started while the non-default context is active.
657 * Beware that libraries that predate this function may not correctly
658 * handle being used from a thread with a thread-default context. Eg,
659 * see g_file_supports_thread_contexts().
664 g_main_context_push_thread_default (GMainContext *context)
667 gboolean acquired_context;
669 acquired_context = g_main_context_acquire (context);
670 g_return_if_fail (acquired_context);
672 if (context == g_main_context_default ())
675 g_main_context_ref (context);
677 stack = g_static_private_get (&thread_context_stack);
680 stack = g_queue_new ();
681 g_static_private_set (&thread_context_stack, stack,
685 g_queue_push_head (stack, context);
689 * g_main_context_pop_thread_default:
690 * @context: a #GMainContext object, or %NULL
692 * Pops @context off the thread-default context stack (verifying that
693 * it was on the top of the stack).
698 g_main_context_pop_thread_default (GMainContext *context)
702 if (context == g_main_context_default ())
705 stack = g_static_private_get (&thread_context_stack);
707 g_return_if_fail (stack != NULL);
708 g_return_if_fail (g_queue_peek_head (stack) == context);
710 g_queue_pop_head (stack);
712 g_main_context_release (context);
714 g_main_context_unref (context);
718 * g_main_context_get_thread_default:
720 * Gets the thread-default #GMainContext for this thread. Asynchronous
721 * operations that want to be able to be run in contexts other than
722 * the default one should call this method or
723 * g_main_context_ref_thread_default() to get a #GMainContext to add
724 * their #GSource<!-- -->s to. (Note that even in single-threaded
725 * programs applications may sometimes want to temporarily push a
726 * non-default context, so it is not safe to assume that this will
727 * always return %NULL if you are running in the default thread.)
729 * If you need to hold a reference on the context, use
730 * g_main_context_ref_thread_default() instead.
732 * Returns: (transfer none): the thread-default #GMainContext, or
733 * %NULL if the thread-default context is the global default context.
738 g_main_context_get_thread_default (void)
742 stack = g_static_private_get (&thread_context_stack);
744 return g_queue_peek_head (stack);
750 * g_main_context_ref_thread_default:
752 * Gets the thread-default #GMainContext for this thread, as with
753 * g_main_context_get_thread_default(), but also adds a reference to
754 * it with g_main_context_ref(). In addition, unlike
755 * g_main_context_get_thread_default(), if the thread-default context
756 * is the global default context, this will return that #GMainContext
757 * (with a ref added to it) rather than returning %NULL.
759 * Returns: (transfer full): the thread-default #GMainContext. Unref
760 * with g_main_context_unref() when you are done with it.
765 g_main_context_ref_thread_default (void)
767 GMainContext *context;
769 context = g_main_context_get_thread_default ();
771 context = g_main_context_default ();
772 return g_main_context_ref (context);
775 /* Hooks for adding to the main loop */
779 * @source_funcs: structure containing functions that implement
780 * the sources behavior.
781 * @struct_size: size of the #GSource structure to create.
783 * Creates a new #GSource structure. The size is specified to
784 * allow creating structures derived from #GSource that contain
785 * additional data. The size passed in must be at least
786 * <literal>sizeof (GSource)</literal>.
788 * The source will not initially be associated with any #GMainContext
789 * and must be added to one with g_source_attach() before it will be
792 * Return value: the newly-created #GSource.
795 g_source_new (GSourceFuncs *source_funcs,
800 g_return_val_if_fail (source_funcs != NULL, NULL);
801 g_return_val_if_fail (struct_size >= sizeof (GSource), NULL);
803 source = (GSource*) g_malloc0 (struct_size);
805 source->source_funcs = source_funcs;
806 source->ref_count = 1;
808 source->priority = G_PRIORITY_DEFAULT;
810 source->flags = G_HOOK_FLAG_ACTIVE;
812 /* NULL/0 initialization for all other fields */
817 /* Holds context's lock
820 g_source_list_add (GSource *source,
821 GMainContext *context)
823 GSource *tmp_source, *last_source;
825 if (source->priv && source->priv->parent_source)
827 /* Put the source immediately before its parent */
828 tmp_source = source->priv->parent_source;
829 last_source = source->priv->parent_source->prev;
834 tmp_source = context->source_list;
835 while (tmp_source && tmp_source->priority <= source->priority)
837 last_source = tmp_source;
838 tmp_source = tmp_source->next;
842 source->next = tmp_source;
844 tmp_source->prev = source;
846 source->prev = last_source;
848 last_source->next = source;
850 context->source_list = source;
853 /* Holds context's lock
856 g_source_list_remove (GSource *source,
857 GMainContext *context)
860 source->prev->next = source->next;
862 context->source_list = source->next;
865 source->next->prev = source->prev;
872 g_source_attach_unlocked (GSource *source,
873 GMainContext *context)
878 source->context = context;
879 result = source->source_id = context->next_id++;
882 g_source_list_add (source, context);
884 tmp_list = source->poll_fds;
887 g_main_context_add_poll_unlocked (context, source->priority, tmp_list->data);
888 tmp_list = tmp_list->next;
893 tmp_list = source->priv->child_sources;
896 g_source_attach_unlocked (tmp_list->data, context);
897 tmp_list = tmp_list->next;
906 * @source: a #GSource
907 * @context: a #GMainContext (if %NULL, the default context will be used)
909 * Adds a #GSource to a @context so that it will be executed within
910 * that context. Remove it by calling g_source_destroy().
912 * Return value: the ID (greater than 0) for the source within the
916 g_source_attach (GSource *source,
917 GMainContext *context)
921 g_return_val_if_fail (source->context == NULL, 0);
922 g_return_val_if_fail (!SOURCE_DESTROYED (source), 0);
925 context = g_main_context_default ();
927 LOCK_CONTEXT (context);
929 result = g_source_attach_unlocked (source, context);
931 /* If another thread has acquired the context, wake it up since it
932 * might be in poll() right now.
934 if (context->owner && context->owner != G_THREAD_SELF)
935 g_wakeup_signal (context->wakeup);
937 UNLOCK_CONTEXT (context);
943 g_source_destroy_internal (GSource *source,
944 GMainContext *context,
948 LOCK_CONTEXT (context);
950 if (!SOURCE_DESTROYED (source))
953 gpointer old_cb_data;
954 GSourceCallbackFuncs *old_cb_funcs;
956 source->flags &= ~G_HOOK_FLAG_ACTIVE;
958 old_cb_data = source->callback_data;
959 old_cb_funcs = source->callback_funcs;
961 source->callback_data = NULL;
962 source->callback_funcs = NULL;
966 UNLOCK_CONTEXT (context);
967 old_cb_funcs->unref (old_cb_data);
968 LOCK_CONTEXT (context);
971 if (!SOURCE_BLOCKED (source))
973 tmp_list = source->poll_fds;
976 g_main_context_remove_poll_unlocked (context, tmp_list->data);
977 tmp_list = tmp_list->next;
981 if (source->priv && source->priv->child_sources)
983 /* This is safe because even if a child_source finalizer or
984 * closure notify tried to modify source->priv->child_sources
985 * from outside the lock, it would fail since
986 * SOURCE_DESTROYED(source) is now TRUE.
988 tmp_list = source->priv->child_sources;
991 g_source_destroy_internal (tmp_list->data, context, TRUE);
992 g_source_unref_internal (tmp_list->data, context, TRUE);
993 tmp_list = tmp_list->next;
995 g_slist_free (source->priv->child_sources);
996 source->priv->child_sources = NULL;
999 g_source_unref_internal (source, context, TRUE);
1003 UNLOCK_CONTEXT (context);
1008 * @source: a #GSource
1010 * Removes a source from its #GMainContext, if any, and mark it as
1011 * destroyed. The source cannot be subsequently added to another
1015 g_source_destroy (GSource *source)
1017 GMainContext *context;
1019 g_return_if_fail (source != NULL);
1021 context = source->context;
1024 g_source_destroy_internal (source, context, FALSE);
1026 source->flags &= ~G_HOOK_FLAG_ACTIVE;
1031 * @source: a #GSource
1033 * Returns the numeric ID for a particular source. The ID of a source
1034 * is a positive integer which is unique within a particular main loop
1035 * context. The reverse
1036 * mapping from ID to source is done by g_main_context_find_source_by_id().
1038 * Return value: the ID (greater than 0) for the source
1041 g_source_get_id (GSource *source)
1045 g_return_val_if_fail (source != NULL, 0);
1046 g_return_val_if_fail (source->context != NULL, 0);
1048 LOCK_CONTEXT (source->context);
1049 result = source->source_id;
1050 UNLOCK_CONTEXT (source->context);
1056 * g_source_get_context:
1057 * @source: a #GSource
1059 * Gets the #GMainContext with which the source is associated.
1060 * Calling this function on a destroyed source is an error.
1062 * Return value: (transfer none): the #GMainContext with which the
1063 * source is associated, or %NULL if the context has not
1064 * yet been added to a source.
1067 g_source_get_context (GSource *source)
1069 g_return_val_if_fail (!SOURCE_DESTROYED (source), NULL);
1071 return source->context;
1075 * g_source_add_poll:
1076 * @source:a #GSource
1077 * @fd: a #GPollFD structure holding information about a file
1078 * descriptor to watch.
1080 * Adds a file descriptor to the set of file descriptors polled for
1081 * this source. This is usually combined with g_source_new() to add an
1082 * event source. The event source's check function will typically test
1083 * the @revents field in the #GPollFD struct and return %TRUE if events need
1087 g_source_add_poll (GSource *source,
1090 GMainContext *context;
1092 g_return_if_fail (source != NULL);
1093 g_return_if_fail (fd != NULL);
1094 g_return_if_fail (!SOURCE_DESTROYED (source));
1096 context = source->context;
1099 LOCK_CONTEXT (context);
1101 source->poll_fds = g_slist_prepend (source->poll_fds, fd);
1105 if (!SOURCE_BLOCKED (source))
1106 g_main_context_add_poll_unlocked (context, source->priority, fd);
1107 UNLOCK_CONTEXT (context);
1112 * g_source_remove_poll:
1113 * @source:a #GSource
1114 * @fd: a #GPollFD structure previously passed to g_source_add_poll().
1116 * Removes a file descriptor from the set of file descriptors polled for
1120 g_source_remove_poll (GSource *source,
1123 GMainContext *context;
1125 g_return_if_fail (source != NULL);
1126 g_return_if_fail (fd != NULL);
1127 g_return_if_fail (!SOURCE_DESTROYED (source));
1129 context = source->context;
1132 LOCK_CONTEXT (context);
1134 source->poll_fds = g_slist_remove (source->poll_fds, fd);
1138 if (!SOURCE_BLOCKED (source))
1139 g_main_context_remove_poll_unlocked (context, fd);
1140 UNLOCK_CONTEXT (context);
1145 * g_source_add_child_source:
1146 * @source:a #GSource
1147 * @child_source: a second #GSource that @source should "poll"
1149 * Adds @child_source to @source as a "polled" source; when @source is
1150 * added to a #GMainContext, @child_source will be automatically added
1151 * with the same priority, when @child_source is triggered, it will
1152 * cause @source to dispatch (in addition to calling its own
1153 * callback), and when @source is destroyed, it will destroy
1154 * @child_source as well. (@source will also still be dispatched if
1155 * its own prepare/check functions indicate that it is ready.)
1157 * If you don't need @child_source to do anything on its own when it
1158 * triggers, you can call g_source_set_dummy_callback() on it to set a
1159 * callback that does nothing (except return %TRUE if appropriate).
1161 * @source will hold a reference on @child_source while @child_source
1162 * is attached to it.
1167 g_source_add_child_source (GSource *source,
1168 GSource *child_source)
1170 GMainContext *context;
1172 g_return_if_fail (source != NULL);
1173 g_return_if_fail (child_source != NULL);
1174 g_return_if_fail (!SOURCE_DESTROYED (source));
1175 g_return_if_fail (!SOURCE_DESTROYED (child_source));
1176 g_return_if_fail (child_source->context == NULL);
1177 g_return_if_fail (child_source->priv == NULL || child_source->priv->parent_source == NULL);
1179 context = source->context;
1182 LOCK_CONTEXT (context);
1185 source->priv = g_slice_new0 (GSourcePrivate);
1186 if (!child_source->priv)
1187 child_source->priv = g_slice_new0 (GSourcePrivate);
1189 source->priv->child_sources = g_slist_prepend (source->priv->child_sources,
1190 g_source_ref (child_source));
1191 child_source->priv->parent_source = source;
1192 g_source_set_priority_unlocked (child_source, context, source->priority);
1196 UNLOCK_CONTEXT (context);
1197 g_source_attach (child_source, context);
1202 * g_source_remove_child_source:
1203 * @source:a #GSource
1204 * @child_source: a #GSource previously passed to
1205 * g_source_add_child_source().
1207 * Detaches @child_source from @source and destroys it.
1212 g_source_remove_child_source (GSource *source,
1213 GSource *child_source)
1215 GMainContext *context;
1217 g_return_if_fail (source != NULL);
1218 g_return_if_fail (child_source != NULL);
1219 g_return_if_fail (child_source->priv != NULL && child_source->priv->parent_source == source);
1220 g_return_if_fail (!SOURCE_DESTROYED (source));
1221 g_return_if_fail (!SOURCE_DESTROYED (child_source));
1223 context = source->context;
1226 LOCK_CONTEXT (context);
1228 source->priv->child_sources = g_slist_remove (source->priv->child_sources, child_source);
1229 g_source_destroy_internal (child_source, context, TRUE);
1230 g_source_unref_internal (child_source, context, TRUE);
1233 UNLOCK_CONTEXT (context);
1237 * g_source_set_callback_indirect:
1238 * @source: the source
1239 * @callback_data: pointer to callback data "object"
1240 * @callback_funcs: functions for reference counting @callback_data
1241 * and getting the callback and data
1243 * Sets the callback function storing the data as a refcounted callback
1244 * "object". This is used internally. Note that calling
1245 * g_source_set_callback_indirect() assumes
1246 * an initial reference count on @callback_data, and thus
1247 * @callback_funcs->unref will eventually be called once more
1248 * than @callback_funcs->ref.
1251 g_source_set_callback_indirect (GSource *source,
1252 gpointer callback_data,
1253 GSourceCallbackFuncs *callback_funcs)
1255 GMainContext *context;
1256 gpointer old_cb_data;
1257 GSourceCallbackFuncs *old_cb_funcs;
1259 g_return_if_fail (source != NULL);
1260 g_return_if_fail (callback_funcs != NULL || callback_data == NULL);
1262 context = source->context;
1265 LOCK_CONTEXT (context);
1267 old_cb_data = source->callback_data;
1268 old_cb_funcs = source->callback_funcs;
1270 source->callback_data = callback_data;
1271 source->callback_funcs = callback_funcs;
1274 UNLOCK_CONTEXT (context);
1277 old_cb_funcs->unref (old_cb_data);
1281 g_source_callback_ref (gpointer cb_data)
1283 GSourceCallback *callback = cb_data;
1285 callback->ref_count++;
1290 g_source_callback_unref (gpointer cb_data)
1292 GSourceCallback *callback = cb_data;
1294 callback->ref_count--;
1295 if (callback->ref_count == 0)
1297 if (callback->notify)
1298 callback->notify (callback->data);
1304 g_source_callback_get (gpointer cb_data,
1309 GSourceCallback *callback = cb_data;
1311 *func = callback->func;
1312 *data = callback->data;
1315 static GSourceCallbackFuncs g_source_callback_funcs = {
1316 g_source_callback_ref,
1317 g_source_callback_unref,
1318 g_source_callback_get,
1322 * g_source_set_callback:
1323 * @source: the source
1324 * @func: a callback function
1325 * @data: the data to pass to callback function
1326 * @notify: a function to call when @data is no longer in use, or %NULL.
1328 * Sets the callback function for a source. The callback for a source is
1329 * called from the source's dispatch function.
1331 * The exact type of @func depends on the type of source; ie. you
1332 * should not count on @func being called with @data as its first
1335 * Typically, you won't use this function. Instead use functions specific
1336 * to the type of source you are using.
1339 g_source_set_callback (GSource *source,
1342 GDestroyNotify notify)
1344 GSourceCallback *new_callback;
1346 g_return_if_fail (source != NULL);
1348 new_callback = g_new (GSourceCallback, 1);
1350 new_callback->ref_count = 1;
1351 new_callback->func = func;
1352 new_callback->data = data;
1353 new_callback->notify = notify;
1355 g_source_set_callback_indirect (source, new_callback, &g_source_callback_funcs);
1360 * g_source_set_funcs:
1361 * @source: a #GSource
1362 * @funcs: the new #GSourceFuncs
1364 * Sets the source functions (can be used to override
1365 * default implementations) of an unattached source.
1370 g_source_set_funcs (GSource *source,
1371 GSourceFuncs *funcs)
1373 g_return_if_fail (source != NULL);
1374 g_return_if_fail (source->context == NULL);
1375 g_return_if_fail (source->ref_count > 0);
1376 g_return_if_fail (funcs != NULL);
1378 source->source_funcs = funcs;
1382 g_source_set_priority_unlocked (GSource *source,
1383 GMainContext *context,
1388 source->priority = priority;
1392 /* Remove the source from the context's source and then
1393 * add it back so it is sorted in the correct place
1395 g_source_list_remove (source, source->context);
1396 g_source_list_add (source, source->context);
1398 if (!SOURCE_BLOCKED (source))
1400 tmp_list = source->poll_fds;
1403 g_main_context_remove_poll_unlocked (context, tmp_list->data);
1404 g_main_context_add_poll_unlocked (context, priority, tmp_list->data);
1406 tmp_list = tmp_list->next;
1411 if (source->priv && source->priv->child_sources)
1413 tmp_list = source->priv->child_sources;
1416 g_source_set_priority_unlocked (tmp_list->data, context, priority);
1417 tmp_list = tmp_list->next;
1423 * g_source_set_priority:
1424 * @source: a #GSource
1425 * @priority: the new priority.
1427 * Sets the priority of a source. While the main loop is being run, a
1428 * source will be dispatched if it is ready to be dispatched and no
1429 * sources at a higher (numerically smaller) priority are ready to be
1433 g_source_set_priority (GSource *source,
1436 GMainContext *context;
1438 g_return_if_fail (source != NULL);
1440 context = source->context;
1443 LOCK_CONTEXT (context);
1444 g_source_set_priority_unlocked (source, context, priority);
1446 UNLOCK_CONTEXT (source->context);
1450 * g_source_get_priority:
1451 * @source: a #GSource
1453 * Gets the priority of a source.
1455 * Return value: the priority of the source
1458 g_source_get_priority (GSource *source)
1460 g_return_val_if_fail (source != NULL, 0);
1462 return source->priority;
1466 * g_source_set_can_recurse:
1467 * @source: a #GSource
1468 * @can_recurse: whether recursion is allowed for this source
1470 * Sets whether a source can be called recursively. If @can_recurse is
1471 * %TRUE, then while the source is being dispatched then this source
1472 * will be processed normally. Otherwise, all processing of this
1473 * source is blocked until the dispatch function returns.
1476 g_source_set_can_recurse (GSource *source,
1477 gboolean can_recurse)
1479 GMainContext *context;
1481 g_return_if_fail (source != NULL);
1483 context = source->context;
1486 LOCK_CONTEXT (context);
1489 source->flags |= G_SOURCE_CAN_RECURSE;
1491 source->flags &= ~G_SOURCE_CAN_RECURSE;
1494 UNLOCK_CONTEXT (context);
1498 * g_source_get_can_recurse:
1499 * @source: a #GSource
1501 * Checks whether a source is allowed to be called recursively.
1502 * see g_source_set_can_recurse().
1504 * Return value: whether recursion is allowed.
1507 g_source_get_can_recurse (GSource *source)
1509 g_return_val_if_fail (source != NULL, FALSE);
1511 return (source->flags & G_SOURCE_CAN_RECURSE) != 0;
1516 * g_source_set_name:
1517 * @source: a #GSource
1518 * @name: debug name for the source
1520 * Sets a name for the source, used in debugging and profiling.
1521 * The name defaults to #NULL.
1523 * The source name should describe in a human-readable way
1524 * what the source does. For example, "X11 event queue"
1525 * or "GTK+ repaint idle handler" or whatever it is.
1527 * It is permitted to call this function multiple times, but is not
1528 * recommended due to the potential performance impact. For example,
1529 * one could change the name in the "check" function of a #GSourceFuncs
1530 * to include details like the event type in the source name.
1535 g_source_set_name (GSource *source,
1538 g_return_if_fail (source != NULL);
1540 /* setting back to NULL is allowed, just because it's
1541 * weird if get_name can return NULL but you can't
1545 g_free (source->name);
1546 source->name = g_strdup (name);
1550 * g_source_get_name:
1551 * @source: a #GSource
1553 * Gets a name for the source, used in debugging and profiling.
1554 * The name may be #NULL if it has never been set with
1555 * g_source_set_name().
1557 * Return value: the name of the source
1561 g_source_get_name (GSource *source)
1563 g_return_val_if_fail (source != NULL, NULL);
1565 return source->name;
1569 * g_source_set_name_by_id:
1570 * @tag: a #GSource ID
1571 * @name: debug name for the source
1573 * Sets the name of a source using its ID.
1575 * This is a convenience utility to set source names from the return
1576 * value of g_idle_add(), g_timeout_add(), etc.
1581 g_source_set_name_by_id (guint tag,
1586 g_return_if_fail (tag > 0);
1588 source = g_main_context_find_source_by_id (NULL, tag);
1592 g_source_set_name (source, name);
1598 * @source: a #GSource
1600 * Increases the reference count on a source by one.
1602 * Return value: @source
1605 g_source_ref (GSource *source)
1607 GMainContext *context;
1609 g_return_val_if_fail (source != NULL, NULL);
1611 context = source->context;
1614 LOCK_CONTEXT (context);
1616 source->ref_count++;
1619 UNLOCK_CONTEXT (context);
1624 /* g_source_unref() but possible to call within context lock
1627 g_source_unref_internal (GSource *source,
1628 GMainContext *context,
1631 gpointer old_cb_data = NULL;
1632 GSourceCallbackFuncs *old_cb_funcs = NULL;
1634 g_return_if_fail (source != NULL);
1636 if (!have_lock && context)
1637 LOCK_CONTEXT (context);
1639 source->ref_count--;
1640 if (source->ref_count == 0)
1642 old_cb_data = source->callback_data;
1643 old_cb_funcs = source->callback_funcs;
1645 source->callback_data = NULL;
1646 source->callback_funcs = NULL;
1650 if (!SOURCE_DESTROYED (source))
1651 g_warning (G_STRLOC ": ref_count == 0, but source was still attached to a context!");
1652 g_source_list_remove (source, context);
1655 if (source->source_funcs->finalize)
1658 UNLOCK_CONTEXT (context);
1659 source->source_funcs->finalize (source);
1661 LOCK_CONTEXT (context);
1664 g_free (source->name);
1665 source->name = NULL;
1667 g_slist_free (source->poll_fds);
1668 source->poll_fds = NULL;
1672 g_slice_free (GSourcePrivate, source->priv);
1673 source->priv = NULL;
1679 if (!have_lock && context)
1680 UNLOCK_CONTEXT (context);
1685 UNLOCK_CONTEXT (context);
1687 old_cb_funcs->unref (old_cb_data);
1690 LOCK_CONTEXT (context);
1696 * @source: a #GSource
1698 * Decreases the reference count of a source by one. If the
1699 * resulting reference count is zero the source and associated
1700 * memory will be destroyed.
1703 g_source_unref (GSource *source)
1705 g_return_if_fail (source != NULL);
1707 g_source_unref_internal (source, source->context, FALSE);
1711 * g_main_context_find_source_by_id:
1712 * @context: a #GMainContext (if %NULL, the default context will be used)
1713 * @source_id: the source ID, as returned by g_source_get_id().
1715 * Finds a #GSource given a pair of context and ID.
1717 * Return value: (transfer none): the #GSource if found, otherwise, %NULL
1720 g_main_context_find_source_by_id (GMainContext *context,
1725 g_return_val_if_fail (source_id > 0, NULL);
1727 if (context == NULL)
1728 context = g_main_context_default ();
1730 LOCK_CONTEXT (context);
1732 source = context->source_list;
1735 if (!SOURCE_DESTROYED (source) &&
1736 source->source_id == source_id)
1738 source = source->next;
1741 UNLOCK_CONTEXT (context);
1747 * g_main_context_find_source_by_funcs_user_data:
1748 * @context: a #GMainContext (if %NULL, the default context will be used).
1749 * @funcs: the @source_funcs passed to g_source_new().
1750 * @user_data: the user data from the callback.
1752 * Finds a source with the given source functions and user data. If
1753 * multiple sources exist with the same source function and user data,
1754 * the first one found will be returned.
1756 * Return value: (transfer none): the source, if one was found, otherwise %NULL
1759 g_main_context_find_source_by_funcs_user_data (GMainContext *context,
1760 GSourceFuncs *funcs,
1765 g_return_val_if_fail (funcs != NULL, NULL);
1767 if (context == NULL)
1768 context = g_main_context_default ();
1770 LOCK_CONTEXT (context);
1772 source = context->source_list;
1775 if (!SOURCE_DESTROYED (source) &&
1776 source->source_funcs == funcs &&
1777 source->callback_funcs)
1779 GSourceFunc callback;
1780 gpointer callback_data;
1782 source->callback_funcs->get (source->callback_data, source, &callback, &callback_data);
1784 if (callback_data == user_data)
1787 source = source->next;
1790 UNLOCK_CONTEXT (context);
1796 * g_main_context_find_source_by_user_data:
1797 * @context: a #GMainContext
1798 * @user_data: the user_data for the callback.
1800 * Finds a source with the given user data for the callback. If
1801 * multiple sources exist with the same user data, the first
1802 * one found will be returned.
1804 * Return value: (transfer none): the source, if one was found, otherwise %NULL
1807 g_main_context_find_source_by_user_data (GMainContext *context,
1812 if (context == NULL)
1813 context = g_main_context_default ();
1815 LOCK_CONTEXT (context);
1817 source = context->source_list;
1820 if (!SOURCE_DESTROYED (source) &&
1821 source->callback_funcs)
1823 GSourceFunc callback;
1824 gpointer callback_data = NULL;
1826 source->callback_funcs->get (source->callback_data, source, &callback, &callback_data);
1828 if (callback_data == user_data)
1831 source = source->next;
1834 UNLOCK_CONTEXT (context);
1841 * @tag: the ID of the source to remove.
1843 * Removes the source with the given id from the default main context.
1845 * a #GSource is given by g_source_get_id(), or will be returned by the
1846 * functions g_source_attach(), g_idle_add(), g_idle_add_full(),
1847 * g_timeout_add(), g_timeout_add_full(), g_child_watch_add(),
1848 * g_child_watch_add_full(), g_io_add_watch(), and g_io_add_watch_full().
1850 * See also g_source_destroy(). You must use g_source_destroy() for sources
1851 * added to a non-default main context.
1853 * Return value: %TRUE if the source was found and removed.
1856 g_source_remove (guint tag)
1860 g_return_val_if_fail (tag > 0, FALSE);
1862 source = g_main_context_find_source_by_id (NULL, tag);
1864 g_source_destroy (source);
1866 return source != NULL;
1870 * g_source_remove_by_user_data:
1871 * @user_data: the user_data for the callback.
1873 * Removes a source from the default main loop context given the user
1874 * data for the callback. If multiple sources exist with the same user
1875 * data, only one will be destroyed.
1877 * Return value: %TRUE if a source was found and removed.
1880 g_source_remove_by_user_data (gpointer user_data)
1884 source = g_main_context_find_source_by_user_data (NULL, user_data);
1887 g_source_destroy (source);
1895 * g_source_remove_by_funcs_user_data:
1896 * @funcs: The @source_funcs passed to g_source_new()
1897 * @user_data: the user data for the callback
1899 * Removes a source from the default main loop context given the
1900 * source functions and user data. If multiple sources exist with the
1901 * same source functions and user data, only one will be destroyed.
1903 * Return value: %TRUE if a source was found and removed.
1906 g_source_remove_by_funcs_user_data (GSourceFuncs *funcs,
1911 g_return_val_if_fail (funcs != NULL, FALSE);
1913 source = g_main_context_find_source_by_funcs_user_data (NULL, funcs, user_data);
1916 g_source_destroy (source);
1924 * g_get_current_time:
1925 * @result: #GTimeVal structure in which to store current time.
1927 * Equivalent to the UNIX gettimeofday() function, but portable.
1929 * You may find g_get_real_time() to be more convenient.
1932 g_get_current_time (GTimeVal *result)
1937 g_return_if_fail (result != NULL);
1939 /*this is required on alpha, there the timeval structs are int's
1940 not longs and a cast only would fail horribly*/
1941 gettimeofday (&r, NULL);
1942 result->tv_sec = r.tv_sec;
1943 result->tv_usec = r.tv_usec;
1948 g_return_if_fail (result != NULL);
1950 GetSystemTimeAsFileTime (&ft);
1951 memmove (&time64, &ft, sizeof (FILETIME));
1953 /* Convert from 100s of nanoseconds since 1601-01-01
1954 * to Unix epoch. Yes, this is Y2038 unsafe.
1956 time64 -= G_GINT64_CONSTANT (116444736000000000);
1959 result->tv_sec = time64 / 1000000;
1960 result->tv_usec = time64 % 1000000;
1967 * Queries the system wall-clock time.
1969 * This call is functionally equivalent to g_get_current_time() except
1970 * that the return value is often more convenient than dealing with a
1973 * You should only use this call if you are actually interested in the real
1974 * wall-clock time. g_get_monotonic_time() is probably more useful for
1975 * measuring intervals.
1977 * Returns: the number of microseconds since January 1, 1970 UTC.
1982 g_get_real_time (void)
1986 g_get_current_time (&tv);
1988 return (((gint64) tv.tv_sec) * 1000000) + tv.tv_usec;
1992 * g_get_monotonic_time:
1994 * Queries the system monotonic time, if available.
1996 * On POSIX systems with clock_gettime() and %CLOCK_MONOTONIC this call
1997 * is a very shallow wrapper for that. Otherwise, we make a best effort
1998 * that probably involves returning the wall clock time (with at least
1999 * microsecond accuracy, subject to the limitations of the OS kernel).
2001 * It's important to note that POSIX %CLOCK_MONOTONIC does not count
2002 * time spent while the machine is suspended.
2004 * On Windows, "limitations of the OS kernel" is a rather substantial
2005 * statement. Depending on the configuration of the system, the wall
2006 * clock time is updated as infrequently as 64 times a second (which
2007 * is approximately every 16ms).
2009 * Returns: the monotonic time, in microseconds
2014 g_get_monotonic_time (void)
2016 #ifdef HAVE_CLOCK_GETTIME
2017 /* librt clock_gettime() is our first choice */
2019 #ifdef HAVE_MONOTONIC_CLOCK
2020 static volatile gsize clockid = 0;
2022 static clockid_t clockid = CLOCK_REALTIME;
2026 #ifdef HAVE_MONOTONIC_CLOCK
2027 if (g_once_init_enter (&clockid))
2029 clockid_t best_clockid;
2031 if (sysconf (_SC_MONOTONIC_CLOCK) >= 0)
2032 best_clockid = CLOCK_MONOTONIC;
2034 best_clockid = CLOCK_REALTIME;
2035 g_once_init_leave (&clockid, (gsize)best_clockid);
2039 clock_gettime (clockid, &ts);
2041 /* In theory monotonic time can have any epoch.
2043 * glib presently assumes the following:
2045 * 1) The epoch comes some time after the birth of Jesus of Nazareth, but
2046 * not more than 10000 years later.
2048 * 2) The current time also falls sometime within this range.
2050 * These two reasonable assumptions leave us with a maximum deviation from
2051 * the epoch of 10000 years, or 315569520000000000 seconds.
2053 * If we restrict ourselves to this range then the number of microseconds
2054 * will always fit well inside the constraints of a int64 (by a factor of
2057 * If you actually hit the following assertion, probably you should file a
2058 * bug against your operating system for being excessively silly.
2060 g_assert (G_GINT64_CONSTANT (-315569520000000000) < ts.tv_sec &&
2061 ts.tv_sec < G_GINT64_CONSTANT (315569520000000000));
2063 return (((gint64) ts.tv_sec) * 1000000) + (ts.tv_nsec / 1000);
2066 /* It may look like we are discarding accuracy on Windows (since its
2067 * current time is expressed in 100s of nanoseconds) but according to
2068 * many sources, the time is only updated 64 times per second, so
2069 * microsecond accuracy is more than enough.
2074 g_get_current_time (&tv);
2076 return (((gint64) tv.tv_sec) * 1000000) + tv.tv_usec;
2082 g_main_dispatch_free (gpointer dispatch)
2084 g_slice_free (GMainDispatch, dispatch);
2087 /* Running the main loop */
2089 static GMainDispatch *
2092 static GStaticPrivate depth_private = G_STATIC_PRIVATE_INIT;
2093 GMainDispatch *dispatch = g_static_private_get (&depth_private);
2096 dispatch = g_slice_new0 (GMainDispatch);
2097 g_static_private_set (&depth_private, dispatch, g_main_dispatch_free);
2106 * Returns the depth of the stack of calls to
2107 * g_main_context_dispatch() on any #GMainContext in the current thread.
2108 * That is, when called from the toplevel, it gives 0. When
2109 * called from within a callback from g_main_context_iteration()
2110 * (or g_main_loop_run(), etc.) it returns 1. When called from within
2111 * a callback to a recursive call to g_main_context_iteration(),
2112 * it returns 2. And so forth.
2114 * This function is useful in a situation like the following:
2115 * Imagine an extremely simple "garbage collected" system.
2118 * static GList *free_list;
2121 * allocate_memory (gsize size)
2123 * gpointer result = g_malloc (size);
2124 * free_list = g_list_prepend (free_list, result);
2129 * free_allocated_memory (void)
2132 * for (l = free_list; l; l = l->next);
2134 * g_list_free (free_list);
2142 * g_main_context_iteration (NULL, TRUE);
2143 * free_allocated_memory();
2147 * This works from an application, however, if you want to do the same
2148 * thing from a library, it gets more difficult, since you no longer
2149 * control the main loop. You might think you can simply use an idle
2150 * function to make the call to free_allocated_memory(), but that
2151 * doesn't work, since the idle function could be called from a
2152 * recursive callback. This can be fixed by using g_main_depth()
2156 * allocate_memory (gsize size)
2158 * FreeListBlock *block = g_new (FreeListBlock, 1);
2159 * block->mem = g_malloc (size);
2160 * block->depth = g_main_depth ();
2161 * free_list = g_list_prepend (free_list, block);
2162 * return block->mem;
2166 * free_allocated_memory (void)
2170 * int depth = g_main_depth ();
2171 * for (l = free_list; l; );
2173 * GList *next = l->next;
2174 * FreeListBlock *block = l->data;
2175 * if (block->depth > depth)
2177 * g_free (block->mem);
2179 * free_list = g_list_delete_link (free_list, l);
2187 * There is a temptation to use g_main_depth() to solve
2188 * problems with reentrancy. For instance, while waiting for data
2189 * to be received from the network in response to a menu item,
2190 * the menu item might be selected again. It might seem that
2191 * one could make the menu item's callback return immediately
2192 * and do nothing if g_main_depth() returns a value greater than 1.
2193 * However, this should be avoided since the user then sees selecting
2194 * the menu item do nothing. Furthermore, you'll find yourself adding
2195 * these checks all over your code, since there are doubtless many,
2196 * many things that the user could do. Instead, you can use the
2197 * following techniques:
2202 * Use gtk_widget_set_sensitive() or modal dialogs to prevent
2203 * the user from interacting with elements while the main
2204 * loop is recursing.
2209 * Avoid main loop recursion in situations where you can't handle
2210 * arbitrary callbacks. Instead, structure your code so that you
2211 * simply return to the main loop and then get called again when
2212 * there is more work to do.
2217 * Return value: The main loop recursion level in the current thread
2222 GMainDispatch *dispatch = get_dispatch ();
2223 return dispatch->depth;
2227 * g_main_current_source:
2229 * Returns the currently firing source for this thread.
2231 * Return value: (transfer none): The currently firing source or %NULL.
2236 g_main_current_source (void)
2238 GMainDispatch *dispatch = get_dispatch ();
2239 return dispatch->dispatching_sources ? dispatch->dispatching_sources->data : NULL;
2243 * g_source_is_destroyed:
2244 * @source: a #GSource
2246 * Returns whether @source has been destroyed.
2248 * This is important when you operate upon your objects
2249 * from within idle handlers, but may have freed the object
2250 * before the dispatch of your idle handler.
2254 * idle_callback (gpointer data)
2256 * SomeWidget *self = data;
2258 * GDK_THREADS_ENTER (<!-- -->);
2259 * /<!-- -->* do stuff with self *<!-- -->/
2260 * self->idle_id = 0;
2261 * GDK_THREADS_LEAVE (<!-- -->);
2267 * some_widget_do_stuff_later (SomeWidget *self)
2269 * self->idle_id = g_idle_add (idle_callback, self);
2273 * some_widget_finalize (GObject *object)
2275 * SomeWidget *self = SOME_WIDGET (object);
2277 * if (self->idle_id)
2278 * g_source_remove (self->idle_id);
2280 * G_OBJECT_CLASS (parent_class)->finalize (object);
2284 * This will fail in a multi-threaded application if the
2285 * widget is destroyed before the idle handler fires due
2286 * to the use after free in the callback. A solution, to
2287 * this particular problem, is to check to if the source
2288 * has already been destroy within the callback.
2292 * idle_callback (gpointer data)
2294 * SomeWidget *self = data;
2296 * GDK_THREADS_ENTER ();
2297 * if (!g_source_is_destroyed (g_main_current_source ()))
2299 * /<!-- -->* do stuff with self *<!-- -->/
2301 * GDK_THREADS_LEAVE ();
2307 * Return value: %TRUE if the source has been destroyed
2312 g_source_is_destroyed (GSource *source)
2314 return SOURCE_DESTROYED (source);
2317 /* Temporarily remove all this source's file descriptors from the
2318 * poll(), so that if data comes available for one of the file descriptors
2319 * we don't continually spin in the poll()
2321 /* HOLDS: source->context's lock */
2323 block_source (GSource *source)
2327 g_return_if_fail (!SOURCE_BLOCKED (source));
2329 tmp_list = source->poll_fds;
2332 g_main_context_remove_poll_unlocked (source->context, tmp_list->data);
2333 tmp_list = tmp_list->next;
2337 /* HOLDS: source->context's lock */
2339 unblock_source (GSource *source)
2343 g_return_if_fail (!SOURCE_BLOCKED (source)); /* Source already unblocked */
2344 g_return_if_fail (!SOURCE_DESTROYED (source));
2346 tmp_list = source->poll_fds;
2349 g_main_context_add_poll_unlocked (source->context, source->priority, tmp_list->data);
2350 tmp_list = tmp_list->next;
2354 /* HOLDS: context's lock */
2356 g_main_dispatch (GMainContext *context)
2358 GMainDispatch *current = get_dispatch ();
2361 for (i = 0; i < context->pending_dispatches->len; i++)
2363 GSource *source = context->pending_dispatches->pdata[i];
2365 context->pending_dispatches->pdata[i] = NULL;
2368 source->flags &= ~G_SOURCE_READY;
2370 if (!SOURCE_DESTROYED (source))
2372 gboolean was_in_call;
2373 gpointer user_data = NULL;
2374 GSourceFunc callback = NULL;
2375 GSourceCallbackFuncs *cb_funcs;
2377 gboolean need_destroy;
2379 gboolean (*dispatch) (GSource *,
2382 GSList current_source_link;
2384 dispatch = source->source_funcs->dispatch;
2385 cb_funcs = source->callback_funcs;
2386 cb_data = source->callback_data;
2389 cb_funcs->ref (cb_data);
2391 if ((source->flags & G_SOURCE_CAN_RECURSE) == 0)
2392 block_source (source);
2394 was_in_call = source->flags & G_HOOK_FLAG_IN_CALL;
2395 source->flags |= G_HOOK_FLAG_IN_CALL;
2398 cb_funcs->get (cb_data, source, &callback, &user_data);
2400 UNLOCK_CONTEXT (context);
2403 /* The on-stack allocation of the GSList is unconventional, but
2404 * we know that the lifetime of the link is bounded to this
2405 * function as the link is kept in a thread specific list and
2406 * not manipulated outside of this function and its descendants.
2407 * Avoiding the overhead of a g_slist_alloc() is useful as many
2408 * applications do little more than dispatch events.
2410 * This is a performance hack - do not revert to g_slist_prepend()!
2412 current_source_link.data = source;
2413 current_source_link.next = current->dispatching_sources;
2414 current->dispatching_sources = ¤t_source_link;
2415 need_destroy = ! dispatch (source,
2418 g_assert (current->dispatching_sources == ¤t_source_link);
2419 current->dispatching_sources = current_source_link.next;
2423 cb_funcs->unref (cb_data);
2425 LOCK_CONTEXT (context);
2428 source->flags &= ~G_HOOK_FLAG_IN_CALL;
2430 if ((source->flags & G_SOURCE_CAN_RECURSE) == 0 &&
2431 !SOURCE_DESTROYED (source))
2432 unblock_source (source);
2434 /* Note: this depends on the fact that we can't switch
2435 * sources from one main context to another
2437 if (need_destroy && !SOURCE_DESTROYED (source))
2439 g_assert (source->context == context);
2440 g_source_destroy_internal (source, context, TRUE);
2444 SOURCE_UNREF (source, context);
2447 g_ptr_array_set_size (context->pending_dispatches, 0);
2450 /* Holds context's lock */
2451 static inline GSource *
2452 next_valid_source (GMainContext *context,
2455 GSource *new_source = source ? source->next : context->source_list;
2459 if (!SOURCE_DESTROYED (new_source))
2461 new_source->ref_count++;
2465 new_source = new_source->next;
2469 SOURCE_UNREF (source, context);
2475 * g_main_context_acquire:
2476 * @context: a #GMainContext
2478 * Tries to become the owner of the specified context.
2479 * If some other thread is the owner of the context,
2480 * returns %FALSE immediately. Ownership is properly
2481 * recursive: the owner can require ownership again
2482 * and will release ownership when g_main_context_release()
2483 * is called as many times as g_main_context_acquire().
2485 * You must be the owner of a context before you
2486 * can call g_main_context_prepare(), g_main_context_query(),
2487 * g_main_context_check(), g_main_context_dispatch().
2489 * Return value: %TRUE if the operation succeeded, and
2490 * this thread is now the owner of @context.
2493 g_main_context_acquire (GMainContext *context)
2495 gboolean result = FALSE;
2496 GThread *self = G_THREAD_SELF;
2498 if (context == NULL)
2499 context = g_main_context_default ();
2501 LOCK_CONTEXT (context);
2503 if (!context->owner)
2505 context->owner = self;
2506 g_assert (context->owner_count == 0);
2509 if (context->owner == self)
2511 context->owner_count++;
2515 UNLOCK_CONTEXT (context);
2521 * g_main_context_release:
2522 * @context: a #GMainContext
2524 * Releases ownership of a context previously acquired by this thread
2525 * with g_main_context_acquire(). If the context was acquired multiple
2526 * times, the ownership will be released only when g_main_context_release()
2527 * is called as many times as it was acquired.
2530 g_main_context_release (GMainContext *context)
2532 if (context == NULL)
2533 context = g_main_context_default ();
2535 LOCK_CONTEXT (context);
2537 context->owner_count--;
2538 if (context->owner_count == 0)
2540 context->owner = NULL;
2542 if (context->waiters)
2544 GMainWaiter *waiter = context->waiters->data;
2545 gboolean loop_internal_waiter = (waiter->mutex == &context->mutex);
2546 context->waiters = g_slist_delete_link (context->waiters,
2548 if (!loop_internal_waiter)
2549 g_mutex_lock (waiter->mutex);
2551 g_cond_signal (waiter->cond);
2553 if (!loop_internal_waiter)
2554 g_mutex_unlock (waiter->mutex);
2558 UNLOCK_CONTEXT (context);
2562 * g_main_context_wait:
2563 * @context: a #GMainContext
2564 * @cond: a condition variable
2565 * @mutex: a mutex, currently held
2567 * Tries to become the owner of the specified context,
2568 * as with g_main_context_acquire(). But if another thread
2569 * is the owner, atomically drop @mutex and wait on @cond until
2570 * that owner releases ownership or until @cond is signaled, then
2571 * try again (once) to become the owner.
2573 * Return value: %TRUE if the operation succeeded, and
2574 * this thread is now the owner of @context.
2577 g_main_context_wait (GMainContext *context,
2581 gboolean result = FALSE;
2582 GThread *self = G_THREAD_SELF;
2583 gboolean loop_internal_waiter;
2585 if (context == NULL)
2586 context = g_main_context_default ();
2588 loop_internal_waiter = (mutex == &context->mutex);
2590 if (!loop_internal_waiter)
2591 LOCK_CONTEXT (context);
2593 if (context->owner && context->owner != self)
2598 waiter.mutex = mutex;
2600 context->waiters = g_slist_append (context->waiters, &waiter);
2602 if (!loop_internal_waiter)
2603 UNLOCK_CONTEXT (context);
2604 g_cond_wait (cond, mutex);
2605 if (!loop_internal_waiter)
2606 LOCK_CONTEXT (context);
2608 context->waiters = g_slist_remove (context->waiters, &waiter);
2611 if (!context->owner)
2613 context->owner = self;
2614 g_assert (context->owner_count == 0);
2617 if (context->owner == self)
2619 context->owner_count++;
2623 if (!loop_internal_waiter)
2624 UNLOCK_CONTEXT (context);
2630 * g_main_context_prepare:
2631 * @context: a #GMainContext
2632 * @priority: location to store priority of highest priority
2633 * source already ready.
2635 * Prepares to poll sources within a main loop. The resulting information
2636 * for polling is determined by calling g_main_context_query ().
2638 * Return value: %TRUE if some source is ready to be dispatched
2642 g_main_context_prepare (GMainContext *context,
2647 gint current_priority = G_MAXINT;
2650 if (context == NULL)
2651 context = g_main_context_default ();
2653 LOCK_CONTEXT (context);
2655 context->time_is_fresh = FALSE;
2657 if (context->in_check_or_prepare)
2659 g_warning ("g_main_context_prepare() called recursively from within a source's check() or "
2660 "prepare() member.");
2661 UNLOCK_CONTEXT (context);
2666 /* If recursing, finish up current dispatch, before starting over */
2667 if (context->pending_dispatches)
2670 g_main_dispatch (context, ¤t_time);
2672 UNLOCK_CONTEXT (context);
2677 /* If recursing, clear list of pending dispatches */
2679 for (i = 0; i < context->pending_dispatches->len; i++)
2681 if (context->pending_dispatches->pdata[i])
2682 SOURCE_UNREF ((GSource *)context->pending_dispatches->pdata[i], context);
2684 g_ptr_array_set_size (context->pending_dispatches, 0);
2686 /* Prepare all sources */
2688 context->timeout = -1;
2690 source = next_valid_source (context, NULL);
2693 gint source_timeout = -1;
2695 if ((n_ready > 0) && (source->priority > current_priority))
2697 SOURCE_UNREF (source, context);
2700 if (SOURCE_BLOCKED (source))
2703 if (!(source->flags & G_SOURCE_READY))
2706 gboolean (*prepare) (GSource *source,
2709 prepare = source->source_funcs->prepare;
2710 context->in_check_or_prepare++;
2711 UNLOCK_CONTEXT (context);
2713 result = (*prepare) (source, &source_timeout);
2715 LOCK_CONTEXT (context);
2716 context->in_check_or_prepare--;
2720 GSource *ready_source = source;
2722 while (ready_source)
2724 ready_source->flags |= G_SOURCE_READY;
2725 ready_source = ready_source->priv ? ready_source->priv->parent_source : NULL;
2730 if (source->flags & G_SOURCE_READY)
2733 current_priority = source->priority;
2734 context->timeout = 0;
2737 if (source_timeout >= 0)
2739 if (context->timeout < 0)
2740 context->timeout = source_timeout;
2742 context->timeout = MIN (context->timeout, source_timeout);
2746 source = next_valid_source (context, source);
2749 UNLOCK_CONTEXT (context);
2752 *priority = current_priority;
2754 return (n_ready > 0);
2758 * g_main_context_query:
2759 * @context: a #GMainContext
2760 * @max_priority: maximum priority source to check
2761 * @timeout_: (out): location to store timeout to be used in polling
2762 * @fds: (out caller-allocates) (array length=n_fds): location to
2763 * store #GPollFD records that need to be polled.
2764 * @n_fds: length of @fds.
2766 * Determines information necessary to poll this main loop.
2768 * Return value: the number of records actually stored in @fds,
2769 * or, if more than @n_fds records need to be stored, the number
2770 * of records that need to be stored.
2773 g_main_context_query (GMainContext *context,
2782 LOCK_CONTEXT (context);
2784 pollrec = context->poll_records;
2786 while (pollrec && max_priority >= pollrec->priority)
2788 /* We need to include entries with fd->events == 0 in the array because
2789 * otherwise if the application changes fd->events behind our back and
2790 * makes it non-zero, we'll be out of sync when we check the fds[] array.
2791 * (Changing fd->events after adding an FD wasn't an anticipated use of
2792 * this API, but it occurs in practice.) */
2795 fds[n_poll].fd = pollrec->fd->fd;
2796 /* In direct contradiction to the Unix98 spec, IRIX runs into
2797 * difficulty if you pass in POLLERR, POLLHUP or POLLNVAL
2798 * flags in the events field of the pollfd while it should
2799 * just ignoring them. So we mask them out here.
2801 fds[n_poll].events = pollrec->fd->events & ~(G_IO_ERR|G_IO_HUP|G_IO_NVAL);
2802 fds[n_poll].revents = 0;
2805 pollrec = pollrec->next;
2809 context->poll_changed = FALSE;
2813 *timeout = context->timeout;
2815 context->time_is_fresh = FALSE;
2818 UNLOCK_CONTEXT (context);
2824 * g_main_context_check:
2825 * @context: a #GMainContext
2826 * @max_priority: the maximum numerical priority of sources to check
2827 * @fds: (array length=n_fds): array of #GPollFD's that was passed to
2828 * the last call to g_main_context_query()
2829 * @n_fds: return value of g_main_context_query()
2831 * Passes the results of polling back to the main loop.
2833 * Return value: %TRUE if some sources are ready to be dispatched.
2836 g_main_context_check (GMainContext *context,
2846 LOCK_CONTEXT (context);
2848 if (context->in_check_or_prepare)
2850 g_warning ("g_main_context_check() called recursively from within a source's check() or "
2851 "prepare() member.");
2852 UNLOCK_CONTEXT (context);
2856 if (context->wake_up_rec.events)
2857 g_wakeup_acknowledge (context->wakeup);
2859 /* If the set of poll file descriptors changed, bail out
2860 * and let the main loop rerun
2862 if (context->poll_changed)
2864 UNLOCK_CONTEXT (context);
2868 pollrec = context->poll_records;
2872 if (pollrec->fd->events)
2873 pollrec->fd->revents = fds[i].revents;
2875 pollrec = pollrec->next;
2879 source = next_valid_source (context, NULL);
2882 if ((n_ready > 0) && (source->priority > max_priority))
2884 SOURCE_UNREF (source, context);
2887 if (SOURCE_BLOCKED (source))
2890 if (!(source->flags & G_SOURCE_READY))
2893 gboolean (*check) (GSource *source);
2895 check = source->source_funcs->check;
2897 context->in_check_or_prepare++;
2898 UNLOCK_CONTEXT (context);
2900 result = (*check) (source);
2902 LOCK_CONTEXT (context);
2903 context->in_check_or_prepare--;
2907 GSource *ready_source = source;
2909 while (ready_source)
2911 ready_source->flags |= G_SOURCE_READY;
2912 ready_source = ready_source->priv ? ready_source->priv->parent_source : NULL;
2917 if (source->flags & G_SOURCE_READY)
2919 source->ref_count++;
2920 g_ptr_array_add (context->pending_dispatches, source);
2924 /* never dispatch sources with less priority than the first
2925 * one we choose to dispatch
2927 max_priority = source->priority;
2931 source = next_valid_source (context, source);
2934 UNLOCK_CONTEXT (context);
2940 * g_main_context_dispatch:
2941 * @context: a #GMainContext
2943 * Dispatches all pending sources.
2946 g_main_context_dispatch (GMainContext *context)
2948 LOCK_CONTEXT (context);
2950 if (context->pending_dispatches->len > 0)
2952 g_main_dispatch (context);
2955 UNLOCK_CONTEXT (context);
2958 /* HOLDS context lock */
2960 g_main_context_iterate (GMainContext *context,
2967 gboolean some_ready;
2968 gint nfds, allocated_nfds;
2969 GPollFD *fds = NULL;
2971 UNLOCK_CONTEXT (context);
2973 if (!g_main_context_acquire (context))
2975 gboolean got_ownership;
2977 LOCK_CONTEXT (context);
2982 got_ownership = g_main_context_wait (context,
2990 LOCK_CONTEXT (context);
2992 if (!context->cached_poll_array)
2994 context->cached_poll_array_size = context->n_poll_records;
2995 context->cached_poll_array = g_new (GPollFD, context->n_poll_records);
2998 allocated_nfds = context->cached_poll_array_size;
2999 fds = context->cached_poll_array;
3001 UNLOCK_CONTEXT (context);
3003 g_main_context_prepare (context, &max_priority);
3005 while ((nfds = g_main_context_query (context, max_priority, &timeout, fds,
3006 allocated_nfds)) > allocated_nfds)
3008 LOCK_CONTEXT (context);
3010 context->cached_poll_array_size = allocated_nfds = nfds;
3011 context->cached_poll_array = fds = g_new (GPollFD, nfds);
3012 UNLOCK_CONTEXT (context);
3018 g_assert (!g_main_context_fork_detected);
3019 g_main_context_poll (context, timeout, max_priority, fds, nfds);
3021 some_ready = g_main_context_check (context, max_priority, fds, nfds);
3024 g_main_context_dispatch (context);
3026 g_main_context_release (context);
3028 LOCK_CONTEXT (context);
3034 * g_main_context_pending:
3035 * @context: a #GMainContext (if %NULL, the default context will be used)
3037 * Checks if any sources have pending events for the given context.
3039 * Return value: %TRUE if events are pending.
3042 g_main_context_pending (GMainContext *context)
3047 context = g_main_context_default();
3049 LOCK_CONTEXT (context);
3050 retval = g_main_context_iterate (context, FALSE, FALSE, G_THREAD_SELF);
3051 UNLOCK_CONTEXT (context);
3057 * g_main_context_iteration:
3058 * @context: a #GMainContext (if %NULL, the default context will be used)
3059 * @may_block: whether the call may block.
3061 * Runs a single iteration for the given main loop. This involves
3062 * checking to see if any event sources are ready to be processed,
3063 * then if no events sources are ready and @may_block is %TRUE, waiting
3064 * for a source to become ready, then dispatching the highest priority
3065 * events sources that are ready. Otherwise, if @may_block is %FALSE
3066 * sources are not waited to become ready, only those highest priority
3067 * events sources will be dispatched (if any), that are ready at this
3068 * given moment without further waiting.
3070 * Note that even when @may_block is %TRUE, it is still possible for
3071 * g_main_context_iteration() to return %FALSE, since the the wait may
3072 * be interrupted for other reasons than an event source becoming ready.
3074 * Return value: %TRUE if events were dispatched.
3077 g_main_context_iteration (GMainContext *context, gboolean may_block)
3082 context = g_main_context_default();
3084 LOCK_CONTEXT (context);
3085 retval = g_main_context_iterate (context, may_block, TRUE, G_THREAD_SELF);
3086 UNLOCK_CONTEXT (context);
3093 * @context: (allow-none): a #GMainContext (if %NULL, the default context will be used).
3094 * @is_running: set to %TRUE to indicate that the loop is running. This
3095 * is not very important since calling g_main_loop_run() will set this to
3098 * Creates a new #GMainLoop structure.
3100 * Return value: a new #GMainLoop.
3103 g_main_loop_new (GMainContext *context,
3104 gboolean is_running)
3109 context = g_main_context_default();
3111 g_main_context_ref (context);
3113 loop = g_new0 (GMainLoop, 1);
3114 loop->context = context;
3115 loop->is_running = is_running != FALSE;
3116 loop->ref_count = 1;
3123 * @loop: a #GMainLoop
3125 * Increases the reference count on a #GMainLoop object by one.
3127 * Return value: @loop
3130 g_main_loop_ref (GMainLoop *loop)
3132 g_return_val_if_fail (loop != NULL, NULL);
3133 g_return_val_if_fail (g_atomic_int_get (&loop->ref_count) > 0, NULL);
3135 g_atomic_int_inc (&loop->ref_count);
3141 * g_main_loop_unref:
3142 * @loop: a #GMainLoop
3144 * Decreases the reference count on a #GMainLoop object by one. If
3145 * the result is zero, free the loop and free all associated memory.
3148 g_main_loop_unref (GMainLoop *loop)
3150 g_return_if_fail (loop != NULL);
3151 g_return_if_fail (g_atomic_int_get (&loop->ref_count) > 0);
3153 if (!g_atomic_int_dec_and_test (&loop->ref_count))
3156 g_main_context_unref (loop->context);
3162 * @loop: a #GMainLoop
3164 * Runs a main loop until g_main_loop_quit() is called on the loop.
3165 * If this is called for the thread of the loop's #GMainContext,
3166 * it will process events from the loop, otherwise it will
3170 g_main_loop_run (GMainLoop *loop)
3172 GThread *self = G_THREAD_SELF;
3174 g_return_if_fail (loop != NULL);
3175 g_return_if_fail (g_atomic_int_get (&loop->ref_count) > 0);
3177 if (!g_main_context_acquire (loop->context))
3179 gboolean got_ownership = FALSE;
3181 /* Another thread owns this context */
3182 LOCK_CONTEXT (loop->context);
3184 g_atomic_int_inc (&loop->ref_count);
3186 if (!loop->is_running)
3187 loop->is_running = TRUE;
3189 while (loop->is_running && !got_ownership)
3190 got_ownership = g_main_context_wait (loop->context,
3191 &loop->context->cond,
3192 &loop->context->mutex);
3194 if (!loop->is_running)
3196 UNLOCK_CONTEXT (loop->context);
3198 g_main_context_release (loop->context);
3199 g_main_loop_unref (loop);
3203 g_assert (got_ownership);
3206 LOCK_CONTEXT (loop->context);
3208 if (loop->context->in_check_or_prepare)
3210 g_warning ("g_main_loop_run(): called recursively from within a source's "
3211 "check() or prepare() member, iteration not possible.");
3215 g_atomic_int_inc (&loop->ref_count);
3216 loop->is_running = TRUE;
3217 while (loop->is_running)
3218 g_main_context_iterate (loop->context, TRUE, TRUE, self);
3220 UNLOCK_CONTEXT (loop->context);
3222 g_main_context_release (loop->context);
3224 g_main_loop_unref (loop);
3229 * @loop: a #GMainLoop
3231 * Stops a #GMainLoop from running. Any calls to g_main_loop_run()
3232 * for the loop will return.
3234 * Note that sources that have already been dispatched when
3235 * g_main_loop_quit() is called will still be executed.
3238 g_main_loop_quit (GMainLoop *loop)
3240 g_return_if_fail (loop != NULL);
3241 g_return_if_fail (g_atomic_int_get (&loop->ref_count) > 0);
3243 LOCK_CONTEXT (loop->context);
3244 loop->is_running = FALSE;
3245 g_wakeup_signal (loop->context->wakeup);
3247 g_cond_broadcast (&loop->context->cond);
3249 UNLOCK_CONTEXT (loop->context);
3253 * g_main_loop_is_running:
3254 * @loop: a #GMainLoop.
3256 * Checks to see if the main loop is currently being run via g_main_loop_run().
3258 * Return value: %TRUE if the mainloop is currently being run.
3261 g_main_loop_is_running (GMainLoop *loop)
3263 g_return_val_if_fail (loop != NULL, FALSE);
3264 g_return_val_if_fail (g_atomic_int_get (&loop->ref_count) > 0, FALSE);
3266 return loop->is_running;
3270 * g_main_loop_get_context:
3271 * @loop: a #GMainLoop.
3273 * Returns the #GMainContext of @loop.
3275 * Return value: (transfer none): the #GMainContext of @loop
3278 g_main_loop_get_context (GMainLoop *loop)
3280 g_return_val_if_fail (loop != NULL, NULL);
3281 g_return_val_if_fail (g_atomic_int_get (&loop->ref_count) > 0, NULL);
3283 return loop->context;
3286 /* HOLDS: context's lock */
3288 g_main_context_poll (GMainContext *context,
3294 #ifdef G_MAIN_POLL_DEBUG
3300 GPollFunc poll_func;
3302 if (n_fds || timeout != 0)
3304 #ifdef G_MAIN_POLL_DEBUG
3305 if (_g_main_poll_debug)
3307 g_print ("polling context=%p n=%d timeout=%d\n",
3308 context, n_fds, timeout);
3309 poll_timer = g_timer_new ();
3313 LOCK_CONTEXT (context);
3315 poll_func = context->poll_func;
3317 UNLOCK_CONTEXT (context);
3318 if ((*poll_func) (fds, n_fds, timeout) < 0 && errno != EINTR)
3321 g_warning ("poll(2) failed due to: %s.",
3322 g_strerror (errno));
3324 /* If g_poll () returns -1, it has already called g_warning() */
3328 #ifdef G_MAIN_POLL_DEBUG
3329 if (_g_main_poll_debug)
3331 LOCK_CONTEXT (context);
3333 g_print ("g_main_poll(%d) timeout: %d - elapsed %12.10f seconds",
3336 g_timer_elapsed (poll_timer, NULL));
3337 g_timer_destroy (poll_timer);
3338 pollrec = context->poll_records;
3340 while (pollrec != NULL)
3345 if (fds[i].fd == pollrec->fd->fd &&
3346 pollrec->fd->events &&
3349 g_print (" [" G_POLLFD_FORMAT " :", fds[i].fd);
3350 if (fds[i].revents & G_IO_IN)
3352 if (fds[i].revents & G_IO_OUT)
3354 if (fds[i].revents & G_IO_PRI)
3356 if (fds[i].revents & G_IO_ERR)
3358 if (fds[i].revents & G_IO_HUP)
3360 if (fds[i].revents & G_IO_NVAL)
3366 pollrec = pollrec->next;
3370 UNLOCK_CONTEXT (context);
3373 } /* if (n_fds || timeout != 0) */
3377 * g_main_context_add_poll:
3378 * @context: a #GMainContext (or %NULL for the default context)
3379 * @fd: a #GPollFD structure holding information about a file
3380 * descriptor to watch.
3381 * @priority: the priority for this file descriptor which should be
3382 * the same as the priority used for g_source_attach() to ensure that the
3383 * file descriptor is polled whenever the results may be needed.
3385 * Adds a file descriptor to the set of file descriptors polled for
3386 * this context. This will very seldom be used directly. Instead
3387 * a typical event source will use g_source_add_poll() instead.
3390 g_main_context_add_poll (GMainContext *context,
3395 context = g_main_context_default ();
3397 g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
3398 g_return_if_fail (fd);
3400 LOCK_CONTEXT (context);
3401 g_main_context_add_poll_unlocked (context, priority, fd);
3402 UNLOCK_CONTEXT (context);
3405 /* HOLDS: main_loop_lock */
3407 g_main_context_add_poll_unlocked (GMainContext *context,
3411 GPollRec *prevrec, *nextrec;
3412 GPollRec *newrec = g_slice_new (GPollRec);
3414 /* This file descriptor may be checked before we ever poll */
3417 newrec->priority = priority;
3419 prevrec = context->poll_records_tail;
3421 while (prevrec && priority < prevrec->priority)
3424 prevrec = prevrec->prev;
3428 prevrec->next = newrec;
3430 context->poll_records = newrec;
3432 newrec->prev = prevrec;
3433 newrec->next = nextrec;
3436 nextrec->prev = newrec;
3438 context->poll_records_tail = newrec;
3440 context->n_poll_records++;
3442 context->poll_changed = TRUE;
3444 /* Now wake up the main loop if it is waiting in the poll() */
3445 g_wakeup_signal (context->wakeup);
3449 * g_main_context_remove_poll:
3450 * @context:a #GMainContext
3451 * @fd: a #GPollFD descriptor previously added with g_main_context_add_poll()
3453 * Removes file descriptor from the set of file descriptors to be
3454 * polled for a particular context.
3457 g_main_context_remove_poll (GMainContext *context,
3461 context = g_main_context_default ();
3463 g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
3464 g_return_if_fail (fd);
3466 LOCK_CONTEXT (context);
3467 g_main_context_remove_poll_unlocked (context, fd);
3468 UNLOCK_CONTEXT (context);
3472 g_main_context_remove_poll_unlocked (GMainContext *context,
3475 GPollRec *pollrec, *prevrec, *nextrec;
3478 pollrec = context->poll_records;
3482 nextrec = pollrec->next;
3483 if (pollrec->fd == fd)
3485 if (prevrec != NULL)
3486 prevrec->next = nextrec;
3488 context->poll_records = nextrec;
3490 if (nextrec != NULL)
3491 nextrec->prev = prevrec;
3493 context->poll_records_tail = prevrec;
3495 g_slice_free (GPollRec, pollrec);
3497 context->n_poll_records--;
3504 context->poll_changed = TRUE;
3506 /* Now wake up the main loop if it is waiting in the poll() */
3507 g_wakeup_signal (context->wakeup);
3511 * g_source_get_current_time:
3512 * @source: a #GSource
3513 * @timeval: #GTimeVal structure in which to store current time.
3515 * This function ignores @source and is otherwise the same as
3516 * g_get_current_time().
3518 * Deprecated: 2.28: use g_source_get_time() instead
3521 g_source_get_current_time (GSource *source,
3524 g_get_current_time (timeval);
3528 * g_source_get_time:
3529 * @source: a #GSource
3531 * Gets the time to be used when checking this source. The advantage of
3532 * calling this function over calling g_get_monotonic_time() directly is
3533 * that when checking multiple sources, GLib can cache a single value
3534 * instead of having to repeatedly get the system monotonic time.
3536 * The time here is the system monotonic time, if available, or some
3537 * other reasonable alternative otherwise. See g_get_monotonic_time().
3539 * Returns: the monotonic time in microseconds
3544 g_source_get_time (GSource *source)
3546 GMainContext *context;
3549 g_return_val_if_fail (source->context != NULL, 0);
3551 context = source->context;
3553 LOCK_CONTEXT (context);
3555 if (!context->time_is_fresh)
3557 context->time = g_get_monotonic_time ();
3558 context->time_is_fresh = TRUE;
3561 result = context->time;
3563 UNLOCK_CONTEXT (context);
3569 * g_main_context_set_poll_func:
3570 * @context: a #GMainContext
3571 * @func: the function to call to poll all file descriptors
3573 * Sets the function to use to handle polling of file descriptors. It
3574 * will be used instead of the poll() system call
3575 * (or GLib's replacement function, which is used where
3576 * poll() isn't available).
3578 * This function could possibly be used to integrate the GLib event
3579 * loop with an external event loop.
3582 g_main_context_set_poll_func (GMainContext *context,
3586 context = g_main_context_default ();
3588 g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
3590 LOCK_CONTEXT (context);
3593 context->poll_func = func;
3595 context->poll_func = g_poll;
3597 UNLOCK_CONTEXT (context);
3601 * g_main_context_get_poll_func:
3602 * @context: a #GMainContext
3604 * Gets the poll function set by g_main_context_set_poll_func().
3606 * Return value: the poll function
3609 g_main_context_get_poll_func (GMainContext *context)
3614 context = g_main_context_default ();
3616 g_return_val_if_fail (g_atomic_int_get (&context->ref_count) > 0, NULL);
3618 LOCK_CONTEXT (context);
3619 result = context->poll_func;
3620 UNLOCK_CONTEXT (context);
3626 * g_main_context_wakeup:
3627 * @context: a #GMainContext
3629 * If @context is currently waiting in a poll(), interrupt
3630 * the poll(), and continue the iteration process.
3633 g_main_context_wakeup (GMainContext *context)
3636 context = g_main_context_default ();
3638 g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
3640 g_wakeup_signal (context->wakeup);
3644 * g_main_context_is_owner:
3645 * @context: a #GMainContext
3647 * Determines whether this thread holds the (recursive)
3648 * ownership of this #GMainContext. This is useful to
3649 * know before waiting on another thread that may be
3650 * blocking to get ownership of @context.
3652 * Returns: %TRUE if current thread is owner of @context.
3657 g_main_context_is_owner (GMainContext *context)
3662 context = g_main_context_default ();
3664 LOCK_CONTEXT (context);
3665 is_owner = context->owner == G_THREAD_SELF;
3666 UNLOCK_CONTEXT (context);
3674 g_timeout_set_expiration (GTimeoutSource *timeout_source,
3675 gint64 current_time)
3677 timeout_source->expiration = current_time +
3678 (guint64) timeout_source->interval * 1000;
3680 if (timeout_source->seconds)
3683 static gint timer_perturb = -1;
3685 if (timer_perturb == -1)
3688 * we want a per machine/session unique 'random' value; try the dbus
3689 * address first, that has a UUID in it. If there is no dbus, use the
3690 * hostname for hashing.
3692 const char *session_bus_address = g_getenv ("DBUS_SESSION_BUS_ADDRESS");
3693 if (!session_bus_address)
3694 session_bus_address = g_getenv ("HOSTNAME");
3695 if (session_bus_address)
3696 timer_perturb = ABS ((gint) g_str_hash (session_bus_address)) % 1000000;
3701 /* We want the microseconds part of the timeout to land on the
3702 * 'timer_perturb' mark, but we need to make sure we don't try to
3703 * set the timeout in the past. We do this by ensuring that we
3704 * always only *increase* the expiration time by adding a full
3705 * second in the case that the microsecond portion decreases.
3707 timeout_source->expiration -= timer_perturb;
3709 remainder = timeout_source->expiration % 1000000;
3710 if (remainder >= 1000000/4)
3711 timeout_source->expiration += 1000000;
3713 timeout_source->expiration -= remainder;
3714 timeout_source->expiration += timer_perturb;
3719 g_timeout_prepare (GSource *source,
3722 GTimeoutSource *timeout_source = (GTimeoutSource *) source;
3723 gint64 now = g_source_get_time (source);
3725 if (now < timeout_source->expiration)
3727 /* Round up to ensure that we don't try again too early */
3728 *timeout = (timeout_source->expiration - now + 999) / 1000;
3737 g_timeout_check (GSource *source)
3739 GTimeoutSource *timeout_source = (GTimeoutSource *) source;
3740 gint64 now = g_source_get_time (source);
3742 return timeout_source->expiration <= now;
3746 g_timeout_dispatch (GSource *source,
3747 GSourceFunc callback,
3750 GTimeoutSource *timeout_source = (GTimeoutSource *)source;
3755 g_warning ("Timeout source dispatched without callback\n"
3756 "You must call g_source_set_callback().");
3760 again = callback (user_data);
3763 g_timeout_set_expiration (timeout_source, g_source_get_time (source));
3769 * g_timeout_source_new:
3770 * @interval: the timeout interval in milliseconds.
3772 * Creates a new timeout source.
3774 * The source will not initially be associated with any #GMainContext
3775 * and must be added to one with g_source_attach() before it will be
3778 * The interval given is in terms of monotonic time, not wall clock
3779 * time. See g_get_monotonic_time().
3781 * Return value: the newly-created timeout source
3784 g_timeout_source_new (guint interval)
3786 GSource *source = g_source_new (&g_timeout_funcs, sizeof (GTimeoutSource));
3787 GTimeoutSource *timeout_source = (GTimeoutSource *)source;
3789 timeout_source->interval = interval;
3790 g_timeout_set_expiration (timeout_source, g_get_monotonic_time ());
3796 * g_timeout_source_new_seconds:
3797 * @interval: the timeout interval in seconds
3799 * Creates a new timeout source.
3801 * The source will not initially be associated with any #GMainContext
3802 * and must be added to one with g_source_attach() before it will be
3805 * The scheduling granularity/accuracy of this timeout source will be
3808 * The interval given in terms of monotonic time, not wall clock time.
3809 * See g_get_monotonic_time().
3811 * Return value: the newly-created timeout source
3816 g_timeout_source_new_seconds (guint interval)
3818 GSource *source = g_source_new (&g_timeout_funcs, sizeof (GTimeoutSource));
3819 GTimeoutSource *timeout_source = (GTimeoutSource *)source;
3821 timeout_source->interval = 1000 * interval;
3822 timeout_source->seconds = TRUE;
3824 g_timeout_set_expiration (timeout_source, g_get_monotonic_time ());
3831 * g_timeout_add_full:
3832 * @priority: the priority of the timeout source. Typically this will be in
3833 * the range between #G_PRIORITY_DEFAULT and #G_PRIORITY_HIGH.
3834 * @interval: the time between calls to the function, in milliseconds
3835 * (1/1000ths of a second)
3836 * @function: function to call
3837 * @data: data to pass to @function
3838 * @notify: function to call when the timeout is removed, or %NULL
3840 * Sets a function to be called at regular intervals, with the given
3841 * priority. The function is called repeatedly until it returns
3842 * %FALSE, at which point the timeout is automatically destroyed and
3843 * the function will not be called again. The @notify function is
3844 * called when the timeout is destroyed. The first call to the
3845 * function will be at the end of the first @interval.
3847 * Note that timeout functions may be delayed, due to the processing of other
3848 * event sources. Thus they should not be relied on for precise timing.
3849 * After each call to the timeout function, the time of the next
3850 * timeout is recalculated based on the current time and the given interval
3851 * (it does not try to 'catch up' time lost in delays).
3853 * This internally creates a main loop source using g_timeout_source_new()
3854 * and attaches it to the main loop context using g_source_attach(). You can
3855 * do these steps manually if you need greater control.
3857 * The interval given in terms of monotonic time, not wall clock time.
3858 * See g_get_monotonic_time().
3860 * Return value: the ID (greater than 0) of the event source.
3861 * Rename to: g_timeout_add
3864 g_timeout_add_full (gint priority,
3866 GSourceFunc function,
3868 GDestroyNotify notify)
3873 g_return_val_if_fail (function != NULL, 0);
3875 source = g_timeout_source_new (interval);
3877 if (priority != G_PRIORITY_DEFAULT)
3878 g_source_set_priority (source, priority);
3880 g_source_set_callback (source, function, data, notify);
3881 id = g_source_attach (source, NULL);
3882 g_source_unref (source);
3889 * @interval: the time between calls to the function, in milliseconds
3890 * (1/1000ths of a second)
3891 * @function: function to call
3892 * @data: data to pass to @function
3894 * Sets a function to be called at regular intervals, with the default
3895 * priority, #G_PRIORITY_DEFAULT. The function is called repeatedly
3896 * until it returns %FALSE, at which point the timeout is automatically
3897 * destroyed and the function will not be called again. The first call
3898 * to the function will be at the end of the first @interval.
3900 * Note that timeout functions may be delayed, due to the processing of other
3901 * event sources. Thus they should not be relied on for precise timing.
3902 * After each call to the timeout function, the time of the next
3903 * timeout is recalculated based on the current time and the given interval
3904 * (it does not try to 'catch up' time lost in delays).
3906 * If you want to have a timer in the "seconds" range and do not care
3907 * about the exact time of the first call of the timer, use the
3908 * g_timeout_add_seconds() function; this function allows for more
3909 * optimizations and more efficient system power usage.
3911 * This internally creates a main loop source using g_timeout_source_new()
3912 * and attaches it to the main loop context using g_source_attach(). You can
3913 * do these steps manually if you need greater control.
3915 * The interval given is in terms of monotonic time, not wall clock
3916 * time. See g_get_monotonic_time().
3918 * Return value: the ID (greater than 0) of the event source.
3921 g_timeout_add (guint32 interval,
3922 GSourceFunc function,
3925 return g_timeout_add_full (G_PRIORITY_DEFAULT,
3926 interval, function, data, NULL);
3930 * g_timeout_add_seconds_full:
3931 * @priority: the priority of the timeout source. Typically this will be in
3932 * the range between #G_PRIORITY_DEFAULT and #G_PRIORITY_HIGH.
3933 * @interval: the time between calls to the function, in seconds
3934 * @function: function to call
3935 * @data: data to pass to @function
3936 * @notify: function to call when the timeout is removed, or %NULL
3938 * Sets a function to be called at regular intervals, with @priority.
3939 * The function is called repeatedly until it returns %FALSE, at which
3940 * point the timeout is automatically destroyed and the function will
3941 * not be called again.
3943 * Unlike g_timeout_add(), this function operates at whole second granularity.
3944 * The initial starting point of the timer is determined by the implementation
3945 * and the implementation is expected to group multiple timers together so that
3946 * they fire all at the same time.
3947 * To allow this grouping, the @interval to the first timer is rounded
3948 * and can deviate up to one second from the specified interval.
3949 * Subsequent timer iterations will generally run at the specified interval.
3951 * Note that timeout functions may be delayed, due to the processing of other
3952 * event sources. Thus they should not be relied on for precise timing.
3953 * After each call to the timeout function, the time of the next
3954 * timeout is recalculated based on the current time and the given @interval
3956 * If you want timing more precise than whole seconds, use g_timeout_add()
3959 * The grouping of timers to fire at the same time results in a more power
3960 * and CPU efficient behavior so if your timer is in multiples of seconds
3961 * and you don't require the first timer exactly one second from now, the
3962 * use of g_timeout_add_seconds() is preferred over g_timeout_add().
3964 * This internally creates a main loop source using
3965 * g_timeout_source_new_seconds() and attaches it to the main loop context
3966 * using g_source_attach(). You can do these steps manually if you need
3969 * The interval given is in terms of monotonic time, not wall clock
3970 * time. See g_get_monotonic_time().
3972 * Return value: the ID (greater than 0) of the event source.
3974 * Rename to: g_timeout_add_seconds
3978 g_timeout_add_seconds_full (gint priority,
3980 GSourceFunc function,
3982 GDestroyNotify notify)
3987 g_return_val_if_fail (function != NULL, 0);
3989 source = g_timeout_source_new_seconds (interval);
3991 if (priority != G_PRIORITY_DEFAULT)
3992 g_source_set_priority (source, priority);
3994 g_source_set_callback (source, function, data, notify);
3995 id = g_source_attach (source, NULL);
3996 g_source_unref (source);
4002 * g_timeout_add_seconds:
4003 * @interval: the time between calls to the function, in seconds
4004 * @function: function to call
4005 * @data: data to pass to @function
4007 * Sets a function to be called at regular intervals with the default
4008 * priority, #G_PRIORITY_DEFAULT. The function is called repeatedly until
4009 * it returns %FALSE, at which point the timeout is automatically destroyed
4010 * and the function will not be called again.
4012 * This internally creates a main loop source using
4013 * g_timeout_source_new_seconds() and attaches it to the main loop context
4014 * using g_source_attach(). You can do these steps manually if you need
4015 * greater control. Also see g_timeout_add_seconds_full().
4017 * Note that the first call of the timer may not be precise for timeouts
4018 * of one second. If you need finer precision and have such a timeout,
4019 * you may want to use g_timeout_add() instead.
4021 * The interval given is in terms of monotonic time, not wall clock
4022 * time. See g_get_monotonic_time().
4024 * Return value: the ID (greater than 0) of the event source.
4029 g_timeout_add_seconds (guint interval,
4030 GSourceFunc function,
4033 g_return_val_if_fail (function != NULL, 0);
4035 return g_timeout_add_seconds_full (G_PRIORITY_DEFAULT, interval, function, data, NULL);
4038 /* Child watch functions */
4043 g_child_watch_prepare (GSource *source,
4051 g_child_watch_check (GSource *source)
4053 GChildWatchSource *child_watch_source;
4054 gboolean child_exited;
4056 child_watch_source = (GChildWatchSource *) source;
4058 child_exited = child_watch_source->poll.revents & G_IO_IN;
4065 * Note: We do _not_ check for the special value of STILL_ACTIVE
4066 * since we know that the process has exited and doing so runs into
4067 * problems if the child process "happens to return STILL_ACTIVE(259)"
4068 * as Microsoft's Platform SDK puts it.
4070 if (!GetExitCodeProcess (child_watch_source->pid, &child_status))
4072 gchar *emsg = g_win32_error_message (GetLastError ());
4073 g_warning (G_STRLOC ": GetExitCodeProcess() failed: %s", emsg);
4076 child_watch_source->child_status = -1;
4079 child_watch_source->child_status = child_status;
4082 return child_exited;
4086 g_child_watch_finalize (GSource *source)
4090 #else /* G_OS_WIN32 */
4093 wake_source (GSource *source)
4095 GMainContext *context;
4097 /* This should be thread-safe:
4099 * - if the source is currently being added to a context, that
4100 * context will be woken up anyway
4102 * - if the source is currently being destroyed, we simply need not
4105 * - the memory for the source will remain valid until after the
4106 * source finalize function was called (which would remove the
4107 * source from the global list which we are currently holding the
4110 * - the GMainContext will either be NULL or point to a live
4113 * - the GMainContext will remain valid since we hold the
4114 * main_context_list lock
4116 * Since we are holding a lot of locks here, don't try to enter any
4117 * more GMainContext functions for fear of dealock -- just hit the
4118 * GWakeup and run. Even if that's safe now, it could easily become
4119 * unsafe with some very minor changes in the future, and signal
4120 * handling is not the most well-tested codepath.
4122 G_LOCK(main_context_list);
4123 context = source->context;
4125 g_wakeup_signal (context->wakeup);
4126 G_UNLOCK(main_context_list);
4130 dispatch_unix_signals (void)
4134 /* clear this first incase another one arrives while we're processing */
4135 any_unix_signal_pending = FALSE;
4137 G_LOCK(unix_signal_lock);
4139 /* handle GChildWatchSource instances */
4140 if (unix_signal_pending[SIGCHLD])
4142 unix_signal_pending[SIGCHLD] = FALSE;
4144 /* The only way we can do this is to scan all of the children.
4146 * The docs promise that we will not reap children that we are not
4147 * explicitly watching, so that ties our hands from calling
4148 * waitpid(-1). We also can't use siginfo's si_pid field since if
4149 * multiple SIGCHLD arrive at the same time, one of them can be
4150 * dropped (since a given UNIX signal can only be pending once).
4152 for (node = unix_child_watches; node; node = node->next)
4154 GChildWatchSource *source = node->data;
4156 if (!source->child_exited)
4158 if (waitpid (source->pid, &source->child_status, WNOHANG) > 0)
4160 source->child_exited = TRUE;
4162 wake_source ((GSource *) source);
4168 /* handle GUnixSignalWatchSource instances */
4169 for (node = unix_signal_watches; node; node = node->next)
4171 GUnixSignalWatchSource *source = node->data;
4173 if (!source->pending)
4175 if (unix_signal_pending[source->signum])
4177 unix_signal_pending[source->signum] = FALSE;
4178 source->pending = TRUE;
4180 wake_source ((GSource *) source);
4185 G_UNLOCK(unix_signal_lock);
4189 g_child_watch_prepare (GSource *source,
4192 GChildWatchSource *child_watch_source;
4194 child_watch_source = (GChildWatchSource *) source;
4196 return child_watch_source->child_exited;
4200 g_child_watch_check (GSource *source)
4202 GChildWatchSource *child_watch_source;
4204 child_watch_source = (GChildWatchSource *) source;
4206 return child_watch_source->child_exited;
4210 g_unix_signal_watch_prepare (GSource *source,
4213 GUnixSignalWatchSource *unix_signal_source;
4215 unix_signal_source = (GUnixSignalWatchSource *) source;
4217 return unix_signal_source->pending;
4221 g_unix_signal_watch_check (GSource *source)
4223 GUnixSignalWatchSource *unix_signal_source;
4225 unix_signal_source = (GUnixSignalWatchSource *) source;
4227 return unix_signal_source->pending;
4231 g_unix_signal_watch_dispatch (GSource *source,
4232 GSourceFunc callback,
4235 GUnixSignalWatchSource *unix_signal_source;
4237 unix_signal_source = (GUnixSignalWatchSource *) source;
4241 g_warning ("Unix signal source dispatched without callback\n"
4242 "You must call g_source_set_callback().");
4246 (callback) (user_data);
4248 unix_signal_source->pending = FALSE;
4254 ensure_unix_signal_handler_installed_unlocked (int signum)
4256 static sigset_t installed_signal_mask;
4257 static gboolean initialized;
4258 struct sigaction action;
4262 sigemptyset (&installed_signal_mask);
4263 g_get_worker_context ();
4267 if (sigismember (&installed_signal_mask, signum))
4270 sigaddset (&installed_signal_mask, signum);
4272 action.sa_handler = g_unix_signal_handler;
4273 sigemptyset (&action.sa_mask);
4274 action.sa_flags = SA_RESTART | SA_NOCLDSTOP;
4275 sigaction (signum, &action, NULL);
4279 _g_main_create_unix_signal_watch (int signum)
4282 GUnixSignalWatchSource *unix_signal_source;
4284 source = g_source_new (&g_unix_signal_funcs, sizeof (GUnixSignalWatchSource));
4285 unix_signal_source = (GUnixSignalWatchSource *) source;
4287 unix_signal_source->signum = signum;
4288 unix_signal_source->pending = FALSE;
4290 G_LOCK (unix_signal_lock);
4291 ensure_unix_signal_handler_installed_unlocked (signum);
4292 unix_signal_watches = g_slist_prepend (unix_signal_watches, unix_signal_source);
4293 if (unix_signal_pending[signum])
4294 unix_signal_source->pending = TRUE;
4295 unix_signal_pending[signum] = FALSE;
4296 G_UNLOCK (unix_signal_lock);
4302 g_unix_signal_watch_finalize (GSource *source)
4304 G_LOCK (unix_signal_lock);
4305 unix_signal_watches = g_slist_remove (unix_signal_watches, source);
4306 G_UNLOCK (unix_signal_lock);
4310 g_child_watch_finalize (GSource *source)
4312 G_LOCK (unix_signal_lock);
4313 unix_child_watches = g_slist_remove (unix_child_watches, source);
4314 G_UNLOCK (unix_signal_lock);
4317 #endif /* G_OS_WIN32 */
4320 g_child_watch_dispatch (GSource *source,
4321 GSourceFunc callback,
4324 GChildWatchSource *child_watch_source;
4325 GChildWatchFunc child_watch_callback = (GChildWatchFunc) callback;
4327 child_watch_source = (GChildWatchSource *) source;
4331 g_warning ("Child watch source dispatched without callback\n"
4332 "You must call g_source_set_callback().");
4336 (child_watch_callback) (child_watch_source->pid, child_watch_source->child_status, user_data);
4338 /* We never keep a child watch source around as the child is gone */
4345 g_unix_signal_handler (int signum)
4347 unix_signal_pending[signum] = TRUE;
4348 any_unix_signal_pending = TRUE;
4350 g_wakeup_signal (glib_worker_context->wakeup);
4353 #endif /* !G_OS_WIN32 */
4356 * g_child_watch_source_new:
4357 * @pid: process to watch. On POSIX the pid of a child process. On
4358 * Windows a handle for a process (which doesn't have to be a child).
4360 * Creates a new child_watch source.
4362 * The source will not initially be associated with any #GMainContext
4363 * and must be added to one with g_source_attach() before it will be
4366 * Note that child watch sources can only be used in conjunction with
4367 * <literal>g_spawn...</literal> when the %G_SPAWN_DO_NOT_REAP_CHILD
4370 * Note that on platforms where #GPid must be explicitly closed
4371 * (see g_spawn_close_pid()) @pid must not be closed while the
4372 * source is still active. Typically, you will want to call
4373 * g_spawn_close_pid() in the callback function for the source.
4375 * Note further that using g_child_watch_source_new() is not
4376 * compatible with calling <literal>waitpid(-1)</literal> in
4377 * the application. Calling waitpid() for individual pids will
4380 * Return value: the newly-created child watch source
4385 g_child_watch_source_new (GPid pid)
4387 GSource *source = g_source_new (&g_child_watch_funcs, sizeof (GChildWatchSource));
4388 GChildWatchSource *child_watch_source = (GChildWatchSource *)source;
4390 child_watch_source->pid = pid;
4393 child_watch_source->poll.fd = (gintptr) pid;
4394 child_watch_source->poll.events = G_IO_IN;
4396 g_source_add_poll (source, &child_watch_source->poll);
4397 #else /* G_OS_WIN32 */
4398 G_LOCK (unix_signal_lock);
4399 ensure_unix_signal_handler_installed_unlocked (SIGCHLD);
4400 unix_child_watches = g_slist_prepend (unix_child_watches, child_watch_source);
4401 if (waitpid (pid, &child_watch_source->child_status, WNOHANG) > 0)
4402 child_watch_source->child_exited = TRUE;
4403 G_UNLOCK (unix_signal_lock);
4404 #endif /* G_OS_WIN32 */
4410 * g_child_watch_add_full:
4411 * @priority: the priority of the idle source. Typically this will be in the
4412 * range between #G_PRIORITY_DEFAULT_IDLE and #G_PRIORITY_HIGH_IDLE.
4413 * @pid: process to watch. On POSIX the pid of a child process. On
4414 * Windows a handle for a process (which doesn't have to be a child).
4415 * @function: function to call
4416 * @data: data to pass to @function
4417 * @notify: function to call when the idle is removed, or %NULL
4419 * Sets a function to be called when the child indicated by @pid
4420 * exits, at the priority @priority.
4422 * If you obtain @pid from g_spawn_async() or g_spawn_async_with_pipes()
4423 * you will need to pass #G_SPAWN_DO_NOT_REAP_CHILD as flag to
4424 * the spawn function for the child watching to work.
4426 * Note that on platforms where #GPid must be explicitly closed
4427 * (see g_spawn_close_pid()) @pid must not be closed while the
4428 * source is still active. Typically, you will want to call
4429 * g_spawn_close_pid() in the callback function for the source.
4431 * GLib supports only a single callback per process id.
4433 * This internally creates a main loop source using
4434 * g_child_watch_source_new() and attaches it to the main loop context
4435 * using g_source_attach(). You can do these steps manually if you
4436 * need greater control.
4438 * Return value: the ID (greater than 0) of the event source.
4440 * Rename to: g_child_watch_add
4444 g_child_watch_add_full (gint priority,
4446 GChildWatchFunc function,
4448 GDestroyNotify notify)
4453 g_return_val_if_fail (function != NULL, 0);
4455 source = g_child_watch_source_new (pid);
4457 if (priority != G_PRIORITY_DEFAULT)
4458 g_source_set_priority (source, priority);
4460 g_source_set_callback (source, (GSourceFunc) function, data, notify);
4461 id = g_source_attach (source, NULL);
4462 g_source_unref (source);
4468 * g_child_watch_add:
4469 * @pid: process id to watch. On POSIX the pid of a child process. On
4470 * Windows a handle for a process (which doesn't have to be a child).
4471 * @function: function to call
4472 * @data: data to pass to @function
4474 * Sets a function to be called when the child indicated by @pid
4475 * exits, at a default priority, #G_PRIORITY_DEFAULT.
4477 * If you obtain @pid from g_spawn_async() or g_spawn_async_with_pipes()
4478 * you will need to pass #G_SPAWN_DO_NOT_REAP_CHILD as flag to
4479 * the spawn function for the child watching to work.
4481 * Note that on platforms where #GPid must be explicitly closed
4482 * (see g_spawn_close_pid()) @pid must not be closed while the
4483 * source is still active. Typically, you will want to call
4484 * g_spawn_close_pid() in the callback function for the source.
4486 * GLib supports only a single callback per process id.
4488 * This internally creates a main loop source using
4489 * g_child_watch_source_new() and attaches it to the main loop context
4490 * using g_source_attach(). You can do these steps manually if you
4491 * need greater control.
4493 * Return value: the ID (greater than 0) of the event source.
4498 g_child_watch_add (GPid pid,
4499 GChildWatchFunc function,
4502 return g_child_watch_add_full (G_PRIORITY_DEFAULT, pid, function, data, NULL);
4506 /* Idle functions */
4509 g_idle_prepare (GSource *source,
4518 g_idle_check (GSource *source)
4524 g_idle_dispatch (GSource *source,
4525 GSourceFunc callback,
4530 g_warning ("Idle source dispatched without callback\n"
4531 "You must call g_source_set_callback().");
4535 return callback (user_data);
4539 * g_idle_source_new:
4541 * Creates a new idle source.
4543 * The source will not initially be associated with any #GMainContext
4544 * and must be added to one with g_source_attach() before it will be
4545 * executed. Note that the default priority for idle sources is
4546 * %G_PRIORITY_DEFAULT_IDLE, as compared to other sources which
4547 * have a default priority of %G_PRIORITY_DEFAULT.
4549 * Return value: the newly-created idle source
4552 g_idle_source_new (void)
4556 source = g_source_new (&g_idle_funcs, sizeof (GSource));
4557 g_source_set_priority (source, G_PRIORITY_DEFAULT_IDLE);
4564 * @priority: the priority of the idle source. Typically this will be in the
4565 * range between #G_PRIORITY_DEFAULT_IDLE and #G_PRIORITY_HIGH_IDLE.
4566 * @function: function to call
4567 * @data: data to pass to @function
4568 * @notify: function to call when the idle is removed, or %NULL
4570 * Adds a function to be called whenever there are no higher priority
4571 * events pending. If the function returns %FALSE it is automatically
4572 * removed from the list of event sources and will not be called again.
4574 * This internally creates a main loop source using g_idle_source_new()
4575 * and attaches it to the main loop context using g_source_attach().
4576 * You can do these steps manually if you need greater control.
4578 * Return value: the ID (greater than 0) of the event source.
4579 * Rename to: g_idle_add
4582 g_idle_add_full (gint priority,
4583 GSourceFunc function,
4585 GDestroyNotify notify)
4590 g_return_val_if_fail (function != NULL, 0);
4592 source = g_idle_source_new ();
4594 if (priority != G_PRIORITY_DEFAULT_IDLE)
4595 g_source_set_priority (source, priority);
4597 g_source_set_callback (source, function, data, notify);
4598 id = g_source_attach (source, NULL);
4599 g_source_unref (source);
4606 * @function: function to call
4607 * @data: data to pass to @function.
4609 * Adds a function to be called whenever there are no higher priority
4610 * events pending to the default main loop. The function is given the
4611 * default idle priority, #G_PRIORITY_DEFAULT_IDLE. If the function
4612 * returns %FALSE it is automatically removed from the list of event
4613 * sources and will not be called again.
4615 * This internally creates a main loop source using g_idle_source_new()
4616 * and attaches it to the main loop context using g_source_attach().
4617 * You can do these steps manually if you need greater control.
4619 * Return value: the ID (greater than 0) of the event source.
4622 g_idle_add (GSourceFunc function,
4625 return g_idle_add_full (G_PRIORITY_DEFAULT_IDLE, function, data, NULL);
4629 * g_idle_remove_by_data:
4630 * @data: the data for the idle source's callback.
4632 * Removes the idle function with the given data.
4634 * Return value: %TRUE if an idle source was found and removed.
4637 g_idle_remove_by_data (gpointer data)
4639 return g_source_remove_by_funcs_user_data (&g_idle_funcs, data);
4643 * g_main_context_invoke:
4644 * @context: (allow-none): a #GMainContext, or %NULL
4645 * @function: function to call
4646 * @data: data to pass to @function
4648 * Invokes a function in such a way that @context is owned during the
4649 * invocation of @function.
4651 * If @context is %NULL then the global default main context — as
4652 * returned by g_main_context_default() — is used.
4654 * If @context is owned by the current thread, @function is called
4655 * directly. Otherwise, if @context is the thread-default main context
4656 * of the current thread and g_main_context_acquire() succeeds, then
4657 * @function is called and g_main_context_release() is called
4660 * In any other case, an idle source is created to call @function and
4661 * that source is attached to @context (presumably to be run in another
4662 * thread). The idle source is attached with #G_PRIORITY_DEFAULT
4663 * priority. If you want a different priority, use
4664 * g_main_context_invoke_full().
4666 * Note that, as with normal idle functions, @function should probably
4667 * return %FALSE. If it returns %TRUE, it will be continuously run in a
4668 * loop (and may prevent this call from returning).
4673 g_main_context_invoke (GMainContext *context,
4674 GSourceFunc function,
4677 g_main_context_invoke_full (context,
4679 function, data, NULL);
4683 * g_main_context_invoke_full:
4684 * @context: (allow-none): a #GMainContext, or %NULL
4685 * @priority: the priority at which to run @function
4686 * @function: function to call
4687 * @data: data to pass to @function
4688 * @notify: a function to call when @data is no longer in use, or %NULL.
4690 * Invokes a function in such a way that @context is owned during the
4691 * invocation of @function.
4693 * This function is the same as g_main_context_invoke() except that it
4694 * lets you specify the priority incase @function ends up being
4695 * scheduled as an idle and also lets you give a #GDestroyNotify for @data.
4697 * @notify should not assume that it is called from any particular
4698 * thread or with any particular context acquired.
4703 g_main_context_invoke_full (GMainContext *context,
4705 GSourceFunc function,
4707 GDestroyNotify notify)
4709 g_return_if_fail (function != NULL);
4712 context = g_main_context_default ();
4714 if (g_main_context_is_owner (context))
4716 while (function (data));
4723 GMainContext *thread_default;
4725 thread_default = g_main_context_get_thread_default ();
4727 if (!thread_default)
4728 thread_default = g_main_context_default ();
4730 if (thread_default == context && g_main_context_acquire (context))
4732 while (function (data));
4734 g_main_context_release (context);
4743 source = g_idle_source_new ();
4744 g_source_set_priority (source, priority);
4745 g_source_set_callback (source, function, data, notify);
4746 g_source_attach (source, context);
4747 g_source_unref (source);
4753 glib_worker_main (gpointer data)
4757 g_main_context_iteration (glib_worker_context, TRUE);
4760 if (any_unix_signal_pending)
4761 dispatch_unix_signals ();
4765 return NULL; /* worst GCC warning message ever... */
4769 g_get_worker_context (void)
4771 static gsize initialised;
4773 if (g_once_init_enter (&initialised))
4775 GError *error = NULL;
4777 glib_worker_context = g_main_context_new ();
4778 if (g_thread_new ("gmain", glib_worker_main, NULL, FALSE, &error) == NULL)
4779 g_error ("Creating GLib worker thread failed: %s\n", error->message);
4781 g_once_init_leave (&initialised, TRUE);
4784 return glib_worker_context;