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"
53 #include <sys/eventfd.h>
58 #include <sys/types.h>
61 #ifdef HAVE_SYS_TIME_H
63 #endif /* HAVE_SYS_TIME_H */
66 #endif /* HAVE_UNISTD_H */
73 #endif /* G_OS_WIN32 */
76 #include <sys/socket.h>
78 #endif /* G_OS_BEOS */
83 #include "giochannel.h"
87 #include "gstrfuncs.h"
88 #include "gtestutils.h"
89 #include "gthreadprivate.h"
95 #ifdef G_MAIN_POLL_DEBUG
103 * @title: The Main Event Loop
104 * @short_description: manages all available sources of events
106 * The main event loop manages all the available sources of events for
107 * GLib and GTK+ applications. These events can come from any number of
108 * different types of sources such as file descriptors (plain files,
109 * pipes or sockets) and timeouts. New types of event sources can also
110 * be added using g_source_attach().
112 * To allow multiple independent sets of sources to be handled in
113 * different threads, each source is associated with a #GMainContext.
114 * A GMainContext can only be running in a single thread, but
115 * sources can be added to it and removed from it from other threads.
117 * Each event source is assigned a priority. The default priority,
118 * #G_PRIORITY_DEFAULT, is 0. Values less than 0 denote higher priorities.
119 * Values greater than 0 denote lower priorities. Events from high priority
120 * sources are always processed before events from lower priority sources.
122 * Idle functions can also be added, and assigned a priority. These will
123 * be run whenever no events with a higher priority are ready to be processed.
125 * The #GMainLoop data type represents a main event loop. A GMainLoop is
126 * created with g_main_loop_new(). After adding the initial event sources,
127 * g_main_loop_run() is called. This continuously checks for new events from
128 * each of the event sources and dispatches them. Finally, the processing of
129 * an event from one of the sources leads to a call to g_main_loop_quit() to
130 * exit the main loop, and g_main_loop_run() returns.
132 * It is possible to create new instances of #GMainLoop recursively.
133 * This is often used in GTK+ applications when showing modal dialog
134 * boxes. Note that event sources are associated with a particular
135 * #GMainContext, and will be checked and dispatched for all main
136 * loops associated with that GMainContext.
138 * GTK+ contains wrappers of some of these functions, e.g. gtk_main(),
139 * gtk_main_quit() and gtk_events_pending().
141 * <refsect2><title>Creating new source types</title>
142 * <para>One of the unusual features of the #GMainLoop functionality
143 * is that new types of event source can be created and used in
144 * addition to the builtin type of event source. A new event source
145 * type is used for handling GDK events. A new source type is created
146 * by <firstterm>deriving</firstterm> from the #GSource structure.
147 * The derived type of source is represented by a structure that has
148 * the #GSource structure as a first element, and other elements specific
149 * to the new source type. To create an instance of the new source type,
150 * call g_source_new() passing in the size of the derived structure and
151 * a table of functions. These #GSourceFuncs determine the behavior of
152 * the new source type.</para>
153 * <para>New source types basically interact with the main context
154 * in two ways. Their prepare function in #GSourceFuncs can set a timeout
155 * to determine the maximum amount of time that the main loop will sleep
156 * before checking the source again. In addition, or as well, the source
157 * can add file descriptors to the set that the main context checks using
158 * g_source_add_poll().</para>
160 * <refsect2><title>Customizing the main loop iteration</title>
161 * <para>Single iterations of a #GMainContext can be run with
162 * g_main_context_iteration(). In some cases, more detailed control
163 * of exactly how the details of the main loop work is desired, for
164 * instance, when integrating the #GMainLoop with an external main loop.
165 * In such cases, you can call the component functions of
166 * g_main_context_iteration() directly. These functions are
167 * g_main_context_prepare(), g_main_context_query(),
168 * g_main_context_check() and g_main_context_dispatch().</para>
169 * <para>The operation of these functions can best be seen in terms
170 * of a state diagram, as shown in <xref linkend="mainloop-states"/>.</para>
171 * <figure id="mainloop-states"><title>States of a Main Context</title>
172 * <graphic fileref="mainloop-states.gif" format="GIF"></graphic>
179 typedef struct _GTimeoutSource GTimeoutSource;
180 typedef struct _GChildWatchSource GChildWatchSource;
181 typedef struct _GUnixSignalWatchSource GUnixSignalWatchSource;
182 typedef struct _GPollRec GPollRec;
183 typedef struct _GSourceCallback GSourceCallback;
187 G_SOURCE_READY = 1 << G_HOOK_FLAG_USER_SHIFT,
188 G_SOURCE_CAN_RECURSE = 1 << (G_HOOK_FLAG_USER_SHIFT + 1)
191 typedef struct _GMainWaiter GMainWaiter;
199 typedef struct _GMainDispatch GMainDispatch;
201 struct _GMainDispatch
204 GSList *dispatching_sources; /* stack of current sources */
207 #ifdef G_MAIN_POLL_DEBUG
208 gboolean _g_main_poll_debug = FALSE;
213 /* The following lock is used for both the list of sources
214 * and the list of poll records
224 GPtrArray *pending_dispatches;
225 gint timeout; /* Timeout for current iteration */
228 GSource *source_list;
229 gint in_check_or_prepare;
231 GPollRec *poll_records, *poll_records_tail;
232 guint n_poll_records;
233 GPollFD *cached_poll_array;
234 guint cached_poll_array_size;
239 gboolean poll_waiting;
241 /* Flag indicating whether the set of fd's changed during a poll */
242 gboolean poll_changed;
247 gboolean time_is_fresh;
249 gboolean real_time_is_fresh;
252 struct _GSourceCallback
257 GDestroyNotify notify;
262 GMainContext *context;
267 struct _GTimeoutSource
275 struct _GChildWatchSource
282 #else /* G_OS_WIN32 */
284 gboolean child_exited;
285 #endif /* G_OS_WIN32 */
288 struct _GUnixSignalWatchSource
303 struct _GSourcePrivate
305 GSList *child_sources;
306 GSource *parent_source;
309 #define LOCK_CONTEXT(context) g_static_mutex_lock (&context->mutex)
310 #define UNLOCK_CONTEXT(context) g_static_mutex_unlock (&context->mutex)
311 #define G_THREAD_SELF g_thread_self ()
313 #define SOURCE_DESTROYED(source) (((source)->flags & G_HOOK_FLAG_ACTIVE) == 0)
314 #define SOURCE_BLOCKED(source) (((source)->flags & G_HOOK_FLAG_IN_CALL) != 0 && \
315 ((source)->flags & G_SOURCE_CAN_RECURSE) == 0)
317 #define SOURCE_UNREF(source, context) \
319 if ((source)->ref_count > 1) \
320 (source)->ref_count--; \
322 g_source_unref_internal ((source), (context), TRUE); \
326 /* Forward declarations */
328 static void g_source_unref_internal (GSource *source,
329 GMainContext *context,
331 static void g_source_destroy_internal (GSource *source,
332 GMainContext *context,
334 static void g_source_set_priority_unlocked (GSource *source,
335 GMainContext *context,
337 static void g_main_context_poll (GMainContext *context,
342 static void g_main_context_add_poll_unlocked (GMainContext *context,
345 static void g_main_context_remove_poll_unlocked (GMainContext *context,
347 static void g_main_context_wakeup_unlocked (GMainContext *context);
349 static void _g_main_wake_up_all_contexts (void);
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,
364 static gpointer unix_signal_helper_thread (gpointer data) G_GNUC_NORETURN;
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 G_LOCK_DEFINE_STATIC (main_loop);
382 static GMainContext *default_main_context;
383 static GSList *main_contexts_without_pipe = NULL;
387 /* The UNIX signal pipe contains a single byte specifying which
388 * signal was received.
390 #define _UNIX_SIGNAL_PIPE_SIGCHLD_CHAR 'C'
391 #define _UNIX_SIGNAL_PIPE_SIGHUP_CHAR 'H'
392 #define _UNIX_SIGNAL_PIPE_SIGINT_CHAR 'I'
393 #define _UNIX_SIGNAL_PIPE_SIGTERM_CHAR 'T'
394 /* Guards all the data below */
395 G_LOCK_DEFINE_STATIC (unix_signal_lock);
397 UNIX_SIGNAL_UNINITIALIZED = 0,
398 UNIX_SIGNAL_INITIALIZED_SINGLE,
399 UNIX_SIGNAL_INITIALIZED_THREADED
401 static gint unix_signal_init_state = UNIX_SIGNAL_UNINITIALIZED;
403 /* These are only used in the UNIX_SIGNAL_INITIALIZED_SINGLE case */
404 gboolean sighup_delivered : 1;
405 gboolean sigint_delivered : 1;
406 gboolean sigterm_delivered : 1;
408 static sigset_t unix_signal_mask;
409 static UnixSignalState unix_signal_state;
410 static gint unix_signal_wake_up_pipe[2];
411 GSList *unix_signal_watches;
413 /* Not guarded ( FIXME should it be? ) */
414 static gint child_watch_count = 1;
416 static GSourceFuncs g_unix_signal_funcs =
418 g_unix_signal_watch_prepare,
419 g_unix_signal_watch_check,
420 g_unix_signal_watch_dispatch,
421 g_unix_signal_watch_finalize
423 #endif /* !G_OS_WIN32 */
424 G_LOCK_DEFINE_STATIC (main_context_list);
425 static GSList *main_context_list = NULL;
427 GSourceFuncs g_timeout_funcs =
435 GSourceFuncs g_child_watch_funcs =
437 g_child_watch_prepare,
439 g_child_watch_dispatch,
443 GSourceFuncs g_idle_funcs =
452 * g_main_context_ref:
453 * @context: a #GMainContext
455 * Increases the reference count on a #GMainContext object by one.
457 * Returns: the @context that was passed in (since 2.6)
460 g_main_context_ref (GMainContext *context)
462 g_return_val_if_fail (context != NULL, NULL);
463 g_return_val_if_fail (g_atomic_int_get (&context->ref_count) > 0, NULL);
465 g_atomic_int_inc (&context->ref_count);
471 poll_rec_list_free (GMainContext *context,
474 g_slice_free_chain (GPollRec, list, next);
478 * g_main_context_unref:
479 * @context: a #GMainContext
481 * Decreases the reference count on a #GMainContext object by one. If
482 * the result is zero, free the context and free all associated memory.
485 g_main_context_unref (GMainContext *context)
488 g_return_if_fail (context != NULL);
489 g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
491 if (!g_atomic_int_dec_and_test (&context->ref_count))
494 G_LOCK (main_context_list);
495 main_context_list = g_slist_remove (main_context_list, context);
496 G_UNLOCK (main_context_list);
498 source = context->source_list;
501 GSource *next = source->next;
502 g_source_destroy_internal (source, context, FALSE);
506 g_static_mutex_free (&context->mutex);
508 g_ptr_array_free (context->pending_dispatches, TRUE);
509 g_free (context->cached_poll_array);
511 poll_rec_list_free (context, context->poll_records);
513 if (g_thread_supported())
514 g_wakeup_free (context->wakeup);
517 main_contexts_without_pipe = g_slist_remove (main_contexts_without_pipe,
520 if (context->cond != NULL)
521 g_cond_free (context->cond);
527 g_main_context_init_pipe (GMainContext *context)
529 context->wakeup = g_wakeup_new ();
530 g_wakeup_get_pollfd (context->wakeup, &context->wake_up_rec);
531 g_main_context_add_poll_unlocked (context, 0, &context->wake_up_rec);
535 _g_main_thread_init (void)
539 curr = main_contexts_without_pipe;
542 g_main_context_init_pipe ((GMainContext *)curr->data);
545 g_slist_free (main_contexts_without_pipe);
546 main_contexts_without_pipe = NULL;
550 * g_main_context_new:
552 * Creates a new #GMainContext structure.
554 * Return value: the new #GMainContext
557 g_main_context_new (void)
559 GMainContext *context = g_new0 (GMainContext, 1);
561 #ifdef G_MAIN_POLL_DEBUG
563 static gboolean beenhere = FALSE;
567 if (getenv ("G_MAIN_POLL_DEBUG") != NULL)
568 _g_main_poll_debug = TRUE;
574 g_static_mutex_init (&context->mutex);
576 context->owner = NULL;
577 context->waiters = NULL;
579 context->ref_count = 1;
581 context->next_id = 1;
583 context->source_list = NULL;
585 context->poll_func = g_poll;
587 context->cached_poll_array = NULL;
588 context->cached_poll_array_size = 0;
590 context->pending_dispatches = g_ptr_array_new ();
592 context->time_is_fresh = FALSE;
593 context->real_time_is_fresh = FALSE;
595 if (g_thread_supported ())
596 g_main_context_init_pipe (context);
598 main_contexts_without_pipe = g_slist_prepend (main_contexts_without_pipe,
601 G_LOCK (main_context_list);
602 main_context_list = g_slist_append (main_context_list, context);
604 #ifdef G_MAIN_POLL_DEBUG
605 if (_g_main_poll_debug)
606 g_print ("created context=%p\n", context);
609 G_UNLOCK (main_context_list);
615 * g_main_context_default:
617 * Returns the global default main context. This is the main context
618 * used for main loop functions when a main loop is not explicitly
619 * specified, and corresponds to the "main" main loop. See also
620 * g_main_context_get_thread_default().
622 * Return value: (transfer none): the global default main context.
625 g_main_context_default (void)
631 if (!default_main_context)
633 default_main_context = g_main_context_new ();
634 #ifdef G_MAIN_POLL_DEBUG
635 if (_g_main_poll_debug)
636 g_print ("default context=%p\n", default_main_context);
640 G_UNLOCK (main_loop);
642 return default_main_context;
645 static GStaticPrivate thread_context_stack = G_STATIC_PRIVATE_INIT;
648 free_context_stack (gpointer data)
650 GQueue *stack = data;
651 GMainContext *context;
653 while (!g_queue_is_empty (stack))
655 context = g_queue_pop_head (stack);
656 g_main_context_release (context);
658 g_main_context_unref (context);
660 g_queue_free (stack);
664 * g_main_context_push_thread_default:
665 * @context: a #GMainContext, or %NULL for the global default context
667 * Acquires @context and sets it as the thread-default context for the
668 * current thread. This will cause certain asynchronous operations
669 * (such as most <link linkend="gio">gio</link>-based I/O) which are
670 * started in this thread to run under @context and deliver their
671 * results to its main loop, rather than running under the global
672 * default context in the main thread. Note that calling this function
673 * changes the context returned by
674 * g_main_context_get_thread_default(), <emphasis>not</emphasis> the
675 * one returned by g_main_context_default(), so it does not affect the
676 * context used by functions like g_idle_add().
678 * Normally you would call this function shortly after creating a new
679 * thread, passing it a #GMainContext which will be run by a
680 * #GMainLoop in that thread, to set a new default context for all
681 * async operations in that thread. (In this case, you don't need to
682 * ever call g_main_context_pop_thread_default().) In some cases
683 * however, you may want to schedule a single operation in a
684 * non-default context, or temporarily use a non-default context in
685 * the main thread. In that case, you can wrap the call to the
686 * asynchronous operation inside a
687 * g_main_context_push_thread_default() /
688 * g_main_context_pop_thread_default() pair, but it is up to you to
689 * ensure that no other asynchronous operations accidentally get
690 * started while the non-default context is active.
692 * Beware that libraries that predate this function may not correctly
693 * handle being used from a thread with a thread-default context. Eg,
694 * see g_file_supports_thread_contexts().
699 g_main_context_push_thread_default (GMainContext *context)
702 gboolean acquired_context;
704 acquired_context = g_main_context_acquire (context);
705 g_return_if_fail (acquired_context);
707 if (context == g_main_context_default ())
710 g_main_context_ref (context);
712 stack = g_static_private_get (&thread_context_stack);
715 stack = g_queue_new ();
716 g_static_private_set (&thread_context_stack, stack,
720 g_queue_push_head (stack, context);
724 * g_main_context_pop_thread_default:
725 * @context: a #GMainContext object, or %NULL
727 * Pops @context off the thread-default context stack (verifying that
728 * it was on the top of the stack).
733 g_main_context_pop_thread_default (GMainContext *context)
737 if (context == g_main_context_default ())
740 stack = g_static_private_get (&thread_context_stack);
742 g_return_if_fail (stack != NULL);
743 g_return_if_fail (g_queue_peek_head (stack) == context);
745 g_queue_pop_head (stack);
747 g_main_context_release (context);
749 g_main_context_unref (context);
753 * g_main_context_get_thread_default:
755 * Gets the thread-default #GMainContext for this thread. Asynchronous
756 * operations that want to be able to be run in contexts other than
757 * the default one should call this method to get a #GMainContext to
758 * add their #GSource<!-- -->s to. (Note that even in single-threaded
759 * programs applications may sometimes want to temporarily push a
760 * non-default context, so it is not safe to assume that this will
761 * always return %NULL if threads are not initialized.)
763 * Returns: (transfer none): the thread-default #GMainContext, or
764 * %NULL if the thread-default context is the global default context.
769 g_main_context_get_thread_default (void)
773 stack = g_static_private_get (&thread_context_stack);
775 return g_queue_peek_head (stack);
780 /* Hooks for adding to the main loop */
784 * @source_funcs: structure containing functions that implement
785 * the sources behavior.
786 * @struct_size: size of the #GSource structure to create.
788 * Creates a new #GSource structure. The size is specified to
789 * allow creating structures derived from #GSource that contain
790 * additional data. The size passed in must be at least
791 * <literal>sizeof (GSource)</literal>.
793 * The source will not initially be associated with any #GMainContext
794 * and must be added to one with g_source_attach() before it will be
797 * Return value: the newly-created #GSource.
800 g_source_new (GSourceFuncs *source_funcs,
805 g_return_val_if_fail (source_funcs != NULL, NULL);
806 g_return_val_if_fail (struct_size >= sizeof (GSource), NULL);
808 source = (GSource*) g_malloc0 (struct_size);
810 source->source_funcs = source_funcs;
811 source->ref_count = 1;
813 source->priority = G_PRIORITY_DEFAULT;
815 source->flags = G_HOOK_FLAG_ACTIVE;
817 /* NULL/0 initialization for all other fields */
822 /* Holds context's lock
825 g_source_list_add (GSource *source,
826 GMainContext *context)
828 GSource *tmp_source, *last_source;
830 if (source->priv && source->priv->parent_source)
832 /* Put the source immediately before its parent */
833 tmp_source = source->priv->parent_source;
834 last_source = source->priv->parent_source->prev;
839 tmp_source = context->source_list;
840 while (tmp_source && tmp_source->priority <= source->priority)
842 last_source = tmp_source;
843 tmp_source = tmp_source->next;
847 source->next = tmp_source;
849 tmp_source->prev = source;
851 source->prev = last_source;
853 last_source->next = source;
855 context->source_list = source;
858 /* Holds context's lock
861 g_source_list_remove (GSource *source,
862 GMainContext *context)
865 source->prev->next = source->next;
867 context->source_list = source->next;
870 source->next->prev = source->prev;
877 g_source_attach_unlocked (GSource *source,
878 GMainContext *context)
883 source->context = context;
884 result = source->source_id = context->next_id++;
887 g_source_list_add (source, context);
889 tmp_list = source->poll_fds;
892 g_main_context_add_poll_unlocked (context, source->priority, tmp_list->data);
893 tmp_list = tmp_list->next;
898 tmp_list = source->priv->child_sources;
901 g_source_attach_unlocked (tmp_list->data, context);
902 tmp_list = tmp_list->next;
911 * @source: a #GSource
912 * @context: a #GMainContext (if %NULL, the default context will be used)
914 * Adds a #GSource to a @context so that it will be executed within
915 * that context. Remove it by calling g_source_destroy().
917 * Return value: the ID (greater than 0) for the source within the
921 g_source_attach (GSource *source,
922 GMainContext *context)
926 g_return_val_if_fail (source->context == NULL, 0);
927 g_return_val_if_fail (!SOURCE_DESTROYED (source), 0);
930 context = g_main_context_default ();
932 LOCK_CONTEXT (context);
934 result = g_source_attach_unlocked (source, context);
936 /* Now wake up the main loop if it is waiting in the poll() */
937 g_main_context_wakeup_unlocked (context);
939 UNLOCK_CONTEXT (context);
945 g_source_destroy_internal (GSource *source,
946 GMainContext *context,
950 LOCK_CONTEXT (context);
952 if (!SOURCE_DESTROYED (source))
955 gpointer old_cb_data;
956 GSourceCallbackFuncs *old_cb_funcs;
958 source->flags &= ~G_HOOK_FLAG_ACTIVE;
960 old_cb_data = source->callback_data;
961 old_cb_funcs = source->callback_funcs;
963 source->callback_data = NULL;
964 source->callback_funcs = NULL;
968 UNLOCK_CONTEXT (context);
969 old_cb_funcs->unref (old_cb_data);
970 LOCK_CONTEXT (context);
973 if (!SOURCE_BLOCKED (source))
975 tmp_list = source->poll_fds;
978 g_main_context_remove_poll_unlocked (context, tmp_list->data);
979 tmp_list = tmp_list->next;
983 if (source->priv && source->priv->child_sources)
985 /* This is safe because even if a child_source finalizer or
986 * closure notify tried to modify source->priv->child_sources
987 * from outside the lock, it would fail since
988 * SOURCE_DESTROYED(source) is now TRUE.
990 tmp_list = source->priv->child_sources;
993 g_source_destroy_internal (tmp_list->data, context, TRUE);
994 g_source_unref_internal (tmp_list->data, context, TRUE);
995 tmp_list = tmp_list->next;
997 g_slist_free (source->priv->child_sources);
998 source->priv->child_sources = NULL;
1001 g_source_unref_internal (source, context, TRUE);
1005 UNLOCK_CONTEXT (context);
1010 * @source: a #GSource
1012 * Removes a source from its #GMainContext, if any, and mark it as
1013 * destroyed. The source cannot be subsequently added to another
1017 g_source_destroy (GSource *source)
1019 GMainContext *context;
1021 g_return_if_fail (source != NULL);
1023 context = source->context;
1026 g_source_destroy_internal (source, context, FALSE);
1028 source->flags &= ~G_HOOK_FLAG_ACTIVE;
1033 * @source: a #GSource
1035 * Returns the numeric ID for a particular source. The ID of a source
1036 * is a positive integer which is unique within a particular main loop
1037 * context. The reverse
1038 * mapping from ID to source is done by g_main_context_find_source_by_id().
1040 * Return value: the ID (greater than 0) for the source
1043 g_source_get_id (GSource *source)
1047 g_return_val_if_fail (source != NULL, 0);
1048 g_return_val_if_fail (source->context != NULL, 0);
1050 LOCK_CONTEXT (source->context);
1051 result = source->source_id;
1052 UNLOCK_CONTEXT (source->context);
1058 * g_source_get_context:
1059 * @source: a #GSource
1061 * Gets the #GMainContext with which the source is associated.
1062 * Calling this function on a destroyed source is an error.
1064 * Return value: (transfer none): the #GMainContext with which the
1065 * source is associated, or %NULL if the context has not
1066 * yet been added to a source.
1069 g_source_get_context (GSource *source)
1071 g_return_val_if_fail (!SOURCE_DESTROYED (source), NULL);
1073 return source->context;
1077 * g_source_add_poll:
1078 * @source:a #GSource
1079 * @fd: a #GPollFD structure holding information about a file
1080 * descriptor to watch.
1082 * Adds a file descriptor to the set of file descriptors polled for
1083 * this source. This is usually combined with g_source_new() to add an
1084 * event source. The event source's check function will typically test
1085 * the @revents field in the #GPollFD struct and return %TRUE if events need
1089 g_source_add_poll (GSource *source,
1092 GMainContext *context;
1094 g_return_if_fail (source != NULL);
1095 g_return_if_fail (fd != NULL);
1096 g_return_if_fail (!SOURCE_DESTROYED (source));
1098 context = source->context;
1101 LOCK_CONTEXT (context);
1103 source->poll_fds = g_slist_prepend (source->poll_fds, fd);
1107 if (!SOURCE_BLOCKED (source))
1108 g_main_context_add_poll_unlocked (context, source->priority, fd);
1109 UNLOCK_CONTEXT (context);
1114 * g_source_remove_poll:
1115 * @source:a #GSource
1116 * @fd: a #GPollFD structure previously passed to g_source_add_poll().
1118 * Removes a file descriptor from the set of file descriptors polled for
1122 g_source_remove_poll (GSource *source,
1125 GMainContext *context;
1127 g_return_if_fail (source != NULL);
1128 g_return_if_fail (fd != NULL);
1129 g_return_if_fail (!SOURCE_DESTROYED (source));
1131 context = source->context;
1134 LOCK_CONTEXT (context);
1136 source->poll_fds = g_slist_remove (source->poll_fds, fd);
1140 if (!SOURCE_BLOCKED (source))
1141 g_main_context_remove_poll_unlocked (context, fd);
1142 UNLOCK_CONTEXT (context);
1147 * g_source_add_child_source:
1148 * @source:a #GSource
1149 * @child_source: a second #GSource that @source should "poll"
1151 * Adds @child_source to @source as a "polled" source; when @source is
1152 * added to a #GMainContext, @child_source will be automatically added
1153 * with the same priority, when @child_source is triggered, it will
1154 * cause @source to dispatch (in addition to calling its own
1155 * callback), and when @source is destroyed, it will destroy
1156 * @child_source as well. (@source will also still be dispatched if
1157 * its own prepare/check functions indicate that it is ready.)
1159 * If you don't need @child_source to do anything on its own when it
1160 * triggers, you can call g_source_set_dummy_callback() on it to set a
1161 * callback that does nothing (except return %TRUE if appropriate).
1163 * @source will hold a reference on @child_source while @child_source
1164 * is attached to it.
1169 g_source_add_child_source (GSource *source,
1170 GSource *child_source)
1172 GMainContext *context;
1174 g_return_if_fail (source != NULL);
1175 g_return_if_fail (child_source != NULL);
1176 g_return_if_fail (!SOURCE_DESTROYED (source));
1177 g_return_if_fail (!SOURCE_DESTROYED (child_source));
1178 g_return_if_fail (child_source->context == NULL);
1179 g_return_if_fail (child_source->priv == NULL || child_source->priv->parent_source == NULL);
1181 context = source->context;
1184 LOCK_CONTEXT (context);
1187 source->priv = g_slice_new0 (GSourcePrivate);
1188 if (!child_source->priv)
1189 child_source->priv = g_slice_new0 (GSourcePrivate);
1191 source->priv->child_sources = g_slist_prepend (source->priv->child_sources,
1192 g_source_ref (child_source));
1193 child_source->priv->parent_source = source;
1194 g_source_set_priority_unlocked (child_source, context, source->priority);
1198 UNLOCK_CONTEXT (context);
1199 g_source_attach (child_source, context);
1204 * g_source_remove_child_source:
1205 * @source:a #GSource
1206 * @child_source: a #GSource previously passed to
1207 * g_source_add_child_source().
1209 * Detaches @child_source from @source and destroys it.
1214 g_source_remove_child_source (GSource *source,
1215 GSource *child_source)
1217 GMainContext *context;
1219 g_return_if_fail (source != NULL);
1220 g_return_if_fail (child_source != NULL);
1221 g_return_if_fail (child_source->priv != NULL && child_source->priv->parent_source == source);
1222 g_return_if_fail (!SOURCE_DESTROYED (source));
1223 g_return_if_fail (!SOURCE_DESTROYED (child_source));
1225 context = source->context;
1228 LOCK_CONTEXT (context);
1230 source->priv->child_sources = g_slist_remove (source->priv->child_sources, child_source);
1231 g_source_destroy_internal (child_source, context, TRUE);
1232 g_source_unref_internal (child_source, context, TRUE);
1235 UNLOCK_CONTEXT (context);
1239 * g_source_set_callback_indirect:
1240 * @source: the source
1241 * @callback_data: pointer to callback data "object"
1242 * @callback_funcs: functions for reference counting @callback_data
1243 * and getting the callback and data
1245 * Sets the callback function storing the data as a refcounted callback
1246 * "object". This is used internally. Note that calling
1247 * g_source_set_callback_indirect() assumes
1248 * an initial reference count on @callback_data, and thus
1249 * @callback_funcs->unref will eventually be called once more
1250 * than @callback_funcs->ref.
1253 g_source_set_callback_indirect (GSource *source,
1254 gpointer callback_data,
1255 GSourceCallbackFuncs *callback_funcs)
1257 GMainContext *context;
1258 gpointer old_cb_data;
1259 GSourceCallbackFuncs *old_cb_funcs;
1261 g_return_if_fail (source != NULL);
1262 g_return_if_fail (callback_funcs != NULL || callback_data == NULL);
1264 context = source->context;
1267 LOCK_CONTEXT (context);
1269 old_cb_data = source->callback_data;
1270 old_cb_funcs = source->callback_funcs;
1272 source->callback_data = callback_data;
1273 source->callback_funcs = callback_funcs;
1276 UNLOCK_CONTEXT (context);
1279 old_cb_funcs->unref (old_cb_data);
1283 g_source_callback_ref (gpointer cb_data)
1285 GSourceCallback *callback = cb_data;
1287 callback->ref_count++;
1292 g_source_callback_unref (gpointer cb_data)
1294 GSourceCallback *callback = cb_data;
1296 callback->ref_count--;
1297 if (callback->ref_count == 0)
1299 if (callback->notify)
1300 callback->notify (callback->data);
1306 g_source_callback_get (gpointer cb_data,
1311 GSourceCallback *callback = cb_data;
1313 *func = callback->func;
1314 *data = callback->data;
1317 static GSourceCallbackFuncs g_source_callback_funcs = {
1318 g_source_callback_ref,
1319 g_source_callback_unref,
1320 g_source_callback_get,
1324 * g_source_set_callback:
1325 * @source: the source
1326 * @func: a callback function
1327 * @data: the data to pass to callback function
1328 * @notify: a function to call when @data is no longer in use, or %NULL.
1330 * Sets the callback function for a source. The callback for a source is
1331 * called from the source's dispatch function.
1333 * The exact type of @func depends on the type of source; ie. you
1334 * should not count on @func being called with @data as its first
1337 * Typically, you won't use this function. Instead use functions specific
1338 * to the type of source you are using.
1341 g_source_set_callback (GSource *source,
1344 GDestroyNotify notify)
1346 GSourceCallback *new_callback;
1348 g_return_if_fail (source != NULL);
1350 new_callback = g_new (GSourceCallback, 1);
1352 new_callback->ref_count = 1;
1353 new_callback->func = func;
1354 new_callback->data = data;
1355 new_callback->notify = notify;
1357 g_source_set_callback_indirect (source, new_callback, &g_source_callback_funcs);
1362 * g_source_set_funcs:
1363 * @source: a #GSource
1364 * @funcs: the new #GSourceFuncs
1366 * Sets the source functions (can be used to override
1367 * default implementations) of an unattached source.
1372 g_source_set_funcs (GSource *source,
1373 GSourceFuncs *funcs)
1375 g_return_if_fail (source != NULL);
1376 g_return_if_fail (source->context == NULL);
1377 g_return_if_fail (source->ref_count > 0);
1378 g_return_if_fail (funcs != NULL);
1380 source->source_funcs = funcs;
1384 g_source_set_priority_unlocked (GSource *source,
1385 GMainContext *context,
1390 source->priority = priority;
1394 /* Remove the source from the context's source and then
1395 * add it back so it is sorted in the correct place
1397 g_source_list_remove (source, source->context);
1398 g_source_list_add (source, source->context);
1400 if (!SOURCE_BLOCKED (source))
1402 tmp_list = source->poll_fds;
1405 g_main_context_remove_poll_unlocked (context, tmp_list->data);
1406 g_main_context_add_poll_unlocked (context, priority, tmp_list->data);
1408 tmp_list = tmp_list->next;
1413 if (source->priv && source->priv->child_sources)
1415 tmp_list = source->priv->child_sources;
1418 g_source_set_priority_unlocked (tmp_list->data, context, priority);
1419 tmp_list = tmp_list->next;
1425 * g_source_set_priority:
1426 * @source: a #GSource
1427 * @priority: the new priority.
1429 * Sets the priority of a source. While the main loop is being run, a
1430 * source will be dispatched if it is ready to be dispatched and no
1431 * sources at a higher (numerically smaller) priority are ready to be
1435 g_source_set_priority (GSource *source,
1438 GMainContext *context;
1440 g_return_if_fail (source != NULL);
1442 context = source->context;
1445 LOCK_CONTEXT (context);
1446 g_source_set_priority_unlocked (source, context, priority);
1448 UNLOCK_CONTEXT (source->context);
1452 * g_source_get_priority:
1453 * @source: a #GSource
1455 * Gets the priority of a source.
1457 * Return value: the priority of the source
1460 g_source_get_priority (GSource *source)
1462 g_return_val_if_fail (source != NULL, 0);
1464 return source->priority;
1468 * g_source_set_can_recurse:
1469 * @source: a #GSource
1470 * @can_recurse: whether recursion is allowed for this source
1472 * Sets whether a source can be called recursively. If @can_recurse is
1473 * %TRUE, then while the source is being dispatched then this source
1474 * will be processed normally. Otherwise, all processing of this
1475 * source is blocked until the dispatch function returns.
1478 g_source_set_can_recurse (GSource *source,
1479 gboolean can_recurse)
1481 GMainContext *context;
1483 g_return_if_fail (source != NULL);
1485 context = source->context;
1488 LOCK_CONTEXT (context);
1491 source->flags |= G_SOURCE_CAN_RECURSE;
1493 source->flags &= ~G_SOURCE_CAN_RECURSE;
1496 UNLOCK_CONTEXT (context);
1500 * g_source_get_can_recurse:
1501 * @source: a #GSource
1503 * Checks whether a source is allowed to be called recursively.
1504 * see g_source_set_can_recurse().
1506 * Return value: whether recursion is allowed.
1509 g_source_get_can_recurse (GSource *source)
1511 g_return_val_if_fail (source != NULL, FALSE);
1513 return (source->flags & G_SOURCE_CAN_RECURSE) != 0;
1518 * g_source_set_name:
1519 * @source: a #GSource
1520 * @name: debug name for the source
1522 * Sets a name for the source, used in debugging and profiling.
1523 * The name defaults to #NULL.
1525 * The source name should describe in a human-readable way
1526 * what the source does. For example, "X11 event queue"
1527 * or "GTK+ repaint idle handler" or whatever it is.
1529 * It is permitted to call this function multiple times, but is not
1530 * recommended due to the potential performance impact. For example,
1531 * one could change the name in the "check" function of a #GSourceFuncs
1532 * to include details like the event type in the source name.
1537 g_source_set_name (GSource *source,
1540 g_return_if_fail (source != NULL);
1542 /* setting back to NULL is allowed, just because it's
1543 * weird if get_name can return NULL but you can't
1547 g_free (source->name);
1548 source->name = g_strdup (name);
1552 * g_source_get_name:
1553 * @source: a #GSource
1555 * Gets a name for the source, used in debugging and profiling.
1556 * The name may be #NULL if it has never been set with
1557 * g_source_set_name().
1559 * Return value: the name of the source
1563 g_source_get_name (GSource *source)
1565 g_return_val_if_fail (source != NULL, NULL);
1567 return source->name;
1571 * g_source_set_name_by_id:
1572 * @tag: a #GSource ID
1573 * @name: debug name for the source
1575 * Sets the name of a source using its ID.
1577 * This is a convenience utility to set source names from the return
1578 * value of g_idle_add(), g_timeout_add(), etc.
1583 g_source_set_name_by_id (guint tag,
1588 g_return_if_fail (tag > 0);
1590 source = g_main_context_find_source_by_id (NULL, tag);
1594 g_source_set_name (source, name);
1600 * @source: a #GSource
1602 * Increases the reference count on a source by one.
1604 * Return value: @source
1607 g_source_ref (GSource *source)
1609 GMainContext *context;
1611 g_return_val_if_fail (source != NULL, NULL);
1613 context = source->context;
1616 LOCK_CONTEXT (context);
1618 source->ref_count++;
1621 UNLOCK_CONTEXT (context);
1626 /* g_source_unref() but possible to call within context lock
1629 g_source_unref_internal (GSource *source,
1630 GMainContext *context,
1633 gpointer old_cb_data = NULL;
1634 GSourceCallbackFuncs *old_cb_funcs = NULL;
1636 g_return_if_fail (source != NULL);
1638 if (!have_lock && context)
1639 LOCK_CONTEXT (context);
1641 source->ref_count--;
1642 if (source->ref_count == 0)
1644 old_cb_data = source->callback_data;
1645 old_cb_funcs = source->callback_funcs;
1647 source->callback_data = NULL;
1648 source->callback_funcs = NULL;
1652 if (!SOURCE_DESTROYED (source))
1653 g_warning (G_STRLOC ": ref_count == 0, but source was still attached to a context!");
1654 g_source_list_remove (source, context);
1657 if (source->source_funcs->finalize)
1660 UNLOCK_CONTEXT (context);
1661 source->source_funcs->finalize (source);
1663 LOCK_CONTEXT (context);
1666 g_free (source->name);
1667 source->name = NULL;
1669 g_slist_free (source->poll_fds);
1670 source->poll_fds = NULL;
1674 g_slice_free (GSourcePrivate, source->priv);
1675 source->priv = NULL;
1681 if (!have_lock && context)
1682 UNLOCK_CONTEXT (context);
1687 UNLOCK_CONTEXT (context);
1689 old_cb_funcs->unref (old_cb_data);
1692 LOCK_CONTEXT (context);
1698 * @source: a #GSource
1700 * Decreases the reference count of a source by one. If the
1701 * resulting reference count is zero the source and associated
1702 * memory will be destroyed.
1705 g_source_unref (GSource *source)
1707 g_return_if_fail (source != NULL);
1709 g_source_unref_internal (source, source->context, FALSE);
1713 * g_main_context_find_source_by_id:
1714 * @context: a #GMainContext (if %NULL, the default context will be used)
1715 * @source_id: the source ID, as returned by g_source_get_id().
1717 * Finds a #GSource given a pair of context and ID.
1719 * Return value: (transfer none): the #GSource if found, otherwise, %NULL
1722 g_main_context_find_source_by_id (GMainContext *context,
1727 g_return_val_if_fail (source_id > 0, NULL);
1729 if (context == NULL)
1730 context = g_main_context_default ();
1732 LOCK_CONTEXT (context);
1734 source = context->source_list;
1737 if (!SOURCE_DESTROYED (source) &&
1738 source->source_id == source_id)
1740 source = source->next;
1743 UNLOCK_CONTEXT (context);
1749 * g_main_context_find_source_by_funcs_user_data:
1750 * @context: a #GMainContext (if %NULL, the default context will be used).
1751 * @funcs: the @source_funcs passed to g_source_new().
1752 * @user_data: the user data from the callback.
1754 * Finds a source with the given source functions and user data. If
1755 * multiple sources exist with the same source function and user data,
1756 * the first one found will be returned.
1758 * Return value: (transfer none): the source, if one was found, otherwise %NULL
1761 g_main_context_find_source_by_funcs_user_data (GMainContext *context,
1762 GSourceFuncs *funcs,
1767 g_return_val_if_fail (funcs != NULL, NULL);
1769 if (context == NULL)
1770 context = g_main_context_default ();
1772 LOCK_CONTEXT (context);
1774 source = context->source_list;
1777 if (!SOURCE_DESTROYED (source) &&
1778 source->source_funcs == funcs &&
1779 source->callback_funcs)
1781 GSourceFunc callback;
1782 gpointer callback_data;
1784 source->callback_funcs->get (source->callback_data, source, &callback, &callback_data);
1786 if (callback_data == user_data)
1789 source = source->next;
1792 UNLOCK_CONTEXT (context);
1798 * g_main_context_find_source_by_user_data:
1799 * @context: a #GMainContext
1800 * @user_data: the user_data for the callback.
1802 * Finds a source with the given user data for the callback. If
1803 * multiple sources exist with the same user data, the first
1804 * one found will be returned.
1806 * Return value: (transfer none): the source, if one was found, otherwise %NULL
1809 g_main_context_find_source_by_user_data (GMainContext *context,
1814 if (context == NULL)
1815 context = g_main_context_default ();
1817 LOCK_CONTEXT (context);
1819 source = context->source_list;
1822 if (!SOURCE_DESTROYED (source) &&
1823 source->callback_funcs)
1825 GSourceFunc callback;
1826 gpointer callback_data = NULL;
1828 source->callback_funcs->get (source->callback_data, source, &callback, &callback_data);
1830 if (callback_data == user_data)
1833 source = source->next;
1836 UNLOCK_CONTEXT (context);
1843 * @tag: the ID of the source to remove.
1845 * Removes the source with the given id from the default main context.
1847 * a #GSource is given by g_source_get_id(), or will be returned by the
1848 * functions g_source_attach(), g_idle_add(), g_idle_add_full(),
1849 * g_timeout_add(), g_timeout_add_full(), g_child_watch_add(),
1850 * g_child_watch_add_full(), g_io_add_watch(), and g_io_add_watch_full().
1852 * See also g_source_destroy(). You must use g_source_destroy() for sources
1853 * added to a non-default main context.
1855 * Return value: %TRUE if the source was found and removed.
1858 g_source_remove (guint tag)
1862 g_return_val_if_fail (tag > 0, FALSE);
1864 source = g_main_context_find_source_by_id (NULL, tag);
1866 g_source_destroy (source);
1868 return source != NULL;
1872 * g_source_remove_by_user_data:
1873 * @user_data: the user_data for the callback.
1875 * Removes a source from the default main loop context given the user
1876 * data for the callback. If multiple sources exist with the same user
1877 * data, only one will be destroyed.
1879 * Return value: %TRUE if a source was found and removed.
1882 g_source_remove_by_user_data (gpointer user_data)
1886 source = g_main_context_find_source_by_user_data (NULL, user_data);
1889 g_source_destroy (source);
1897 * g_source_remove_by_funcs_user_data:
1898 * @funcs: The @source_funcs passed to g_source_new()
1899 * @user_data: the user data for the callback
1901 * Removes a source from the default main loop context given the
1902 * source functions and user data. If multiple sources exist with the
1903 * same source functions and user data, only one will be destroyed.
1905 * Return value: %TRUE if a source was found and removed.
1908 g_source_remove_by_funcs_user_data (GSourceFuncs *funcs,
1913 g_return_val_if_fail (funcs != NULL, FALSE);
1915 source = g_main_context_find_source_by_funcs_user_data (NULL, funcs, user_data);
1918 g_source_destroy (source);
1926 * g_get_current_time:
1927 * @result: #GTimeVal structure in which to store current time.
1929 * Equivalent to the UNIX gettimeofday() function, but portable.
1931 * You may find g_get_real_time() to be more convenient.
1934 g_get_current_time (GTimeVal *result)
1939 g_return_if_fail (result != NULL);
1941 /*this is required on alpha, there the timeval structs are int's
1942 not longs and a cast only would fail horribly*/
1943 gettimeofday (&r, NULL);
1944 result->tv_sec = r.tv_sec;
1945 result->tv_usec = r.tv_usec;
1950 g_return_if_fail (result != NULL);
1952 GetSystemTimeAsFileTime (&ft);
1953 memmove (&time64, &ft, sizeof (FILETIME));
1955 /* Convert from 100s of nanoseconds since 1601-01-01
1956 * to Unix epoch. Yes, this is Y2038 unsafe.
1958 time64 -= G_GINT64_CONSTANT (116444736000000000);
1961 result->tv_sec = time64 / 1000000;
1962 result->tv_usec = time64 % 1000000;
1969 * Queries the system wall-clock time.
1971 * This call is functionally equivalent to g_get_current_time() except
1972 * that the return value is often more convenient than dealing with a
1975 * You should only use this call if you are actually interested in the real
1976 * wall-clock time. g_get_monotonic_time() is probably more useful for
1977 * measuring intervals.
1979 * Returns: the number of microseconds since January 1, 1970 UTC.
1984 g_get_real_time (void)
1988 g_get_current_time (&tv);
1990 return (((gint64) tv.tv_sec) * 1000000) + tv.tv_usec;
1994 * g_get_monotonic_time:
1996 * Queries the system monotonic time, if available.
1998 * On POSIX systems with clock_gettime() and %CLOCK_MONOTONIC this call
1999 * is a very shallow wrapper for that. Otherwise, we make a best effort
2000 * that probably involves returning the wall clock time (with at least
2001 * microsecond accuracy, subject to the limitations of the OS kernel).
2003 * It's important to note that POSIX %CLOCK_MONOTONIC does not count
2004 * time spent while the machine is suspended.
2006 * On Windows, "limitations of the OS kernel" is a rather substantial
2007 * statement. Depending on the configuration of the system, the wall
2008 * clock time is updated as infrequently as 64 times a second (which
2009 * is approximately every 16ms).
2011 * Returns: the monotonic time, in microseconds
2016 g_get_monotonic_time (void)
2018 #ifdef HAVE_CLOCK_GETTIME
2019 /* librt clock_gettime() is our first choice */
2021 #ifdef HAVE_MONOTONIC_CLOCK
2022 static volatile gsize clockid = 0;
2024 static clockid_t clockid = CLOCK_REALTIME;
2028 #ifdef HAVE_MONOTONIC_CLOCK
2029 if (g_once_init_enter (&clockid))
2031 clockid_t best_clockid;
2033 if (sysconf (_SC_MONOTONIC_CLOCK) >= 0)
2034 best_clockid = CLOCK_MONOTONIC;
2036 best_clockid = CLOCK_REALTIME;
2037 g_once_init_leave (&clockid, (gsize)best_clockid);
2041 clock_gettime (clockid, &ts);
2043 /* In theory monotonic time can have any epoch.
2045 * glib presently assumes the following:
2047 * 1) The epoch comes some time after the birth of Jesus of Nazareth, but
2048 * not more than 10000 years later.
2050 * 2) The current time also falls sometime within this range.
2052 * These two reasonable assumptions leave us with a maximum deviation from
2053 * the epoch of 10000 years, or 315569520000000000 seconds.
2055 * If we restrict ourselves to this range then the number of microseconds
2056 * will always fit well inside the constraints of a int64 (by a factor of
2059 * If you actually hit the following assertion, probably you should file a
2060 * bug against your operating system for being excessively silly.
2062 g_assert (G_GINT64_CONSTANT (-315569520000000000) < ts.tv_sec &&
2063 ts.tv_sec < G_GINT64_CONSTANT (315569520000000000));
2065 return (((gint64) ts.tv_sec) * 1000000) + (ts.tv_nsec / 1000);
2068 /* It may look like we are discarding accuracy on Windows (since its
2069 * current time is expressed in 100s of nanoseconds) but according to
2070 * many sources, the time is only updated 64 times per second, so
2071 * microsecond accuracy is more than enough.
2076 g_get_current_time (&tv);
2078 return (((gint64) tv.tv_sec) * 1000000) + tv.tv_usec;
2084 g_main_dispatch_free (gpointer dispatch)
2086 g_slice_free (GMainDispatch, dispatch);
2089 /* Running the main loop */
2091 static GMainDispatch *
2094 static GStaticPrivate depth_private = G_STATIC_PRIVATE_INIT;
2095 GMainDispatch *dispatch = g_static_private_get (&depth_private);
2098 dispatch = g_slice_new0 (GMainDispatch);
2099 g_static_private_set (&depth_private, dispatch, g_main_dispatch_free);
2108 * Returns the depth of the stack of calls to
2109 * g_main_context_dispatch() on any #GMainContext in the current thread.
2110 * That is, when called from the toplevel, it gives 0. When
2111 * called from within a callback from g_main_context_iteration()
2112 * (or g_main_loop_run(), etc.) it returns 1. When called from within
2113 * a callback to a recursive call to g_main_context_iteration(),
2114 * it returns 2. And so forth.
2116 * This function is useful in a situation like the following:
2117 * Imagine an extremely simple "garbage collected" system.
2120 * static GList *free_list;
2123 * allocate_memory (gsize size)
2125 * gpointer result = g_malloc (size);
2126 * free_list = g_list_prepend (free_list, result);
2131 * free_allocated_memory (void)
2134 * for (l = free_list; l; l = l->next);
2136 * g_list_free (free_list);
2144 * g_main_context_iteration (NULL, TRUE);
2145 * free_allocated_memory();
2149 * This works from an application, however, if you want to do the same
2150 * thing from a library, it gets more difficult, since you no longer
2151 * control the main loop. You might think you can simply use an idle
2152 * function to make the call to free_allocated_memory(), but that
2153 * doesn't work, since the idle function could be called from a
2154 * recursive callback. This can be fixed by using g_main_depth()
2158 * allocate_memory (gsize size)
2160 * FreeListBlock *block = g_new (FreeListBlock, 1);
2161 * block->mem = g_malloc (size);
2162 * block->depth = g_main_depth ();
2163 * free_list = g_list_prepend (free_list, block);
2164 * return block->mem;
2168 * free_allocated_memory (void)
2172 * int depth = g_main_depth ();
2173 * for (l = free_list; l; );
2175 * GList *next = l->next;
2176 * FreeListBlock *block = l->data;
2177 * if (block->depth > depth)
2179 * g_free (block->mem);
2181 * free_list = g_list_delete_link (free_list, l);
2189 * There is a temptation to use g_main_depth() to solve
2190 * problems with reentrancy. For instance, while waiting for data
2191 * to be received from the network in response to a menu item,
2192 * the menu item might be selected again. It might seem that
2193 * one could make the menu item's callback return immediately
2194 * and do nothing if g_main_depth() returns a value greater than 1.
2195 * However, this should be avoided since the user then sees selecting
2196 * the menu item do nothing. Furthermore, you'll find yourself adding
2197 * these checks all over your code, since there are doubtless many,
2198 * many things that the user could do. Instead, you can use the
2199 * following techniques:
2204 * Use gtk_widget_set_sensitive() or modal dialogs to prevent
2205 * the user from interacting with elements while the main
2206 * loop is recursing.
2211 * Avoid main loop recursion in situations where you can't handle
2212 * arbitrary callbacks. Instead, structure your code so that you
2213 * simply return to the main loop and then get called again when
2214 * there is more work to do.
2219 * Return value: The main loop recursion level in the current thread
2224 GMainDispatch *dispatch = get_dispatch ();
2225 return dispatch->depth;
2229 * g_main_current_source:
2231 * Returns the currently firing source for this thread.
2233 * Return value: (transfer none): The currently firing source or %NULL.
2238 g_main_current_source (void)
2240 GMainDispatch *dispatch = get_dispatch ();
2241 return dispatch->dispatching_sources ? dispatch->dispatching_sources->data : NULL;
2245 * g_source_is_destroyed:
2246 * @source: a #GSource
2248 * Returns whether @source has been destroyed.
2250 * This is important when you operate upon your objects
2251 * from within idle handlers, but may have freed the object
2252 * before the dispatch of your idle handler.
2256 * idle_callback (gpointer data)
2258 * SomeWidget *self = data;
2260 * GDK_THREADS_ENTER (<!-- -->);
2261 * /<!-- -->* do stuff with self *<!-- -->/
2262 * self->idle_id = 0;
2263 * GDK_THREADS_LEAVE (<!-- -->);
2269 * some_widget_do_stuff_later (SomeWidget *self)
2271 * self->idle_id = g_idle_add (idle_callback, self);
2275 * some_widget_finalize (GObject *object)
2277 * SomeWidget *self = SOME_WIDGET (object);
2279 * if (self->idle_id)
2280 * g_source_remove (self->idle_id);
2282 * G_OBJECT_CLASS (parent_class)->finalize (object);
2286 * This will fail in a multi-threaded application if the
2287 * widget is destroyed before the idle handler fires due
2288 * to the use after free in the callback. A solution, to
2289 * this particular problem, is to check to if the source
2290 * has already been destroy within the callback.
2294 * idle_callback (gpointer data)
2296 * SomeWidget *self = data;
2298 * GDK_THREADS_ENTER ();
2299 * if (!g_source_is_destroyed (g_main_current_source ()))
2301 * /<!-- -->* do stuff with self *<!-- -->/
2303 * GDK_THREADS_LEAVE ();
2309 * Return value: %TRUE if the source has been destroyed
2314 g_source_is_destroyed (GSource *source)
2316 return SOURCE_DESTROYED (source);
2319 /* Temporarily remove all this source's file descriptors from the
2320 * poll(), so that if data comes available for one of the file descriptors
2321 * we don't continually spin in the poll()
2323 /* HOLDS: source->context's lock */
2325 block_source (GSource *source)
2329 g_return_if_fail (!SOURCE_BLOCKED (source));
2331 tmp_list = source->poll_fds;
2334 g_main_context_remove_poll_unlocked (source->context, tmp_list->data);
2335 tmp_list = tmp_list->next;
2339 /* HOLDS: source->context's lock */
2341 unblock_source (GSource *source)
2345 g_return_if_fail (!SOURCE_BLOCKED (source)); /* Source already unblocked */
2346 g_return_if_fail (!SOURCE_DESTROYED (source));
2348 tmp_list = source->poll_fds;
2351 g_main_context_add_poll_unlocked (source->context, source->priority, tmp_list->data);
2352 tmp_list = tmp_list->next;
2356 /* HOLDS: context's lock */
2358 g_main_dispatch (GMainContext *context)
2360 GMainDispatch *current = get_dispatch ();
2363 for (i = 0; i < context->pending_dispatches->len; i++)
2365 GSource *source = context->pending_dispatches->pdata[i];
2367 context->pending_dispatches->pdata[i] = NULL;
2370 source->flags &= ~G_SOURCE_READY;
2372 if (!SOURCE_DESTROYED (source))
2374 gboolean was_in_call;
2375 gpointer user_data = NULL;
2376 GSourceFunc callback = NULL;
2377 GSourceCallbackFuncs *cb_funcs;
2379 gboolean need_destroy;
2381 gboolean (*dispatch) (GSource *,
2384 GSList current_source_link;
2386 dispatch = source->source_funcs->dispatch;
2387 cb_funcs = source->callback_funcs;
2388 cb_data = source->callback_data;
2391 cb_funcs->ref (cb_data);
2393 if ((source->flags & G_SOURCE_CAN_RECURSE) == 0)
2394 block_source (source);
2396 was_in_call = source->flags & G_HOOK_FLAG_IN_CALL;
2397 source->flags |= G_HOOK_FLAG_IN_CALL;
2400 cb_funcs->get (cb_data, source, &callback, &user_data);
2402 UNLOCK_CONTEXT (context);
2405 /* The on-stack allocation of the GSList is unconventional, but
2406 * we know that the lifetime of the link is bounded to this
2407 * function as the link is kept in a thread specific list and
2408 * not manipulated outside of this function and its descendants.
2409 * Avoiding the overhead of a g_slist_alloc() is useful as many
2410 * applications do little more than dispatch events.
2412 * This is a performance hack - do not revert to g_slist_prepend()!
2414 current_source_link.data = source;
2415 current_source_link.next = current->dispatching_sources;
2416 current->dispatching_sources = ¤t_source_link;
2417 need_destroy = ! dispatch (source,
2420 g_assert (current->dispatching_sources == ¤t_source_link);
2421 current->dispatching_sources = current_source_link.next;
2425 cb_funcs->unref (cb_data);
2427 LOCK_CONTEXT (context);
2430 source->flags &= ~G_HOOK_FLAG_IN_CALL;
2432 if ((source->flags & G_SOURCE_CAN_RECURSE) == 0 &&
2433 !SOURCE_DESTROYED (source))
2434 unblock_source (source);
2436 /* Note: this depends on the fact that we can't switch
2437 * sources from one main context to another
2439 if (need_destroy && !SOURCE_DESTROYED (source))
2441 g_assert (source->context == context);
2442 g_source_destroy_internal (source, context, TRUE);
2446 SOURCE_UNREF (source, context);
2449 g_ptr_array_set_size (context->pending_dispatches, 0);
2452 /* Holds context's lock */
2453 static inline GSource *
2454 next_valid_source (GMainContext *context,
2457 GSource *new_source = source ? source->next : context->source_list;
2461 if (!SOURCE_DESTROYED (new_source))
2463 new_source->ref_count++;
2467 new_source = new_source->next;
2471 SOURCE_UNREF (source, context);
2477 * g_main_context_acquire:
2478 * @context: a #GMainContext
2480 * Tries to become the owner of the specified context.
2481 * If some other thread is the owner of the context,
2482 * returns %FALSE immediately. Ownership is properly
2483 * recursive: the owner can require ownership again
2484 * and will release ownership when g_main_context_release()
2485 * is called as many times as g_main_context_acquire().
2487 * You must be the owner of a context before you
2488 * can call g_main_context_prepare(), g_main_context_query(),
2489 * g_main_context_check(), g_main_context_dispatch().
2491 * Return value: %TRUE if the operation succeeded, and
2492 * this thread is now the owner of @context.
2495 g_main_context_acquire (GMainContext *context)
2497 gboolean result = FALSE;
2498 GThread *self = G_THREAD_SELF;
2500 if (context == NULL)
2501 context = g_main_context_default ();
2503 LOCK_CONTEXT (context);
2505 if (!context->owner)
2507 context->owner = self;
2508 g_assert (context->owner_count == 0);
2511 if (context->owner == self)
2513 context->owner_count++;
2517 UNLOCK_CONTEXT (context);
2523 * g_main_context_release:
2524 * @context: a #GMainContext
2526 * Releases ownership of a context previously acquired by this thread
2527 * with g_main_context_acquire(). If the context was acquired multiple
2528 * times, the ownership will be released only when g_main_context_release()
2529 * is called as many times as it was acquired.
2532 g_main_context_release (GMainContext *context)
2534 if (context == NULL)
2535 context = g_main_context_default ();
2537 LOCK_CONTEXT (context);
2539 context->owner_count--;
2540 if (context->owner_count == 0)
2542 context->owner = NULL;
2544 if (context->waiters)
2546 GMainWaiter *waiter = context->waiters->data;
2547 gboolean loop_internal_waiter =
2548 (waiter->mutex == g_static_mutex_get_mutex (&context->mutex));
2549 context->waiters = g_slist_delete_link (context->waiters,
2551 if (!loop_internal_waiter)
2552 g_mutex_lock (waiter->mutex);
2554 g_cond_signal (waiter->cond);
2556 if (!loop_internal_waiter)
2557 g_mutex_unlock (waiter->mutex);
2561 UNLOCK_CONTEXT (context);
2565 * g_main_context_wait:
2566 * @context: a #GMainContext
2567 * @cond: a condition variable
2568 * @mutex: a mutex, currently held
2570 * Tries to become the owner of the specified context,
2571 * as with g_main_context_acquire(). But if another thread
2572 * is the owner, atomically drop @mutex and wait on @cond until
2573 * that owner releases ownership or until @cond is signaled, then
2574 * try again (once) to become the owner.
2576 * Return value: %TRUE if the operation succeeded, and
2577 * this thread is now the owner of @context.
2580 g_main_context_wait (GMainContext *context,
2584 gboolean result = FALSE;
2585 GThread *self = G_THREAD_SELF;
2586 gboolean loop_internal_waiter;
2588 if (context == NULL)
2589 context = g_main_context_default ();
2591 loop_internal_waiter = (mutex == g_static_mutex_get_mutex (&context->mutex));
2593 if (!loop_internal_waiter)
2594 LOCK_CONTEXT (context);
2596 if (context->owner && context->owner != self)
2601 waiter.mutex = mutex;
2603 context->waiters = g_slist_append (context->waiters, &waiter);
2605 if (!loop_internal_waiter)
2606 UNLOCK_CONTEXT (context);
2607 g_cond_wait (cond, mutex);
2608 if (!loop_internal_waiter)
2609 LOCK_CONTEXT (context);
2611 context->waiters = g_slist_remove (context->waiters, &waiter);
2614 if (!context->owner)
2616 context->owner = self;
2617 g_assert (context->owner_count == 0);
2620 if (context->owner == self)
2622 context->owner_count++;
2626 if (!loop_internal_waiter)
2627 UNLOCK_CONTEXT (context);
2633 * g_main_context_prepare:
2634 * @context: a #GMainContext
2635 * @priority: location to store priority of highest priority
2636 * source already ready.
2638 * Prepares to poll sources within a main loop. The resulting information
2639 * for polling is determined by calling g_main_context_query ().
2641 * Return value: %TRUE if some source is ready to be dispatched
2645 g_main_context_prepare (GMainContext *context,
2650 gint current_priority = G_MAXINT;
2653 if (context == NULL)
2654 context = g_main_context_default ();
2656 LOCK_CONTEXT (context);
2658 context->time_is_fresh = FALSE;
2659 context->real_time_is_fresh = FALSE;
2661 if (context->in_check_or_prepare)
2663 g_warning ("g_main_context_prepare() called recursively from within a source's check() or "
2664 "prepare() member.");
2665 UNLOCK_CONTEXT (context);
2669 if (context->poll_waiting)
2671 g_warning("g_main_context_prepare(): main loop already active in another thread");
2672 UNLOCK_CONTEXT (context);
2676 context->poll_waiting = TRUE;
2679 /* If recursing, finish up current dispatch, before starting over */
2680 if (context->pending_dispatches)
2683 g_main_dispatch (context, ¤t_time);
2685 UNLOCK_CONTEXT (context);
2690 /* If recursing, clear list of pending dispatches */
2692 for (i = 0; i < context->pending_dispatches->len; i++)
2694 if (context->pending_dispatches->pdata[i])
2695 SOURCE_UNREF ((GSource *)context->pending_dispatches->pdata[i], context);
2697 g_ptr_array_set_size (context->pending_dispatches, 0);
2699 /* Prepare all sources */
2701 context->timeout = -1;
2703 source = next_valid_source (context, NULL);
2706 gint source_timeout = -1;
2708 if ((n_ready > 0) && (source->priority > current_priority))
2710 SOURCE_UNREF (source, context);
2713 if (SOURCE_BLOCKED (source))
2716 if (!(source->flags & G_SOURCE_READY))
2719 gboolean (*prepare) (GSource *source,
2722 prepare = source->source_funcs->prepare;
2723 context->in_check_or_prepare++;
2724 UNLOCK_CONTEXT (context);
2726 result = (*prepare) (source, &source_timeout);
2728 LOCK_CONTEXT (context);
2729 context->in_check_or_prepare--;
2733 GSource *ready_source = source;
2735 while (ready_source)
2737 ready_source->flags |= G_SOURCE_READY;
2738 ready_source = ready_source->priv ? ready_source->priv->parent_source : NULL;
2743 if (source->flags & G_SOURCE_READY)
2746 current_priority = source->priority;
2747 context->timeout = 0;
2750 if (source_timeout >= 0)
2752 if (context->timeout < 0)
2753 context->timeout = source_timeout;
2755 context->timeout = MIN (context->timeout, source_timeout);
2759 source = next_valid_source (context, source);
2762 UNLOCK_CONTEXT (context);
2765 *priority = current_priority;
2767 return (n_ready > 0);
2771 * g_main_context_query:
2772 * @context: a #GMainContext
2773 * @max_priority: maximum priority source to check
2774 * @timeout_: (out): location to store timeout to be used in polling
2775 * @fds: (out caller-allocates) (array length=n_fds): location to
2776 * store #GPollFD records that need to be polled.
2777 * @n_fds: length of @fds.
2779 * Determines information necessary to poll this main loop.
2781 * Return value: the number of records actually stored in @fds,
2782 * or, if more than @n_fds records need to be stored, the number
2783 * of records that need to be stored.
2786 g_main_context_query (GMainContext *context,
2795 LOCK_CONTEXT (context);
2797 pollrec = context->poll_records;
2799 while (pollrec && max_priority >= pollrec->priority)
2801 /* We need to include entries with fd->events == 0 in the array because
2802 * otherwise if the application changes fd->events behind our back and
2803 * makes it non-zero, we'll be out of sync when we check the fds[] array.
2804 * (Changing fd->events after adding an FD wasn't an anticipated use of
2805 * this API, but it occurs in practice.) */
2808 fds[n_poll].fd = pollrec->fd->fd;
2809 /* In direct contradiction to the Unix98 spec, IRIX runs into
2810 * difficulty if you pass in POLLERR, POLLHUP or POLLNVAL
2811 * flags in the events field of the pollfd while it should
2812 * just ignoring them. So we mask them out here.
2814 fds[n_poll].events = pollrec->fd->events & ~(G_IO_ERR|G_IO_HUP|G_IO_NVAL);
2815 fds[n_poll].revents = 0;
2818 pollrec = pollrec->next;
2822 context->poll_changed = FALSE;
2826 *timeout = context->timeout;
2829 context->time_is_fresh = FALSE;
2830 context->real_time_is_fresh = FALSE;
2834 UNLOCK_CONTEXT (context);
2840 * g_main_context_check:
2841 * @context: a #GMainContext
2842 * @max_priority: the maximum numerical priority of sources to check
2843 * @fds: (array length=n_fds): array of #GPollFD's that was passed to
2844 * the last call to g_main_context_query()
2845 * @n_fds: return value of g_main_context_query()
2847 * Passes the results of polling back to the main loop.
2849 * Return value: %TRUE if some sources are ready to be dispatched.
2852 g_main_context_check (GMainContext *context,
2862 LOCK_CONTEXT (context);
2864 if (context->in_check_or_prepare)
2866 g_warning ("g_main_context_check() called recursively from within a source's check() or "
2867 "prepare() member.");
2868 UNLOCK_CONTEXT (context);
2872 if (!context->poll_waiting)
2873 g_wakeup_acknowledge (context->wakeup);
2876 context->poll_waiting = FALSE;
2878 /* If the set of poll file descriptors changed, bail out
2879 * and let the main loop rerun
2881 if (context->poll_changed)
2883 UNLOCK_CONTEXT (context);
2887 pollrec = context->poll_records;
2891 if (pollrec->fd->events)
2892 pollrec->fd->revents = fds[i].revents;
2894 pollrec = pollrec->next;
2898 source = next_valid_source (context, NULL);
2901 if ((n_ready > 0) && (source->priority > max_priority))
2903 SOURCE_UNREF (source, context);
2906 if (SOURCE_BLOCKED (source))
2909 if (!(source->flags & G_SOURCE_READY))
2912 gboolean (*check) (GSource *source);
2914 check = source->source_funcs->check;
2916 context->in_check_or_prepare++;
2917 UNLOCK_CONTEXT (context);
2919 result = (*check) (source);
2921 LOCK_CONTEXT (context);
2922 context->in_check_or_prepare--;
2926 GSource *ready_source = source;
2928 while (ready_source)
2930 ready_source->flags |= G_SOURCE_READY;
2931 ready_source = ready_source->priv ? ready_source->priv->parent_source : NULL;
2936 if (source->flags & G_SOURCE_READY)
2938 source->ref_count++;
2939 g_ptr_array_add (context->pending_dispatches, source);
2943 /* never dispatch sources with less priority than the first
2944 * one we choose to dispatch
2946 max_priority = source->priority;
2950 source = next_valid_source (context, source);
2953 UNLOCK_CONTEXT (context);
2959 * g_main_context_dispatch:
2960 * @context: a #GMainContext
2962 * Dispatches all pending sources.
2965 g_main_context_dispatch (GMainContext *context)
2967 LOCK_CONTEXT (context);
2969 if (context->pending_dispatches->len > 0)
2971 g_main_dispatch (context);
2974 UNLOCK_CONTEXT (context);
2977 /* HOLDS context lock */
2979 g_main_context_iterate (GMainContext *context,
2986 gboolean some_ready;
2987 gint nfds, allocated_nfds;
2988 GPollFD *fds = NULL;
2990 UNLOCK_CONTEXT (context);
2992 if (!g_main_context_acquire (context))
2994 gboolean got_ownership;
2996 LOCK_CONTEXT (context);
2998 g_return_val_if_fail (g_thread_supported (), FALSE);
3004 context->cond = g_cond_new ();
3006 got_ownership = g_main_context_wait (context,
3008 g_static_mutex_get_mutex (&context->mutex));
3014 LOCK_CONTEXT (context);
3016 if (!context->cached_poll_array)
3018 context->cached_poll_array_size = context->n_poll_records;
3019 context->cached_poll_array = g_new (GPollFD, context->n_poll_records);
3022 allocated_nfds = context->cached_poll_array_size;
3023 fds = context->cached_poll_array;
3025 UNLOCK_CONTEXT (context);
3027 g_main_context_prepare (context, &max_priority);
3029 while ((nfds = g_main_context_query (context, max_priority, &timeout, fds,
3030 allocated_nfds)) > allocated_nfds)
3032 LOCK_CONTEXT (context);
3034 context->cached_poll_array_size = allocated_nfds = nfds;
3035 context->cached_poll_array = fds = g_new (GPollFD, nfds);
3036 UNLOCK_CONTEXT (context);
3042 g_main_context_poll (context, timeout, max_priority, fds, nfds);
3044 some_ready = g_main_context_check (context, max_priority, fds, nfds);
3047 g_main_context_dispatch (context);
3049 g_main_context_release (context);
3051 LOCK_CONTEXT (context);
3057 * g_main_context_pending:
3058 * @context: a #GMainContext (if %NULL, the default context will be used)
3060 * Checks if any sources have pending events for the given context.
3062 * Return value: %TRUE if events are pending.
3065 g_main_context_pending (GMainContext *context)
3070 context = g_main_context_default();
3072 LOCK_CONTEXT (context);
3073 retval = g_main_context_iterate (context, FALSE, FALSE, G_THREAD_SELF);
3074 UNLOCK_CONTEXT (context);
3080 * g_main_context_iteration:
3081 * @context: a #GMainContext (if %NULL, the default context will be used)
3082 * @may_block: whether the call may block.
3084 * Runs a single iteration for the given main loop. This involves
3085 * checking to see if any event sources are ready to be processed,
3086 * then if no events sources are ready and @may_block is %TRUE, waiting
3087 * for a source to become ready, then dispatching the highest priority
3088 * events sources that are ready. Otherwise, if @may_block is %FALSE
3089 * sources are not waited to become ready, only those highest priority
3090 * events sources will be dispatched (if any), that are ready at this
3091 * given moment without further waiting.
3093 * Note that even when @may_block is %TRUE, it is still possible for
3094 * g_main_context_iteration() to return %FALSE, since the the wait may
3095 * be interrupted for other reasons than an event source becoming ready.
3097 * Return value: %TRUE if events were dispatched.
3100 g_main_context_iteration (GMainContext *context, gboolean may_block)
3105 context = g_main_context_default();
3107 LOCK_CONTEXT (context);
3108 retval = g_main_context_iterate (context, may_block, TRUE, G_THREAD_SELF);
3109 UNLOCK_CONTEXT (context);
3116 * @context: (allow-none): a #GMainContext (if %NULL, the default context will be used).
3117 * @is_running: set to %TRUE to indicate that the loop is running. This
3118 * is not very important since calling g_main_loop_run() will set this to
3121 * Creates a new #GMainLoop structure.
3123 * Return value: a new #GMainLoop.
3126 g_main_loop_new (GMainContext *context,
3127 gboolean is_running)
3132 context = g_main_context_default();
3134 g_main_context_ref (context);
3136 loop = g_new0 (GMainLoop, 1);
3137 loop->context = context;
3138 loop->is_running = is_running != FALSE;
3139 loop->ref_count = 1;
3146 * @loop: a #GMainLoop
3148 * Increases the reference count on a #GMainLoop object by one.
3150 * Return value: @loop
3153 g_main_loop_ref (GMainLoop *loop)
3155 g_return_val_if_fail (loop != NULL, NULL);
3156 g_return_val_if_fail (g_atomic_int_get (&loop->ref_count) > 0, NULL);
3158 g_atomic_int_inc (&loop->ref_count);
3164 * g_main_loop_unref:
3165 * @loop: a #GMainLoop
3167 * Decreases the reference count on a #GMainLoop object by one. If
3168 * the result is zero, free the loop and free all associated memory.
3171 g_main_loop_unref (GMainLoop *loop)
3173 g_return_if_fail (loop != NULL);
3174 g_return_if_fail (g_atomic_int_get (&loop->ref_count) > 0);
3176 if (!g_atomic_int_dec_and_test (&loop->ref_count))
3179 g_main_context_unref (loop->context);
3185 * @loop: a #GMainLoop
3187 * Runs a main loop until g_main_loop_quit() is called on the loop.
3188 * If this is called for the thread of the loop's #GMainContext,
3189 * it will process events from the loop, otherwise it will
3193 g_main_loop_run (GMainLoop *loop)
3195 GThread *self = G_THREAD_SELF;
3197 g_return_if_fail (loop != NULL);
3198 g_return_if_fail (g_atomic_int_get (&loop->ref_count) > 0);
3200 if (!g_main_context_acquire (loop->context))
3202 gboolean got_ownership = FALSE;
3204 /* Another thread owns this context */
3205 if (!g_thread_supported ())
3207 g_warning ("g_main_loop_run() was called from second thread but "
3208 "g_thread_init() was never called.");
3212 LOCK_CONTEXT (loop->context);
3214 g_atomic_int_inc (&loop->ref_count);
3216 if (!loop->is_running)
3217 loop->is_running = TRUE;
3219 if (!loop->context->cond)
3220 loop->context->cond = g_cond_new ();
3222 while (loop->is_running && !got_ownership)
3223 got_ownership = g_main_context_wait (loop->context,
3224 loop->context->cond,
3225 g_static_mutex_get_mutex (&loop->context->mutex));
3227 if (!loop->is_running)
3229 UNLOCK_CONTEXT (loop->context);
3231 g_main_context_release (loop->context);
3232 g_main_loop_unref (loop);
3236 g_assert (got_ownership);
3239 LOCK_CONTEXT (loop->context);
3241 if (loop->context->in_check_or_prepare)
3243 g_warning ("g_main_loop_run(): called recursively from within a source's "
3244 "check() or prepare() member, iteration not possible.");
3248 g_atomic_int_inc (&loop->ref_count);
3249 loop->is_running = TRUE;
3250 while (loop->is_running)
3251 g_main_context_iterate (loop->context, TRUE, TRUE, self);
3253 UNLOCK_CONTEXT (loop->context);
3255 g_main_context_release (loop->context);
3257 g_main_loop_unref (loop);
3262 * @loop: a #GMainLoop
3264 * Stops a #GMainLoop from running. Any calls to g_main_loop_run()
3265 * for the loop will return.
3267 * Note that sources that have already been dispatched when
3268 * g_main_loop_quit() is called will still be executed.
3271 g_main_loop_quit (GMainLoop *loop)
3273 g_return_if_fail (loop != NULL);
3274 g_return_if_fail (g_atomic_int_get (&loop->ref_count) > 0);
3276 LOCK_CONTEXT (loop->context);
3277 loop->is_running = FALSE;
3278 g_main_context_wakeup_unlocked (loop->context);
3280 if (loop->context->cond)
3281 g_cond_broadcast (loop->context->cond);
3283 UNLOCK_CONTEXT (loop->context);
3287 * g_main_loop_is_running:
3288 * @loop: a #GMainLoop.
3290 * Checks to see if the main loop is currently being run via g_main_loop_run().
3292 * Return value: %TRUE if the mainloop is currently being run.
3295 g_main_loop_is_running (GMainLoop *loop)
3297 g_return_val_if_fail (loop != NULL, FALSE);
3298 g_return_val_if_fail (g_atomic_int_get (&loop->ref_count) > 0, FALSE);
3300 return loop->is_running;
3304 * g_main_loop_get_context:
3305 * @loop: a #GMainLoop.
3307 * Returns the #GMainContext of @loop.
3309 * Return value: (transfer none): the #GMainContext of @loop
3312 g_main_loop_get_context (GMainLoop *loop)
3314 g_return_val_if_fail (loop != NULL, NULL);
3315 g_return_val_if_fail (g_atomic_int_get (&loop->ref_count) > 0, NULL);
3317 return loop->context;
3320 /* HOLDS: context's lock */
3322 g_main_context_poll (GMainContext *context,
3328 #ifdef G_MAIN_POLL_DEBUG
3334 GPollFunc poll_func;
3336 if (n_fds || timeout != 0)
3338 #ifdef G_MAIN_POLL_DEBUG
3339 if (_g_main_poll_debug)
3341 g_print ("polling context=%p n=%d timeout=%d\n",
3342 context, n_fds, timeout);
3343 poll_timer = g_timer_new ();
3347 LOCK_CONTEXT (context);
3349 poll_func = context->poll_func;
3351 UNLOCK_CONTEXT (context);
3352 if ((*poll_func) (fds, n_fds, timeout) < 0 && errno != EINTR)
3355 g_warning ("poll(2) failed due to: %s.",
3356 g_strerror (errno));
3358 /* If g_poll () returns -1, it has already called g_warning() */
3362 #ifdef G_MAIN_POLL_DEBUG
3363 if (_g_main_poll_debug)
3365 LOCK_CONTEXT (context);
3367 g_print ("g_main_poll(%d) timeout: %d - elapsed %12.10f seconds",
3370 g_timer_elapsed (poll_timer, NULL));
3371 g_timer_destroy (poll_timer);
3372 pollrec = context->poll_records;
3374 while (pollrec != NULL)
3379 if (fds[i].fd == pollrec->fd->fd &&
3380 pollrec->fd->events &&
3383 g_print (" [" G_POLLFD_FORMAT " :", fds[i].fd);
3384 if (fds[i].revents & G_IO_IN)
3386 if (fds[i].revents & G_IO_OUT)
3388 if (fds[i].revents & G_IO_PRI)
3390 if (fds[i].revents & G_IO_ERR)
3392 if (fds[i].revents & G_IO_HUP)
3394 if (fds[i].revents & G_IO_NVAL)
3400 pollrec = pollrec->next;
3404 UNLOCK_CONTEXT (context);
3407 } /* if (n_fds || timeout != 0) */
3411 * g_main_context_add_poll:
3412 * @context: a #GMainContext (or %NULL for the default context)
3413 * @fd: a #GPollFD structure holding information about a file
3414 * descriptor to watch.
3415 * @priority: the priority for this file descriptor which should be
3416 * the same as the priority used for g_source_attach() to ensure that the
3417 * file descriptor is polled whenever the results may be needed.
3419 * Adds a file descriptor to the set of file descriptors polled for
3420 * this context. This will very seldom be used directly. Instead
3421 * a typical event source will use g_source_add_poll() instead.
3424 g_main_context_add_poll (GMainContext *context,
3429 context = g_main_context_default ();
3431 g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
3432 g_return_if_fail (fd);
3434 LOCK_CONTEXT (context);
3435 g_main_context_add_poll_unlocked (context, priority, fd);
3436 UNLOCK_CONTEXT (context);
3439 /* HOLDS: main_loop_lock */
3441 g_main_context_add_poll_unlocked (GMainContext *context,
3445 GPollRec *prevrec, *nextrec;
3446 GPollRec *newrec = g_slice_new (GPollRec);
3448 /* This file descriptor may be checked before we ever poll */
3451 newrec->priority = priority;
3453 prevrec = context->poll_records_tail;
3455 while (prevrec && priority < prevrec->priority)
3458 prevrec = prevrec->prev;
3462 prevrec->next = newrec;
3464 context->poll_records = newrec;
3466 newrec->prev = prevrec;
3467 newrec->next = nextrec;
3470 nextrec->prev = newrec;
3472 context->poll_records_tail = newrec;
3474 context->n_poll_records++;
3476 context->poll_changed = TRUE;
3478 /* Now wake up the main loop if it is waiting in the poll() */
3479 g_main_context_wakeup_unlocked (context);
3483 * g_main_context_remove_poll:
3484 * @context:a #GMainContext
3485 * @fd: a #GPollFD descriptor previously added with g_main_context_add_poll()
3487 * Removes file descriptor from the set of file descriptors to be
3488 * polled for a particular context.
3491 g_main_context_remove_poll (GMainContext *context,
3495 context = g_main_context_default ();
3497 g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
3498 g_return_if_fail (fd);
3500 LOCK_CONTEXT (context);
3501 g_main_context_remove_poll_unlocked (context, fd);
3502 UNLOCK_CONTEXT (context);
3506 g_main_context_remove_poll_unlocked (GMainContext *context,
3509 GPollRec *pollrec, *prevrec, *nextrec;
3512 pollrec = context->poll_records;
3516 nextrec = pollrec->next;
3517 if (pollrec->fd == fd)
3519 if (prevrec != NULL)
3520 prevrec->next = nextrec;
3522 context->poll_records = nextrec;
3524 if (nextrec != NULL)
3525 nextrec->prev = prevrec;
3527 context->poll_records_tail = prevrec;
3529 g_slice_free (GPollRec, pollrec);
3531 context->n_poll_records--;
3538 context->poll_changed = TRUE;
3540 /* Now wake up the main loop if it is waiting in the poll() */
3541 g_main_context_wakeup_unlocked (context);
3545 * g_source_get_current_time:
3546 * @source: a #GSource
3547 * @timeval: #GTimeVal structure in which to store current time.
3549 * Gets the "current time" to be used when checking
3550 * this source. The advantage of calling this function over
3551 * calling g_get_current_time() directly is that when
3552 * checking multiple sources, GLib can cache a single value
3553 * instead of having to repeatedly get the system time.
3555 * Deprecated: 2.28: use g_source_get_time() instead
3558 g_source_get_current_time (GSource *source,
3561 GMainContext *context;
3563 g_return_if_fail (source->context != NULL);
3565 context = source->context;
3567 LOCK_CONTEXT (context);
3569 if (!context->real_time_is_fresh)
3571 context->real_time = g_get_real_time ();
3572 context->real_time_is_fresh = TRUE;
3575 timeval->tv_sec = context->real_time / 1000000;
3576 timeval->tv_usec = context->real_time % 1000000;
3578 UNLOCK_CONTEXT (context);
3582 * g_source_get_time:
3583 * @source: a #GSource
3585 * Gets the time to be used when checking this source. The advantage of
3586 * calling this function over calling g_get_monotonic_time() directly is
3587 * that when checking multiple sources, GLib can cache a single value
3588 * instead of having to repeatedly get the system monotonic time.
3590 * The time here is the system monotonic time, if available, or some
3591 * other reasonable alternative otherwise. See g_get_monotonic_time().
3593 * Returns: the monotonic time in microseconds
3598 g_source_get_time (GSource *source)
3600 GMainContext *context;
3603 g_return_val_if_fail (source->context != NULL, 0);
3605 context = source->context;
3607 LOCK_CONTEXT (context);
3609 if (!context->time_is_fresh)
3611 context->time = g_get_monotonic_time ();
3612 context->time_is_fresh = TRUE;
3615 result = context->time;
3617 UNLOCK_CONTEXT (context);
3623 * g_main_context_set_poll_func:
3624 * @context: a #GMainContext
3625 * @func: the function to call to poll all file descriptors
3627 * Sets the function to use to handle polling of file descriptors. It
3628 * will be used instead of the poll() system call
3629 * (or GLib's replacement function, which is used where
3630 * poll() isn't available).
3632 * This function could possibly be used to integrate the GLib event
3633 * loop with an external event loop.
3636 g_main_context_set_poll_func (GMainContext *context,
3640 context = g_main_context_default ();
3642 g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
3644 LOCK_CONTEXT (context);
3647 context->poll_func = func;
3649 context->poll_func = g_poll;
3651 UNLOCK_CONTEXT (context);
3655 * g_main_context_get_poll_func:
3656 * @context: a #GMainContext
3658 * Gets the poll function set by g_main_context_set_poll_func().
3660 * Return value: the poll function
3663 g_main_context_get_poll_func (GMainContext *context)
3668 context = g_main_context_default ();
3670 g_return_val_if_fail (g_atomic_int_get (&context->ref_count) > 0, NULL);
3672 LOCK_CONTEXT (context);
3673 result = context->poll_func;
3674 UNLOCK_CONTEXT (context);
3680 _g_main_wake_up_all_contexts (void)
3684 /* We were woken up. Wake up all other contexts in all other threads */
3685 G_LOCK (main_context_list);
3686 for (list = main_context_list; list; list = list->next)
3688 GMainContext *context = list->data;
3690 LOCK_CONTEXT (context);
3691 g_main_context_wakeup_unlocked (context);
3692 UNLOCK_CONTEXT (context);
3694 G_UNLOCK (main_context_list);
3698 /* HOLDS: context's lock */
3699 /* Wake the main loop up from a poll() */
3701 g_main_context_wakeup_unlocked (GMainContext *context)
3703 if (g_thread_supported() && context->poll_waiting)
3705 context->poll_waiting = FALSE;
3706 g_wakeup_signal (context->wakeup);
3711 * g_main_context_wakeup:
3712 * @context: a #GMainContext
3714 * If @context is currently waiting in a poll(), interrupt
3715 * the poll(), and continue the iteration process.
3718 g_main_context_wakeup (GMainContext *context)
3721 context = g_main_context_default ();
3723 g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
3725 LOCK_CONTEXT (context);
3726 g_main_context_wakeup_unlocked (context);
3727 UNLOCK_CONTEXT (context);
3731 * g_main_context_is_owner:
3732 * @context: a #GMainContext
3734 * Determines whether this thread holds the (recursive)
3735 * ownership of this #GMainContext. This is useful to
3736 * know before waiting on another thread that may be
3737 * blocking to get ownership of @context.
3739 * Returns: %TRUE if current thread is owner of @context.
3744 g_main_context_is_owner (GMainContext *context)
3749 context = g_main_context_default ();
3751 LOCK_CONTEXT (context);
3752 is_owner = context->owner == G_THREAD_SELF;
3753 UNLOCK_CONTEXT (context);
3761 g_timeout_set_expiration (GTimeoutSource *timeout_source,
3762 gint64 current_time)
3764 timeout_source->expiration = current_time +
3765 (guint64) timeout_source->interval * 1000;
3767 if (timeout_source->seconds)
3770 static gint timer_perturb = -1;
3772 if (timer_perturb == -1)
3775 * we want a per machine/session unique 'random' value; try the dbus
3776 * address first, that has a UUID in it. If there is no dbus, use the
3777 * hostname for hashing.
3779 const char *session_bus_address = g_getenv ("DBUS_SESSION_BUS_ADDRESS");
3780 if (!session_bus_address)
3781 session_bus_address = g_getenv ("HOSTNAME");
3782 if (session_bus_address)
3783 timer_perturb = ABS ((gint) g_str_hash (session_bus_address)) % 1000000;
3788 /* We want the microseconds part of the timeout to land on the
3789 * 'timer_perturb' mark, but we need to make sure we don't try to
3790 * set the timeout in the past. We do this by ensuring that we
3791 * always only *increase* the expiration time by adding a full
3792 * second in the case that the microsecond portion decreases.
3794 timeout_source->expiration -= timer_perturb;
3796 remainder = timeout_source->expiration % 1000000;
3797 if (remainder >= 1000000/4)
3798 timeout_source->expiration += 1000000;
3800 timeout_source->expiration -= remainder;
3801 timeout_source->expiration += timer_perturb;
3806 g_timeout_prepare (GSource *source,
3809 GTimeoutSource *timeout_source = (GTimeoutSource *) source;
3810 gint64 now = g_source_get_time (source);
3812 if (now < timeout_source->expiration)
3814 /* Round up to ensure that we don't try again too early */
3815 *timeout = (timeout_source->expiration - now + 999) / 1000;
3824 g_timeout_check (GSource *source)
3826 GTimeoutSource *timeout_source = (GTimeoutSource *) source;
3827 gint64 now = g_source_get_time (source);
3829 return timeout_source->expiration <= now;
3833 g_timeout_dispatch (GSource *source,
3834 GSourceFunc callback,
3837 GTimeoutSource *timeout_source = (GTimeoutSource *)source;
3842 g_warning ("Timeout source dispatched without callback\n"
3843 "You must call g_source_set_callback().");
3847 again = callback (user_data);
3850 g_timeout_set_expiration (timeout_source, g_source_get_time (source));
3856 * g_timeout_source_new:
3857 * @interval: the timeout interval in milliseconds.
3859 * Creates a new timeout source.
3861 * The source will not initially be associated with any #GMainContext
3862 * and must be added to one with g_source_attach() before it will be
3865 * The interval given is in terms of monotonic time, not wall clock
3866 * time. See g_get_monotonic_time().
3868 * Return value: the newly-created timeout source
3871 g_timeout_source_new (guint interval)
3873 GSource *source = g_source_new (&g_timeout_funcs, sizeof (GTimeoutSource));
3874 GTimeoutSource *timeout_source = (GTimeoutSource *)source;
3876 timeout_source->interval = interval;
3877 g_timeout_set_expiration (timeout_source, g_get_monotonic_time ());
3883 * g_timeout_source_new_seconds:
3884 * @interval: the timeout interval in seconds
3886 * Creates a new timeout source.
3888 * The source will not initially be associated with any #GMainContext
3889 * and must be added to one with g_source_attach() before it will be
3892 * The scheduling granularity/accuracy of this timeout source will be
3895 * The interval given in terms of monotonic time, not wall clock time.
3896 * See g_get_monotonic_time().
3898 * Return value: the newly-created timeout source
3903 g_timeout_source_new_seconds (guint interval)
3905 GSource *source = g_source_new (&g_timeout_funcs, sizeof (GTimeoutSource));
3906 GTimeoutSource *timeout_source = (GTimeoutSource *)source;
3908 timeout_source->interval = 1000 * interval;
3909 timeout_source->seconds = TRUE;
3911 g_timeout_set_expiration (timeout_source, g_get_monotonic_time ());
3918 * g_timeout_add_full:
3919 * @priority: the priority of the timeout source. Typically this will be in
3920 * the range between #G_PRIORITY_DEFAULT and #G_PRIORITY_HIGH.
3921 * @interval: the time between calls to the function, in milliseconds
3922 * (1/1000ths of a second)
3923 * @function: function to call
3924 * @data: data to pass to @function
3925 * @notify: function to call when the timeout is removed, or %NULL
3927 * Sets a function to be called at regular intervals, with the given
3928 * priority. The function is called repeatedly until it returns
3929 * %FALSE, at which point the timeout is automatically destroyed and
3930 * the function will not be called again. The @notify function is
3931 * called when the timeout is destroyed. The first call to the
3932 * function will be at the end of the first @interval.
3934 * Note that timeout functions may be delayed, due to the processing of other
3935 * event sources. Thus they should not be relied on for precise timing.
3936 * After each call to the timeout function, the time of the next
3937 * timeout is recalculated based on the current time and the given interval
3938 * (it does not try to 'catch up' time lost in delays).
3940 * This internally creates a main loop source using g_timeout_source_new()
3941 * and attaches it to the main loop context using g_source_attach(). You can
3942 * do these steps manually if you need greater control.
3944 * The interval given in terms of monotonic time, not wall clock time.
3945 * See g_get_monotonic_time().
3947 * Return value: the ID (greater than 0) of the event source.
3948 * Rename to: g_timeout_add
3951 g_timeout_add_full (gint priority,
3953 GSourceFunc function,
3955 GDestroyNotify notify)
3960 g_return_val_if_fail (function != NULL, 0);
3962 source = g_timeout_source_new (interval);
3964 if (priority != G_PRIORITY_DEFAULT)
3965 g_source_set_priority (source, priority);
3967 g_source_set_callback (source, function, data, notify);
3968 id = g_source_attach (source, NULL);
3969 g_source_unref (source);
3976 * @interval: the time between calls to the function, in milliseconds
3977 * (1/1000ths of a second)
3978 * @function: function to call
3979 * @data: data to pass to @function
3981 * Sets a function to be called at regular intervals, with the default
3982 * priority, #G_PRIORITY_DEFAULT. The function is called repeatedly
3983 * until it returns %FALSE, at which point the timeout is automatically
3984 * destroyed and the function will not be called again. The first call
3985 * to the function will be at the end of the first @interval.
3987 * Note that timeout functions may be delayed, due to the processing of other
3988 * event sources. Thus they should not be relied on for precise timing.
3989 * After each call to the timeout function, the time of the next
3990 * timeout is recalculated based on the current time and the given interval
3991 * (it does not try to 'catch up' time lost in delays).
3993 * If you want to have a timer in the "seconds" range and do not care
3994 * about the exact time of the first call of the timer, use the
3995 * g_timeout_add_seconds() function; this function allows for more
3996 * optimizations and more efficient system power usage.
3998 * This internally creates a main loop source using g_timeout_source_new()
3999 * and attaches it to the main loop context using g_source_attach(). You can
4000 * do these steps manually if you need greater control.
4002 * The interval given is in terms of monotonic time, not wall clock
4003 * time. See g_get_monotonic_time().
4005 * Return value: the ID (greater than 0) of the event source.
4008 g_timeout_add (guint32 interval,
4009 GSourceFunc function,
4012 return g_timeout_add_full (G_PRIORITY_DEFAULT,
4013 interval, function, data, NULL);
4017 * g_timeout_add_seconds_full:
4018 * @priority: the priority of the timeout source. Typically this will be in
4019 * the range between #G_PRIORITY_DEFAULT and #G_PRIORITY_HIGH.
4020 * @interval: the time between calls to the function, in seconds
4021 * @function: function to call
4022 * @data: data to pass to @function
4023 * @notify: function to call when the timeout is removed, or %NULL
4025 * Sets a function to be called at regular intervals, with @priority.
4026 * The function is called repeatedly until it returns %FALSE, at which
4027 * point the timeout is automatically destroyed and the function will
4028 * not be called again.
4030 * Unlike g_timeout_add(), this function operates at whole second granularity.
4031 * The initial starting point of the timer is determined by the implementation
4032 * and the implementation is expected to group multiple timers together so that
4033 * they fire all at the same time.
4034 * To allow this grouping, the @interval to the first timer is rounded
4035 * and can deviate up to one second from the specified interval.
4036 * Subsequent timer iterations will generally run at the specified interval.
4038 * Note that timeout functions may be delayed, due to the processing of other
4039 * event sources. Thus they should not be relied on for precise timing.
4040 * After each call to the timeout function, the time of the next
4041 * timeout is recalculated based on the current time and the given @interval
4043 * If you want timing more precise than whole seconds, use g_timeout_add()
4046 * The grouping of timers to fire at the same time results in a more power
4047 * and CPU efficient behavior so if your timer is in multiples of seconds
4048 * and you don't require the first timer exactly one second from now, the
4049 * use of g_timeout_add_seconds() is preferred over g_timeout_add().
4051 * This internally creates a main loop source using
4052 * g_timeout_source_new_seconds() and attaches it to the main loop context
4053 * using g_source_attach(). You can do these steps manually if you need
4056 * The interval given is in terms of monotonic time, not wall clock
4057 * time. See g_get_monotonic_time().
4059 * Return value: the ID (greater than 0) of the event source.
4061 * Rename to: g_timeout_add_seconds
4065 g_timeout_add_seconds_full (gint priority,
4067 GSourceFunc function,
4069 GDestroyNotify notify)
4074 g_return_val_if_fail (function != NULL, 0);
4076 source = g_timeout_source_new_seconds (interval);
4078 if (priority != G_PRIORITY_DEFAULT)
4079 g_source_set_priority (source, priority);
4081 g_source_set_callback (source, function, data, notify);
4082 id = g_source_attach (source, NULL);
4083 g_source_unref (source);
4089 * g_timeout_add_seconds:
4090 * @interval: the time between calls to the function, in seconds
4091 * @function: function to call
4092 * @data: data to pass to @function
4094 * Sets a function to be called at regular intervals with the default
4095 * priority, #G_PRIORITY_DEFAULT. The function is called repeatedly until
4096 * it returns %FALSE, at which point the timeout is automatically destroyed
4097 * and the function will not be called again.
4099 * This internally creates a main loop source using
4100 * g_timeout_source_new_seconds() and attaches it to the main loop context
4101 * using g_source_attach(). You can do these steps manually if you need
4102 * greater control. Also see g_timeout_add_seconds_full().
4104 * Note that the first call of the timer may not be precise for timeouts
4105 * of one second. If you need finer precision and have such a timeout,
4106 * you may want to use g_timeout_add() instead.
4108 * The interval given is in terms of monotonic time, not wall clock
4109 * time. See g_get_monotonic_time().
4111 * Return value: the ID (greater than 0) of the event source.
4116 g_timeout_add_seconds (guint interval,
4117 GSourceFunc function,
4120 g_return_val_if_fail (function != NULL, 0);
4122 return g_timeout_add_seconds_full (G_PRIORITY_DEFAULT, interval, function, data, NULL);
4125 /* Child watch functions */
4130 g_child_watch_prepare (GSource *source,
4139 g_child_watch_check (GSource *source)
4141 GChildWatchSource *child_watch_source;
4142 gboolean child_exited;
4144 child_watch_source = (GChildWatchSource *) source;
4146 child_exited = child_watch_source->poll.revents & G_IO_IN;
4153 * Note: We do _not_ check for the special value of STILL_ACTIVE
4154 * since we know that the process has exited and doing so runs into
4155 * problems if the child process "happens to return STILL_ACTIVE(259)"
4156 * as Microsoft's Platform SDK puts it.
4158 if (!GetExitCodeProcess (child_watch_source->pid, &child_status))
4160 gchar *emsg = g_win32_error_message (GetLastError ());
4161 g_warning (G_STRLOC ": GetExitCodeProcess() failed: %s", emsg);
4164 child_watch_source->child_status = -1;
4167 child_watch_source->child_status = child_status;
4170 return child_exited;
4173 #else /* G_OS_WIN32 */
4176 check_for_child_exited (GSource *source)
4178 GChildWatchSource *child_watch_source;
4181 /* protect against another SIGCHLD in the middle of this call */
4182 count = child_watch_count;
4184 child_watch_source = (GChildWatchSource *) source;
4186 if (child_watch_source->child_exited)
4189 if (child_watch_source->count < count)
4193 if (waitpid (child_watch_source->pid, &child_status, WNOHANG) > 0)
4195 child_watch_source->child_status = child_status;
4196 child_watch_source->child_exited = TRUE;
4198 child_watch_source->count = count;
4201 return child_watch_source->child_exited;
4205 g_child_watch_prepare (GSource *source,
4210 return check_for_child_exited (source);
4214 g_child_watch_check (GSource *source)
4216 return check_for_child_exited (source);
4220 check_for_signal_delivery (GSource *source)
4222 GUnixSignalWatchSource *unix_signal_source = (GUnixSignalWatchSource*) source;
4225 G_LOCK (unix_signal_lock);
4226 if (unix_signal_init_state == UNIX_SIGNAL_INITIALIZED_SINGLE)
4228 switch (unix_signal_source->signum)
4231 delivered = unix_signal_state.sighup_delivered;
4234 delivered = unix_signal_state.sigint_delivered;
4237 delivered = unix_signal_state.sigterm_delivered;
4240 g_assert_not_reached ();
4247 g_assert (unix_signal_init_state == UNIX_SIGNAL_INITIALIZED_THREADED);
4248 delivered = unix_signal_source->pending;
4250 G_UNLOCK (unix_signal_lock);
4256 g_unix_signal_watch_prepare (GSource *source,
4261 return check_for_signal_delivery (source);
4265 g_unix_signal_watch_check (GSource *source)
4267 return check_for_signal_delivery (source);
4271 g_unix_signal_watch_dispatch (GSource *source,
4272 GSourceFunc callback,
4275 GUnixSignalWatchSource *unix_signal_source;
4277 unix_signal_source = (GUnixSignalWatchSource *) source;
4281 g_warning ("Unix signal source dispatched without callback\n"
4282 "You must call g_source_set_callback().");
4286 (callback) (user_data);
4288 G_LOCK (unix_signal_lock);
4289 if (unix_signal_init_state == UNIX_SIGNAL_INITIALIZED_SINGLE)
4291 switch (unix_signal_source->signum)
4294 unix_signal_state.sighup_delivered = FALSE;
4297 unix_signal_state.sigint_delivered = FALSE;
4300 unix_signal_state.sigterm_delivered = FALSE;
4306 g_assert (unix_signal_init_state == UNIX_SIGNAL_INITIALIZED_THREADED);
4307 unix_signal_source->pending = FALSE;
4309 G_UNLOCK (unix_signal_lock);
4315 ensure_unix_signal_handler_installed_unlocked (int signum)
4317 struct sigaction action;
4318 GError *error = NULL;
4320 if (unix_signal_init_state == UNIX_SIGNAL_UNINITIALIZED)
4322 sigemptyset (&unix_signal_mask);
4325 if (unix_signal_init_state == UNIX_SIGNAL_UNINITIALIZED
4326 || unix_signal_init_state == UNIX_SIGNAL_INITIALIZED_SINGLE)
4328 if (!g_thread_supported ())
4330 /* There is nothing to do for initializing in the non-threaded
4333 if (unix_signal_init_state == UNIX_SIGNAL_UNINITIALIZED)
4334 unix_signal_init_state = UNIX_SIGNAL_INITIALIZED_SINGLE;
4338 if (!g_unix_open_pipe (unix_signal_wake_up_pipe, FD_CLOEXEC, &error))
4339 g_error ("Cannot create UNIX signal wake up pipe: %s\n", error->message);
4340 g_unix_set_fd_nonblocking (unix_signal_wake_up_pipe[1], TRUE, NULL);
4342 /* We create a helper thread that polls on the wakeup pipe indefinitely */
4343 if (g_thread_create (unix_signal_helper_thread, NULL, FALSE, &error) == NULL)
4344 g_error ("Cannot create a thread to monitor UNIX signals: %s\n", error->message);
4346 unix_signal_init_state = UNIX_SIGNAL_INITIALIZED_THREADED;
4350 if (sigismember (&unix_signal_mask, signum))
4353 sigaddset (&unix_signal_mask, signum);
4355 action.sa_handler = g_unix_signal_handler;
4356 sigemptyset (&action.sa_mask);
4357 action.sa_flags = SA_RESTART | SA_NOCLDSTOP;
4358 sigaction (signum, &action, NULL);
4362 _g_main_create_unix_signal_watch (int signum)
4365 GUnixSignalWatchSource *unix_signal_source;
4367 source = g_source_new (&g_unix_signal_funcs, sizeof (GUnixSignalWatchSource));
4368 unix_signal_source = (GUnixSignalWatchSource *) source;
4370 unix_signal_source->signum = signum;
4371 unix_signal_source->pending = FALSE;
4373 G_LOCK (unix_signal_lock);
4374 ensure_unix_signal_handler_installed_unlocked (signum);
4375 unix_signal_watches = g_slist_prepend (unix_signal_watches, unix_signal_source);
4376 G_UNLOCK (unix_signal_lock);
4382 g_unix_signal_watch_finalize (GSource *source)
4384 G_LOCK (unix_signal_lock);
4385 unix_signal_watches = g_slist_remove (unix_signal_watches, source);
4386 G_UNLOCK (unix_signal_lock);
4389 #endif /* G_OS_WIN32 */
4392 g_child_watch_dispatch (GSource *source,
4393 GSourceFunc callback,
4396 GChildWatchSource *child_watch_source;
4397 GChildWatchFunc child_watch_callback = (GChildWatchFunc) callback;
4399 child_watch_source = (GChildWatchSource *) source;
4403 g_warning ("Child watch source dispatched without callback\n"
4404 "You must call g_source_set_callback().");
4408 (child_watch_callback) (child_watch_source->pid, child_watch_source->child_status, user_data);
4410 /* We never keep a child watch source around as the child is gone */
4417 g_unix_signal_handler (int signum)
4419 if (signum == SIGCHLD)
4420 child_watch_count ++;
4422 if (unix_signal_init_state == UNIX_SIGNAL_INITIALIZED_THREADED)
4428 buf[0] = _UNIX_SIGNAL_PIPE_SIGCHLD_CHAR;
4431 buf[0] = _UNIX_SIGNAL_PIPE_SIGHUP_CHAR;
4434 buf[0] = _UNIX_SIGNAL_PIPE_SIGINT_CHAR;
4437 buf[0] = _UNIX_SIGNAL_PIPE_SIGTERM_CHAR;
4440 /* Shouldn't happen */
4443 write (unix_signal_wake_up_pipe[1], buf, 1);
4447 /* We count on the signal interrupting the poll in the same thread. */
4451 /* Nothing to do - the handler will call waitpid() */
4454 unix_signal_state.sighup_delivered = TRUE;
4457 unix_signal_state.sigint_delivered = TRUE;
4460 unix_signal_state.sigterm_delivered = TRUE;
4463 g_assert_not_reached ();
4470 deliver_unix_signal (int signum)
4473 g_assert (signum == SIGHUP || signum == SIGINT || signum == SIGTERM);
4475 G_LOCK (unix_signal_lock);
4476 for (iter = unix_signal_watches; iter; iter = iter->next)
4478 GUnixSignalWatchSource *source = iter->data;
4480 if (source->signum != signum)
4483 source->pending = TRUE;
4485 G_UNLOCK (unix_signal_lock);
4489 * This thread is created whenever anything in GLib needs
4490 * to deal with UNIX signals; at present, just SIGCHLD
4491 * from g_child_watch_source_new().
4493 * Note: We could eventually make this thread a more public interface
4494 * and allow e.g. GDBus to use it instead of its own worker thread.
4497 unix_signal_helper_thread (gpointer data)
4502 ssize_t i, bytes_read;
4503 gboolean sigterm_received = FALSE;
4504 gboolean sigint_received = FALSE;
4505 gboolean sighup_received = FALSE;
4507 bytes_read = read (unix_signal_wake_up_pipe[0], b, sizeof (b));
4510 g_warning ("Failed to read from child watch wake up pipe: %s",
4512 /* Not much we can do here sanely; just wait a second and hope
4515 g_usleep (G_USEC_PER_SEC);
4518 for (i = 0; i < bytes_read; i++)
4522 case _UNIX_SIGNAL_PIPE_SIGCHLD_CHAR:
4523 /* The child watch source will call waitpid() in its
4524 * prepare() and check() methods; however, we don't
4525 * know which pid exited, so we need to wake up
4526 * all contexts. Note: actually we could get the pid
4527 * from the "siginfo_t" via the handler, but to pass
4528 * that info down the pipe would require a more structured
4529 * data stream (as opposed to a single byte).
4532 case _UNIX_SIGNAL_PIPE_SIGTERM_CHAR:
4533 sigterm_received = TRUE;
4535 case _UNIX_SIGNAL_PIPE_SIGHUP_CHAR:
4536 sighup_received = TRUE;
4538 case _UNIX_SIGNAL_PIPE_SIGINT_CHAR:
4539 sigint_received = TRUE;
4542 g_warning ("Invalid char '%c' read from child watch pipe", b[i]);
4546 if (sigterm_received)
4547 deliver_unix_signal (SIGTERM);
4548 if (sigint_received)
4549 deliver_unix_signal (SIGINT);
4550 if (sighup_received)
4551 deliver_unix_signal (SIGHUP);
4552 _g_main_wake_up_all_contexts ();
4557 g_child_watch_source_init (void)
4559 G_LOCK (unix_signal_lock);
4560 ensure_unix_signal_handler_installed_unlocked (SIGCHLD);
4561 G_UNLOCK (unix_signal_lock);
4564 #endif /* !G_OS_WIN32 */
4567 * g_child_watch_source_new:
4568 * @pid: process to watch. On POSIX the pid of a child process. On
4569 * Windows a handle for a process (which doesn't have to be a child).
4571 * Creates a new child_watch source.
4573 * The source will not initially be associated with any #GMainContext
4574 * and must be added to one with g_source_attach() before it will be
4577 * Note that child watch sources can only be used in conjunction with
4578 * <literal>g_spawn...</literal> when the %G_SPAWN_DO_NOT_REAP_CHILD
4581 * Note that on platforms where #GPid must be explicitly closed
4582 * (see g_spawn_close_pid()) @pid must not be closed while the
4583 * source is still active. Typically, you will want to call
4584 * g_spawn_close_pid() in the callback function for the source.
4586 * Note further that using g_child_watch_source_new() is not
4587 * compatible with calling <literal>waitpid(-1)</literal> in
4588 * the application. Calling waitpid() for individual pids will
4591 * Return value: the newly-created child watch source
4596 g_child_watch_source_new (GPid pid)
4598 GSource *source = g_source_new (&g_child_watch_funcs, sizeof (GChildWatchSource));
4599 GChildWatchSource *child_watch_source = (GChildWatchSource *)source;
4602 child_watch_source->poll.fd = (gintptr) pid;
4603 child_watch_source->poll.events = G_IO_IN;
4605 g_source_add_poll (source, &child_watch_source->poll);
4606 #else /* G_OS_WIN32 */
4607 g_child_watch_source_init ();
4608 #endif /* G_OS_WIN32 */
4610 child_watch_source->pid = pid;
4616 * g_child_watch_add_full:
4617 * @priority: the priority of the idle source. Typically this will be in the
4618 * range between #G_PRIORITY_DEFAULT_IDLE and #G_PRIORITY_HIGH_IDLE.
4619 * @pid: process to watch. On POSIX the pid of a child process. On
4620 * Windows a handle for a process (which doesn't have to be a child).
4621 * @function: function to call
4622 * @data: data to pass to @function
4623 * @notify: function to call when the idle is removed, or %NULL
4625 * Sets a function to be called when the child indicated by @pid
4626 * exits, at the priority @priority.
4628 * If you obtain @pid from g_spawn_async() or g_spawn_async_with_pipes()
4629 * you will need to pass #G_SPAWN_DO_NOT_REAP_CHILD as flag to
4630 * the spawn function for the child watching to work.
4632 * Note that on platforms where #GPid must be explicitly closed
4633 * (see g_spawn_close_pid()) @pid must not be closed while the
4634 * source is still active. Typically, you will want to call
4635 * g_spawn_close_pid() in the callback function for the source.
4637 * GLib supports only a single callback per process id.
4639 * This internally creates a main loop source using
4640 * g_child_watch_source_new() and attaches it to the main loop context
4641 * using g_source_attach(). You can do these steps manually if you
4642 * need greater control.
4644 * Return value: the ID (greater than 0) of the event source.
4646 * Rename to: g_child_watch_add
4650 g_child_watch_add_full (gint priority,
4652 GChildWatchFunc function,
4654 GDestroyNotify notify)
4659 g_return_val_if_fail (function != NULL, 0);
4661 source = g_child_watch_source_new (pid);
4663 if (priority != G_PRIORITY_DEFAULT)
4664 g_source_set_priority (source, priority);
4666 g_source_set_callback (source, (GSourceFunc) function, data, notify);
4667 id = g_source_attach (source, NULL);
4668 g_source_unref (source);
4674 * g_child_watch_add:
4675 * @pid: process id to watch. On POSIX the pid of a child process. On
4676 * Windows a handle for a process (which doesn't have to be a child).
4677 * @function: function to call
4678 * @data: data to pass to @function
4680 * Sets a function to be called when the child indicated by @pid
4681 * exits, at a default priority, #G_PRIORITY_DEFAULT.
4683 * If you obtain @pid from g_spawn_async() or g_spawn_async_with_pipes()
4684 * you will need to pass #G_SPAWN_DO_NOT_REAP_CHILD as flag to
4685 * the spawn function for the child watching to work.
4687 * Note that on platforms where #GPid must be explicitly closed
4688 * (see g_spawn_close_pid()) @pid must not be closed while the
4689 * source is still active. Typically, you will want to call
4690 * g_spawn_close_pid() in the callback function for the source.
4692 * GLib supports only a single callback per process id.
4694 * This internally creates a main loop source using
4695 * g_child_watch_source_new() and attaches it to the main loop context
4696 * using g_source_attach(). You can do these steps manually if you
4697 * need greater control.
4699 * Return value: the ID (greater than 0) of the event source.
4704 g_child_watch_add (GPid pid,
4705 GChildWatchFunc function,
4708 return g_child_watch_add_full (G_PRIORITY_DEFAULT, pid, function, data, NULL);
4712 /* Idle functions */
4715 g_idle_prepare (GSource *source,
4724 g_idle_check (GSource *source)
4730 g_idle_dispatch (GSource *source,
4731 GSourceFunc callback,
4736 g_warning ("Idle source dispatched without callback\n"
4737 "You must call g_source_set_callback().");
4741 return callback (user_data);
4745 * g_idle_source_new:
4747 * Creates a new idle source.
4749 * The source will not initially be associated with any #GMainContext
4750 * and must be added to one with g_source_attach() before it will be
4751 * executed. Note that the default priority for idle sources is
4752 * %G_PRIORITY_DEFAULT_IDLE, as compared to other sources which
4753 * have a default priority of %G_PRIORITY_DEFAULT.
4755 * Return value: the newly-created idle source
4758 g_idle_source_new (void)
4762 source = g_source_new (&g_idle_funcs, sizeof (GSource));
4763 g_source_set_priority (source, G_PRIORITY_DEFAULT_IDLE);
4770 * @priority: the priority of the idle source. Typically this will be in the
4771 * range between #G_PRIORITY_DEFAULT_IDLE and #G_PRIORITY_HIGH_IDLE.
4772 * @function: function to call
4773 * @data: data to pass to @function
4774 * @notify: function to call when the idle is removed, or %NULL
4776 * Adds a function to be called whenever there are no higher priority
4777 * events pending. If the function returns %FALSE it is automatically
4778 * removed from the list of event sources and will not be called again.
4780 * This internally creates a main loop source using g_idle_source_new()
4781 * and attaches it to the main loop context using g_source_attach().
4782 * You can do these steps manually if you need greater control.
4784 * Return value: the ID (greater than 0) of the event source.
4785 * Rename to: g_idle_add
4788 g_idle_add_full (gint priority,
4789 GSourceFunc function,
4791 GDestroyNotify notify)
4796 g_return_val_if_fail (function != NULL, 0);
4798 source = g_idle_source_new ();
4800 if (priority != G_PRIORITY_DEFAULT_IDLE)
4801 g_source_set_priority (source, priority);
4803 g_source_set_callback (source, function, data, notify);
4804 id = g_source_attach (source, NULL);
4805 g_source_unref (source);
4812 * @function: function to call
4813 * @data: data to pass to @function.
4815 * Adds a function to be called whenever there are no higher priority
4816 * events pending to the default main loop. The function is given the
4817 * default idle priority, #G_PRIORITY_DEFAULT_IDLE. If the function
4818 * returns %FALSE it is automatically removed from the list of event
4819 * sources and will not be called again.
4821 * This internally creates a main loop source using g_idle_source_new()
4822 * and attaches it to the main loop context using g_source_attach().
4823 * You can do these steps manually if you need greater control.
4825 * Return value: the ID (greater than 0) of the event source.
4828 g_idle_add (GSourceFunc function,
4831 return g_idle_add_full (G_PRIORITY_DEFAULT_IDLE, function, data, NULL);
4835 * g_idle_remove_by_data:
4836 * @data: the data for the idle source's callback.
4838 * Removes the idle function with the given data.
4840 * Return value: %TRUE if an idle source was found and removed.
4843 g_idle_remove_by_data (gpointer data)
4845 return g_source_remove_by_funcs_user_data (&g_idle_funcs, data);
4849 * g_main_context_invoke:
4850 * @context: (allow-none): a #GMainContext, or %NULL
4851 * @function: function to call
4852 * @data: data to pass to @function
4854 * Invokes a function in such a way that @context is owned during the
4855 * invocation of @function.
4857 * If @context is %NULL then the global default main context — as
4858 * returned by g_main_context_default() — is used.
4860 * If @context is owned by the current thread, @function is called
4861 * directly. Otherwise, if @context is the thread-default main context
4862 * of the current thread and g_main_context_acquire() succeeds, then
4863 * @function is called and g_main_context_release() is called
4866 * In any other case, an idle source is created to call @function and
4867 * that source is attached to @context (presumably to be run in another
4868 * thread). The idle source is attached with #G_PRIORITY_DEFAULT
4869 * priority. If you want a different priority, use
4870 * g_main_context_invoke_full().
4872 * Note that, as with normal idle functions, @function should probably
4873 * return %FALSE. If it returns %TRUE, it will be continuously run in a
4874 * loop (and may prevent this call from returning).
4879 g_main_context_invoke (GMainContext *context,
4880 GSourceFunc function,
4883 g_main_context_invoke_full (context,
4885 function, data, NULL);
4889 * g_main_context_invoke_full:
4890 * @context: (allow-none): a #GMainContext, or %NULL
4891 * @priority: the priority at which to run @function
4892 * @function: function to call
4893 * @data: data to pass to @function
4894 * @notify: a function to call when @data is no longer in use, or %NULL.
4896 * Invokes a function in such a way that @context is owned during the
4897 * invocation of @function.
4899 * This function is the same as g_main_context_invoke() except that it
4900 * lets you specify the priority incase @function ends up being
4901 * scheduled as an idle and also lets you give a #GDestroyNotify for @data.
4903 * @notify should not assume that it is called from any particular
4904 * thread or with any particular context acquired.
4909 g_main_context_invoke_full (GMainContext *context,
4911 GSourceFunc function,
4913 GDestroyNotify notify)
4915 g_return_if_fail (function != NULL);
4918 context = g_main_context_default ();
4920 if (g_main_context_is_owner (context))
4922 while (function (data));
4929 GMainContext *thread_default;
4931 thread_default = g_main_context_get_thread_default ();
4933 if (!thread_default)
4934 thread_default = g_main_context_default ();
4936 if (thread_default == context && g_main_context_acquire (context))
4938 while (function (data));
4940 g_main_context_release (context);
4949 source = g_idle_source_new ();
4950 g_source_set_priority (source, priority);
4951 g_source_set_callback (source, function, data, notify);
4952 g_source_attach (source, context);
4953 g_source_unref (source);