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 #ifdef G_THREADS_ENABLED
192 typedef struct _GMainWaiter GMainWaiter;
201 typedef struct _GMainDispatch GMainDispatch;
203 struct _GMainDispatch
206 GSList *dispatching_sources; /* stack of current sources */
209 #ifdef G_MAIN_POLL_DEBUG
210 gboolean _g_main_poll_debug = FALSE;
215 #ifdef G_THREADS_ENABLED
216 /* The following lock is used for both the list of sources
217 * and the list of poll records
228 GPtrArray *pending_dispatches;
229 gint timeout; /* Timeout for current iteration */
232 GSource *source_list;
233 gint in_check_or_prepare;
235 GPollRec *poll_records, *poll_records_tail;
236 guint n_poll_records;
237 GPollFD *cached_poll_array;
238 guint cached_poll_array_size;
240 #ifdef G_THREADS_ENABLED
244 gboolean poll_waiting;
246 /* Flag indicating whether the set of fd's changed during a poll */
247 gboolean poll_changed;
248 #endif /* G_THREADS_ENABLED */
253 gboolean time_is_fresh;
255 gboolean real_time_is_fresh;
258 struct _GSourceCallback
263 GDestroyNotify notify;
268 GMainContext *context;
273 struct _GTimeoutSource
281 struct _GChildWatchSource
288 #else /* G_OS_WIN32 */
290 gboolean child_exited;
291 #endif /* G_OS_WIN32 */
294 struct _GUnixSignalWatchSource
309 struct _GSourcePrivate
311 GSList *child_sources;
312 GSource *parent_source;
315 #ifdef G_THREADS_ENABLED
316 #define LOCK_CONTEXT(context) g_static_mutex_lock (&context->mutex)
317 #define UNLOCK_CONTEXT(context) g_static_mutex_unlock (&context->mutex)
318 #define G_THREAD_SELF g_thread_self ()
320 #define LOCK_CONTEXT(context) (void)0
321 #define UNLOCK_CONTEXT(context) (void)0
322 #define G_THREAD_SELF NULL
325 #define SOURCE_DESTROYED(source) (((source)->flags & G_HOOK_FLAG_ACTIVE) == 0)
326 #define SOURCE_BLOCKED(source) (((source)->flags & G_HOOK_FLAG_IN_CALL) != 0 && \
327 ((source)->flags & G_SOURCE_CAN_RECURSE) == 0)
329 #define SOURCE_UNREF(source, context) \
331 if ((source)->ref_count > 1) \
332 (source)->ref_count--; \
334 g_source_unref_internal ((source), (context), TRUE); \
338 /* Forward declarations */
340 static void g_source_unref_internal (GSource *source,
341 GMainContext *context,
343 static void g_source_destroy_internal (GSource *source,
344 GMainContext *context,
346 static void g_source_set_priority_unlocked (GSource *source,
347 GMainContext *context,
349 static void g_main_context_poll (GMainContext *context,
354 static void g_main_context_add_poll_unlocked (GMainContext *context,
357 static void g_main_context_remove_poll_unlocked (GMainContext *context,
359 static void g_main_context_wakeup_unlocked (GMainContext *context);
361 static void _g_main_wake_up_all_contexts (void);
363 static gboolean g_timeout_prepare (GSource *source,
365 static gboolean g_timeout_check (GSource *source);
366 static gboolean g_timeout_dispatch (GSource *source,
367 GSourceFunc callback,
369 static gboolean g_child_watch_prepare (GSource *source,
371 static gboolean g_child_watch_check (GSource *source);
372 static gboolean g_child_watch_dispatch (GSource *source,
373 GSourceFunc callback,
376 static gpointer unix_signal_helper_thread (gpointer data) G_GNUC_NORETURN;
377 static void g_unix_signal_handler (int signum);
378 static gboolean g_unix_signal_watch_prepare (GSource *source,
380 static gboolean g_unix_signal_watch_check (GSource *source);
381 static gboolean g_unix_signal_watch_dispatch (GSource *source,
382 GSourceFunc callback,
384 static void g_unix_signal_watch_finalize (GSource *source);
386 static gboolean g_idle_prepare (GSource *source,
388 static gboolean g_idle_check (GSource *source);
389 static gboolean g_idle_dispatch (GSource *source,
390 GSourceFunc callback,
393 G_LOCK_DEFINE_STATIC (main_loop);
394 static GMainContext *default_main_context;
395 static GSList *main_contexts_without_pipe = NULL;
399 /* The UNIX signal pipe contains a single byte specifying which
400 * signal was received.
402 #define _UNIX_SIGNAL_PIPE_SIGCHLD_CHAR 'C'
403 #define _UNIX_SIGNAL_PIPE_SIGHUP_CHAR 'H'
404 #define _UNIX_SIGNAL_PIPE_SIGINT_CHAR 'I'
405 #define _UNIX_SIGNAL_PIPE_SIGTERM_CHAR 'T'
406 /* Guards all the data below */
407 G_LOCK_DEFINE_STATIC (unix_signal_lock);
409 UNIX_SIGNAL_UNINITIALIZED = 0,
410 UNIX_SIGNAL_INITIALIZED_SINGLE,
411 UNIX_SIGNAL_INITIALIZED_THREADED
413 static gint unix_signal_init_state = UNIX_SIGNAL_UNINITIALIZED;
415 /* These are only used in the UNIX_SIGNAL_INITIALIZED_SINGLE case */
416 gboolean sighup_delivered : 1;
417 gboolean sigint_delivered : 1;
418 gboolean sigterm_delivered : 1;
420 static sigset_t unix_signal_mask;
421 static UnixSignalState unix_signal_state;
422 static gint unix_signal_wake_up_pipe[2];
423 GSList *unix_signal_watches;
425 /* Not guarded ( FIXME should it be? ) */
426 static gint child_watch_count = 1;
428 static GSourceFuncs g_unix_signal_funcs =
430 g_unix_signal_watch_prepare,
431 g_unix_signal_watch_check,
432 g_unix_signal_watch_dispatch,
433 g_unix_signal_watch_finalize
435 #endif /* !G_OS_WIN32 */
436 G_LOCK_DEFINE_STATIC (main_context_list);
437 static GSList *main_context_list = NULL;
439 GSourceFuncs g_timeout_funcs =
447 GSourceFuncs g_child_watch_funcs =
449 g_child_watch_prepare,
451 g_child_watch_dispatch,
455 GSourceFuncs g_idle_funcs =
464 * g_main_context_ref:
465 * @context: a #GMainContext
467 * Increases the reference count on a #GMainContext object by one.
469 * Returns: the @context that was passed in (since 2.6)
472 g_main_context_ref (GMainContext *context)
474 g_return_val_if_fail (context != NULL, NULL);
475 g_return_val_if_fail (g_atomic_int_get (&context->ref_count) > 0, NULL);
477 g_atomic_int_inc (&context->ref_count);
483 poll_rec_list_free (GMainContext *context,
486 g_slice_free_chain (GPollRec, list, next);
490 * g_main_context_unref:
491 * @context: a #GMainContext
493 * Decreases the reference count on a #GMainContext object by one. If
494 * the result is zero, free the context and free all associated memory.
497 g_main_context_unref (GMainContext *context)
500 g_return_if_fail (context != NULL);
501 g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
503 if (!g_atomic_int_dec_and_test (&context->ref_count))
506 G_LOCK (main_context_list);
507 main_context_list = g_slist_remove (main_context_list, context);
508 G_UNLOCK (main_context_list);
510 source = context->source_list;
513 GSource *next = source->next;
514 g_source_destroy_internal (source, context, FALSE);
518 #ifdef G_THREADS_ENABLED
519 g_static_mutex_free (&context->mutex);
522 g_ptr_array_free (context->pending_dispatches, TRUE);
523 g_free (context->cached_poll_array);
525 poll_rec_list_free (context, context->poll_records);
527 #ifdef G_THREADS_ENABLED
528 if (g_thread_supported())
529 g_wakeup_free (context->wakeup);
532 main_contexts_without_pipe = g_slist_remove (main_contexts_without_pipe,
535 if (context->cond != NULL)
536 g_cond_free (context->cond);
542 #ifdef G_THREADS_ENABLED
544 g_main_context_init_pipe (GMainContext *context)
546 context->wakeup = g_wakeup_new ();
547 g_wakeup_get_pollfd (context->wakeup, &context->wake_up_rec);
548 g_main_context_add_poll_unlocked (context, 0, &context->wake_up_rec);
552 _g_main_thread_init (void)
556 curr = main_contexts_without_pipe;
559 g_main_context_init_pipe ((GMainContext *)curr->data);
562 g_slist_free (main_contexts_without_pipe);
563 main_contexts_without_pipe = NULL;
565 #endif /* G_THREADS_ENABLED */
568 * g_main_context_new:
570 * Creates a new #GMainContext structure.
572 * Return value: the new #GMainContext
575 g_main_context_new (void)
577 GMainContext *context = g_new0 (GMainContext, 1);
579 #ifdef G_MAIN_POLL_DEBUG
581 static gboolean beenhere = FALSE;
585 if (getenv ("G_MAIN_POLL_DEBUG") != NULL)
586 _g_main_poll_debug = TRUE;
592 #ifdef G_THREADS_ENABLED
593 g_static_mutex_init (&context->mutex);
595 context->owner = NULL;
596 context->waiters = NULL;
599 context->ref_count = 1;
601 context->next_id = 1;
603 context->source_list = NULL;
605 context->poll_func = g_poll;
607 context->cached_poll_array = NULL;
608 context->cached_poll_array_size = 0;
610 context->pending_dispatches = g_ptr_array_new ();
612 context->time_is_fresh = FALSE;
613 context->real_time_is_fresh = FALSE;
615 #ifdef G_THREADS_ENABLED
616 if (g_thread_supported ())
617 g_main_context_init_pipe (context);
619 main_contexts_without_pipe = g_slist_prepend (main_contexts_without_pipe,
623 G_LOCK (main_context_list);
624 main_context_list = g_slist_append (main_context_list, context);
626 #ifdef G_MAIN_POLL_DEBUG
627 if (_g_main_poll_debug)
628 g_print ("created context=%p\n", context);
631 G_UNLOCK (main_context_list);
637 * g_main_context_default:
639 * Returns the global default main context. This is the main context
640 * used for main loop functions when a main loop is not explicitly
641 * specified, and corresponds to the "main" main loop. See also
642 * g_main_context_get_thread_default().
644 * Return value: (transfer none): the global default main context.
647 g_main_context_default (void)
653 if (!default_main_context)
655 default_main_context = g_main_context_new ();
656 #ifdef G_MAIN_POLL_DEBUG
657 if (_g_main_poll_debug)
658 g_print ("default context=%p\n", default_main_context);
662 G_UNLOCK (main_loop);
664 return default_main_context;
667 static GStaticPrivate thread_context_stack = G_STATIC_PRIVATE_INIT;
670 free_context_stack (gpointer data)
672 GQueue *stack = data;
673 GMainContext *context;
675 while (!g_queue_is_empty (stack))
677 context = g_queue_pop_head (stack);
678 g_main_context_release (context);
680 g_main_context_unref (context);
682 g_queue_free (stack);
686 * g_main_context_push_thread_default:
687 * @context: a #GMainContext, or %NULL for the global default context
689 * Acquires @context and sets it as the thread-default context for the
690 * current thread. This will cause certain asynchronous operations
691 * (such as most <link linkend="gio">gio</link>-based I/O) which are
692 * started in this thread to run under @context and deliver their
693 * results to its main loop, rather than running under the global
694 * default context in the main thread. Note that calling this function
695 * changes the context returned by
696 * g_main_context_get_thread_default(), <emphasis>not</emphasis> the
697 * one returned by g_main_context_default(), so it does not affect the
698 * context used by functions like g_idle_add().
700 * Normally you would call this function shortly after creating a new
701 * thread, passing it a #GMainContext which will be run by a
702 * #GMainLoop in that thread, to set a new default context for all
703 * async operations in that thread. (In this case, you don't need to
704 * ever call g_main_context_pop_thread_default().) In some cases
705 * however, you may want to schedule a single operation in a
706 * non-default context, or temporarily use a non-default context in
707 * the main thread. In that case, you can wrap the call to the
708 * asynchronous operation inside a
709 * g_main_context_push_thread_default() /
710 * g_main_context_pop_thread_default() pair, but it is up to you to
711 * ensure that no other asynchronous operations accidentally get
712 * started while the non-default context is active.
714 * Beware that libraries that predate this function may not correctly
715 * handle being used from a thread with a thread-default context. Eg,
716 * see g_file_supports_thread_contexts().
721 g_main_context_push_thread_default (GMainContext *context)
724 gboolean acquired_context;
726 acquired_context = g_main_context_acquire (context);
727 g_return_if_fail (acquired_context);
729 if (context == g_main_context_default ())
732 g_main_context_ref (context);
734 stack = g_static_private_get (&thread_context_stack);
737 stack = g_queue_new ();
738 g_static_private_set (&thread_context_stack, stack,
742 g_queue_push_head (stack, context);
746 * g_main_context_pop_thread_default:
747 * @context: a #GMainContext object, or %NULL
749 * Pops @context off the thread-default context stack (verifying that
750 * it was on the top of the stack).
755 g_main_context_pop_thread_default (GMainContext *context)
759 if (context == g_main_context_default ())
762 stack = g_static_private_get (&thread_context_stack);
764 g_return_if_fail (stack != NULL);
765 g_return_if_fail (g_queue_peek_head (stack) == context);
767 g_queue_pop_head (stack);
769 g_main_context_release (context);
771 g_main_context_unref (context);
775 * g_main_context_get_thread_default:
777 * Gets the thread-default #GMainContext for this thread. Asynchronous
778 * operations that want to be able to be run in contexts other than
779 * the default one should call this method to get a #GMainContext to
780 * add their #GSource<!-- -->s to. (Note that even in single-threaded
781 * programs applications may sometimes want to temporarily push a
782 * non-default context, so it is not safe to assume that this will
783 * always return %NULL if threads are not initialized.)
785 * Returns: (transfer none): the thread-default #GMainContext, or
786 * %NULL if the thread-default context is the global default context.
791 g_main_context_get_thread_default (void)
795 stack = g_static_private_get (&thread_context_stack);
797 return g_queue_peek_head (stack);
802 /* Hooks for adding to the main loop */
806 * @source_funcs: structure containing functions that implement
807 * the sources behavior.
808 * @struct_size: size of the #GSource structure to create.
810 * Creates a new #GSource structure. The size is specified to
811 * allow creating structures derived from #GSource that contain
812 * additional data. The size passed in must be at least
813 * <literal>sizeof (GSource)</literal>.
815 * The source will not initially be associated with any #GMainContext
816 * and must be added to one with g_source_attach() before it will be
819 * Return value: the newly-created #GSource.
822 g_source_new (GSourceFuncs *source_funcs,
827 g_return_val_if_fail (source_funcs != NULL, NULL);
828 g_return_val_if_fail (struct_size >= sizeof (GSource), NULL);
830 source = (GSource*) g_malloc0 (struct_size);
832 source->source_funcs = source_funcs;
833 source->ref_count = 1;
835 source->priority = G_PRIORITY_DEFAULT;
837 source->flags = G_HOOK_FLAG_ACTIVE;
839 /* NULL/0 initialization for all other fields */
844 /* Holds context's lock
847 g_source_list_add (GSource *source,
848 GMainContext *context)
850 GSource *tmp_source, *last_source;
852 if (source->priv && source->priv->parent_source)
854 /* Put the source immediately before its parent */
855 tmp_source = source->priv->parent_source;
856 last_source = source->priv->parent_source->prev;
861 tmp_source = context->source_list;
862 while (tmp_source && tmp_source->priority <= source->priority)
864 last_source = tmp_source;
865 tmp_source = tmp_source->next;
869 source->next = tmp_source;
871 tmp_source->prev = source;
873 source->prev = last_source;
875 last_source->next = source;
877 context->source_list = source;
880 /* Holds context's lock
883 g_source_list_remove (GSource *source,
884 GMainContext *context)
887 source->prev->next = source->next;
889 context->source_list = source->next;
892 source->next->prev = source->prev;
899 g_source_attach_unlocked (GSource *source,
900 GMainContext *context)
905 source->context = context;
906 result = source->source_id = context->next_id++;
909 g_source_list_add (source, context);
911 tmp_list = source->poll_fds;
914 g_main_context_add_poll_unlocked (context, source->priority, tmp_list->data);
915 tmp_list = tmp_list->next;
920 tmp_list = source->priv->child_sources;
923 g_source_attach_unlocked (tmp_list->data, context);
924 tmp_list = tmp_list->next;
933 * @source: a #GSource
934 * @context: a #GMainContext (if %NULL, the default context will be used)
936 * Adds a #GSource to a @context so that it will be executed within
937 * that context. Remove it by calling g_source_destroy().
939 * Return value: the ID (greater than 0) for the source within the
943 g_source_attach (GSource *source,
944 GMainContext *context)
948 g_return_val_if_fail (source->context == NULL, 0);
949 g_return_val_if_fail (!SOURCE_DESTROYED (source), 0);
952 context = g_main_context_default ();
954 LOCK_CONTEXT (context);
956 result = g_source_attach_unlocked (source, context);
958 #ifdef G_THREADS_ENABLED
959 /* Now wake up the main loop if it is waiting in the poll() */
960 g_main_context_wakeup_unlocked (context);
963 UNLOCK_CONTEXT (context);
969 g_source_destroy_internal (GSource *source,
970 GMainContext *context,
974 LOCK_CONTEXT (context);
976 if (!SOURCE_DESTROYED (source))
979 gpointer old_cb_data;
980 GSourceCallbackFuncs *old_cb_funcs;
982 source->flags &= ~G_HOOK_FLAG_ACTIVE;
984 old_cb_data = source->callback_data;
985 old_cb_funcs = source->callback_funcs;
987 source->callback_data = NULL;
988 source->callback_funcs = NULL;
992 UNLOCK_CONTEXT (context);
993 old_cb_funcs->unref (old_cb_data);
994 LOCK_CONTEXT (context);
997 if (!SOURCE_BLOCKED (source))
999 tmp_list = source->poll_fds;
1002 g_main_context_remove_poll_unlocked (context, tmp_list->data);
1003 tmp_list = tmp_list->next;
1007 if (source->priv && source->priv->child_sources)
1009 /* This is safe because even if a child_source finalizer or
1010 * closure notify tried to modify source->priv->child_sources
1011 * from outside the lock, it would fail since
1012 * SOURCE_DESTROYED(source) is now TRUE.
1014 tmp_list = source->priv->child_sources;
1017 g_source_destroy_internal (tmp_list->data, context, TRUE);
1018 g_source_unref_internal (tmp_list->data, context, TRUE);
1019 tmp_list = tmp_list->next;
1021 g_slist_free (source->priv->child_sources);
1022 source->priv->child_sources = NULL;
1025 g_source_unref_internal (source, context, TRUE);
1029 UNLOCK_CONTEXT (context);
1034 * @source: a #GSource
1036 * Removes a source from its #GMainContext, if any, and mark it as
1037 * destroyed. The source cannot be subsequently added to another
1041 g_source_destroy (GSource *source)
1043 GMainContext *context;
1045 g_return_if_fail (source != NULL);
1047 context = source->context;
1050 g_source_destroy_internal (source, context, FALSE);
1052 source->flags &= ~G_HOOK_FLAG_ACTIVE;
1057 * @source: a #GSource
1059 * Returns the numeric ID for a particular source. The ID of a source
1060 * is a positive integer which is unique within a particular main loop
1061 * context. The reverse
1062 * mapping from ID to source is done by g_main_context_find_source_by_id().
1064 * Return value: the ID (greater than 0) for the source
1067 g_source_get_id (GSource *source)
1071 g_return_val_if_fail (source != NULL, 0);
1072 g_return_val_if_fail (source->context != NULL, 0);
1074 LOCK_CONTEXT (source->context);
1075 result = source->source_id;
1076 UNLOCK_CONTEXT (source->context);
1082 * g_source_get_context:
1083 * @source: a #GSource
1085 * Gets the #GMainContext with which the source is associated.
1086 * Calling this function on a destroyed source is an error.
1088 * Return value: (transfer none): the #GMainContext with which the
1089 * source is associated, or %NULL if the context has not
1090 * yet been added to a source.
1093 g_source_get_context (GSource *source)
1095 g_return_val_if_fail (!SOURCE_DESTROYED (source), NULL);
1097 return source->context;
1101 * g_source_add_poll:
1102 * @source:a #GSource
1103 * @fd: a #GPollFD structure holding information about a file
1104 * descriptor to watch.
1106 * Adds a file descriptor to the set of file descriptors polled for
1107 * this source. This is usually combined with g_source_new() to add an
1108 * event source. The event source's check function will typically test
1109 * the @revents field in the #GPollFD struct and return %TRUE if events need
1113 g_source_add_poll (GSource *source,
1116 GMainContext *context;
1118 g_return_if_fail (source != NULL);
1119 g_return_if_fail (fd != NULL);
1120 g_return_if_fail (!SOURCE_DESTROYED (source));
1122 context = source->context;
1125 LOCK_CONTEXT (context);
1127 source->poll_fds = g_slist_prepend (source->poll_fds, fd);
1131 if (!SOURCE_BLOCKED (source))
1132 g_main_context_add_poll_unlocked (context, source->priority, fd);
1133 UNLOCK_CONTEXT (context);
1138 * g_source_remove_poll:
1139 * @source:a #GSource
1140 * @fd: a #GPollFD structure previously passed to g_source_add_poll().
1142 * Removes a file descriptor from the set of file descriptors polled for
1146 g_source_remove_poll (GSource *source,
1149 GMainContext *context;
1151 g_return_if_fail (source != NULL);
1152 g_return_if_fail (fd != NULL);
1153 g_return_if_fail (!SOURCE_DESTROYED (source));
1155 context = source->context;
1158 LOCK_CONTEXT (context);
1160 source->poll_fds = g_slist_remove (source->poll_fds, fd);
1164 if (!SOURCE_BLOCKED (source))
1165 g_main_context_remove_poll_unlocked (context, fd);
1166 UNLOCK_CONTEXT (context);
1171 * g_source_add_child_source:
1172 * @source:a #GSource
1173 * @child_source: a second #GSource that @source should "poll"
1175 * Adds @child_source to @source as a "polled" source; when @source is
1176 * added to a #GMainContext, @child_source will be automatically added
1177 * with the same priority, when @child_source is triggered, it will
1178 * cause @source to dispatch (in addition to calling its own
1179 * callback), and when @source is destroyed, it will destroy
1180 * @child_source as well. (@source will also still be dispatched if
1181 * its own prepare/check functions indicate that it is ready.)
1183 * If you don't need @child_source to do anything on its own when it
1184 * triggers, you can call g_source_set_dummy_callback() on it to set a
1185 * callback that does nothing (except return %TRUE if appropriate).
1187 * @source will hold a reference on @child_source while @child_source
1188 * is attached to it.
1193 g_source_add_child_source (GSource *source,
1194 GSource *child_source)
1196 GMainContext *context;
1198 g_return_if_fail (source != NULL);
1199 g_return_if_fail (child_source != NULL);
1200 g_return_if_fail (!SOURCE_DESTROYED (source));
1201 g_return_if_fail (!SOURCE_DESTROYED (child_source));
1202 g_return_if_fail (child_source->context == NULL);
1203 g_return_if_fail (child_source->priv == NULL || child_source->priv->parent_source == NULL);
1205 context = source->context;
1208 LOCK_CONTEXT (context);
1211 source->priv = g_slice_new0 (GSourcePrivate);
1212 if (!child_source->priv)
1213 child_source->priv = g_slice_new0 (GSourcePrivate);
1215 source->priv->child_sources = g_slist_prepend (source->priv->child_sources,
1216 g_source_ref (child_source));
1217 child_source->priv->parent_source = source;
1218 g_source_set_priority_unlocked (child_source, context, source->priority);
1222 UNLOCK_CONTEXT (context);
1223 g_source_attach (child_source, context);
1228 * g_source_remove_child_source:
1229 * @source:a #GSource
1230 * @child_source: a #GSource previously passed to
1231 * g_source_add_child_source().
1233 * Detaches @child_source from @source and destroys it.
1238 g_source_remove_child_source (GSource *source,
1239 GSource *child_source)
1241 GMainContext *context;
1243 g_return_if_fail (source != NULL);
1244 g_return_if_fail (child_source != NULL);
1245 g_return_if_fail (child_source->priv != NULL && child_source->priv->parent_source == source);
1246 g_return_if_fail (!SOURCE_DESTROYED (source));
1247 g_return_if_fail (!SOURCE_DESTROYED (child_source));
1249 context = source->context;
1252 LOCK_CONTEXT (context);
1254 source->priv->child_sources = g_slist_remove (source->priv->child_sources, child_source);
1255 g_source_destroy_internal (child_source, context, TRUE);
1256 g_source_unref_internal (child_source, context, TRUE);
1259 UNLOCK_CONTEXT (context);
1263 * g_source_set_callback_indirect:
1264 * @source: the source
1265 * @callback_data: pointer to callback data "object"
1266 * @callback_funcs: functions for reference counting @callback_data
1267 * and getting the callback and data
1269 * Sets the callback function storing the data as a refcounted callback
1270 * "object". This is used internally. Note that calling
1271 * g_source_set_callback_indirect() assumes
1272 * an initial reference count on @callback_data, and thus
1273 * @callback_funcs->unref will eventually be called once more
1274 * than @callback_funcs->ref.
1277 g_source_set_callback_indirect (GSource *source,
1278 gpointer callback_data,
1279 GSourceCallbackFuncs *callback_funcs)
1281 GMainContext *context;
1282 gpointer old_cb_data;
1283 GSourceCallbackFuncs *old_cb_funcs;
1285 g_return_if_fail (source != NULL);
1286 g_return_if_fail (callback_funcs != NULL || callback_data == NULL);
1288 context = source->context;
1291 LOCK_CONTEXT (context);
1293 old_cb_data = source->callback_data;
1294 old_cb_funcs = source->callback_funcs;
1296 source->callback_data = callback_data;
1297 source->callback_funcs = callback_funcs;
1300 UNLOCK_CONTEXT (context);
1303 old_cb_funcs->unref (old_cb_data);
1307 g_source_callback_ref (gpointer cb_data)
1309 GSourceCallback *callback = cb_data;
1311 callback->ref_count++;
1316 g_source_callback_unref (gpointer cb_data)
1318 GSourceCallback *callback = cb_data;
1320 callback->ref_count--;
1321 if (callback->ref_count == 0)
1323 if (callback->notify)
1324 callback->notify (callback->data);
1330 g_source_callback_get (gpointer cb_data,
1335 GSourceCallback *callback = cb_data;
1337 *func = callback->func;
1338 *data = callback->data;
1341 static GSourceCallbackFuncs g_source_callback_funcs = {
1342 g_source_callback_ref,
1343 g_source_callback_unref,
1344 g_source_callback_get,
1348 * g_source_set_callback:
1349 * @source: the source
1350 * @func: a callback function
1351 * @data: the data to pass to callback function
1352 * @notify: a function to call when @data is no longer in use, or %NULL.
1354 * Sets the callback function for a source. The callback for a source is
1355 * called from the source's dispatch function.
1357 * The exact type of @func depends on the type of source; ie. you
1358 * should not count on @func being called with @data as its first
1361 * Typically, you won't use this function. Instead use functions specific
1362 * to the type of source you are using.
1365 g_source_set_callback (GSource *source,
1368 GDestroyNotify notify)
1370 GSourceCallback *new_callback;
1372 g_return_if_fail (source != NULL);
1374 new_callback = g_new (GSourceCallback, 1);
1376 new_callback->ref_count = 1;
1377 new_callback->func = func;
1378 new_callback->data = data;
1379 new_callback->notify = notify;
1381 g_source_set_callback_indirect (source, new_callback, &g_source_callback_funcs);
1386 * g_source_set_funcs:
1387 * @source: a #GSource
1388 * @funcs: the new #GSourceFuncs
1390 * Sets the source functions (can be used to override
1391 * default implementations) of an unattached source.
1396 g_source_set_funcs (GSource *source,
1397 GSourceFuncs *funcs)
1399 g_return_if_fail (source != NULL);
1400 g_return_if_fail (source->context == NULL);
1401 g_return_if_fail (source->ref_count > 0);
1402 g_return_if_fail (funcs != NULL);
1404 source->source_funcs = funcs;
1408 g_source_set_priority_unlocked (GSource *source,
1409 GMainContext *context,
1414 source->priority = priority;
1418 /* Remove the source from the context's source and then
1419 * add it back so it is sorted in the correct place
1421 g_source_list_remove (source, source->context);
1422 g_source_list_add (source, source->context);
1424 if (!SOURCE_BLOCKED (source))
1426 tmp_list = source->poll_fds;
1429 g_main_context_remove_poll_unlocked (context, tmp_list->data);
1430 g_main_context_add_poll_unlocked (context, priority, tmp_list->data);
1432 tmp_list = tmp_list->next;
1437 if (source->priv && source->priv->child_sources)
1439 tmp_list = source->priv->child_sources;
1442 g_source_set_priority_unlocked (tmp_list->data, context, priority);
1443 tmp_list = tmp_list->next;
1449 * g_source_set_priority:
1450 * @source: a #GSource
1451 * @priority: the new priority.
1453 * Sets the priority of a source. While the main loop is being run, a
1454 * source will be dispatched if it is ready to be dispatched and no
1455 * sources at a higher (numerically smaller) priority are ready to be
1459 g_source_set_priority (GSource *source,
1462 GMainContext *context;
1464 g_return_if_fail (source != NULL);
1466 context = source->context;
1469 LOCK_CONTEXT (context);
1470 g_source_set_priority_unlocked (source, context, priority);
1472 UNLOCK_CONTEXT (source->context);
1476 * g_source_get_priority:
1477 * @source: a #GSource
1479 * Gets the priority of a source.
1481 * Return value: the priority of the source
1484 g_source_get_priority (GSource *source)
1486 g_return_val_if_fail (source != NULL, 0);
1488 return source->priority;
1492 * g_source_set_can_recurse:
1493 * @source: a #GSource
1494 * @can_recurse: whether recursion is allowed for this source
1496 * Sets whether a source can be called recursively. If @can_recurse is
1497 * %TRUE, then while the source is being dispatched then this source
1498 * will be processed normally. Otherwise, all processing of this
1499 * source is blocked until the dispatch function returns.
1502 g_source_set_can_recurse (GSource *source,
1503 gboolean can_recurse)
1505 GMainContext *context;
1507 g_return_if_fail (source != NULL);
1509 context = source->context;
1512 LOCK_CONTEXT (context);
1515 source->flags |= G_SOURCE_CAN_RECURSE;
1517 source->flags &= ~G_SOURCE_CAN_RECURSE;
1520 UNLOCK_CONTEXT (context);
1524 * g_source_get_can_recurse:
1525 * @source: a #GSource
1527 * Checks whether a source is allowed to be called recursively.
1528 * see g_source_set_can_recurse().
1530 * Return value: whether recursion is allowed.
1533 g_source_get_can_recurse (GSource *source)
1535 g_return_val_if_fail (source != NULL, FALSE);
1537 return (source->flags & G_SOURCE_CAN_RECURSE) != 0;
1542 * g_source_set_name:
1543 * @source: a #GSource
1544 * @name: debug name for the source
1546 * Sets a name for the source, used in debugging and profiling.
1547 * The name defaults to #NULL.
1549 * The source name should describe in a human-readable way
1550 * what the source does. For example, "X11 event queue"
1551 * or "GTK+ repaint idle handler" or whatever it is.
1553 * It is permitted to call this function multiple times, but is not
1554 * recommended due to the potential performance impact. For example,
1555 * one could change the name in the "check" function of a #GSourceFuncs
1556 * to include details like the event type in the source name.
1561 g_source_set_name (GSource *source,
1564 g_return_if_fail (source != NULL);
1566 /* setting back to NULL is allowed, just because it's
1567 * weird if get_name can return NULL but you can't
1571 g_free (source->name);
1572 source->name = g_strdup (name);
1576 * g_source_get_name:
1577 * @source: a #GSource
1579 * Gets a name for the source, used in debugging and profiling.
1580 * The name may be #NULL if it has never been set with
1581 * g_source_set_name().
1583 * Return value: the name of the source
1587 g_source_get_name (GSource *source)
1589 g_return_val_if_fail (source != NULL, NULL);
1591 return source->name;
1595 * g_source_set_name_by_id:
1596 * @tag: a #GSource ID
1597 * @name: debug name for the source
1599 * Sets the name of a source using its ID.
1601 * This is a convenience utility to set source names from the return
1602 * value of g_idle_add(), g_timeout_add(), etc.
1607 g_source_set_name_by_id (guint tag,
1612 g_return_if_fail (tag > 0);
1614 source = g_main_context_find_source_by_id (NULL, tag);
1618 g_source_set_name (source, name);
1624 * @source: a #GSource
1626 * Increases the reference count on a source by one.
1628 * Return value: @source
1631 g_source_ref (GSource *source)
1633 GMainContext *context;
1635 g_return_val_if_fail (source != NULL, NULL);
1637 context = source->context;
1640 LOCK_CONTEXT (context);
1642 source->ref_count++;
1645 UNLOCK_CONTEXT (context);
1650 /* g_source_unref() but possible to call within context lock
1653 g_source_unref_internal (GSource *source,
1654 GMainContext *context,
1657 gpointer old_cb_data = NULL;
1658 GSourceCallbackFuncs *old_cb_funcs = NULL;
1660 g_return_if_fail (source != NULL);
1662 if (!have_lock && context)
1663 LOCK_CONTEXT (context);
1665 source->ref_count--;
1666 if (source->ref_count == 0)
1668 old_cb_data = source->callback_data;
1669 old_cb_funcs = source->callback_funcs;
1671 source->callback_data = NULL;
1672 source->callback_funcs = NULL;
1676 if (!SOURCE_DESTROYED (source))
1677 g_warning (G_STRLOC ": ref_count == 0, but source was still attached to a context!");
1678 g_source_list_remove (source, context);
1681 if (source->source_funcs->finalize)
1684 UNLOCK_CONTEXT (context);
1685 source->source_funcs->finalize (source);
1687 LOCK_CONTEXT (context);
1690 g_free (source->name);
1691 source->name = NULL;
1693 g_slist_free (source->poll_fds);
1694 source->poll_fds = NULL;
1698 g_slice_free (GSourcePrivate, source->priv);
1699 source->priv = NULL;
1705 if (!have_lock && context)
1706 UNLOCK_CONTEXT (context);
1711 UNLOCK_CONTEXT (context);
1713 old_cb_funcs->unref (old_cb_data);
1716 LOCK_CONTEXT (context);
1722 * @source: a #GSource
1724 * Decreases the reference count of a source by one. If the
1725 * resulting reference count is zero the source and associated
1726 * memory will be destroyed.
1729 g_source_unref (GSource *source)
1731 g_return_if_fail (source != NULL);
1733 g_source_unref_internal (source, source->context, FALSE);
1737 * g_main_context_find_source_by_id:
1738 * @context: a #GMainContext (if %NULL, the default context will be used)
1739 * @source_id: the source ID, as returned by g_source_get_id().
1741 * Finds a #GSource given a pair of context and ID.
1743 * Return value: (transfer none): the #GSource if found, otherwise, %NULL
1746 g_main_context_find_source_by_id (GMainContext *context,
1751 g_return_val_if_fail (source_id > 0, NULL);
1753 if (context == NULL)
1754 context = g_main_context_default ();
1756 LOCK_CONTEXT (context);
1758 source = context->source_list;
1761 if (!SOURCE_DESTROYED (source) &&
1762 source->source_id == source_id)
1764 source = source->next;
1767 UNLOCK_CONTEXT (context);
1773 * g_main_context_find_source_by_funcs_user_data:
1774 * @context: a #GMainContext (if %NULL, the default context will be used).
1775 * @funcs: the @source_funcs passed to g_source_new().
1776 * @user_data: the user data from the callback.
1778 * Finds a source with the given source functions and user data. If
1779 * multiple sources exist with the same source function and user data,
1780 * the first one found will be returned.
1782 * Return value: (transfer none): the source, if one was found, otherwise %NULL
1785 g_main_context_find_source_by_funcs_user_data (GMainContext *context,
1786 GSourceFuncs *funcs,
1791 g_return_val_if_fail (funcs != NULL, NULL);
1793 if (context == NULL)
1794 context = g_main_context_default ();
1796 LOCK_CONTEXT (context);
1798 source = context->source_list;
1801 if (!SOURCE_DESTROYED (source) &&
1802 source->source_funcs == funcs &&
1803 source->callback_funcs)
1805 GSourceFunc callback;
1806 gpointer callback_data;
1808 source->callback_funcs->get (source->callback_data, source, &callback, &callback_data);
1810 if (callback_data == user_data)
1813 source = source->next;
1816 UNLOCK_CONTEXT (context);
1822 * g_main_context_find_source_by_user_data:
1823 * @context: a #GMainContext
1824 * @user_data: the user_data for the callback.
1826 * Finds a source with the given user data for the callback. If
1827 * multiple sources exist with the same user data, the first
1828 * one found will be returned.
1830 * Return value: (transfer none): the source, if one was found, otherwise %NULL
1833 g_main_context_find_source_by_user_data (GMainContext *context,
1838 if (context == NULL)
1839 context = g_main_context_default ();
1841 LOCK_CONTEXT (context);
1843 source = context->source_list;
1846 if (!SOURCE_DESTROYED (source) &&
1847 source->callback_funcs)
1849 GSourceFunc callback;
1850 gpointer callback_data = NULL;
1852 source->callback_funcs->get (source->callback_data, source, &callback, &callback_data);
1854 if (callback_data == user_data)
1857 source = source->next;
1860 UNLOCK_CONTEXT (context);
1867 * @tag: the ID of the source to remove.
1869 * Removes the source with the given id from the default main context.
1871 * a #GSource is given by g_source_get_id(), or will be returned by the
1872 * functions g_source_attach(), g_idle_add(), g_idle_add_full(),
1873 * g_timeout_add(), g_timeout_add_full(), g_child_watch_add(),
1874 * g_child_watch_add_full(), g_io_add_watch(), and g_io_add_watch_full().
1876 * See also g_source_destroy(). You must use g_source_destroy() for sources
1877 * added to a non-default main context.
1879 * Return value: %TRUE if the source was found and removed.
1882 g_source_remove (guint tag)
1886 g_return_val_if_fail (tag > 0, FALSE);
1888 source = g_main_context_find_source_by_id (NULL, tag);
1890 g_source_destroy (source);
1892 return source != NULL;
1896 * g_source_remove_by_user_data:
1897 * @user_data: the user_data for the callback.
1899 * Removes a source from the default main loop context given the user
1900 * data for the callback. If multiple sources exist with the same user
1901 * data, only one will be destroyed.
1903 * Return value: %TRUE if a source was found and removed.
1906 g_source_remove_by_user_data (gpointer user_data)
1910 source = g_main_context_find_source_by_user_data (NULL, user_data);
1913 g_source_destroy (source);
1921 * g_source_remove_by_funcs_user_data:
1922 * @funcs: The @source_funcs passed to g_source_new()
1923 * @user_data: the user data for the callback
1925 * Removes a source from the default main loop context given the
1926 * source functions and user data. If multiple sources exist with the
1927 * same source functions and user data, only one will be destroyed.
1929 * Return value: %TRUE if a source was found and removed.
1932 g_source_remove_by_funcs_user_data (GSourceFuncs *funcs,
1937 g_return_val_if_fail (funcs != NULL, FALSE);
1939 source = g_main_context_find_source_by_funcs_user_data (NULL, funcs, user_data);
1942 g_source_destroy (source);
1950 * g_get_current_time:
1951 * @result: #GTimeVal structure in which to store current time.
1953 * Equivalent to the UNIX gettimeofday() function, but portable.
1955 * You may find g_get_real_time() to be more convenient.
1958 g_get_current_time (GTimeVal *result)
1963 g_return_if_fail (result != NULL);
1965 /*this is required on alpha, there the timeval structs are int's
1966 not longs and a cast only would fail horribly*/
1967 gettimeofday (&r, NULL);
1968 result->tv_sec = r.tv_sec;
1969 result->tv_usec = r.tv_usec;
1974 g_return_if_fail (result != NULL);
1976 GetSystemTimeAsFileTime (&ft);
1977 memmove (&time64, &ft, sizeof (FILETIME));
1979 /* Convert from 100s of nanoseconds since 1601-01-01
1980 * to Unix epoch. Yes, this is Y2038 unsafe.
1982 time64 -= G_GINT64_CONSTANT (116444736000000000);
1985 result->tv_sec = time64 / 1000000;
1986 result->tv_usec = time64 % 1000000;
1993 * Queries the system wall-clock time.
1995 * This call is functionally equivalent to g_get_current_time() except
1996 * that the return value is often more convenient than dealing with a
1999 * You should only use this call if you are actually interested in the real
2000 * wall-clock time. g_get_monotonic_time() is probably more useful for
2001 * measuring intervals.
2003 * Returns: the number of microseconds since January 1, 1970 UTC.
2008 g_get_real_time (void)
2012 g_get_current_time (&tv);
2014 return (((gint64) tv.tv_sec) * 1000000) + tv.tv_usec;
2018 * g_get_monotonic_time:
2020 * Queries the system monotonic time, if available.
2022 * On POSIX systems with clock_gettime() and %CLOCK_MONOTONIC this call
2023 * is a very shallow wrapper for that. Otherwise, we make a best effort
2024 * that probably involves returning the wall clock time (with at least
2025 * microsecond accuracy, subject to the limitations of the OS kernel).
2027 * It's important to note that POSIX %CLOCK_MONOTONIC does not count
2028 * time spent while the machine is suspended.
2030 * On Windows, "limitations of the OS kernel" is a rather substantial
2031 * statement. Depending on the configuration of the system, the wall
2032 * clock time is updated as infrequently as 64 times a second (which
2033 * is approximately every 16ms).
2035 * Returns: the monotonic time, in microseconds
2040 g_get_monotonic_time (void)
2042 #ifdef HAVE_CLOCK_GETTIME
2043 /* librt clock_gettime() is our first choice */
2045 #ifdef HAVE_MONOTONIC_CLOCK
2046 static volatile gsize clockid = 0;
2048 static clockid_t clockid = CLOCK_REALTIME;
2052 #ifdef HAVE_MONOTONIC_CLOCK
2053 if (g_once_init_enter (&clockid))
2055 clockid_t best_clockid;
2057 if (sysconf (_SC_MONOTONIC_CLOCK) >= 0)
2058 best_clockid = CLOCK_MONOTONIC;
2060 best_clockid = CLOCK_REALTIME;
2061 g_once_init_leave (&clockid, (gsize)best_clockid);
2065 clock_gettime (clockid, &ts);
2067 /* In theory monotonic time can have any epoch.
2069 * glib presently assumes the following:
2071 * 1) The epoch comes some time after the birth of Jesus of Nazareth, but
2072 * not more than 10000 years later.
2074 * 2) The current time also falls sometime within this range.
2076 * These two reasonable assumptions leave us with a maximum deviation from
2077 * the epoch of 10000 years, or 315569520000000000 seconds.
2079 * If we restrict ourselves to this range then the number of microseconds
2080 * will always fit well inside the constraints of a int64 (by a factor of
2083 * If you actually hit the following assertion, probably you should file a
2084 * bug against your operating system for being excessively silly.
2086 g_assert (G_GINT64_CONSTANT (-315569520000000000) < ts.tv_sec &&
2087 ts.tv_sec < G_GINT64_CONSTANT (315569520000000000));
2089 return (((gint64) ts.tv_sec) * 1000000) + (ts.tv_nsec / 1000);
2092 /* It may look like we are discarding accuracy on Windows (since its
2093 * current time is expressed in 100s of nanoseconds) but according to
2094 * many sources, the time is only updated 64 times per second, so
2095 * microsecond accuracy is more than enough.
2100 g_get_current_time (&tv);
2102 return (((gint64) tv.tv_sec) * 1000000) + tv.tv_usec;
2108 g_main_dispatch_free (gpointer dispatch)
2110 g_slice_free (GMainDispatch, dispatch);
2113 /* Running the main loop */
2115 static GMainDispatch *
2118 static GStaticPrivate depth_private = G_STATIC_PRIVATE_INIT;
2119 GMainDispatch *dispatch = g_static_private_get (&depth_private);
2122 dispatch = g_slice_new0 (GMainDispatch);
2123 g_static_private_set (&depth_private, dispatch, g_main_dispatch_free);
2132 * Returns the depth of the stack of calls to
2133 * g_main_context_dispatch() on any #GMainContext in the current thread.
2134 * That is, when called from the toplevel, it gives 0. When
2135 * called from within a callback from g_main_context_iteration()
2136 * (or g_main_loop_run(), etc.) it returns 1. When called from within
2137 * a callback to a recursive call to g_main_context_iteration(),
2138 * it returns 2. And so forth.
2140 * This function is useful in a situation like the following:
2141 * Imagine an extremely simple "garbage collected" system.
2144 * static GList *free_list;
2147 * allocate_memory (gsize size)
2149 * gpointer result = g_malloc (size);
2150 * free_list = g_list_prepend (free_list, result);
2155 * free_allocated_memory (void)
2158 * for (l = free_list; l; l = l->next);
2160 * g_list_free (free_list);
2168 * g_main_context_iteration (NULL, TRUE);
2169 * free_allocated_memory();
2173 * This works from an application, however, if you want to do the same
2174 * thing from a library, it gets more difficult, since you no longer
2175 * control the main loop. You might think you can simply use an idle
2176 * function to make the call to free_allocated_memory(), but that
2177 * doesn't work, since the idle function could be called from a
2178 * recursive callback. This can be fixed by using g_main_depth()
2182 * allocate_memory (gsize size)
2184 * FreeListBlock *block = g_new (FreeListBlock, 1);
2185 * block->mem = g_malloc (size);
2186 * block->depth = g_main_depth ();
2187 * free_list = g_list_prepend (free_list, block);
2188 * return block->mem;
2192 * free_allocated_memory (void)
2196 * int depth = g_main_depth ();
2197 * for (l = free_list; l; );
2199 * GList *next = l->next;
2200 * FreeListBlock *block = l->data;
2201 * if (block->depth > depth)
2203 * g_free (block->mem);
2205 * free_list = g_list_delete_link (free_list, l);
2213 * There is a temptation to use g_main_depth() to solve
2214 * problems with reentrancy. For instance, while waiting for data
2215 * to be received from the network in response to a menu item,
2216 * the menu item might be selected again. It might seem that
2217 * one could make the menu item's callback return immediately
2218 * and do nothing if g_main_depth() returns a value greater than 1.
2219 * However, this should be avoided since the user then sees selecting
2220 * the menu item do nothing. Furthermore, you'll find yourself adding
2221 * these checks all over your code, since there are doubtless many,
2222 * many things that the user could do. Instead, you can use the
2223 * following techniques:
2228 * Use gtk_widget_set_sensitive() or modal dialogs to prevent
2229 * the user from interacting with elements while the main
2230 * loop is recursing.
2235 * Avoid main loop recursion in situations where you can't handle
2236 * arbitrary callbacks. Instead, structure your code so that you
2237 * simply return to the main loop and then get called again when
2238 * there is more work to do.
2243 * Return value: The main loop recursion level in the current thread
2248 GMainDispatch *dispatch = get_dispatch ();
2249 return dispatch->depth;
2253 * g_main_current_source:
2255 * Returns the currently firing source for this thread.
2257 * Return value: (transfer none): The currently firing source or %NULL.
2262 g_main_current_source (void)
2264 GMainDispatch *dispatch = get_dispatch ();
2265 return dispatch->dispatching_sources ? dispatch->dispatching_sources->data : NULL;
2269 * g_source_is_destroyed:
2270 * @source: a #GSource
2272 * Returns whether @source has been destroyed.
2274 * This is important when you operate upon your objects
2275 * from within idle handlers, but may have freed the object
2276 * before the dispatch of your idle handler.
2280 * idle_callback (gpointer data)
2282 * SomeWidget *self = data;
2284 * GDK_THREADS_ENTER (<!-- -->);
2285 * /<!-- -->* do stuff with self *<!-- -->/
2286 * self->idle_id = 0;
2287 * GDK_THREADS_LEAVE (<!-- -->);
2293 * some_widget_do_stuff_later (SomeWidget *self)
2295 * self->idle_id = g_idle_add (idle_callback, self);
2299 * some_widget_finalize (GObject *object)
2301 * SomeWidget *self = SOME_WIDGET (object);
2303 * if (self->idle_id)
2304 * g_source_remove (self->idle_id);
2306 * G_OBJECT_CLASS (parent_class)->finalize (object);
2310 * This will fail in a multi-threaded application if the
2311 * widget is destroyed before the idle handler fires due
2312 * to the use after free in the callback. A solution, to
2313 * this particular problem, is to check to if the source
2314 * has already been destroy within the callback.
2318 * idle_callback (gpointer data)
2320 * SomeWidget *self = data;
2322 * GDK_THREADS_ENTER ();
2323 * if (!g_source_is_destroyed (g_main_current_source ()))
2325 * /<!-- -->* do stuff with self *<!-- -->/
2327 * GDK_THREADS_LEAVE ();
2333 * Return value: %TRUE if the source has been destroyed
2338 g_source_is_destroyed (GSource *source)
2340 return SOURCE_DESTROYED (source);
2343 /* Temporarily remove all this source's file descriptors from the
2344 * poll(), so that if data comes available for one of the file descriptors
2345 * we don't continually spin in the poll()
2347 /* HOLDS: source->context's lock */
2349 block_source (GSource *source)
2353 g_return_if_fail (!SOURCE_BLOCKED (source));
2355 tmp_list = source->poll_fds;
2358 g_main_context_remove_poll_unlocked (source->context, tmp_list->data);
2359 tmp_list = tmp_list->next;
2363 /* HOLDS: source->context's lock */
2365 unblock_source (GSource *source)
2369 g_return_if_fail (!SOURCE_BLOCKED (source)); /* Source already unblocked */
2370 g_return_if_fail (!SOURCE_DESTROYED (source));
2372 tmp_list = source->poll_fds;
2375 g_main_context_add_poll_unlocked (source->context, source->priority, tmp_list->data);
2376 tmp_list = tmp_list->next;
2380 /* HOLDS: context's lock */
2382 g_main_dispatch (GMainContext *context)
2384 GMainDispatch *current = get_dispatch ();
2387 for (i = 0; i < context->pending_dispatches->len; i++)
2389 GSource *source = context->pending_dispatches->pdata[i];
2391 context->pending_dispatches->pdata[i] = NULL;
2394 source->flags &= ~G_SOURCE_READY;
2396 if (!SOURCE_DESTROYED (source))
2398 gboolean was_in_call;
2399 gpointer user_data = NULL;
2400 GSourceFunc callback = NULL;
2401 GSourceCallbackFuncs *cb_funcs;
2403 gboolean need_destroy;
2405 gboolean (*dispatch) (GSource *,
2408 GSList current_source_link;
2410 dispatch = source->source_funcs->dispatch;
2411 cb_funcs = source->callback_funcs;
2412 cb_data = source->callback_data;
2415 cb_funcs->ref (cb_data);
2417 if ((source->flags & G_SOURCE_CAN_RECURSE) == 0)
2418 block_source (source);
2420 was_in_call = source->flags & G_HOOK_FLAG_IN_CALL;
2421 source->flags |= G_HOOK_FLAG_IN_CALL;
2424 cb_funcs->get (cb_data, source, &callback, &user_data);
2426 UNLOCK_CONTEXT (context);
2429 /* The on-stack allocation of the GSList is unconventional, but
2430 * we know that the lifetime of the link is bounded to this
2431 * function as the link is kept in a thread specific list and
2432 * not manipulated outside of this function and its descendants.
2433 * Avoiding the overhead of a g_slist_alloc() is useful as many
2434 * applications do little more than dispatch events.
2436 * This is a performance hack - do not revert to g_slist_prepend()!
2438 current_source_link.data = source;
2439 current_source_link.next = current->dispatching_sources;
2440 current->dispatching_sources = ¤t_source_link;
2441 need_destroy = ! dispatch (source,
2444 g_assert (current->dispatching_sources == ¤t_source_link);
2445 current->dispatching_sources = current_source_link.next;
2449 cb_funcs->unref (cb_data);
2451 LOCK_CONTEXT (context);
2454 source->flags &= ~G_HOOK_FLAG_IN_CALL;
2456 if ((source->flags & G_SOURCE_CAN_RECURSE) == 0 &&
2457 !SOURCE_DESTROYED (source))
2458 unblock_source (source);
2460 /* Note: this depends on the fact that we can't switch
2461 * sources from one main context to another
2463 if (need_destroy && !SOURCE_DESTROYED (source))
2465 g_assert (source->context == context);
2466 g_source_destroy_internal (source, context, TRUE);
2470 SOURCE_UNREF (source, context);
2473 g_ptr_array_set_size (context->pending_dispatches, 0);
2476 /* Holds context's lock */
2477 static inline GSource *
2478 next_valid_source (GMainContext *context,
2481 GSource *new_source = source ? source->next : context->source_list;
2485 if (!SOURCE_DESTROYED (new_source))
2487 new_source->ref_count++;
2491 new_source = new_source->next;
2495 SOURCE_UNREF (source, context);
2501 * g_main_context_acquire:
2502 * @context: a #GMainContext
2504 * Tries to become the owner of the specified context.
2505 * If some other thread is the owner of the context,
2506 * returns %FALSE immediately. Ownership is properly
2507 * recursive: the owner can require ownership again
2508 * and will release ownership when g_main_context_release()
2509 * is called as many times as g_main_context_acquire().
2511 * You must be the owner of a context before you
2512 * can call g_main_context_prepare(), g_main_context_query(),
2513 * g_main_context_check(), g_main_context_dispatch().
2515 * Return value: %TRUE if the operation succeeded, and
2516 * this thread is now the owner of @context.
2519 g_main_context_acquire (GMainContext *context)
2521 #ifdef G_THREADS_ENABLED
2522 gboolean result = FALSE;
2523 GThread *self = G_THREAD_SELF;
2525 if (context == NULL)
2526 context = g_main_context_default ();
2528 LOCK_CONTEXT (context);
2530 if (!context->owner)
2532 context->owner = self;
2533 g_assert (context->owner_count == 0);
2536 if (context->owner == self)
2538 context->owner_count++;
2542 UNLOCK_CONTEXT (context);
2545 #else /* !G_THREADS_ENABLED */
2547 #endif /* G_THREADS_ENABLED */
2551 * g_main_context_release:
2552 * @context: a #GMainContext
2554 * Releases ownership of a context previously acquired by this thread
2555 * with g_main_context_acquire(). If the context was acquired multiple
2556 * times, the ownership will be released only when g_main_context_release()
2557 * is called as many times as it was acquired.
2560 g_main_context_release (GMainContext *context)
2562 #ifdef G_THREADS_ENABLED
2563 if (context == NULL)
2564 context = g_main_context_default ();
2566 LOCK_CONTEXT (context);
2568 context->owner_count--;
2569 if (context->owner_count == 0)
2571 context->owner = NULL;
2573 if (context->waiters)
2575 GMainWaiter *waiter = context->waiters->data;
2576 gboolean loop_internal_waiter =
2577 (waiter->mutex == g_static_mutex_get_mutex (&context->mutex));
2578 context->waiters = g_slist_delete_link (context->waiters,
2580 if (!loop_internal_waiter)
2581 g_mutex_lock (waiter->mutex);
2583 g_cond_signal (waiter->cond);
2585 if (!loop_internal_waiter)
2586 g_mutex_unlock (waiter->mutex);
2590 UNLOCK_CONTEXT (context);
2591 #endif /* G_THREADS_ENABLED */
2595 * g_main_context_wait:
2596 * @context: a #GMainContext
2597 * @cond: a condition variable
2598 * @mutex: a mutex, currently held
2600 * Tries to become the owner of the specified context,
2601 * as with g_main_context_acquire(). But if another thread
2602 * is the owner, atomically drop @mutex and wait on @cond until
2603 * that owner releases ownership or until @cond is signaled, then
2604 * try again (once) to become the owner.
2606 * Return value: %TRUE if the operation succeeded, and
2607 * this thread is now the owner of @context.
2610 g_main_context_wait (GMainContext *context,
2614 #ifdef G_THREADS_ENABLED
2615 gboolean result = FALSE;
2616 GThread *self = G_THREAD_SELF;
2617 gboolean loop_internal_waiter;
2619 if (context == NULL)
2620 context = g_main_context_default ();
2622 loop_internal_waiter = (mutex == g_static_mutex_get_mutex (&context->mutex));
2624 if (!loop_internal_waiter)
2625 LOCK_CONTEXT (context);
2627 if (context->owner && context->owner != self)
2632 waiter.mutex = mutex;
2634 context->waiters = g_slist_append (context->waiters, &waiter);
2636 if (!loop_internal_waiter)
2637 UNLOCK_CONTEXT (context);
2638 g_cond_wait (cond, mutex);
2639 if (!loop_internal_waiter)
2640 LOCK_CONTEXT (context);
2642 context->waiters = g_slist_remove (context->waiters, &waiter);
2645 if (!context->owner)
2647 context->owner = self;
2648 g_assert (context->owner_count == 0);
2651 if (context->owner == self)
2653 context->owner_count++;
2657 if (!loop_internal_waiter)
2658 UNLOCK_CONTEXT (context);
2661 #else /* !G_THREADS_ENABLED */
2663 #endif /* G_THREADS_ENABLED */
2667 * g_main_context_prepare:
2668 * @context: a #GMainContext
2669 * @priority: location to store priority of highest priority
2670 * source already ready.
2672 * Prepares to poll sources within a main loop. The resulting information
2673 * for polling is determined by calling g_main_context_query ().
2675 * Return value: %TRUE if some source is ready to be dispatched
2679 g_main_context_prepare (GMainContext *context,
2684 gint current_priority = G_MAXINT;
2687 if (context == NULL)
2688 context = g_main_context_default ();
2690 LOCK_CONTEXT (context);
2692 context->time_is_fresh = FALSE;
2693 context->real_time_is_fresh = FALSE;
2695 if (context->in_check_or_prepare)
2697 g_warning ("g_main_context_prepare() called recursively from within a source's check() or "
2698 "prepare() member.");
2699 UNLOCK_CONTEXT (context);
2703 #ifdef G_THREADS_ENABLED
2704 if (context->poll_waiting)
2706 g_warning("g_main_context_prepare(): main loop already active in another thread");
2707 UNLOCK_CONTEXT (context);
2711 context->poll_waiting = TRUE;
2712 #endif /* G_THREADS_ENABLED */
2715 /* If recursing, finish up current dispatch, before starting over */
2716 if (context->pending_dispatches)
2719 g_main_dispatch (context, ¤t_time);
2721 UNLOCK_CONTEXT (context);
2726 /* If recursing, clear list of pending dispatches */
2728 for (i = 0; i < context->pending_dispatches->len; i++)
2730 if (context->pending_dispatches->pdata[i])
2731 SOURCE_UNREF ((GSource *)context->pending_dispatches->pdata[i], context);
2733 g_ptr_array_set_size (context->pending_dispatches, 0);
2735 /* Prepare all sources */
2737 context->timeout = -1;
2739 source = next_valid_source (context, NULL);
2742 gint source_timeout = -1;
2744 if ((n_ready > 0) && (source->priority > current_priority))
2746 SOURCE_UNREF (source, context);
2749 if (SOURCE_BLOCKED (source))
2752 if (!(source->flags & G_SOURCE_READY))
2755 gboolean (*prepare) (GSource *source,
2758 prepare = source->source_funcs->prepare;
2759 context->in_check_or_prepare++;
2760 UNLOCK_CONTEXT (context);
2762 result = (*prepare) (source, &source_timeout);
2764 LOCK_CONTEXT (context);
2765 context->in_check_or_prepare--;
2769 GSource *ready_source = source;
2771 while (ready_source)
2773 ready_source->flags |= G_SOURCE_READY;
2774 ready_source = ready_source->priv ? ready_source->priv->parent_source : NULL;
2779 if (source->flags & G_SOURCE_READY)
2782 current_priority = source->priority;
2783 context->timeout = 0;
2786 if (source_timeout >= 0)
2788 if (context->timeout < 0)
2789 context->timeout = source_timeout;
2791 context->timeout = MIN (context->timeout, source_timeout);
2795 source = next_valid_source (context, source);
2798 UNLOCK_CONTEXT (context);
2801 *priority = current_priority;
2803 return (n_ready > 0);
2807 * g_main_context_query:
2808 * @context: a #GMainContext
2809 * @max_priority: maximum priority source to check
2810 * @timeout_: (out): location to store timeout to be used in polling
2811 * @fds: (out caller-allocates) (array length=n_fds): location to
2812 * store #GPollFD records that need to be polled.
2813 * @n_fds: length of @fds.
2815 * Determines information necessary to poll this main loop.
2817 * Return value: the number of records actually stored in @fds,
2818 * or, if more than @n_fds records need to be stored, the number
2819 * of records that need to be stored.
2822 g_main_context_query (GMainContext *context,
2831 LOCK_CONTEXT (context);
2833 pollrec = context->poll_records;
2835 while (pollrec && max_priority >= pollrec->priority)
2837 /* We need to include entries with fd->events == 0 in the array because
2838 * otherwise if the application changes fd->events behind our back and
2839 * makes it non-zero, we'll be out of sync when we check the fds[] array.
2840 * (Changing fd->events after adding an FD wasn't an anticipated use of
2841 * this API, but it occurs in practice.) */
2844 fds[n_poll].fd = pollrec->fd->fd;
2845 /* In direct contradiction to the Unix98 spec, IRIX runs into
2846 * difficulty if you pass in POLLERR, POLLHUP or POLLNVAL
2847 * flags in the events field of the pollfd while it should
2848 * just ignoring them. So we mask them out here.
2850 fds[n_poll].events = pollrec->fd->events & ~(G_IO_ERR|G_IO_HUP|G_IO_NVAL);
2851 fds[n_poll].revents = 0;
2854 pollrec = pollrec->next;
2858 #ifdef G_THREADS_ENABLED
2859 context->poll_changed = FALSE;
2864 *timeout = context->timeout;
2867 context->time_is_fresh = FALSE;
2868 context->real_time_is_fresh = FALSE;
2872 UNLOCK_CONTEXT (context);
2878 * g_main_context_check:
2879 * @context: a #GMainContext
2880 * @max_priority: the maximum numerical priority of sources to check
2881 * @fds: (array length=n_fds): array of #GPollFD's that was passed to
2882 * the last call to g_main_context_query()
2883 * @n_fds: return value of g_main_context_query()
2885 * Passes the results of polling back to the main loop.
2887 * Return value: %TRUE if some sources are ready to be dispatched.
2890 g_main_context_check (GMainContext *context,
2900 LOCK_CONTEXT (context);
2902 if (context->in_check_or_prepare)
2904 g_warning ("g_main_context_check() called recursively from within a source's check() or "
2905 "prepare() member.");
2906 UNLOCK_CONTEXT (context);
2910 #ifdef G_THREADS_ENABLED
2911 if (!context->poll_waiting)
2912 g_wakeup_acknowledge (context->wakeup);
2915 context->poll_waiting = FALSE;
2917 /* If the set of poll file descriptors changed, bail out
2918 * and let the main loop rerun
2920 if (context->poll_changed)
2922 UNLOCK_CONTEXT (context);
2925 #endif /* G_THREADS_ENABLED */
2927 pollrec = context->poll_records;
2931 if (pollrec->fd->events)
2932 pollrec->fd->revents = fds[i].revents;
2934 pollrec = pollrec->next;
2938 source = next_valid_source (context, NULL);
2941 if ((n_ready > 0) && (source->priority > max_priority))
2943 SOURCE_UNREF (source, context);
2946 if (SOURCE_BLOCKED (source))
2949 if (!(source->flags & G_SOURCE_READY))
2952 gboolean (*check) (GSource *source);
2954 check = source->source_funcs->check;
2956 context->in_check_or_prepare++;
2957 UNLOCK_CONTEXT (context);
2959 result = (*check) (source);
2961 LOCK_CONTEXT (context);
2962 context->in_check_or_prepare--;
2966 GSource *ready_source = source;
2968 while (ready_source)
2970 ready_source->flags |= G_SOURCE_READY;
2971 ready_source = ready_source->priv ? ready_source->priv->parent_source : NULL;
2976 if (source->flags & G_SOURCE_READY)
2978 source->ref_count++;
2979 g_ptr_array_add (context->pending_dispatches, source);
2983 /* never dispatch sources with less priority than the first
2984 * one we choose to dispatch
2986 max_priority = source->priority;
2990 source = next_valid_source (context, source);
2993 UNLOCK_CONTEXT (context);
2999 * g_main_context_dispatch:
3000 * @context: a #GMainContext
3002 * Dispatches all pending sources.
3005 g_main_context_dispatch (GMainContext *context)
3007 LOCK_CONTEXT (context);
3009 if (context->pending_dispatches->len > 0)
3011 g_main_dispatch (context);
3014 UNLOCK_CONTEXT (context);
3017 /* HOLDS context lock */
3019 g_main_context_iterate (GMainContext *context,
3026 gboolean some_ready;
3027 gint nfds, allocated_nfds;
3028 GPollFD *fds = NULL;
3030 UNLOCK_CONTEXT (context);
3032 #ifdef G_THREADS_ENABLED
3033 if (!g_main_context_acquire (context))
3035 gboolean got_ownership;
3037 LOCK_CONTEXT (context);
3039 g_return_val_if_fail (g_thread_supported (), FALSE);
3045 context->cond = g_cond_new ();
3047 got_ownership = g_main_context_wait (context,
3049 g_static_mutex_get_mutex (&context->mutex));
3055 LOCK_CONTEXT (context);
3056 #endif /* G_THREADS_ENABLED */
3058 if (!context->cached_poll_array)
3060 context->cached_poll_array_size = context->n_poll_records;
3061 context->cached_poll_array = g_new (GPollFD, context->n_poll_records);
3064 allocated_nfds = context->cached_poll_array_size;
3065 fds = context->cached_poll_array;
3067 UNLOCK_CONTEXT (context);
3069 g_main_context_prepare (context, &max_priority);
3071 while ((nfds = g_main_context_query (context, max_priority, &timeout, fds,
3072 allocated_nfds)) > allocated_nfds)
3074 LOCK_CONTEXT (context);
3076 context->cached_poll_array_size = allocated_nfds = nfds;
3077 context->cached_poll_array = fds = g_new (GPollFD, nfds);
3078 UNLOCK_CONTEXT (context);
3084 g_main_context_poll (context, timeout, max_priority, fds, nfds);
3086 some_ready = g_main_context_check (context, max_priority, fds, nfds);
3089 g_main_context_dispatch (context);
3091 #ifdef G_THREADS_ENABLED
3092 g_main_context_release (context);
3093 #endif /* G_THREADS_ENABLED */
3095 LOCK_CONTEXT (context);
3101 * g_main_context_pending:
3102 * @context: a #GMainContext (if %NULL, the default context will be used)
3104 * Checks if any sources have pending events for the given context.
3106 * Return value: %TRUE if events are pending.
3109 g_main_context_pending (GMainContext *context)
3114 context = g_main_context_default();
3116 LOCK_CONTEXT (context);
3117 retval = g_main_context_iterate (context, FALSE, FALSE, G_THREAD_SELF);
3118 UNLOCK_CONTEXT (context);
3124 * g_main_context_iteration:
3125 * @context: a #GMainContext (if %NULL, the default context will be used)
3126 * @may_block: whether the call may block.
3128 * Runs a single iteration for the given main loop. This involves
3129 * checking to see if any event sources are ready to be processed,
3130 * then if no events sources are ready and @may_block is %TRUE, waiting
3131 * for a source to become ready, then dispatching the highest priority
3132 * events sources that are ready. Otherwise, if @may_block is %FALSE
3133 * sources are not waited to become ready, only those highest priority
3134 * events sources will be dispatched (if any), that are ready at this
3135 * given moment without further waiting.
3137 * Note that even when @may_block is %TRUE, it is still possible for
3138 * g_main_context_iteration() to return %FALSE, since the the wait may
3139 * be interrupted for other reasons than an event source becoming ready.
3141 * Return value: %TRUE if events were dispatched.
3144 g_main_context_iteration (GMainContext *context, gboolean may_block)
3149 context = g_main_context_default();
3151 LOCK_CONTEXT (context);
3152 retval = g_main_context_iterate (context, may_block, TRUE, G_THREAD_SELF);
3153 UNLOCK_CONTEXT (context);
3160 * @context: (allow-none): a #GMainContext (if %NULL, the default context will be used).
3161 * @is_running: set to %TRUE to indicate that the loop is running. This
3162 * is not very important since calling g_main_loop_run() will set this to
3165 * Creates a new #GMainLoop structure.
3167 * Return value: a new #GMainLoop.
3170 g_main_loop_new (GMainContext *context,
3171 gboolean is_running)
3176 context = g_main_context_default();
3178 g_main_context_ref (context);
3180 loop = g_new0 (GMainLoop, 1);
3181 loop->context = context;
3182 loop->is_running = is_running != FALSE;
3183 loop->ref_count = 1;
3190 * @loop: a #GMainLoop
3192 * Increases the reference count on a #GMainLoop object by one.
3194 * Return value: @loop
3197 g_main_loop_ref (GMainLoop *loop)
3199 g_return_val_if_fail (loop != NULL, NULL);
3200 g_return_val_if_fail (g_atomic_int_get (&loop->ref_count) > 0, NULL);
3202 g_atomic_int_inc (&loop->ref_count);
3208 * g_main_loop_unref:
3209 * @loop: a #GMainLoop
3211 * Decreases the reference count on a #GMainLoop object by one. If
3212 * the result is zero, free the loop and free all associated memory.
3215 g_main_loop_unref (GMainLoop *loop)
3217 g_return_if_fail (loop != NULL);
3218 g_return_if_fail (g_atomic_int_get (&loop->ref_count) > 0);
3220 if (!g_atomic_int_dec_and_test (&loop->ref_count))
3223 g_main_context_unref (loop->context);
3229 * @loop: a #GMainLoop
3231 * Runs a main loop until g_main_loop_quit() is called on the loop.
3232 * If this is called for the thread of the loop's #GMainContext,
3233 * it will process events from the loop, otherwise it will
3237 g_main_loop_run (GMainLoop *loop)
3239 GThread *self = G_THREAD_SELF;
3241 g_return_if_fail (loop != NULL);
3242 g_return_if_fail (g_atomic_int_get (&loop->ref_count) > 0);
3244 #ifdef G_THREADS_ENABLED
3245 if (!g_main_context_acquire (loop->context))
3247 gboolean got_ownership = FALSE;
3249 /* Another thread owns this context */
3250 if (!g_thread_supported ())
3252 g_warning ("g_main_loop_run() was called from second thread but "
3253 "g_thread_init() was never called.");
3257 LOCK_CONTEXT (loop->context);
3259 g_atomic_int_inc (&loop->ref_count);
3261 if (!loop->is_running)
3262 loop->is_running = TRUE;
3264 if (!loop->context->cond)
3265 loop->context->cond = g_cond_new ();
3267 while (loop->is_running && !got_ownership)
3268 got_ownership = g_main_context_wait (loop->context,
3269 loop->context->cond,
3270 g_static_mutex_get_mutex (&loop->context->mutex));
3272 if (!loop->is_running)
3274 UNLOCK_CONTEXT (loop->context);
3276 g_main_context_release (loop->context);
3277 g_main_loop_unref (loop);
3281 g_assert (got_ownership);
3284 LOCK_CONTEXT (loop->context);
3285 #endif /* G_THREADS_ENABLED */
3287 if (loop->context->in_check_or_prepare)
3289 g_warning ("g_main_loop_run(): called recursively from within a source's "
3290 "check() or prepare() member, iteration not possible.");
3294 g_atomic_int_inc (&loop->ref_count);
3295 loop->is_running = TRUE;
3296 while (loop->is_running)
3297 g_main_context_iterate (loop->context, TRUE, TRUE, self);
3299 UNLOCK_CONTEXT (loop->context);
3301 #ifdef G_THREADS_ENABLED
3302 g_main_context_release (loop->context);
3303 #endif /* G_THREADS_ENABLED */
3305 g_main_loop_unref (loop);
3310 * @loop: a #GMainLoop
3312 * Stops a #GMainLoop from running. Any calls to g_main_loop_run()
3313 * for the loop will return.
3315 * Note that sources that have already been dispatched when
3316 * g_main_loop_quit() is called will still be executed.
3319 g_main_loop_quit (GMainLoop *loop)
3321 g_return_if_fail (loop != NULL);
3322 g_return_if_fail (g_atomic_int_get (&loop->ref_count) > 0);
3324 LOCK_CONTEXT (loop->context);
3325 loop->is_running = FALSE;
3326 g_main_context_wakeup_unlocked (loop->context);
3328 #ifdef G_THREADS_ENABLED
3329 if (loop->context->cond)
3330 g_cond_broadcast (loop->context->cond);
3331 #endif /* G_THREADS_ENABLED */
3333 UNLOCK_CONTEXT (loop->context);
3337 * g_main_loop_is_running:
3338 * @loop: a #GMainLoop.
3340 * Checks to see if the main loop is currently being run via g_main_loop_run().
3342 * Return value: %TRUE if the mainloop is currently being run.
3345 g_main_loop_is_running (GMainLoop *loop)
3347 g_return_val_if_fail (loop != NULL, FALSE);
3348 g_return_val_if_fail (g_atomic_int_get (&loop->ref_count) > 0, FALSE);
3350 return loop->is_running;
3354 * g_main_loop_get_context:
3355 * @loop: a #GMainLoop.
3357 * Returns the #GMainContext of @loop.
3359 * Return value: (transfer none): the #GMainContext of @loop
3362 g_main_loop_get_context (GMainLoop *loop)
3364 g_return_val_if_fail (loop != NULL, NULL);
3365 g_return_val_if_fail (g_atomic_int_get (&loop->ref_count) > 0, NULL);
3367 return loop->context;
3370 /* HOLDS: context's lock */
3372 g_main_context_poll (GMainContext *context,
3378 #ifdef G_MAIN_POLL_DEBUG
3384 GPollFunc poll_func;
3386 if (n_fds || timeout != 0)
3388 #ifdef G_MAIN_POLL_DEBUG
3389 if (_g_main_poll_debug)
3391 g_print ("polling context=%p n=%d timeout=%d\n",
3392 context, n_fds, timeout);
3393 poll_timer = g_timer_new ();
3397 LOCK_CONTEXT (context);
3399 poll_func = context->poll_func;
3401 UNLOCK_CONTEXT (context);
3402 if ((*poll_func) (fds, n_fds, timeout) < 0 && errno != EINTR)
3405 g_warning ("poll(2) failed due to: %s.",
3406 g_strerror (errno));
3408 /* If g_poll () returns -1, it has already called g_warning() */
3412 #ifdef G_MAIN_POLL_DEBUG
3413 if (_g_main_poll_debug)
3415 LOCK_CONTEXT (context);
3417 g_print ("g_main_poll(%d) timeout: %d - elapsed %12.10f seconds",
3420 g_timer_elapsed (poll_timer, NULL));
3421 g_timer_destroy (poll_timer);
3422 pollrec = context->poll_records;
3424 while (pollrec != NULL)
3429 if (fds[i].fd == pollrec->fd->fd &&
3430 pollrec->fd->events &&
3433 g_print (" [" G_POLLFD_FORMAT " :", fds[i].fd);
3434 if (fds[i].revents & G_IO_IN)
3436 if (fds[i].revents & G_IO_OUT)
3438 if (fds[i].revents & G_IO_PRI)
3440 if (fds[i].revents & G_IO_ERR)
3442 if (fds[i].revents & G_IO_HUP)
3444 if (fds[i].revents & G_IO_NVAL)
3450 pollrec = pollrec->next;
3454 UNLOCK_CONTEXT (context);
3457 } /* if (n_fds || timeout != 0) */
3461 * g_main_context_add_poll:
3462 * @context: a #GMainContext (or %NULL for the default context)
3463 * @fd: a #GPollFD structure holding information about a file
3464 * descriptor to watch.
3465 * @priority: the priority for this file descriptor which should be
3466 * the same as the priority used for g_source_attach() to ensure that the
3467 * file descriptor is polled whenever the results may be needed.
3469 * Adds a file descriptor to the set of file descriptors polled for
3470 * this context. This will very seldom be used directly. Instead
3471 * a typical event source will use g_source_add_poll() instead.
3474 g_main_context_add_poll (GMainContext *context,
3479 context = g_main_context_default ();
3481 g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
3482 g_return_if_fail (fd);
3484 LOCK_CONTEXT (context);
3485 g_main_context_add_poll_unlocked (context, priority, fd);
3486 UNLOCK_CONTEXT (context);
3489 /* HOLDS: main_loop_lock */
3491 g_main_context_add_poll_unlocked (GMainContext *context,
3495 GPollRec *prevrec, *nextrec;
3496 GPollRec *newrec = g_slice_new (GPollRec);
3498 /* This file descriptor may be checked before we ever poll */
3501 newrec->priority = priority;
3503 prevrec = context->poll_records_tail;
3505 while (prevrec && priority < prevrec->priority)
3508 prevrec = prevrec->prev;
3512 prevrec->next = newrec;
3514 context->poll_records = newrec;
3516 newrec->prev = prevrec;
3517 newrec->next = nextrec;
3520 nextrec->prev = newrec;
3522 context->poll_records_tail = newrec;
3524 context->n_poll_records++;
3526 #ifdef G_THREADS_ENABLED
3527 context->poll_changed = TRUE;
3529 /* Now wake up the main loop if it is waiting in the poll() */
3530 g_main_context_wakeup_unlocked (context);
3535 * g_main_context_remove_poll:
3536 * @context:a #GMainContext
3537 * @fd: a #GPollFD descriptor previously added with g_main_context_add_poll()
3539 * Removes file descriptor from the set of file descriptors to be
3540 * polled for a particular context.
3543 g_main_context_remove_poll (GMainContext *context,
3547 context = g_main_context_default ();
3549 g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
3550 g_return_if_fail (fd);
3552 LOCK_CONTEXT (context);
3553 g_main_context_remove_poll_unlocked (context, fd);
3554 UNLOCK_CONTEXT (context);
3558 g_main_context_remove_poll_unlocked (GMainContext *context,
3561 GPollRec *pollrec, *prevrec, *nextrec;
3564 pollrec = context->poll_records;
3568 nextrec = pollrec->next;
3569 if (pollrec->fd == fd)
3571 if (prevrec != NULL)
3572 prevrec->next = nextrec;
3574 context->poll_records = nextrec;
3576 if (nextrec != NULL)
3577 nextrec->prev = prevrec;
3579 context->poll_records_tail = prevrec;
3581 g_slice_free (GPollRec, pollrec);
3583 context->n_poll_records--;
3590 #ifdef G_THREADS_ENABLED
3591 context->poll_changed = TRUE;
3593 /* Now wake up the main loop if it is waiting in the poll() */
3594 g_main_context_wakeup_unlocked (context);
3599 * g_source_get_current_time:
3600 * @source: a #GSource
3601 * @timeval: #GTimeVal structure in which to store current time.
3603 * Gets the "current time" to be used when checking
3604 * this source. The advantage of calling this function over
3605 * calling g_get_current_time() directly is that when
3606 * checking multiple sources, GLib can cache a single value
3607 * instead of having to repeatedly get the system time.
3609 * Deprecated: 2.28: use g_source_get_time() instead
3612 g_source_get_current_time (GSource *source,
3615 GMainContext *context;
3617 g_return_if_fail (source->context != NULL);
3619 context = source->context;
3621 LOCK_CONTEXT (context);
3623 if (!context->real_time_is_fresh)
3625 context->real_time = g_get_real_time ();
3626 context->real_time_is_fresh = TRUE;
3629 timeval->tv_sec = context->real_time / 1000000;
3630 timeval->tv_usec = context->real_time % 1000000;
3632 UNLOCK_CONTEXT (context);
3636 * g_source_get_time:
3637 * @source: a #GSource
3639 * Gets the time to be used when checking this source. The advantage of
3640 * calling this function over calling g_get_monotonic_time() directly is
3641 * that when checking multiple sources, GLib can cache a single value
3642 * instead of having to repeatedly get the system monotonic time.
3644 * The time here is the system monotonic time, if available, or some
3645 * other reasonable alternative otherwise. See g_get_monotonic_time().
3647 * Returns: the monotonic time in microseconds
3652 g_source_get_time (GSource *source)
3654 GMainContext *context;
3657 g_return_val_if_fail (source->context != NULL, 0);
3659 context = source->context;
3661 LOCK_CONTEXT (context);
3663 if (!context->time_is_fresh)
3665 context->time = g_get_monotonic_time ();
3666 context->time_is_fresh = TRUE;
3669 result = context->time;
3671 UNLOCK_CONTEXT (context);
3677 * g_main_context_set_poll_func:
3678 * @context: a #GMainContext
3679 * @func: the function to call to poll all file descriptors
3681 * Sets the function to use to handle polling of file descriptors. It
3682 * will be used instead of the poll() system call
3683 * (or GLib's replacement function, which is used where
3684 * poll() isn't available).
3686 * This function could possibly be used to integrate the GLib event
3687 * loop with an external event loop.
3690 g_main_context_set_poll_func (GMainContext *context,
3694 context = g_main_context_default ();
3696 g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
3698 LOCK_CONTEXT (context);
3701 context->poll_func = func;
3703 context->poll_func = g_poll;
3705 UNLOCK_CONTEXT (context);
3709 * g_main_context_get_poll_func:
3710 * @context: a #GMainContext
3712 * Gets the poll function set by g_main_context_set_poll_func().
3714 * Return value: the poll function
3717 g_main_context_get_poll_func (GMainContext *context)
3722 context = g_main_context_default ();
3724 g_return_val_if_fail (g_atomic_int_get (&context->ref_count) > 0, NULL);
3726 LOCK_CONTEXT (context);
3727 result = context->poll_func;
3728 UNLOCK_CONTEXT (context);
3734 _g_main_wake_up_all_contexts (void)
3738 /* We were woken up. Wake up all other contexts in all other threads */
3739 G_LOCK (main_context_list);
3740 for (list = main_context_list; list; list = list->next)
3742 GMainContext *context = list->data;
3744 LOCK_CONTEXT (context);
3745 g_main_context_wakeup_unlocked (context);
3746 UNLOCK_CONTEXT (context);
3748 G_UNLOCK (main_context_list);
3752 /* HOLDS: context's lock */
3753 /* Wake the main loop up from a poll() */
3755 g_main_context_wakeup_unlocked (GMainContext *context)
3757 #ifdef G_THREADS_ENABLED
3758 if (g_thread_supported() && context->poll_waiting)
3760 context->poll_waiting = FALSE;
3761 g_wakeup_signal (context->wakeup);
3767 * g_main_context_wakeup:
3768 * @context: a #GMainContext
3770 * If @context is currently waiting in a poll(), interrupt
3771 * the poll(), and continue the iteration process.
3774 g_main_context_wakeup (GMainContext *context)
3777 context = g_main_context_default ();
3779 g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
3781 LOCK_CONTEXT (context);
3782 g_main_context_wakeup_unlocked (context);
3783 UNLOCK_CONTEXT (context);
3787 * g_main_context_is_owner:
3788 * @context: a #GMainContext
3790 * Determines whether this thread holds the (recursive)
3791 * ownership of this #GMainContext. This is useful to
3792 * know before waiting on another thread that may be
3793 * blocking to get ownership of @context.
3795 * Returns: %TRUE if current thread is owner of @context.
3800 g_main_context_is_owner (GMainContext *context)
3805 context = g_main_context_default ();
3807 #ifdef G_THREADS_ENABLED
3808 LOCK_CONTEXT (context);
3809 is_owner = context->owner == G_THREAD_SELF;
3810 UNLOCK_CONTEXT (context);
3821 g_timeout_set_expiration (GTimeoutSource *timeout_source,
3822 gint64 current_time)
3824 timeout_source->expiration = current_time +
3825 (guint64) timeout_source->interval * 1000;
3827 if (timeout_source->seconds)
3830 static gint timer_perturb = -1;
3832 if (timer_perturb == -1)
3835 * we want a per machine/session unique 'random' value; try the dbus
3836 * address first, that has a UUID in it. If there is no dbus, use the
3837 * hostname for hashing.
3839 const char *session_bus_address = g_getenv ("DBUS_SESSION_BUS_ADDRESS");
3840 if (!session_bus_address)
3841 session_bus_address = g_getenv ("HOSTNAME");
3842 if (session_bus_address)
3843 timer_perturb = ABS ((gint) g_str_hash (session_bus_address)) % 1000000;
3848 /* We want the microseconds part of the timeout to land on the
3849 * 'timer_perturb' mark, but we need to make sure we don't try to
3850 * set the timeout in the past. We do this by ensuring that we
3851 * always only *increase* the expiration time by adding a full
3852 * second in the case that the microsecond portion decreases.
3854 timeout_source->expiration -= timer_perturb;
3856 remainder = timeout_source->expiration % 1000000;
3857 if (remainder >= 1000000/4)
3858 timeout_source->expiration += 1000000;
3860 timeout_source->expiration -= remainder;
3861 timeout_source->expiration += timer_perturb;
3866 g_timeout_prepare (GSource *source,
3869 GTimeoutSource *timeout_source = (GTimeoutSource *) source;
3870 gint64 now = g_source_get_time (source);
3872 if (now < timeout_source->expiration)
3874 /* Round up to ensure that we don't try again too early */
3875 *timeout = (timeout_source->expiration - now + 999) / 1000;
3884 g_timeout_check (GSource *source)
3886 GTimeoutSource *timeout_source = (GTimeoutSource *) source;
3887 gint64 now = g_source_get_time (source);
3889 return timeout_source->expiration <= now;
3893 g_timeout_dispatch (GSource *source,
3894 GSourceFunc callback,
3897 GTimeoutSource *timeout_source = (GTimeoutSource *)source;
3902 g_warning ("Timeout source dispatched without callback\n"
3903 "You must call g_source_set_callback().");
3907 again = callback (user_data);
3910 g_timeout_set_expiration (timeout_source, g_source_get_time (source));
3916 * g_timeout_source_new:
3917 * @interval: the timeout interval in milliseconds.
3919 * Creates a new timeout source.
3921 * The source will not initially be associated with any #GMainContext
3922 * and must be added to one with g_source_attach() before it will be
3925 * The interval given is in terms of monotonic time, not wall clock
3926 * time. See g_get_monotonic_time().
3928 * Return value: the newly-created timeout source
3931 g_timeout_source_new (guint interval)
3933 GSource *source = g_source_new (&g_timeout_funcs, sizeof (GTimeoutSource));
3934 GTimeoutSource *timeout_source = (GTimeoutSource *)source;
3936 timeout_source->interval = interval;
3937 g_timeout_set_expiration (timeout_source, g_get_monotonic_time ());
3943 * g_timeout_source_new_seconds:
3944 * @interval: the timeout interval in seconds
3946 * Creates a new timeout source.
3948 * The source will not initially be associated with any #GMainContext
3949 * and must be added to one with g_source_attach() before it will be
3952 * The scheduling granularity/accuracy of this timeout source will be
3955 * The interval given in terms of monotonic time, not wall clock time.
3956 * See g_get_monotonic_time().
3958 * Return value: the newly-created timeout source
3963 g_timeout_source_new_seconds (guint interval)
3965 GSource *source = g_source_new (&g_timeout_funcs, sizeof (GTimeoutSource));
3966 GTimeoutSource *timeout_source = (GTimeoutSource *)source;
3968 timeout_source->interval = 1000 * interval;
3969 timeout_source->seconds = TRUE;
3971 g_timeout_set_expiration (timeout_source, g_get_monotonic_time ());
3978 * g_timeout_add_full:
3979 * @priority: the priority of the timeout source. Typically this will be in
3980 * the range between #G_PRIORITY_DEFAULT and #G_PRIORITY_HIGH.
3981 * @interval: the time between calls to the function, in milliseconds
3982 * (1/1000ths of a second)
3983 * @function: function to call
3984 * @data: data to pass to @function
3985 * @notify: function to call when the timeout is removed, or %NULL
3987 * Sets a function to be called at regular intervals, with the given
3988 * priority. The function is called repeatedly until it returns
3989 * %FALSE, at which point the timeout is automatically destroyed and
3990 * the function will not be called again. The @notify function is
3991 * called when the timeout is destroyed. The first call to the
3992 * function will be at the end of the first @interval.
3994 * Note that timeout functions may be delayed, due to the processing of other
3995 * event sources. Thus they should not be relied on for precise timing.
3996 * After each call to the timeout function, the time of the next
3997 * timeout is recalculated based on the current time and the given interval
3998 * (it does not try to 'catch up' time lost in delays).
4000 * This internally creates a main loop source using g_timeout_source_new()
4001 * and attaches it to the main loop context using g_source_attach(). You can
4002 * do these steps manually if you need greater control.
4004 * The interval given in terms of monotonic time, not wall clock time.
4005 * See g_get_monotonic_time().
4007 * Return value: the ID (greater than 0) of the event source.
4008 * Rename to: g_timeout_add
4011 g_timeout_add_full (gint priority,
4013 GSourceFunc function,
4015 GDestroyNotify notify)
4020 g_return_val_if_fail (function != NULL, 0);
4022 source = g_timeout_source_new (interval);
4024 if (priority != G_PRIORITY_DEFAULT)
4025 g_source_set_priority (source, priority);
4027 g_source_set_callback (source, function, data, notify);
4028 id = g_source_attach (source, NULL);
4029 g_source_unref (source);
4036 * @interval: the time between calls to the function, in milliseconds
4037 * (1/1000ths of a second)
4038 * @function: function to call
4039 * @data: data to pass to @function
4041 * Sets a function to be called at regular intervals, with the default
4042 * priority, #G_PRIORITY_DEFAULT. The function is called repeatedly
4043 * until it returns %FALSE, at which point the timeout is automatically
4044 * destroyed and the function will not be called again. The first call
4045 * to the function will be at the end of the first @interval.
4047 * Note that timeout functions may be delayed, due to the processing of other
4048 * event sources. Thus they should not be relied on for precise timing.
4049 * After each call to the timeout function, the time of the next
4050 * timeout is recalculated based on the current time and the given interval
4051 * (it does not try to 'catch up' time lost in delays).
4053 * If you want to have a timer in the "seconds" range and do not care
4054 * about the exact time of the first call of the timer, use the
4055 * g_timeout_add_seconds() function; this function allows for more
4056 * optimizations and more efficient system power usage.
4058 * This internally creates a main loop source using g_timeout_source_new()
4059 * and attaches it to the main loop context using g_source_attach(). You can
4060 * do these steps manually if you need greater control.
4062 * The interval given is in terms of monotonic time, not wall clock
4063 * time. See g_get_monotonic_time().
4065 * Return value: the ID (greater than 0) of the event source.
4068 g_timeout_add (guint32 interval,
4069 GSourceFunc function,
4072 return g_timeout_add_full (G_PRIORITY_DEFAULT,
4073 interval, function, data, NULL);
4077 * g_timeout_add_seconds_full:
4078 * @priority: the priority of the timeout source. Typically this will be in
4079 * the range between #G_PRIORITY_DEFAULT and #G_PRIORITY_HIGH.
4080 * @interval: the time between calls to the function, in seconds
4081 * @function: function to call
4082 * @data: data to pass to @function
4083 * @notify: function to call when the timeout is removed, or %NULL
4085 * Sets a function to be called at regular intervals, with @priority.
4086 * The function is called repeatedly until it returns %FALSE, at which
4087 * point the timeout is automatically destroyed and the function will
4088 * not be called again.
4090 * Unlike g_timeout_add(), this function operates at whole second granularity.
4091 * The initial starting point of the timer is determined by the implementation
4092 * and the implementation is expected to group multiple timers together so that
4093 * they fire all at the same time.
4094 * To allow this grouping, the @interval to the first timer is rounded
4095 * and can deviate up to one second from the specified interval.
4096 * Subsequent timer iterations will generally run at the specified interval.
4098 * Note that timeout functions may be delayed, due to the processing of other
4099 * event sources. Thus they should not be relied on for precise timing.
4100 * After each call to the timeout function, the time of the next
4101 * timeout is recalculated based on the current time and the given @interval
4103 * If you want timing more precise than whole seconds, use g_timeout_add()
4106 * The grouping of timers to fire at the same time results in a more power
4107 * and CPU efficient behavior so if your timer is in multiples of seconds
4108 * and you don't require the first timer exactly one second from now, the
4109 * use of g_timeout_add_seconds() is preferred over g_timeout_add().
4111 * This internally creates a main loop source using
4112 * g_timeout_source_new_seconds() and attaches it to the main loop context
4113 * using g_source_attach(). You can do these steps manually if you need
4116 * The interval given is in terms of monotonic time, not wall clock
4117 * time. See g_get_monotonic_time().
4119 * Return value: the ID (greater than 0) of the event source.
4121 * Rename to: g_timeout_add_seconds
4125 g_timeout_add_seconds_full (gint priority,
4127 GSourceFunc function,
4129 GDestroyNotify notify)
4134 g_return_val_if_fail (function != NULL, 0);
4136 source = g_timeout_source_new_seconds (interval);
4138 if (priority != G_PRIORITY_DEFAULT)
4139 g_source_set_priority (source, priority);
4141 g_source_set_callback (source, function, data, notify);
4142 id = g_source_attach (source, NULL);
4143 g_source_unref (source);
4149 * g_timeout_add_seconds:
4150 * @interval: the time between calls to the function, in seconds
4151 * @function: function to call
4152 * @data: data to pass to @function
4154 * Sets a function to be called at regular intervals with the default
4155 * priority, #G_PRIORITY_DEFAULT. The function is called repeatedly until
4156 * it returns %FALSE, at which point the timeout is automatically destroyed
4157 * and the function will not be called again.
4159 * This internally creates a main loop source using
4160 * g_timeout_source_new_seconds() and attaches it to the main loop context
4161 * using g_source_attach(). You can do these steps manually if you need
4162 * greater control. Also see g_timeout_add_seconds_full().
4164 * Note that the first call of the timer may not be precise for timeouts
4165 * of one second. If you need finer precision and have such a timeout,
4166 * you may want to use g_timeout_add() instead.
4168 * The interval given is in terms of monotonic time, not wall clock
4169 * time. See g_get_monotonic_time().
4171 * Return value: the ID (greater than 0) of the event source.
4176 g_timeout_add_seconds (guint interval,
4177 GSourceFunc function,
4180 g_return_val_if_fail (function != NULL, 0);
4182 return g_timeout_add_seconds_full (G_PRIORITY_DEFAULT, interval, function, data, NULL);
4185 /* Child watch functions */
4190 g_child_watch_prepare (GSource *source,
4199 g_child_watch_check (GSource *source)
4201 GChildWatchSource *child_watch_source;
4202 gboolean child_exited;
4204 child_watch_source = (GChildWatchSource *) source;
4206 child_exited = child_watch_source->poll.revents & G_IO_IN;
4213 * Note: We do _not_ check for the special value of STILL_ACTIVE
4214 * since we know that the process has exited and doing so runs into
4215 * problems if the child process "happens to return STILL_ACTIVE(259)"
4216 * as Microsoft's Platform SDK puts it.
4218 if (!GetExitCodeProcess (child_watch_source->pid, &child_status))
4220 gchar *emsg = g_win32_error_message (GetLastError ());
4221 g_warning (G_STRLOC ": GetExitCodeProcess() failed: %s", emsg);
4224 child_watch_source->child_status = -1;
4227 child_watch_source->child_status = child_status;
4230 return child_exited;
4233 #else /* G_OS_WIN32 */
4236 check_for_child_exited (GSource *source)
4238 GChildWatchSource *child_watch_source;
4241 /* protect against another SIGCHLD in the middle of this call */
4242 count = child_watch_count;
4244 child_watch_source = (GChildWatchSource *) source;
4246 if (child_watch_source->child_exited)
4249 if (child_watch_source->count < count)
4253 if (waitpid (child_watch_source->pid, &child_status, WNOHANG) > 0)
4255 child_watch_source->child_status = child_status;
4256 child_watch_source->child_exited = TRUE;
4258 child_watch_source->count = count;
4261 return child_watch_source->child_exited;
4265 g_child_watch_prepare (GSource *source,
4270 return check_for_child_exited (source);
4274 g_child_watch_check (GSource *source)
4276 return check_for_child_exited (source);
4280 check_for_signal_delivery (GSource *source)
4282 GUnixSignalWatchSource *unix_signal_source = (GUnixSignalWatchSource*) source;
4285 G_LOCK (unix_signal_lock);
4286 if (unix_signal_init_state == UNIX_SIGNAL_INITIALIZED_SINGLE)
4288 switch (unix_signal_source->signum)
4291 delivered = unix_signal_state.sighup_delivered;
4294 delivered = unix_signal_state.sigint_delivered;
4297 delivered = unix_signal_state.sigterm_delivered;
4300 g_assert_not_reached ();
4307 g_assert (unix_signal_init_state == UNIX_SIGNAL_INITIALIZED_THREADED);
4308 delivered = unix_signal_source->pending;
4310 G_UNLOCK (unix_signal_lock);
4316 g_unix_signal_watch_prepare (GSource *source,
4321 return check_for_signal_delivery (source);
4325 g_unix_signal_watch_check (GSource *source)
4327 return check_for_signal_delivery (source);
4331 g_unix_signal_watch_dispatch (GSource *source,
4332 GSourceFunc callback,
4335 GUnixSignalWatchSource *unix_signal_source;
4337 unix_signal_source = (GUnixSignalWatchSource *) source;
4341 g_warning ("Unix signal source dispatched without callback\n"
4342 "You must call g_source_set_callback().");
4346 (callback) (user_data);
4348 G_LOCK (unix_signal_lock);
4349 if (unix_signal_init_state == UNIX_SIGNAL_INITIALIZED_SINGLE)
4351 switch (unix_signal_source->signum)
4354 unix_signal_state.sighup_delivered = FALSE;
4357 unix_signal_state.sigint_delivered = FALSE;
4360 unix_signal_state.sigterm_delivered = FALSE;
4366 g_assert (unix_signal_init_state == UNIX_SIGNAL_INITIALIZED_THREADED);
4367 unix_signal_source->pending = FALSE;
4369 G_UNLOCK (unix_signal_lock);
4375 ensure_unix_signal_handler_installed_unlocked (int signum)
4377 struct sigaction action;
4378 GError *error = NULL;
4380 if (unix_signal_init_state == UNIX_SIGNAL_UNINITIALIZED)
4382 sigemptyset (&unix_signal_mask);
4385 if (unix_signal_init_state == UNIX_SIGNAL_UNINITIALIZED
4386 || unix_signal_init_state == UNIX_SIGNAL_INITIALIZED_SINGLE)
4388 if (!g_thread_supported ())
4390 /* There is nothing to do for initializing in the non-threaded
4393 if (unix_signal_init_state == UNIX_SIGNAL_UNINITIALIZED)
4394 unix_signal_init_state = UNIX_SIGNAL_INITIALIZED_SINGLE;
4398 if (!g_unix_open_pipe (unix_signal_wake_up_pipe, FD_CLOEXEC, &error))
4399 g_error ("Cannot create UNIX signal wake up pipe: %s\n", error->message);
4400 g_unix_set_fd_nonblocking (unix_signal_wake_up_pipe[1], TRUE, NULL);
4402 /* We create a helper thread that polls on the wakeup pipe indefinitely */
4403 if (g_thread_create (unix_signal_helper_thread, NULL, FALSE, &error) == NULL)
4404 g_error ("Cannot create a thread to monitor UNIX signals: %s\n", error->message);
4406 unix_signal_init_state = UNIX_SIGNAL_INITIALIZED_THREADED;
4410 if (sigismember (&unix_signal_mask, signum))
4413 sigaddset (&unix_signal_mask, signum);
4415 action.sa_handler = g_unix_signal_handler;
4416 sigemptyset (&action.sa_mask);
4417 action.sa_flags = SA_RESTART | SA_NOCLDSTOP;
4418 sigaction (signum, &action, NULL);
4422 _g_main_create_unix_signal_watch (int signum)
4425 GUnixSignalWatchSource *unix_signal_source;
4427 source = g_source_new (&g_unix_signal_funcs, sizeof (GUnixSignalWatchSource));
4428 unix_signal_source = (GUnixSignalWatchSource *) source;
4430 unix_signal_source->signum = signum;
4431 unix_signal_source->pending = FALSE;
4433 G_LOCK (unix_signal_lock);
4434 ensure_unix_signal_handler_installed_unlocked (signum);
4435 unix_signal_watches = g_slist_prepend (unix_signal_watches, unix_signal_source);
4436 G_UNLOCK (unix_signal_lock);
4442 g_unix_signal_watch_finalize (GSource *source)
4444 G_LOCK (unix_signal_lock);
4445 unix_signal_watches = g_slist_remove (unix_signal_watches, source);
4446 G_UNLOCK (unix_signal_lock);
4449 #endif /* G_OS_WIN32 */
4452 g_child_watch_dispatch (GSource *source,
4453 GSourceFunc callback,
4456 GChildWatchSource *child_watch_source;
4457 GChildWatchFunc child_watch_callback = (GChildWatchFunc) callback;
4459 child_watch_source = (GChildWatchSource *) source;
4463 g_warning ("Child watch source dispatched without callback\n"
4464 "You must call g_source_set_callback().");
4468 (child_watch_callback) (child_watch_source->pid, child_watch_source->child_status, user_data);
4470 /* We never keep a child watch source around as the child is gone */
4477 g_unix_signal_handler (int signum)
4479 if (signum == SIGCHLD)
4480 child_watch_count ++;
4482 if (unix_signal_init_state == UNIX_SIGNAL_INITIALIZED_THREADED)
4488 buf[0] = _UNIX_SIGNAL_PIPE_SIGCHLD_CHAR;
4491 buf[0] = _UNIX_SIGNAL_PIPE_SIGHUP_CHAR;
4494 buf[0] = _UNIX_SIGNAL_PIPE_SIGINT_CHAR;
4497 buf[0] = _UNIX_SIGNAL_PIPE_SIGTERM_CHAR;
4500 /* Shouldn't happen */
4503 write (unix_signal_wake_up_pipe[1], buf, 1);
4507 /* We count on the signal interrupting the poll in the same thread. */
4511 /* Nothing to do - the handler will call waitpid() */
4514 unix_signal_state.sighup_delivered = TRUE;
4517 unix_signal_state.sigint_delivered = TRUE;
4520 unix_signal_state.sigterm_delivered = TRUE;
4523 g_assert_not_reached ();
4530 deliver_unix_signal (int signum)
4533 g_assert (signum == SIGHUP || signum == SIGINT || signum == SIGTERM);
4535 G_LOCK (unix_signal_lock);
4536 for (iter = unix_signal_watches; iter; iter = iter->next)
4538 GUnixSignalWatchSource *source = iter->data;
4540 if (source->signum != signum)
4543 source->pending = TRUE;
4545 G_UNLOCK (unix_signal_lock);
4549 * This thread is created whenever anything in GLib needs
4550 * to deal with UNIX signals; at present, just SIGCHLD
4551 * from g_child_watch_source_new().
4553 * Note: We could eventually make this thread a more public interface
4554 * and allow e.g. GDBus to use it instead of its own worker thread.
4557 unix_signal_helper_thread (gpointer data)
4562 ssize_t i, bytes_read;
4563 gboolean sigterm_received = FALSE;
4564 gboolean sigint_received = FALSE;
4565 gboolean sighup_received = FALSE;
4567 bytes_read = read (unix_signal_wake_up_pipe[0], b, sizeof (b));
4570 g_warning ("Failed to read from child watch wake up pipe: %s",
4572 /* Not much we can do here sanely; just wait a second and hope
4575 g_usleep (G_USEC_PER_SEC);
4578 for (i = 0; i < bytes_read; i++)
4582 case _UNIX_SIGNAL_PIPE_SIGCHLD_CHAR:
4583 /* The child watch source will call waitpid() in its
4584 * prepare() and check() methods; however, we don't
4585 * know which pid exited, so we need to wake up
4586 * all contexts. Note: actually we could get the pid
4587 * from the "siginfo_t" via the handler, but to pass
4588 * that info down the pipe would require a more structured
4589 * data stream (as opposed to a single byte).
4592 case _UNIX_SIGNAL_PIPE_SIGTERM_CHAR:
4593 sigterm_received = TRUE;
4595 case _UNIX_SIGNAL_PIPE_SIGHUP_CHAR:
4596 sighup_received = TRUE;
4598 case _UNIX_SIGNAL_PIPE_SIGINT_CHAR:
4599 sigint_received = TRUE;
4602 g_warning ("Invalid char '%c' read from child watch pipe", b[i]);
4606 if (sigterm_received)
4607 deliver_unix_signal (SIGTERM);
4608 if (sigint_received)
4609 deliver_unix_signal (SIGINT);
4610 if (sighup_received)
4611 deliver_unix_signal (SIGHUP);
4612 _g_main_wake_up_all_contexts ();
4617 g_child_watch_source_init (void)
4619 G_LOCK (unix_signal_lock);
4620 ensure_unix_signal_handler_installed_unlocked (SIGCHLD);
4621 G_UNLOCK (unix_signal_lock);
4624 #endif /* !G_OS_WIN32 */
4627 * g_child_watch_source_new:
4628 * @pid: process to watch. On POSIX the pid of a child process. On
4629 * Windows a handle for a process (which doesn't have to be a child).
4631 * Creates a new child_watch source.
4633 * The source will not initially be associated with any #GMainContext
4634 * and must be added to one with g_source_attach() before it will be
4637 * Note that child watch sources can only be used in conjunction with
4638 * <literal>g_spawn...</literal> when the %G_SPAWN_DO_NOT_REAP_CHILD
4641 * Note that on platforms where #GPid must be explicitly closed
4642 * (see g_spawn_close_pid()) @pid must not be closed while the
4643 * source is still active. Typically, you will want to call
4644 * g_spawn_close_pid() in the callback function for the source.
4646 * Note further that using g_child_watch_source_new() is not
4647 * compatible with calling <literal>waitpid(-1)</literal> in
4648 * the application. Calling waitpid() for individual pids will
4651 * Return value: the newly-created child watch source
4656 g_child_watch_source_new (GPid pid)
4658 GSource *source = g_source_new (&g_child_watch_funcs, sizeof (GChildWatchSource));
4659 GChildWatchSource *child_watch_source = (GChildWatchSource *)source;
4662 child_watch_source->poll.fd = (gintptr) pid;
4663 child_watch_source->poll.events = G_IO_IN;
4665 g_source_add_poll (source, &child_watch_source->poll);
4666 #else /* G_OS_WIN32 */
4667 g_child_watch_source_init ();
4668 #endif /* G_OS_WIN32 */
4670 child_watch_source->pid = pid;
4676 * g_child_watch_add_full:
4677 * @priority: the priority of the idle source. Typically this will be in the
4678 * range between #G_PRIORITY_DEFAULT_IDLE and #G_PRIORITY_HIGH_IDLE.
4679 * @pid: process to watch. On POSIX the pid of a child process. On
4680 * Windows a handle for a process (which doesn't have to be a child).
4681 * @function: function to call
4682 * @data: data to pass to @function
4683 * @notify: function to call when the idle is removed, or %NULL
4685 * Sets a function to be called when the child indicated by @pid
4686 * exits, at the priority @priority.
4688 * If you obtain @pid from g_spawn_async() or g_spawn_async_with_pipes()
4689 * you will need to pass #G_SPAWN_DO_NOT_REAP_CHILD as flag to
4690 * the spawn function for the child watching to work.
4692 * Note that on platforms where #GPid must be explicitly closed
4693 * (see g_spawn_close_pid()) @pid must not be closed while the
4694 * source is still active. Typically, you will want to call
4695 * g_spawn_close_pid() in the callback function for the source.
4697 * GLib supports only a single callback per process id.
4699 * This internally creates a main loop source using
4700 * g_child_watch_source_new() and attaches it to the main loop context
4701 * using g_source_attach(). You can do these steps manually if you
4702 * need greater control.
4704 * Return value: the ID (greater than 0) of the event source.
4706 * Rename to: g_child_watch_add
4710 g_child_watch_add_full (gint priority,
4712 GChildWatchFunc function,
4714 GDestroyNotify notify)
4719 g_return_val_if_fail (function != NULL, 0);
4721 source = g_child_watch_source_new (pid);
4723 if (priority != G_PRIORITY_DEFAULT)
4724 g_source_set_priority (source, priority);
4726 g_source_set_callback (source, (GSourceFunc) function, data, notify);
4727 id = g_source_attach (source, NULL);
4728 g_source_unref (source);
4734 * g_child_watch_add:
4735 * @pid: process id to watch. On POSIX the pid of a child process. On
4736 * Windows a handle for a process (which doesn't have to be a child).
4737 * @function: function to call
4738 * @data: data to pass to @function
4740 * Sets a function to be called when the child indicated by @pid
4741 * exits, at a default priority, #G_PRIORITY_DEFAULT.
4743 * If you obtain @pid from g_spawn_async() or g_spawn_async_with_pipes()
4744 * you will need to pass #G_SPAWN_DO_NOT_REAP_CHILD as flag to
4745 * the spawn function for the child watching to work.
4747 * Note that on platforms where #GPid must be explicitly closed
4748 * (see g_spawn_close_pid()) @pid must not be closed while the
4749 * source is still active. Typically, you will want to call
4750 * g_spawn_close_pid() in the callback function for the source.
4752 * GLib supports only a single callback per process id.
4754 * This internally creates a main loop source using
4755 * g_child_watch_source_new() and attaches it to the main loop context
4756 * using g_source_attach(). You can do these steps manually if you
4757 * need greater control.
4759 * Return value: the ID (greater than 0) of the event source.
4764 g_child_watch_add (GPid pid,
4765 GChildWatchFunc function,
4768 return g_child_watch_add_full (G_PRIORITY_DEFAULT, pid, function, data, NULL);
4772 /* Idle functions */
4775 g_idle_prepare (GSource *source,
4784 g_idle_check (GSource *source)
4790 g_idle_dispatch (GSource *source,
4791 GSourceFunc callback,
4796 g_warning ("Idle source dispatched without callback\n"
4797 "You must call g_source_set_callback().");
4801 return callback (user_data);
4805 * g_idle_source_new:
4807 * Creates a new idle source.
4809 * The source will not initially be associated with any #GMainContext
4810 * and must be added to one with g_source_attach() before it will be
4811 * executed. Note that the default priority for idle sources is
4812 * %G_PRIORITY_DEFAULT_IDLE, as compared to other sources which
4813 * have a default priority of %G_PRIORITY_DEFAULT.
4815 * Return value: the newly-created idle source
4818 g_idle_source_new (void)
4822 source = g_source_new (&g_idle_funcs, sizeof (GSource));
4823 g_source_set_priority (source, G_PRIORITY_DEFAULT_IDLE);
4830 * @priority: the priority of the idle source. Typically this will be in the
4831 * range between #G_PRIORITY_DEFAULT_IDLE and #G_PRIORITY_HIGH_IDLE.
4832 * @function: function to call
4833 * @data: data to pass to @function
4834 * @notify: function to call when the idle is removed, or %NULL
4836 * Adds a function to be called whenever there are no higher priority
4837 * events pending. If the function returns %FALSE it is automatically
4838 * removed from the list of event sources and will not be called again.
4840 * This internally creates a main loop source using g_idle_source_new()
4841 * and attaches it to the main loop context using g_source_attach().
4842 * You can do these steps manually if you need greater control.
4844 * Return value: the ID (greater than 0) of the event source.
4845 * Rename to: g_idle_add
4848 g_idle_add_full (gint priority,
4849 GSourceFunc function,
4851 GDestroyNotify notify)
4856 g_return_val_if_fail (function != NULL, 0);
4858 source = g_idle_source_new ();
4860 if (priority != G_PRIORITY_DEFAULT_IDLE)
4861 g_source_set_priority (source, priority);
4863 g_source_set_callback (source, function, data, notify);
4864 id = g_source_attach (source, NULL);
4865 g_source_unref (source);
4872 * @function: function to call
4873 * @data: data to pass to @function.
4875 * Adds a function to be called whenever there are no higher priority
4876 * events pending to the default main loop. The function is given the
4877 * default idle priority, #G_PRIORITY_DEFAULT_IDLE. If the function
4878 * returns %FALSE it is automatically removed from the list of event
4879 * sources and will not be called again.
4881 * This internally creates a main loop source using g_idle_source_new()
4882 * and attaches it to the main loop context using g_source_attach().
4883 * You can do these steps manually if you need greater control.
4885 * Return value: the ID (greater than 0) of the event source.
4888 g_idle_add (GSourceFunc function,
4891 return g_idle_add_full (G_PRIORITY_DEFAULT_IDLE, function, data, NULL);
4895 * g_idle_remove_by_data:
4896 * @data: the data for the idle source's callback.
4898 * Removes the idle function with the given data.
4900 * Return value: %TRUE if an idle source was found and removed.
4903 g_idle_remove_by_data (gpointer data)
4905 return g_source_remove_by_funcs_user_data (&g_idle_funcs, data);
4909 * g_main_context_invoke:
4910 * @context: (allow-none): a #GMainContext, or %NULL
4911 * @function: function to call
4912 * @data: data to pass to @function
4914 * Invokes a function in such a way that @context is owned during the
4915 * invocation of @function.
4917 * If @context is %NULL then the global default main context — as
4918 * returned by g_main_context_default() — is used.
4920 * If @context is owned by the current thread, @function is called
4921 * directly. Otherwise, if @context is the thread-default main context
4922 * of the current thread and g_main_context_acquire() succeeds, then
4923 * @function is called and g_main_context_release() is called
4926 * In any other case, an idle source is created to call @function and
4927 * that source is attached to @context (presumably to be run in another
4928 * thread). The idle source is attached with #G_PRIORITY_DEFAULT
4929 * priority. If you want a different priority, use
4930 * g_main_context_invoke_full().
4932 * Note that, as with normal idle functions, @function should probably
4933 * return %FALSE. If it returns %TRUE, it will be continuously run in a
4934 * loop (and may prevent this call from returning).
4939 g_main_context_invoke (GMainContext *context,
4940 GSourceFunc function,
4943 g_main_context_invoke_full (context,
4945 function, data, NULL);
4949 * g_main_context_invoke_full:
4950 * @context: (allow-none): a #GMainContext, or %NULL
4951 * @priority: the priority at which to run @function
4952 * @function: function to call
4953 * @data: data to pass to @function
4954 * @notify: a function to call when @data is no longer in use, or %NULL.
4956 * Invokes a function in such a way that @context is owned during the
4957 * invocation of @function.
4959 * This function is the same as g_main_context_invoke() except that it
4960 * lets you specify the priority incase @function ends up being
4961 * scheduled as an idle and also lets you give a #GDestroyNotify for @data.
4963 * @notify should not assume that it is called from any particular
4964 * thread or with any particular context acquired.
4969 g_main_context_invoke_full (GMainContext *context,
4971 GSourceFunc function,
4973 GDestroyNotify notify)
4975 g_return_if_fail (function != NULL);
4978 context = g_main_context_default ();
4980 if (g_main_context_is_owner (context))
4982 while (function (data));
4989 GMainContext *thread_default;
4991 thread_default = g_main_context_get_thread_default ();
4993 if (!thread_default)
4994 thread_default = g_main_context_default ();
4996 if (thread_default == context && g_main_context_acquire (context))
4998 while (function (data));
5000 g_main_context_release (context);
5009 source = g_idle_source_new ();
5010 g_source_set_priority (source, priority);
5011 g_source_set_callback (source, function, data, notify);
5012 g_source_attach (source, context);
5013 g_source_unref (source);