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: 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: the thread-default #GMainContext, or %NULL if the
786 * 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: the #GMainContext with which the source is associated,
1089 * or %NULL if the context has not yet been added
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: 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: 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: 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 * Note that, on Windows, "limitations of the OS kernel" is a rather
2028 * substantial statement. Depending on the configuration of the system,
2029 * the wall clock time is updated as infrequently as 64 times a second
2030 * (which is approximately every 16ms).
2032 * Returns: the monotonic time, in microseconds
2037 g_get_monotonic_time (void)
2039 #ifdef HAVE_CLOCK_GETTIME
2040 /* librt clock_gettime() is our first choice */
2042 static int clockid = CLOCK_REALTIME;
2045 #ifdef HAVE_MONOTONIC_CLOCK
2046 /* We have to check if we actually have monotonic clock support.
2048 * There is no thread safety issue here since there is no harm if we
2052 static gboolean checked;
2054 if G_UNLIKELY (!checked)
2056 if (sysconf (_SC_MONOTONIC_CLOCK) >= 0)
2057 clockid = CLOCK_MONOTONIC;
2063 clock_gettime (clockid, &ts);
2065 /* In theory monotonic time can have any epoch.
2067 * glib presently assumes the following:
2069 * 1) The epoch comes some time after the birth of Jesus of Nazareth, but
2070 * not more than 10000 years later.
2072 * 2) The current time also falls sometime within this range.
2074 * These two reasonable assumptions leave us with a maximum deviation from
2075 * the epoch of 10000 years, or 315569520000000000 seconds.
2077 * If we restrict ourselves to this range then the number of microseconds
2078 * will always fit well inside the constraints of a int64 (by a factor of
2081 * If you actually hit the following assertion, probably you should file a
2082 * bug against your operating system for being excessively silly.
2084 g_assert (G_GINT64_CONSTANT (-315569520000000000) < ts.tv_sec &&
2085 ts.tv_sec < G_GINT64_CONSTANT (315569520000000000));
2087 return (((gint64) ts.tv_sec) * 1000000) + (ts.tv_nsec / 1000);
2090 /* It may look like we are discarding accuracy on Windows (since its
2091 * current time is expressed in 100s of nanoseconds) but according to
2092 * many sources, the time is only updated 64 times per second, so
2093 * microsecond accuracy is more than enough.
2098 g_get_current_time (&tv);
2100 return (((gint64) tv.tv_sec) * 1000000) + tv.tv_usec;
2106 g_main_dispatch_free (gpointer dispatch)
2108 g_slice_free (GMainDispatch, dispatch);
2111 /* Running the main loop */
2113 static GMainDispatch *
2116 static GStaticPrivate depth_private = G_STATIC_PRIVATE_INIT;
2117 GMainDispatch *dispatch = g_static_private_get (&depth_private);
2120 dispatch = g_slice_new0 (GMainDispatch);
2121 g_static_private_set (&depth_private, dispatch, g_main_dispatch_free);
2130 * Returns the depth of the stack of calls to
2131 * g_main_context_dispatch() on any #GMainContext in the current thread.
2132 * That is, when called from the toplevel, it gives 0. When
2133 * called from within a callback from g_main_context_iteration()
2134 * (or g_main_loop_run(), etc.) it returns 1. When called from within
2135 * a callback to a recursive call to g_main_context_iteration(),
2136 * it returns 2. And so forth.
2138 * This function is useful in a situation like the following:
2139 * Imagine an extremely simple "garbage collected" system.
2142 * static GList *free_list;
2145 * allocate_memory (gsize size)
2147 * gpointer result = g_malloc (size);
2148 * free_list = g_list_prepend (free_list, result);
2153 * free_allocated_memory (void)
2156 * for (l = free_list; l; l = l->next);
2158 * g_list_free (free_list);
2166 * g_main_context_iteration (NULL, TRUE);
2167 * free_allocated_memory();
2171 * This works from an application, however, if you want to do the same
2172 * thing from a library, it gets more difficult, since you no longer
2173 * control the main loop. You might think you can simply use an idle
2174 * function to make the call to free_allocated_memory(), but that
2175 * doesn't work, since the idle function could be called from a
2176 * recursive callback. This can be fixed by using g_main_depth()
2180 * allocate_memory (gsize size)
2182 * FreeListBlock *block = g_new (FreeListBlock, 1);
2183 * block->mem = g_malloc (size);
2184 * block->depth = g_main_depth ();
2185 * free_list = g_list_prepend (free_list, block);
2186 * return block->mem;
2190 * free_allocated_memory (void)
2194 * int depth = g_main_depth ();
2195 * for (l = free_list; l; );
2197 * GList *next = l->next;
2198 * FreeListBlock *block = l->data;
2199 * if (block->depth > depth)
2201 * g_free (block->mem);
2203 * free_list = g_list_delete_link (free_list, l);
2211 * There is a temptation to use g_main_depth() to solve
2212 * problems with reentrancy. For instance, while waiting for data
2213 * to be received from the network in response to a menu item,
2214 * the menu item might be selected again. It might seem that
2215 * one could make the menu item's callback return immediately
2216 * and do nothing if g_main_depth() returns a value greater than 1.
2217 * However, this should be avoided since the user then sees selecting
2218 * the menu item do nothing. Furthermore, you'll find yourself adding
2219 * these checks all over your code, since there are doubtless many,
2220 * many things that the user could do. Instead, you can use the
2221 * following techniques:
2226 * Use gtk_widget_set_sensitive() or modal dialogs to prevent
2227 * the user from interacting with elements while the main
2228 * loop is recursing.
2233 * Avoid main loop recursion in situations where you can't handle
2234 * arbitrary callbacks. Instead, structure your code so that you
2235 * simply return to the main loop and then get called again when
2236 * there is more work to do.
2241 * Return value: The main loop recursion level in the current thread
2246 GMainDispatch *dispatch = get_dispatch ();
2247 return dispatch->depth;
2251 * g_main_current_source:
2253 * Returns the currently firing source for this thread.
2255 * Return value: The currently firing source or %NULL.
2260 g_main_current_source (void)
2262 GMainDispatch *dispatch = get_dispatch ();
2263 return dispatch->dispatching_sources ? dispatch->dispatching_sources->data : NULL;
2267 * g_source_is_destroyed:
2268 * @source: a #GSource
2270 * Returns whether @source has been destroyed.
2272 * This is important when you operate upon your objects
2273 * from within idle handlers, but may have freed the object
2274 * before the dispatch of your idle handler.
2278 * idle_callback (gpointer data)
2280 * SomeWidget *self = data;
2282 * GDK_THREADS_ENTER (<!-- -->);
2283 * /<!-- -->* do stuff with self *<!-- -->/
2284 * self->idle_id = 0;
2285 * GDK_THREADS_LEAVE (<!-- -->);
2291 * some_widget_do_stuff_later (SomeWidget *self)
2293 * self->idle_id = g_idle_add (idle_callback, self);
2297 * some_widget_finalize (GObject *object)
2299 * SomeWidget *self = SOME_WIDGET (object);
2301 * if (self->idle_id)
2302 * g_source_remove (self->idle_id);
2304 * G_OBJECT_CLASS (parent_class)->finalize (object);
2308 * This will fail in a multi-threaded application if the
2309 * widget is destroyed before the idle handler fires due
2310 * to the use after free in the callback. A solution, to
2311 * this particular problem, is to check to if the source
2312 * has already been destroy within the callback.
2316 * idle_callback (gpointer data)
2318 * SomeWidget *self = data;
2320 * GDK_THREADS_ENTER ();
2321 * if (!g_source_is_destroyed (g_main_current_source ()))
2323 * /<!-- -->* do stuff with self *<!-- -->/
2325 * GDK_THREADS_LEAVE ();
2331 * Return value: %TRUE if the source has been destroyed
2336 g_source_is_destroyed (GSource *source)
2338 return SOURCE_DESTROYED (source);
2341 /* Temporarily remove all this source's file descriptors from the
2342 * poll(), so that if data comes available for one of the file descriptors
2343 * we don't continually spin in the poll()
2345 /* HOLDS: source->context's lock */
2347 block_source (GSource *source)
2351 g_return_if_fail (!SOURCE_BLOCKED (source));
2353 tmp_list = source->poll_fds;
2356 g_main_context_remove_poll_unlocked (source->context, tmp_list->data);
2357 tmp_list = tmp_list->next;
2361 /* HOLDS: source->context's lock */
2363 unblock_source (GSource *source)
2367 g_return_if_fail (!SOURCE_BLOCKED (source)); /* Source already unblocked */
2368 g_return_if_fail (!SOURCE_DESTROYED (source));
2370 tmp_list = source->poll_fds;
2373 g_main_context_add_poll_unlocked (source->context, source->priority, tmp_list->data);
2374 tmp_list = tmp_list->next;
2378 /* HOLDS: context's lock */
2380 g_main_dispatch (GMainContext *context)
2382 GMainDispatch *current = get_dispatch ();
2385 for (i = 0; i < context->pending_dispatches->len; i++)
2387 GSource *source = context->pending_dispatches->pdata[i];
2389 context->pending_dispatches->pdata[i] = NULL;
2392 source->flags &= ~G_SOURCE_READY;
2394 if (!SOURCE_DESTROYED (source))
2396 gboolean was_in_call;
2397 gpointer user_data = NULL;
2398 GSourceFunc callback = NULL;
2399 GSourceCallbackFuncs *cb_funcs;
2401 gboolean need_destroy;
2403 gboolean (*dispatch) (GSource *,
2406 GSList current_source_link;
2408 dispatch = source->source_funcs->dispatch;
2409 cb_funcs = source->callback_funcs;
2410 cb_data = source->callback_data;
2413 cb_funcs->ref (cb_data);
2415 if ((source->flags & G_SOURCE_CAN_RECURSE) == 0)
2416 block_source (source);
2418 was_in_call = source->flags & G_HOOK_FLAG_IN_CALL;
2419 source->flags |= G_HOOK_FLAG_IN_CALL;
2422 cb_funcs->get (cb_data, source, &callback, &user_data);
2424 UNLOCK_CONTEXT (context);
2427 /* The on-stack allocation of the GSList is unconventional, but
2428 * we know that the lifetime of the link is bounded to this
2429 * function as the link is kept in a thread specific list and
2430 * not manipulated outside of this function and its descendants.
2431 * Avoiding the overhead of a g_slist_alloc() is useful as many
2432 * applications do little more than dispatch events.
2434 * This is a performance hack - do not revert to g_slist_prepend()!
2436 current_source_link.data = source;
2437 current_source_link.next = current->dispatching_sources;
2438 current->dispatching_sources = ¤t_source_link;
2439 need_destroy = ! dispatch (source,
2442 g_assert (current->dispatching_sources == ¤t_source_link);
2443 current->dispatching_sources = current_source_link.next;
2447 cb_funcs->unref (cb_data);
2449 LOCK_CONTEXT (context);
2452 source->flags &= ~G_HOOK_FLAG_IN_CALL;
2454 if ((source->flags & G_SOURCE_CAN_RECURSE) == 0 &&
2455 !SOURCE_DESTROYED (source))
2456 unblock_source (source);
2458 /* Note: this depends on the fact that we can't switch
2459 * sources from one main context to another
2461 if (need_destroy && !SOURCE_DESTROYED (source))
2463 g_assert (source->context == context);
2464 g_source_destroy_internal (source, context, TRUE);
2468 SOURCE_UNREF (source, context);
2471 g_ptr_array_set_size (context->pending_dispatches, 0);
2474 /* Holds context's lock */
2475 static inline GSource *
2476 next_valid_source (GMainContext *context,
2479 GSource *new_source = source ? source->next : context->source_list;
2483 if (!SOURCE_DESTROYED (new_source))
2485 new_source->ref_count++;
2489 new_source = new_source->next;
2493 SOURCE_UNREF (source, context);
2499 * g_main_context_acquire:
2500 * @context: a #GMainContext
2502 * Tries to become the owner of the specified context.
2503 * If some other thread is the owner of the context,
2504 * returns %FALSE immediately. Ownership is properly
2505 * recursive: the owner can require ownership again
2506 * and will release ownership when g_main_context_release()
2507 * is called as many times as g_main_context_acquire().
2509 * You must be the owner of a context before you
2510 * can call g_main_context_prepare(), g_main_context_query(),
2511 * g_main_context_check(), g_main_context_dispatch().
2513 * Return value: %TRUE if the operation succeeded, and
2514 * this thread is now the owner of @context.
2517 g_main_context_acquire (GMainContext *context)
2519 #ifdef G_THREADS_ENABLED
2520 gboolean result = FALSE;
2521 GThread *self = G_THREAD_SELF;
2523 if (context == NULL)
2524 context = g_main_context_default ();
2526 LOCK_CONTEXT (context);
2528 if (!context->owner)
2530 context->owner = self;
2531 g_assert (context->owner_count == 0);
2534 if (context->owner == self)
2536 context->owner_count++;
2540 UNLOCK_CONTEXT (context);
2543 #else /* !G_THREADS_ENABLED */
2545 #endif /* G_THREADS_ENABLED */
2549 * g_main_context_release:
2550 * @context: a #GMainContext
2552 * Releases ownership of a context previously acquired by this thread
2553 * with g_main_context_acquire(). If the context was acquired multiple
2554 * times, the ownership will be released only when g_main_context_release()
2555 * is called as many times as it was acquired.
2558 g_main_context_release (GMainContext *context)
2560 #ifdef G_THREADS_ENABLED
2561 if (context == NULL)
2562 context = g_main_context_default ();
2564 LOCK_CONTEXT (context);
2566 context->owner_count--;
2567 if (context->owner_count == 0)
2569 context->owner = NULL;
2571 if (context->waiters)
2573 GMainWaiter *waiter = context->waiters->data;
2574 gboolean loop_internal_waiter =
2575 (waiter->mutex == g_static_mutex_get_mutex (&context->mutex));
2576 context->waiters = g_slist_delete_link (context->waiters,
2578 if (!loop_internal_waiter)
2579 g_mutex_lock (waiter->mutex);
2581 g_cond_signal (waiter->cond);
2583 if (!loop_internal_waiter)
2584 g_mutex_unlock (waiter->mutex);
2588 UNLOCK_CONTEXT (context);
2589 #endif /* G_THREADS_ENABLED */
2593 * g_main_context_wait:
2594 * @context: a #GMainContext
2595 * @cond: a condition variable
2596 * @mutex: a mutex, currently held
2598 * Tries to become the owner of the specified context,
2599 * as with g_main_context_acquire(). But if another thread
2600 * is the owner, atomically drop @mutex and wait on @cond until
2601 * that owner releases ownership or until @cond is signaled, then
2602 * try again (once) to become the owner.
2604 * Return value: %TRUE if the operation succeeded, and
2605 * this thread is now the owner of @context.
2608 g_main_context_wait (GMainContext *context,
2612 #ifdef G_THREADS_ENABLED
2613 gboolean result = FALSE;
2614 GThread *self = G_THREAD_SELF;
2615 gboolean loop_internal_waiter;
2617 if (context == NULL)
2618 context = g_main_context_default ();
2620 loop_internal_waiter = (mutex == g_static_mutex_get_mutex (&context->mutex));
2622 if (!loop_internal_waiter)
2623 LOCK_CONTEXT (context);
2625 if (context->owner && context->owner != self)
2630 waiter.mutex = mutex;
2632 context->waiters = g_slist_append (context->waiters, &waiter);
2634 if (!loop_internal_waiter)
2635 UNLOCK_CONTEXT (context);
2636 g_cond_wait (cond, mutex);
2637 if (!loop_internal_waiter)
2638 LOCK_CONTEXT (context);
2640 context->waiters = g_slist_remove (context->waiters, &waiter);
2643 if (!context->owner)
2645 context->owner = self;
2646 g_assert (context->owner_count == 0);
2649 if (context->owner == self)
2651 context->owner_count++;
2655 if (!loop_internal_waiter)
2656 UNLOCK_CONTEXT (context);
2659 #else /* !G_THREADS_ENABLED */
2661 #endif /* G_THREADS_ENABLED */
2665 * g_main_context_prepare:
2666 * @context: a #GMainContext
2667 * @priority: location to store priority of highest priority
2668 * source already ready.
2670 * Prepares to poll sources within a main loop. The resulting information
2671 * for polling is determined by calling g_main_context_query ().
2673 * Return value: %TRUE if some source is ready to be dispatched
2677 g_main_context_prepare (GMainContext *context,
2682 gint current_priority = G_MAXINT;
2685 if (context == NULL)
2686 context = g_main_context_default ();
2688 LOCK_CONTEXT (context);
2690 context->time_is_fresh = FALSE;
2691 context->real_time_is_fresh = FALSE;
2693 if (context->in_check_or_prepare)
2695 g_warning ("g_main_context_prepare() called recursively from within a source's check() or "
2696 "prepare() member.");
2697 UNLOCK_CONTEXT (context);
2701 #ifdef G_THREADS_ENABLED
2702 if (context->poll_waiting)
2704 g_warning("g_main_context_prepare(): main loop already active in another thread");
2705 UNLOCK_CONTEXT (context);
2709 context->poll_waiting = TRUE;
2710 #endif /* G_THREADS_ENABLED */
2713 /* If recursing, finish up current dispatch, before starting over */
2714 if (context->pending_dispatches)
2717 g_main_dispatch (context, ¤t_time);
2719 UNLOCK_CONTEXT (context);
2724 /* If recursing, clear list of pending dispatches */
2726 for (i = 0; i < context->pending_dispatches->len; i++)
2728 if (context->pending_dispatches->pdata[i])
2729 SOURCE_UNREF ((GSource *)context->pending_dispatches->pdata[i], context);
2731 g_ptr_array_set_size (context->pending_dispatches, 0);
2733 /* Prepare all sources */
2735 context->timeout = -1;
2737 source = next_valid_source (context, NULL);
2740 gint source_timeout = -1;
2742 if ((n_ready > 0) && (source->priority > current_priority))
2744 SOURCE_UNREF (source, context);
2747 if (SOURCE_BLOCKED (source))
2750 if (!(source->flags & G_SOURCE_READY))
2753 gboolean (*prepare) (GSource *source,
2756 prepare = source->source_funcs->prepare;
2757 context->in_check_or_prepare++;
2758 UNLOCK_CONTEXT (context);
2760 result = (*prepare) (source, &source_timeout);
2762 LOCK_CONTEXT (context);
2763 context->in_check_or_prepare--;
2767 GSource *ready_source = source;
2769 while (ready_source)
2771 ready_source->flags |= G_SOURCE_READY;
2772 ready_source = ready_source->priv ? ready_source->priv->parent_source : NULL;
2777 if (source->flags & G_SOURCE_READY)
2780 current_priority = source->priority;
2781 context->timeout = 0;
2784 if (source_timeout >= 0)
2786 if (context->timeout < 0)
2787 context->timeout = source_timeout;
2789 context->timeout = MIN (context->timeout, source_timeout);
2793 source = next_valid_source (context, source);
2796 UNLOCK_CONTEXT (context);
2799 *priority = current_priority;
2801 return (n_ready > 0);
2805 * g_main_context_query:
2806 * @context: a #GMainContext
2807 * @max_priority: maximum priority source to check
2808 * @timeout_: location to store timeout to be used in polling
2809 * @fds: location to store #GPollFD records that need to be polled.
2810 * @n_fds: length of @fds.
2812 * Determines information necessary to poll this main loop.
2814 * Return value: the number of records actually stored in @fds,
2815 * or, if more than @n_fds records need to be stored, the number
2816 * of records that need to be stored.
2819 g_main_context_query (GMainContext *context,
2828 LOCK_CONTEXT (context);
2830 pollrec = context->poll_records;
2832 while (pollrec && max_priority >= pollrec->priority)
2834 /* We need to include entries with fd->events == 0 in the array because
2835 * otherwise if the application changes fd->events behind our back and
2836 * makes it non-zero, we'll be out of sync when we check the fds[] array.
2837 * (Changing fd->events after adding an FD wasn't an anticipated use of
2838 * this API, but it occurs in practice.) */
2841 fds[n_poll].fd = pollrec->fd->fd;
2842 /* In direct contradiction to the Unix98 spec, IRIX runs into
2843 * difficulty if you pass in POLLERR, POLLHUP or POLLNVAL
2844 * flags in the events field of the pollfd while it should
2845 * just ignoring them. So we mask them out here.
2847 fds[n_poll].events = pollrec->fd->events & ~(G_IO_ERR|G_IO_HUP|G_IO_NVAL);
2848 fds[n_poll].revents = 0;
2851 pollrec = pollrec->next;
2855 #ifdef G_THREADS_ENABLED
2856 context->poll_changed = FALSE;
2861 *timeout = context->timeout;
2864 context->time_is_fresh = FALSE;
2865 context->real_time_is_fresh = FALSE;
2869 UNLOCK_CONTEXT (context);
2875 * g_main_context_check:
2876 * @context: a #GMainContext
2877 * @max_priority: the maximum numerical priority of sources to check
2878 * @fds: array of #GPollFD's that was passed to the last call to
2879 * g_main_context_query()
2880 * @n_fds: return value of g_main_context_query()
2882 * Passes the results of polling back to the main loop.
2884 * Return value: %TRUE if some sources are ready to be dispatched.
2887 g_main_context_check (GMainContext *context,
2897 LOCK_CONTEXT (context);
2899 if (context->in_check_or_prepare)
2901 g_warning ("g_main_context_check() called recursively from within a source's check() or "
2902 "prepare() member.");
2903 UNLOCK_CONTEXT (context);
2907 #ifdef G_THREADS_ENABLED
2908 if (!context->poll_waiting)
2909 g_wakeup_acknowledge (context->wakeup);
2912 context->poll_waiting = FALSE;
2914 /* If the set of poll file descriptors changed, bail out
2915 * and let the main loop rerun
2917 if (context->poll_changed)
2919 UNLOCK_CONTEXT (context);
2922 #endif /* G_THREADS_ENABLED */
2924 pollrec = context->poll_records;
2928 if (pollrec->fd->events)
2929 pollrec->fd->revents = fds[i].revents;
2931 pollrec = pollrec->next;
2935 source = next_valid_source (context, NULL);
2938 if ((n_ready > 0) && (source->priority > max_priority))
2940 SOURCE_UNREF (source, context);
2943 if (SOURCE_BLOCKED (source))
2946 if (!(source->flags & G_SOURCE_READY))
2949 gboolean (*check) (GSource *source);
2951 check = source->source_funcs->check;
2953 context->in_check_or_prepare++;
2954 UNLOCK_CONTEXT (context);
2956 result = (*check) (source);
2958 LOCK_CONTEXT (context);
2959 context->in_check_or_prepare--;
2963 GSource *ready_source = source;
2965 while (ready_source)
2967 ready_source->flags |= G_SOURCE_READY;
2968 ready_source = ready_source->priv ? ready_source->priv->parent_source : NULL;
2973 if (source->flags & G_SOURCE_READY)
2975 source->ref_count++;
2976 g_ptr_array_add (context->pending_dispatches, source);
2980 /* never dispatch sources with less priority than the first
2981 * one we choose to dispatch
2983 max_priority = source->priority;
2987 source = next_valid_source (context, source);
2990 UNLOCK_CONTEXT (context);
2996 * g_main_context_dispatch:
2997 * @context: a #GMainContext
2999 * Dispatches all pending sources.
3002 g_main_context_dispatch (GMainContext *context)
3004 LOCK_CONTEXT (context);
3006 if (context->pending_dispatches->len > 0)
3008 g_main_dispatch (context);
3011 UNLOCK_CONTEXT (context);
3014 /* HOLDS context lock */
3016 g_main_context_iterate (GMainContext *context,
3023 gboolean some_ready;
3024 gint nfds, allocated_nfds;
3025 GPollFD *fds = NULL;
3027 UNLOCK_CONTEXT (context);
3029 #ifdef G_THREADS_ENABLED
3030 if (!g_main_context_acquire (context))
3032 gboolean got_ownership;
3034 LOCK_CONTEXT (context);
3036 g_return_val_if_fail (g_thread_supported (), FALSE);
3042 context->cond = g_cond_new ();
3044 got_ownership = g_main_context_wait (context,
3046 g_static_mutex_get_mutex (&context->mutex));
3052 LOCK_CONTEXT (context);
3053 #endif /* G_THREADS_ENABLED */
3055 if (!context->cached_poll_array)
3057 context->cached_poll_array_size = context->n_poll_records;
3058 context->cached_poll_array = g_new (GPollFD, context->n_poll_records);
3061 allocated_nfds = context->cached_poll_array_size;
3062 fds = context->cached_poll_array;
3064 UNLOCK_CONTEXT (context);
3066 g_main_context_prepare (context, &max_priority);
3068 while ((nfds = g_main_context_query (context, max_priority, &timeout, fds,
3069 allocated_nfds)) > allocated_nfds)
3071 LOCK_CONTEXT (context);
3073 context->cached_poll_array_size = allocated_nfds = nfds;
3074 context->cached_poll_array = fds = g_new (GPollFD, nfds);
3075 UNLOCK_CONTEXT (context);
3081 g_main_context_poll (context, timeout, max_priority, fds, nfds);
3083 some_ready = g_main_context_check (context, max_priority, fds, nfds);
3086 g_main_context_dispatch (context);
3088 #ifdef G_THREADS_ENABLED
3089 g_main_context_release (context);
3090 #endif /* G_THREADS_ENABLED */
3092 LOCK_CONTEXT (context);
3098 * g_main_context_pending:
3099 * @context: a #GMainContext (if %NULL, the default context will be used)
3101 * Checks if any sources have pending events for the given context.
3103 * Return value: %TRUE if events are pending.
3106 g_main_context_pending (GMainContext *context)
3111 context = g_main_context_default();
3113 LOCK_CONTEXT (context);
3114 retval = g_main_context_iterate (context, FALSE, FALSE, G_THREAD_SELF);
3115 UNLOCK_CONTEXT (context);
3121 * g_main_context_iteration:
3122 * @context: a #GMainContext (if %NULL, the default context will be used)
3123 * @may_block: whether the call may block.
3125 * Runs a single iteration for the given main loop. This involves
3126 * checking to see if any event sources are ready to be processed,
3127 * then if no events sources are ready and @may_block is %TRUE, waiting
3128 * for a source to become ready, then dispatching the highest priority
3129 * events sources that are ready. Otherwise, if @may_block is %FALSE
3130 * sources are not waited to become ready, only those highest priority
3131 * events sources will be dispatched (if any), that are ready at this
3132 * given moment without further waiting.
3134 * Note that even when @may_block is %TRUE, it is still possible for
3135 * g_main_context_iteration() to return %FALSE, since the the wait may
3136 * be interrupted for other reasons than an event source becoming ready.
3138 * Return value: %TRUE if events were dispatched.
3141 g_main_context_iteration (GMainContext *context, gboolean may_block)
3146 context = g_main_context_default();
3148 LOCK_CONTEXT (context);
3149 retval = g_main_context_iterate (context, may_block, TRUE, G_THREAD_SELF);
3150 UNLOCK_CONTEXT (context);
3157 * @context: (allow-none): a #GMainContext (if %NULL, the default context will be used).
3158 * @is_running: set to %TRUE to indicate that the loop is running. This
3159 * is not very important since calling g_main_loop_run() will set this to
3162 * Creates a new #GMainLoop structure.
3164 * Return value: a new #GMainLoop.
3167 g_main_loop_new (GMainContext *context,
3168 gboolean is_running)
3173 context = g_main_context_default();
3175 g_main_context_ref (context);
3177 loop = g_new0 (GMainLoop, 1);
3178 loop->context = context;
3179 loop->is_running = is_running != FALSE;
3180 loop->ref_count = 1;
3187 * @loop: a #GMainLoop
3189 * Increases the reference count on a #GMainLoop object by one.
3191 * Return value: @loop
3194 g_main_loop_ref (GMainLoop *loop)
3196 g_return_val_if_fail (loop != NULL, NULL);
3197 g_return_val_if_fail (g_atomic_int_get (&loop->ref_count) > 0, NULL);
3199 g_atomic_int_inc (&loop->ref_count);
3205 * g_main_loop_unref:
3206 * @loop: a #GMainLoop
3208 * Decreases the reference count on a #GMainLoop object by one. If
3209 * the result is zero, free the loop and free all associated memory.
3212 g_main_loop_unref (GMainLoop *loop)
3214 g_return_if_fail (loop != NULL);
3215 g_return_if_fail (g_atomic_int_get (&loop->ref_count) > 0);
3217 if (!g_atomic_int_dec_and_test (&loop->ref_count))
3220 g_main_context_unref (loop->context);
3226 * @loop: a #GMainLoop
3228 * Runs a main loop until g_main_loop_quit() is called on the loop.
3229 * If this is called for the thread of the loop's #GMainContext,
3230 * it will process events from the loop, otherwise it will
3234 g_main_loop_run (GMainLoop *loop)
3236 GThread *self = G_THREAD_SELF;
3238 g_return_if_fail (loop != NULL);
3239 g_return_if_fail (g_atomic_int_get (&loop->ref_count) > 0);
3241 #ifdef G_THREADS_ENABLED
3242 if (!g_main_context_acquire (loop->context))
3244 gboolean got_ownership = FALSE;
3246 /* Another thread owns this context */
3247 if (!g_thread_supported ())
3249 g_warning ("g_main_loop_run() was called from second thread but "
3250 "g_thread_init() was never called.");
3254 LOCK_CONTEXT (loop->context);
3256 g_atomic_int_inc (&loop->ref_count);
3258 if (!loop->is_running)
3259 loop->is_running = TRUE;
3261 if (!loop->context->cond)
3262 loop->context->cond = g_cond_new ();
3264 while (loop->is_running && !got_ownership)
3265 got_ownership = g_main_context_wait (loop->context,
3266 loop->context->cond,
3267 g_static_mutex_get_mutex (&loop->context->mutex));
3269 if (!loop->is_running)
3271 UNLOCK_CONTEXT (loop->context);
3273 g_main_context_release (loop->context);
3274 g_main_loop_unref (loop);
3278 g_assert (got_ownership);
3281 LOCK_CONTEXT (loop->context);
3282 #endif /* G_THREADS_ENABLED */
3284 if (loop->context->in_check_or_prepare)
3286 g_warning ("g_main_loop_run(): called recursively from within a source's "
3287 "check() or prepare() member, iteration not possible.");
3291 g_atomic_int_inc (&loop->ref_count);
3292 loop->is_running = TRUE;
3293 while (loop->is_running)
3294 g_main_context_iterate (loop->context, TRUE, TRUE, self);
3296 UNLOCK_CONTEXT (loop->context);
3298 #ifdef G_THREADS_ENABLED
3299 g_main_context_release (loop->context);
3300 #endif /* G_THREADS_ENABLED */
3302 g_main_loop_unref (loop);
3307 * @loop: a #GMainLoop
3309 * Stops a #GMainLoop from running. Any calls to g_main_loop_run()
3310 * for the loop will return.
3312 * Note that sources that have already been dispatched when
3313 * g_main_loop_quit() is called will still be executed.
3316 g_main_loop_quit (GMainLoop *loop)
3318 g_return_if_fail (loop != NULL);
3319 g_return_if_fail (g_atomic_int_get (&loop->ref_count) > 0);
3321 LOCK_CONTEXT (loop->context);
3322 loop->is_running = FALSE;
3323 g_main_context_wakeup_unlocked (loop->context);
3325 #ifdef G_THREADS_ENABLED
3326 if (loop->context->cond)
3327 g_cond_broadcast (loop->context->cond);
3328 #endif /* G_THREADS_ENABLED */
3330 UNLOCK_CONTEXT (loop->context);
3334 * g_main_loop_is_running:
3335 * @loop: a #GMainLoop.
3337 * Checks to see if the main loop is currently being run via g_main_loop_run().
3339 * Return value: %TRUE if the mainloop is currently being run.
3342 g_main_loop_is_running (GMainLoop *loop)
3344 g_return_val_if_fail (loop != NULL, FALSE);
3345 g_return_val_if_fail (g_atomic_int_get (&loop->ref_count) > 0, FALSE);
3347 return loop->is_running;
3351 * g_main_loop_get_context:
3352 * @loop: a #GMainLoop.
3354 * Returns the #GMainContext of @loop.
3356 * Return value: the #GMainContext of @loop
3359 g_main_loop_get_context (GMainLoop *loop)
3361 g_return_val_if_fail (loop != NULL, NULL);
3362 g_return_val_if_fail (g_atomic_int_get (&loop->ref_count) > 0, NULL);
3364 return loop->context;
3367 /* HOLDS: context's lock */
3369 g_main_context_poll (GMainContext *context,
3375 #ifdef G_MAIN_POLL_DEBUG
3381 GPollFunc poll_func;
3383 if (n_fds || timeout != 0)
3385 #ifdef G_MAIN_POLL_DEBUG
3386 if (_g_main_poll_debug)
3388 g_print ("polling context=%p n=%d timeout=%d\n",
3389 context, n_fds, timeout);
3390 poll_timer = g_timer_new ();
3394 LOCK_CONTEXT (context);
3396 poll_func = context->poll_func;
3398 UNLOCK_CONTEXT (context);
3399 if ((*poll_func) (fds, n_fds, timeout) < 0 && errno != EINTR)
3402 g_warning ("poll(2) failed due to: %s.",
3403 g_strerror (errno));
3405 /* If g_poll () returns -1, it has already called g_warning() */
3409 #ifdef G_MAIN_POLL_DEBUG
3410 if (_g_main_poll_debug)
3412 LOCK_CONTEXT (context);
3414 g_print ("g_main_poll(%d) timeout: %d - elapsed %12.10f seconds",
3417 g_timer_elapsed (poll_timer, NULL));
3418 g_timer_destroy (poll_timer);
3419 pollrec = context->poll_records;
3421 while (pollrec != NULL)
3426 if (fds[i].fd == pollrec->fd->fd &&
3427 pollrec->fd->events &&
3430 g_print (" [" G_POLLFD_FORMAT " :", fds[i].fd);
3431 if (fds[i].revents & G_IO_IN)
3433 if (fds[i].revents & G_IO_OUT)
3435 if (fds[i].revents & G_IO_PRI)
3437 if (fds[i].revents & G_IO_ERR)
3439 if (fds[i].revents & G_IO_HUP)
3441 if (fds[i].revents & G_IO_NVAL)
3447 pollrec = pollrec->next;
3451 UNLOCK_CONTEXT (context);
3454 } /* if (n_fds || timeout != 0) */
3458 * g_main_context_add_poll:
3459 * @context: a #GMainContext (or %NULL for the default context)
3460 * @fd: a #GPollFD structure holding information about a file
3461 * descriptor to watch.
3462 * @priority: the priority for this file descriptor which should be
3463 * the same as the priority used for g_source_attach() to ensure that the
3464 * file descriptor is polled whenever the results may be needed.
3466 * Adds a file descriptor to the set of file descriptors polled for
3467 * this context. This will very seldomly be used directly. Instead
3468 * a typical event source will use g_source_add_poll() instead.
3471 g_main_context_add_poll (GMainContext *context,
3476 context = g_main_context_default ();
3478 g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
3479 g_return_if_fail (fd);
3481 LOCK_CONTEXT (context);
3482 g_main_context_add_poll_unlocked (context, priority, fd);
3483 UNLOCK_CONTEXT (context);
3486 /* HOLDS: main_loop_lock */
3488 g_main_context_add_poll_unlocked (GMainContext *context,
3492 GPollRec *prevrec, *nextrec;
3493 GPollRec *newrec = g_slice_new (GPollRec);
3495 /* This file descriptor may be checked before we ever poll */
3498 newrec->priority = priority;
3500 prevrec = context->poll_records_tail;
3502 while (prevrec && priority < prevrec->priority)
3505 prevrec = prevrec->prev;
3509 prevrec->next = newrec;
3511 context->poll_records = newrec;
3513 newrec->prev = prevrec;
3514 newrec->next = nextrec;
3517 nextrec->prev = newrec;
3519 context->poll_records_tail = newrec;
3521 context->n_poll_records++;
3523 #ifdef G_THREADS_ENABLED
3524 context->poll_changed = TRUE;
3526 /* Now wake up the main loop if it is waiting in the poll() */
3527 g_main_context_wakeup_unlocked (context);
3532 * g_main_context_remove_poll:
3533 * @context:a #GMainContext
3534 * @fd: a #GPollFD descriptor previously added with g_main_context_add_poll()
3536 * Removes file descriptor from the set of file descriptors to be
3537 * polled for a particular context.
3540 g_main_context_remove_poll (GMainContext *context,
3544 context = g_main_context_default ();
3546 g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
3547 g_return_if_fail (fd);
3549 LOCK_CONTEXT (context);
3550 g_main_context_remove_poll_unlocked (context, fd);
3551 UNLOCK_CONTEXT (context);
3555 g_main_context_remove_poll_unlocked (GMainContext *context,
3558 GPollRec *pollrec, *prevrec, *nextrec;
3561 pollrec = context->poll_records;
3565 nextrec = pollrec->next;
3566 if (pollrec->fd == fd)
3568 if (prevrec != NULL)
3569 prevrec->next = nextrec;
3571 context->poll_records = nextrec;
3573 if (nextrec != NULL)
3574 nextrec->prev = prevrec;
3576 context->poll_records_tail = prevrec;
3578 g_slice_free (GPollRec, pollrec);
3580 context->n_poll_records--;
3587 #ifdef G_THREADS_ENABLED
3588 context->poll_changed = TRUE;
3590 /* Now wake up the main loop if it is waiting in the poll() */
3591 g_main_context_wakeup_unlocked (context);
3596 * g_source_get_current_time:
3597 * @source: a #GSource
3598 * @timeval: #GTimeVal structure in which to store current time.
3600 * Gets the "current time" to be used when checking
3601 * this source. The advantage of calling this function over
3602 * calling g_get_current_time() directly is that when
3603 * checking multiple sources, GLib can cache a single value
3604 * instead of having to repeatedly get the system time.
3606 * Deprecated: 2.28: use g_source_get_time() instead
3609 g_source_get_current_time (GSource *source,
3612 GMainContext *context;
3614 g_return_if_fail (source->context != NULL);
3616 context = source->context;
3618 LOCK_CONTEXT (context);
3620 if (!context->real_time_is_fresh)
3622 context->real_time = g_get_real_time ();
3623 context->real_time_is_fresh = TRUE;
3626 timeval->tv_sec = context->real_time / 1000000;
3627 timeval->tv_usec = context->real_time % 1000000;
3629 UNLOCK_CONTEXT (context);
3633 * g_source_get_time:
3634 * @source: a #GSource
3636 * Gets the time to be used when checking this source. The advantage of
3637 * calling this function over calling g_get_monotonic_time() directly is
3638 * that when checking multiple sources, GLib can cache a single value
3639 * instead of having to repeatedly get the system monotonic time.
3641 * The time here is the system monotonic time, if available, or some
3642 * other reasonable alternative otherwise. See g_get_monotonic_time().
3644 * Returns: the monotonic time in microseconds
3649 g_source_get_time (GSource *source)
3651 GMainContext *context;
3654 g_return_val_if_fail (source->context != NULL, 0);
3656 context = source->context;
3658 LOCK_CONTEXT (context);
3660 if (!context->time_is_fresh)
3662 context->time = g_get_monotonic_time ();
3663 context->time_is_fresh = TRUE;
3666 result = context->time;
3668 UNLOCK_CONTEXT (context);
3674 * g_main_context_set_poll_func:
3675 * @context: a #GMainContext
3676 * @func: the function to call to poll all file descriptors
3678 * Sets the function to use to handle polling of file descriptors. It
3679 * will be used instead of the poll() system call
3680 * (or GLib's replacement function, which is used where
3681 * poll() isn't available).
3683 * This function could possibly be used to integrate the GLib event
3684 * loop with an external event loop.
3687 g_main_context_set_poll_func (GMainContext *context,
3691 context = g_main_context_default ();
3693 g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
3695 LOCK_CONTEXT (context);
3698 context->poll_func = func;
3700 context->poll_func = g_poll;
3702 UNLOCK_CONTEXT (context);
3706 * g_main_context_get_poll_func:
3707 * @context: a #GMainContext
3709 * Gets the poll function set by g_main_context_set_poll_func().
3711 * Return value: the poll function
3714 g_main_context_get_poll_func (GMainContext *context)
3719 context = g_main_context_default ();
3721 g_return_val_if_fail (g_atomic_int_get (&context->ref_count) > 0, NULL);
3723 LOCK_CONTEXT (context);
3724 result = context->poll_func;
3725 UNLOCK_CONTEXT (context);
3731 _g_main_wake_up_all_contexts (void)
3735 /* We were woken up. Wake up all other contexts in all other threads */
3736 G_LOCK (main_context_list);
3737 for (list = main_context_list; list; list = list->next)
3739 GMainContext *context = list->data;
3741 LOCK_CONTEXT (context);
3742 g_main_context_wakeup_unlocked (context);
3743 UNLOCK_CONTEXT (context);
3745 G_UNLOCK (main_context_list);
3749 /* HOLDS: context's lock */
3750 /* Wake the main loop up from a poll() */
3752 g_main_context_wakeup_unlocked (GMainContext *context)
3754 #ifdef G_THREADS_ENABLED
3755 if (g_thread_supported() && context->poll_waiting)
3757 context->poll_waiting = FALSE;
3758 g_wakeup_signal (context->wakeup);
3764 * g_main_context_wakeup:
3765 * @context: a #GMainContext
3767 * If @context is currently waiting in a poll(), interrupt
3768 * the poll(), and continue the iteration process.
3771 g_main_context_wakeup (GMainContext *context)
3774 context = g_main_context_default ();
3776 g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
3778 LOCK_CONTEXT (context);
3779 g_main_context_wakeup_unlocked (context);
3780 UNLOCK_CONTEXT (context);
3784 * g_main_context_is_owner:
3785 * @context: a #GMainContext
3787 * Determines whether this thread holds the (recursive)
3788 * ownership of this #GMaincontext. This is useful to
3789 * know before waiting on another thread that may be
3790 * blocking to get ownership of @context.
3792 * Returns: %TRUE if current thread is owner of @context.
3797 g_main_context_is_owner (GMainContext *context)
3802 context = g_main_context_default ();
3804 #ifdef G_THREADS_ENABLED
3805 LOCK_CONTEXT (context);
3806 is_owner = context->owner == G_THREAD_SELF;
3807 UNLOCK_CONTEXT (context);
3818 g_timeout_set_expiration (GTimeoutSource *timeout_source,
3819 gint64 current_time)
3821 timeout_source->expiration = current_time +
3822 (guint64) timeout_source->interval * 1000;
3824 if (timeout_source->seconds)
3827 static gint timer_perturb = -1;
3829 if (timer_perturb == -1)
3832 * we want a per machine/session unique 'random' value; try the dbus
3833 * address first, that has a UUID in it. If there is no dbus, use the
3834 * hostname for hashing.
3836 const char *session_bus_address = g_getenv ("DBUS_SESSION_BUS_ADDRESS");
3837 if (!session_bus_address)
3838 session_bus_address = g_getenv ("HOSTNAME");
3839 if (session_bus_address)
3840 timer_perturb = ABS ((gint) g_str_hash (session_bus_address)) % 1000000;
3845 /* We want the microseconds part of the timeout to land on the
3846 * 'timer_perturb' mark, but we need to make sure we don't try to
3847 * set the timeout in the past. We do this by ensuring that we
3848 * always only *increase* the expiration time by adding a full
3849 * second in the case that the microsecond portion decreases.
3851 timeout_source->expiration -= timer_perturb;
3853 remainder = timeout_source->expiration % 1000000;
3854 if (remainder >= 1000000/4)
3855 timeout_source->expiration += 1000000;
3857 timeout_source->expiration -= remainder;
3858 timeout_source->expiration += timer_perturb;
3863 g_timeout_prepare (GSource *source,
3866 GTimeoutSource *timeout_source = (GTimeoutSource *) source;
3867 gint64 now = g_source_get_time (source);
3869 if (now < timeout_source->expiration)
3871 /* Round up to ensure that we don't try again too early */
3872 *timeout = (timeout_source->expiration - now + 999) / 1000;
3881 g_timeout_check (GSource *source)
3883 GTimeoutSource *timeout_source = (GTimeoutSource *) source;
3884 gint64 now = g_source_get_time (source);
3886 return timeout_source->expiration <= now;
3890 g_timeout_dispatch (GSource *source,
3891 GSourceFunc callback,
3894 GTimeoutSource *timeout_source = (GTimeoutSource *)source;
3899 g_warning ("Timeout source dispatched without callback\n"
3900 "You must call g_source_set_callback().");
3904 again = callback (user_data);
3907 g_timeout_set_expiration (timeout_source, g_source_get_time (source));
3913 * g_timeout_source_new:
3914 * @interval: the timeout interval in milliseconds.
3916 * Creates a new timeout source.
3918 * The source will not initially be associated with any #GMainContext
3919 * and must be added to one with g_source_attach() before it will be
3922 * Return value: the newly-created timeout source
3925 g_timeout_source_new (guint interval)
3927 GSource *source = g_source_new (&g_timeout_funcs, sizeof (GTimeoutSource));
3928 GTimeoutSource *timeout_source = (GTimeoutSource *)source;
3930 timeout_source->interval = interval;
3931 g_timeout_set_expiration (timeout_source, g_get_monotonic_time ());
3937 * g_timeout_source_new_seconds:
3938 * @interval: the timeout interval in seconds
3940 * Creates a new timeout source.
3942 * The source will not initially be associated with any #GMainContext
3943 * and must be added to one with g_source_attach() before it will be
3946 * The scheduling granularity/accuracy of this timeout source will be
3949 * Return value: the newly-created timeout source
3954 g_timeout_source_new_seconds (guint interval)
3956 GSource *source = g_source_new (&g_timeout_funcs, sizeof (GTimeoutSource));
3957 GTimeoutSource *timeout_source = (GTimeoutSource *)source;
3959 timeout_source->interval = 1000 * interval;
3960 timeout_source->seconds = TRUE;
3962 g_timeout_set_expiration (timeout_source, g_get_monotonic_time ());
3969 * g_timeout_add_full:
3970 * @priority: the priority of the timeout source. Typically this will be in
3971 * the range between #G_PRIORITY_DEFAULT and #G_PRIORITY_HIGH.
3972 * @interval: the time between calls to the function, in milliseconds
3973 * (1/1000ths of a second)
3974 * @function: function to call
3975 * @data: data to pass to @function
3976 * @notify: function to call when the timeout is removed, or %NULL
3978 * Sets a function to be called at regular intervals, with the given
3979 * priority. The function is called repeatedly until it returns
3980 * %FALSE, at which point the timeout is automatically destroyed and
3981 * the function will not be called again. The @notify function is
3982 * called when the timeout is destroyed. The first call to the
3983 * function will be at the end of the first @interval.
3985 * Note that timeout functions may be delayed, due to the processing of other
3986 * event sources. Thus they should not be relied on for precise timing.
3987 * After each call to the timeout function, the time of the next
3988 * timeout is recalculated based on the current time and the given interval
3989 * (it does not try to 'catch up' time lost in delays).
3991 * This internally creates a main loop source using g_timeout_source_new()
3992 * and attaches it to the main loop context using g_source_attach(). You can
3993 * do these steps manually if you need greater control.
3995 * Return value: the ID (greater than 0) of the event source.
3996 * Rename to: g_timeout_add
3999 g_timeout_add_full (gint priority,
4001 GSourceFunc function,
4003 GDestroyNotify notify)
4008 g_return_val_if_fail (function != NULL, 0);
4010 source = g_timeout_source_new (interval);
4012 if (priority != G_PRIORITY_DEFAULT)
4013 g_source_set_priority (source, priority);
4015 g_source_set_callback (source, function, data, notify);
4016 id = g_source_attach (source, NULL);
4017 g_source_unref (source);
4024 * @interval: the time between calls to the function, in milliseconds
4025 * (1/1000ths of a second)
4026 * @function: function to call
4027 * @data: data to pass to @function
4029 * Sets a function to be called at regular intervals, with the default
4030 * priority, #G_PRIORITY_DEFAULT. The function is called repeatedly
4031 * until it returns %FALSE, at which point the timeout is automatically
4032 * destroyed and the function will not be called again. The first call
4033 * to the function will be at the end of the first @interval.
4035 * Note that timeout functions may be delayed, due to the processing of other
4036 * event sources. Thus they should not be relied on for precise timing.
4037 * After each call to the timeout function, the time of the next
4038 * timeout is recalculated based on the current time and the given interval
4039 * (it does not try to 'catch up' time lost in delays).
4041 * If you want to have a timer in the "seconds" range and do not care
4042 * about the exact time of the first call of the timer, use the
4043 * g_timeout_add_seconds() function; this function allows for more
4044 * optimizations and more efficient system power usage.
4046 * This internally creates a main loop source using g_timeout_source_new()
4047 * and attaches it to the main loop context using g_source_attach(). You can
4048 * do these steps manually if you need greater control.
4050 * Return value: the ID (greater than 0) of the event source.
4053 g_timeout_add (guint32 interval,
4054 GSourceFunc function,
4057 return g_timeout_add_full (G_PRIORITY_DEFAULT,
4058 interval, function, data, NULL);
4062 * g_timeout_add_seconds_full:
4063 * @priority: the priority of the timeout source. Typically this will be in
4064 * the range between #G_PRIORITY_DEFAULT and #G_PRIORITY_HIGH.
4065 * @interval: the time between calls to the function, in seconds
4066 * @function: function to call
4067 * @data: data to pass to @function
4068 * @notify: function to call when the timeout is removed, or %NULL
4070 * Sets a function to be called at regular intervals, with @priority.
4071 * The function is called repeatedly until it returns %FALSE, at which
4072 * point the timeout is automatically destroyed and the function will
4073 * not be called again.
4075 * Unlike g_timeout_add(), this function operates at whole second granularity.
4076 * The initial starting point of the timer is determined by the implementation
4077 * and the implementation is expected to group multiple timers together so that
4078 * they fire all at the same time.
4079 * To allow this grouping, the @interval to the first timer is rounded
4080 * and can deviate up to one second from the specified interval.
4081 * Subsequent timer iterations will generally run at the specified interval.
4083 * Note that timeout functions may be delayed, due to the processing of other
4084 * event sources. Thus they should not be relied on for precise timing.
4085 * After each call to the timeout function, the time of the next
4086 * timeout is recalculated based on the current time and the given @interval
4088 * If you want timing more precise than whole seconds, use g_timeout_add()
4091 * The grouping of timers to fire at the same time results in a more power
4092 * and CPU efficient behavior so if your timer is in multiples of seconds
4093 * and you don't require the first timer exactly one second from now, the
4094 * use of g_timeout_add_seconds() is preferred over g_timeout_add().
4096 * This internally creates a main loop source using
4097 * g_timeout_source_new_seconds() and attaches it to the main loop context
4098 * using g_source_attach(). You can do these steps manually if you need
4101 * Return value: the ID (greater than 0) of the event source.
4103 * Rename to: g_timeout_add_seconds
4107 g_timeout_add_seconds_full (gint priority,
4109 GSourceFunc function,
4111 GDestroyNotify notify)
4116 g_return_val_if_fail (function != NULL, 0);
4118 source = g_timeout_source_new_seconds (interval);
4120 if (priority != G_PRIORITY_DEFAULT)
4121 g_source_set_priority (source, priority);
4123 g_source_set_callback (source, function, data, notify);
4124 id = g_source_attach (source, NULL);
4125 g_source_unref (source);
4131 * g_timeout_add_seconds:
4132 * @interval: the time between calls to the function, in seconds
4133 * @function: function to call
4134 * @data: data to pass to @function
4136 * Sets a function to be called at regular intervals with the default
4137 * priority, #G_PRIORITY_DEFAULT. The function is called repeatedly until
4138 * it returns %FALSE, at which point the timeout is automatically destroyed
4139 * and the function will not be called again.
4141 * This internally creates a main loop source using
4142 * g_timeout_source_new_seconds() and attaches it to the main loop context
4143 * using g_source_attach(). You can do these steps manually if you need
4144 * greater control. Also see g_timeout_add_seconds_full().
4146 * Note that the first call of the timer may not be precise for timeouts
4147 * of one second. If you need finer precision and have such a timeout,
4148 * you may want to use g_timeout_add() instead.
4150 * Return value: the ID (greater than 0) of the event source.
4155 g_timeout_add_seconds (guint interval,
4156 GSourceFunc function,
4159 g_return_val_if_fail (function != NULL, 0);
4161 return g_timeout_add_seconds_full (G_PRIORITY_DEFAULT, interval, function, data, NULL);
4164 /* Child watch functions */
4169 g_child_watch_prepare (GSource *source,
4178 g_child_watch_check (GSource *source)
4180 GChildWatchSource *child_watch_source;
4181 gboolean child_exited;
4183 child_watch_source = (GChildWatchSource *) source;
4185 child_exited = child_watch_source->poll.revents & G_IO_IN;
4192 * Note: We do _not_ check for the special value of STILL_ACTIVE
4193 * since we know that the process has exited and doing so runs into
4194 * problems if the child process "happens to return STILL_ACTIVE(259)"
4195 * as Microsoft's Platform SDK puts it.
4197 if (!GetExitCodeProcess (child_watch_source->pid, &child_status))
4199 gchar *emsg = g_win32_error_message (GetLastError ());
4200 g_warning (G_STRLOC ": GetExitCodeProcess() failed: %s", emsg);
4203 child_watch_source->child_status = -1;
4206 child_watch_source->child_status = child_status;
4209 return child_exited;
4212 #else /* G_OS_WIN32 */
4215 check_for_child_exited (GSource *source)
4217 GChildWatchSource *child_watch_source;
4220 /* protect against another SIGCHLD in the middle of this call */
4221 count = child_watch_count;
4223 child_watch_source = (GChildWatchSource *) source;
4225 if (child_watch_source->child_exited)
4228 if (child_watch_source->count < count)
4232 if (waitpid (child_watch_source->pid, &child_status, WNOHANG) > 0)
4234 child_watch_source->child_status = child_status;
4235 child_watch_source->child_exited = TRUE;
4237 child_watch_source->count = count;
4240 return child_watch_source->child_exited;
4244 g_child_watch_prepare (GSource *source,
4249 return check_for_child_exited (source);
4253 g_child_watch_check (GSource *source)
4255 return check_for_child_exited (source);
4259 check_for_signal_delivery (GSource *source)
4261 GUnixSignalWatchSource *unix_signal_source = (GUnixSignalWatchSource*) source;
4264 G_LOCK (unix_signal_lock);
4265 if (unix_signal_init_state == UNIX_SIGNAL_INITIALIZED_SINGLE)
4267 switch (unix_signal_source->signum)
4270 delivered = unix_signal_state.sighup_delivered;
4273 delivered = unix_signal_state.sigint_delivered;
4276 delivered = unix_signal_state.sigterm_delivered;
4279 g_assert_not_reached ();
4286 g_assert (unix_signal_init_state == UNIX_SIGNAL_INITIALIZED_THREADED);
4287 delivered = unix_signal_source->pending;
4289 G_UNLOCK (unix_signal_lock);
4295 g_unix_signal_watch_prepare (GSource *source,
4300 return check_for_signal_delivery (source);
4304 g_unix_signal_watch_check (GSource *source)
4306 return check_for_signal_delivery (source);
4310 g_unix_signal_watch_dispatch (GSource *source,
4311 GSourceFunc callback,
4314 GUnixSignalWatchSource *unix_signal_source;
4316 unix_signal_source = (GUnixSignalWatchSource *) source;
4320 g_warning ("Unix signal source dispatched without callback\n"
4321 "You must call g_source_set_callback().");
4325 (callback) (user_data);
4327 G_LOCK (unix_signal_lock);
4328 if (unix_signal_init_state == UNIX_SIGNAL_INITIALIZED_SINGLE)
4330 switch (unix_signal_source->signum)
4333 unix_signal_state.sighup_delivered = FALSE;
4336 unix_signal_state.sigint_delivered = FALSE;
4339 unix_signal_state.sigterm_delivered = FALSE;
4345 g_assert (unix_signal_init_state == UNIX_SIGNAL_INITIALIZED_THREADED);
4346 unix_signal_source->pending = FALSE;
4348 G_UNLOCK (unix_signal_lock);
4354 ensure_unix_signal_handler_installed_unlocked (int signum)
4356 struct sigaction action;
4357 GError *error = NULL;
4359 if (unix_signal_init_state == UNIX_SIGNAL_UNINITIALIZED)
4361 sigemptyset (&unix_signal_mask);
4364 if (unix_signal_init_state == UNIX_SIGNAL_UNINITIALIZED
4365 || unix_signal_init_state == UNIX_SIGNAL_INITIALIZED_SINGLE)
4367 if (!g_thread_supported ())
4369 /* There is nothing to do for initializing in the non-threaded
4372 if (unix_signal_init_state == UNIX_SIGNAL_UNINITIALIZED)
4373 unix_signal_init_state = UNIX_SIGNAL_INITIALIZED_SINGLE;
4377 if (!g_unix_open_pipe (unix_signal_wake_up_pipe, FD_CLOEXEC, &error))
4378 g_error ("Cannot create UNIX signal wake up pipe: %s\n", error->message);
4379 g_unix_set_fd_nonblocking (unix_signal_wake_up_pipe[1], TRUE, NULL);
4381 /* We create a helper thread that polls on the wakeup pipe indefinitely */
4382 if (g_thread_create (unix_signal_helper_thread, NULL, FALSE, &error) == NULL)
4383 g_error ("Cannot create a thread to monitor UNIX signals: %s\n", error->message);
4385 unix_signal_init_state = UNIX_SIGNAL_INITIALIZED_THREADED;
4389 if (sigismember (&unix_signal_mask, signum))
4392 sigaddset (&unix_signal_mask, signum);
4394 action.sa_handler = g_unix_signal_handler;
4395 sigemptyset (&action.sa_mask);
4396 action.sa_flags = SA_RESTART | SA_NOCLDSTOP;
4397 sigaction (signum, &action, NULL);
4401 _g_main_create_unix_signal_watch (int signum)
4404 GUnixSignalWatchSource *unix_signal_source;
4406 source = g_source_new (&g_unix_signal_funcs, sizeof (GUnixSignalWatchSource));
4407 unix_signal_source = (GUnixSignalWatchSource *) source;
4409 unix_signal_source->signum = signum;
4410 unix_signal_source->pending = FALSE;
4412 G_LOCK (unix_signal_lock);
4413 ensure_unix_signal_handler_installed_unlocked (signum);
4414 unix_signal_watches = g_slist_prepend (unix_signal_watches, unix_signal_source);
4415 G_UNLOCK (unix_signal_lock);
4421 g_unix_signal_watch_finalize (GSource *source)
4423 G_LOCK (unix_signal_lock);
4424 unix_signal_watches = g_slist_remove (unix_signal_watches, source);
4425 G_UNLOCK (unix_signal_lock);
4428 #endif /* G_OS_WIN32 */
4431 g_child_watch_dispatch (GSource *source,
4432 GSourceFunc callback,
4435 GChildWatchSource *child_watch_source;
4436 GChildWatchFunc child_watch_callback = (GChildWatchFunc) callback;
4438 child_watch_source = (GChildWatchSource *) source;
4442 g_warning ("Child watch source dispatched without callback\n"
4443 "You must call g_source_set_callback().");
4447 (child_watch_callback) (child_watch_source->pid, child_watch_source->child_status, user_data);
4449 /* We never keep a child watch source around as the child is gone */
4456 g_unix_signal_handler (int signum)
4458 if (signum == SIGCHLD)
4459 child_watch_count ++;
4461 if (unix_signal_init_state == UNIX_SIGNAL_INITIALIZED_THREADED)
4467 buf[0] = _UNIX_SIGNAL_PIPE_SIGCHLD_CHAR;
4470 buf[0] = _UNIX_SIGNAL_PIPE_SIGHUP_CHAR;
4473 buf[0] = _UNIX_SIGNAL_PIPE_SIGINT_CHAR;
4476 buf[0] = _UNIX_SIGNAL_PIPE_SIGTERM_CHAR;
4479 /* Shouldn't happen */
4482 write (unix_signal_wake_up_pipe[1], buf, 1);
4486 /* We count on the signal interrupting the poll in the same thread. */
4490 /* Nothing to do - the handler will call waitpid() */
4493 unix_signal_state.sighup_delivered = TRUE;
4496 unix_signal_state.sigint_delivered = TRUE;
4499 unix_signal_state.sigterm_delivered = TRUE;
4502 g_assert_not_reached ();
4509 deliver_unix_signal (int signum)
4512 g_assert (signum == SIGHUP || signum == SIGINT || signum == SIGTERM);
4514 G_LOCK (unix_signal_lock);
4515 for (iter = unix_signal_watches; iter; iter = iter->next)
4517 GUnixSignalWatchSource *source = iter->data;
4519 if (source->signum != signum)
4522 source->pending = TRUE;
4524 G_UNLOCK (unix_signal_lock);
4528 * This thread is created whenever anything in GLib needs
4529 * to deal with UNIX signals; at present, just SIGCHLD
4530 * from g_child_watch_source_new().
4532 * Note: We could eventually make this thread a more public interface
4533 * and allow e.g. GDBus to use it instead of its own worker thread.
4536 unix_signal_helper_thread (gpointer data)
4541 ssize_t i, bytes_read;
4542 gboolean sigterm_received = FALSE;
4543 gboolean sigint_received = FALSE;
4544 gboolean sighup_received = FALSE;
4546 bytes_read = read (unix_signal_wake_up_pipe[0], b, sizeof (b));
4549 g_warning ("Failed to read from child watch wake up pipe: %s",
4551 /* Not much we can do here sanely; just wait a second and hope
4554 g_usleep (G_USEC_PER_SEC);
4557 for (i = 0; i < bytes_read; i++)
4561 case _UNIX_SIGNAL_PIPE_SIGCHLD_CHAR:
4562 /* The child watch source will call waitpid() in its
4563 * prepare() and check() methods; however, we don't
4564 * know which pid exited, so we need to wake up
4565 * all contexts. Note: actually we could get the pid
4566 * from the "siginfo_t" via the handler, but to pass
4567 * that info down the pipe would require a more structured
4568 * data stream (as opposed to a single byte).
4571 case _UNIX_SIGNAL_PIPE_SIGTERM_CHAR:
4572 sigterm_received = TRUE;
4574 case _UNIX_SIGNAL_PIPE_SIGHUP_CHAR:
4575 sighup_received = TRUE;
4577 case _UNIX_SIGNAL_PIPE_SIGINT_CHAR:
4578 sigint_received = TRUE;
4581 g_warning ("Invalid char '%c' read from child watch pipe", b[i]);
4585 if (sigterm_received)
4586 deliver_unix_signal (SIGTERM);
4587 if (sigint_received)
4588 deliver_unix_signal (SIGINT);
4589 if (sighup_received)
4590 deliver_unix_signal (SIGHUP);
4591 _g_main_wake_up_all_contexts ();
4596 g_child_watch_source_init (void)
4598 G_LOCK (unix_signal_lock);
4599 ensure_unix_signal_handler_installed_unlocked (SIGCHLD);
4600 G_UNLOCK (unix_signal_lock);
4603 #endif /* !G_OS_WIN32 */
4606 * g_child_watch_source_new:
4607 * @pid: process to watch. On POSIX the pid of a child process. On
4608 * Windows a handle for a process (which doesn't have to be a child).
4610 * Creates a new child_watch source.
4612 * The source will not initially be associated with any #GMainContext
4613 * and must be added to one with g_source_attach() before it will be
4616 * Note that child watch sources can only be used in conjunction with
4617 * <literal>g_spawn...</literal> when the %G_SPAWN_DO_NOT_REAP_CHILD
4620 * Note that on platforms where #GPid must be explicitly closed
4621 * (see g_spawn_close_pid()) @pid must not be closed while the
4622 * source is still active. Typically, you will want to call
4623 * g_spawn_close_pid() in the callback function for the source.
4625 * Note further that using g_child_watch_source_new() is not
4626 * compatible with calling <literal>waitpid(-1)</literal> in
4627 * the application. Calling waitpid() for individual pids will
4630 * Return value: the newly-created child watch source
4635 g_child_watch_source_new (GPid pid)
4637 GSource *source = g_source_new (&g_child_watch_funcs, sizeof (GChildWatchSource));
4638 GChildWatchSource *child_watch_source = (GChildWatchSource *)source;
4641 child_watch_source->poll.fd = (gintptr) pid;
4642 child_watch_source->poll.events = G_IO_IN;
4644 g_source_add_poll (source, &child_watch_source->poll);
4645 #else /* G_OS_WIN32 */
4646 g_child_watch_source_init ();
4647 #endif /* G_OS_WIN32 */
4649 child_watch_source->pid = pid;
4655 * g_child_watch_add_full:
4656 * @priority: the priority of the idle source. Typically this will be in the
4657 * range between #G_PRIORITY_DEFAULT_IDLE and #G_PRIORITY_HIGH_IDLE.
4658 * @pid: process to watch. On POSIX the pid of a child process. On
4659 * Windows a handle for a process (which doesn't have to be a child).
4660 * @function: function to call
4661 * @data: data to pass to @function
4662 * @notify: function to call when the idle is removed, or %NULL
4664 * Sets a function to be called when the child indicated by @pid
4665 * exits, at the priority @priority.
4667 * If you obtain @pid from g_spawn_async() or g_spawn_async_with_pipes()
4668 * you will need to pass #G_SPAWN_DO_NOT_REAP_CHILD as flag to
4669 * the spawn function for the child watching to work.
4671 * Note that on platforms where #GPid must be explicitly closed
4672 * (see g_spawn_close_pid()) @pid must not be closed while the
4673 * source is still active. Typically, you will want to call
4674 * g_spawn_close_pid() in the callback function for the source.
4676 * GLib supports only a single callback per process id.
4678 * This internally creates a main loop source using
4679 * g_child_watch_source_new() and attaches it to the main loop context
4680 * using g_source_attach(). You can do these steps manually if you
4681 * need greater control.
4683 * Return value: the ID (greater than 0) of the event source.
4685 * Rename to: g_child_watch_add
4689 g_child_watch_add_full (gint priority,
4691 GChildWatchFunc function,
4693 GDestroyNotify notify)
4698 g_return_val_if_fail (function != NULL, 0);
4700 source = g_child_watch_source_new (pid);
4702 if (priority != G_PRIORITY_DEFAULT)
4703 g_source_set_priority (source, priority);
4705 g_source_set_callback (source, (GSourceFunc) function, data, notify);
4706 id = g_source_attach (source, NULL);
4707 g_source_unref (source);
4713 * g_child_watch_add:
4714 * @pid: process id to watch. On POSIX the pid of a child process. On
4715 * Windows a handle for a process (which doesn't have to be a child).
4716 * @function: function to call
4717 * @data: data to pass to @function
4719 * Sets a function to be called when the child indicated by @pid
4720 * exits, at a default priority, #G_PRIORITY_DEFAULT.
4722 * If you obtain @pid from g_spawn_async() or g_spawn_async_with_pipes()
4723 * you will need to pass #G_SPAWN_DO_NOT_REAP_CHILD as flag to
4724 * the spawn function for the child watching to work.
4726 * Note that on platforms where #GPid must be explicitly closed
4727 * (see g_spawn_close_pid()) @pid must not be closed while the
4728 * source is still active. Typically, you will want to call
4729 * g_spawn_close_pid() in the callback function for the source.
4731 * GLib supports only a single callback per process id.
4733 * This internally creates a main loop source using
4734 * g_child_watch_source_new() and attaches it to the main loop context
4735 * using g_source_attach(). You can do these steps manually if you
4736 * need greater control.
4738 * Return value: the ID (greater than 0) of the event source.
4743 g_child_watch_add (GPid pid,
4744 GChildWatchFunc function,
4747 return g_child_watch_add_full (G_PRIORITY_DEFAULT, pid, function, data, NULL);
4751 /* Idle functions */
4754 g_idle_prepare (GSource *source,
4763 g_idle_check (GSource *source)
4769 g_idle_dispatch (GSource *source,
4770 GSourceFunc callback,
4775 g_warning ("Idle source dispatched without callback\n"
4776 "You must call g_source_set_callback().");
4780 return callback (user_data);
4784 * g_idle_source_new:
4786 * Creates a new idle source.
4788 * The source will not initially be associated with any #GMainContext
4789 * and must be added to one with g_source_attach() before it will be
4790 * executed. Note that the default priority for idle sources is
4791 * %G_PRIORITY_DEFAULT_IDLE, as compared to other sources which
4792 * have a default priority of %G_PRIORITY_DEFAULT.
4794 * Return value: the newly-created idle source
4797 g_idle_source_new (void)
4801 source = g_source_new (&g_idle_funcs, sizeof (GSource));
4802 g_source_set_priority (source, G_PRIORITY_DEFAULT_IDLE);
4809 * @priority: the priority of the idle source. Typically this will be in the
4810 * range between #G_PRIORITY_DEFAULT_IDLE and #G_PRIORITY_HIGH_IDLE.
4811 * @function: function to call
4812 * @data: data to pass to @function
4813 * @notify: function to call when the idle is removed, or %NULL
4815 * Adds a function to be called whenever there are no higher priority
4816 * events pending. If the function returns %FALSE it is automatically
4817 * removed from the list of event sources and will not be called again.
4819 * This internally creates a main loop source using g_idle_source_new()
4820 * and attaches it to the main loop context using g_source_attach().
4821 * You can do these steps manually if you need greater control.
4823 * Return value: the ID (greater than 0) of the event source.
4824 * Rename to: g_idle_add
4827 g_idle_add_full (gint priority,
4828 GSourceFunc function,
4830 GDestroyNotify notify)
4835 g_return_val_if_fail (function != NULL, 0);
4837 source = g_idle_source_new ();
4839 if (priority != G_PRIORITY_DEFAULT_IDLE)
4840 g_source_set_priority (source, priority);
4842 g_source_set_callback (source, function, data, notify);
4843 id = g_source_attach (source, NULL);
4844 g_source_unref (source);
4851 * @function: function to call
4852 * @data: data to pass to @function.
4854 * Adds a function to be called whenever there are no higher priority
4855 * events pending to the default main loop. The function is given the
4856 * default idle priority, #G_PRIORITY_DEFAULT_IDLE. If the function
4857 * returns %FALSE it is automatically removed from the list of event
4858 * sources and will not be called again.
4860 * This internally creates a main loop source using g_idle_source_new()
4861 * and attaches it to the main loop context using g_source_attach().
4862 * You can do these steps manually if you need greater control.
4864 * Return value: the ID (greater than 0) of the event source.
4867 g_idle_add (GSourceFunc function,
4870 return g_idle_add_full (G_PRIORITY_DEFAULT_IDLE, function, data, NULL);
4874 * g_idle_remove_by_data:
4875 * @data: the data for the idle source's callback.
4877 * Removes the idle function with the given data.
4879 * Return value: %TRUE if an idle source was found and removed.
4882 g_idle_remove_by_data (gpointer data)
4884 return g_source_remove_by_funcs_user_data (&g_idle_funcs, data);
4888 * g_main_context_invoke:
4889 * @context: a #GMainContext, or %NULL
4890 * @function: function to call
4891 * @data: data to pass to @function
4893 * Invokes a function in such a way that @context is owned during the
4894 * invocation of @function.
4896 * If @context is %NULL then the global default main context — as
4897 * returned by g_main_context_default() — is used.
4899 * If @context is owned by the current thread, @function is called
4900 * directly. Otherwise, if @context is the thread-default main context
4901 * of the current thread and g_main_context_acquire() succeeds, then
4902 * @function is called and g_main_context_release() is called
4905 * In any other case, an idle source is created to call @function and
4906 * that source is attached to @context (presumably to be run in another
4907 * thread). The idle source is attached with #G_PRIORITY_DEFAULT
4908 * priority. If you want a different priority, use
4909 * g_main_context_invoke_full().
4911 * Note that, as with normal idle functions, @function should probably
4912 * return %FALSE. If it returns %TRUE, it will be continuously run in a
4913 * loop (and may prevent this call from returning).
4918 g_main_context_invoke (GMainContext *context,
4919 GSourceFunc function,
4922 g_main_context_invoke_full (context,
4924 function, data, NULL);
4928 * g_main_context_invoke_full:
4929 * @context: a #GMainContext, or %NULL
4930 * @priority: the priority at which to run @function
4931 * @function: function to call
4932 * @data: data to pass to @function
4933 * @notify: a function to call when @data is no longer in use, or %NULL.
4935 * Invokes a function in such a way that @context is owned during the
4936 * invocation of @function.
4938 * This function is the same as g_main_context_invoke() except that it
4939 * lets you specify the priority incase @function ends up being
4940 * scheduled as an idle and also lets you give a #GDestroyNotify for @data.
4942 * @notify should not assume that it is called from any particular
4943 * thread or with any particular context acquired.
4948 g_main_context_invoke_full (GMainContext *context,
4950 GSourceFunc function,
4952 GDestroyNotify notify)
4954 g_return_if_fail (function != NULL);
4957 context = g_main_context_default ();
4959 if (g_main_context_is_owner (context))
4961 while (function (data));
4968 GMainContext *thread_default;
4970 thread_default = g_main_context_get_thread_default ();
4972 if (!thread_default)
4973 thread_default = g_main_context_default ();
4975 if (thread_default == context && g_main_context_acquire (context))
4977 while (function (data));
4979 g_main_context_release (context);
4988 source = g_idle_source_new ();
4989 g_source_set_priority (source, priority);
4990 g_source_set_callback (source, function, data, notify);
4991 g_source_attach (source, context);
4992 g_source_unref (source);