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"
55 #include <sys/types.h>
58 #ifdef HAVE_SYS_TIME_H
60 #endif /* HAVE_SYS_TIME_H */
63 #endif /* HAVE_UNISTD_H */
70 #endif /* G_OS_WIN32 */
73 #include <sys/socket.h>
75 #endif /* G_OS_BEOS */
80 #include "giochannel.h"
84 #include "gstrfuncs.h"
85 #include "gtestutils.h"
86 #include "gthreadprivate.h"
92 #ifdef G_MAIN_POLL_DEBUG
98 * @title: The Main Event Loop
99 * @short_description: manages all available sources of events
101 * The main event loop manages all the available sources of events for
102 * GLib and GTK+ applications. These events can come from any number of
103 * different types of sources such as file descriptors (plain files,
104 * pipes or sockets) and timeouts. New types of event sources can also
105 * be added using g_source_attach().
107 * To allow multiple independent sets of sources to be handled in
108 * different threads, each source is associated with a #GMainContext.
109 * A GMainContext can only be running in a single thread, but
110 * sources can be added to it and removed from it from other threads.
112 * Each event source is assigned a priority. The default priority,
113 * #G_PRIORITY_DEFAULT, is 0. Values less than 0 denote higher priorities.
114 * Values greater than 0 denote lower priorities. Events from high priority
115 * sources are always processed before events from lower priority sources.
117 * Idle functions can also be added, and assigned a priority. These will
118 * be run whenever no events with a higher priority are ready to be processed.
120 * The #GMainLoop data type represents a main event loop. A GMainLoop is
121 * created with g_main_loop_new(). After adding the initial event sources,
122 * g_main_loop_run() is called. This continuously checks for new events from
123 * each of the event sources and dispatches them. Finally, the processing of
124 * an event from one of the sources leads to a call to g_main_loop_quit() to
125 * exit the main loop, and g_main_loop_run() returns.
127 * It is possible to create new instances of #GMainLoop recursively.
128 * This is often used in GTK+ applications when showing modal dialog
129 * boxes. Note that event sources are associated with a particular
130 * #GMainContext, and will be checked and dispatched for all main
131 * loops associated with that GMainContext.
133 * GTK+ contains wrappers of some of these functions, e.g. gtk_main(),
134 * gtk_main_quit() and gtk_events_pending().
136 * <refsect2><title>Creating new source types</title>
137 * <para>One of the unusual features of the #GMainLoop functionality
138 * is that new types of event source can be created and used in
139 * addition to the builtin type of event source. A new event source
140 * type is used for handling GDK events. A new source type is created
141 * by <firstterm>deriving</firstterm> from the #GSource structure.
142 * The derived type of source is represented by a structure that has
143 * the #GSource structure as a first element, and other elements specific
144 * to the new source type. To create an instance of the new source type,
145 * call g_source_new() passing in the size of the derived structure and
146 * a table of functions. These #GSourceFuncs determine the behavior of
147 * the new source type.</para>
148 * <para>New source types basically interact with the main context
149 * in two ways. Their prepare function in #GSourceFuncs can set a timeout
150 * to determine the maximum amount of time that the main loop will sleep
151 * before checking the source again. In addition, or as well, the source
152 * can add file descriptors to the set that the main context checks using
153 * g_source_add_poll().</para>
155 * <refsect2><title>Customizing the main loop iteration</title>
156 * <para>Single iterations of a #GMainContext can be run with
157 * g_main_context_iteration(). In some cases, more detailed control
158 * of exactly how the details of the main loop work is desired, for
159 * instance, when integrating the #GMainLoop with an external main loop.
160 * In such cases, you can call the component functions of
161 * g_main_context_iteration() directly. These functions are
162 * g_main_context_prepare(), g_main_context_query(),
163 * g_main_context_check() and g_main_context_dispatch().</para>
164 * <para>The operation of these functions can best be seen in terms
165 * of a state diagram, as shown in <xref linkend="mainloop-states"/>.</para>
166 * <figure id="mainloop-states"><title>States of a Main Context</title>
167 * <graphic fileref="mainloop-states.gif" format="GIF"></graphic>
174 typedef struct _GTimeoutSource GTimeoutSource;
175 typedef struct _GChildWatchSource GChildWatchSource;
176 typedef struct _GUnixSignalWatchSource GUnixSignalWatchSource;
177 typedef struct _GPollRec GPollRec;
178 typedef struct _GSourceCallback GSourceCallback;
182 G_SOURCE_READY = 1 << G_HOOK_FLAG_USER_SHIFT,
183 G_SOURCE_CAN_RECURSE = 1 << (G_HOOK_FLAG_USER_SHIFT + 1)
186 #ifdef G_THREADS_ENABLED
187 typedef struct _GMainWaiter GMainWaiter;
196 typedef struct _GMainDispatch GMainDispatch;
198 struct _GMainDispatch
201 GSList *dispatching_sources; /* stack of current sources */
204 #ifdef G_MAIN_POLL_DEBUG
205 gboolean _g_main_poll_debug = FALSE;
210 #ifdef G_THREADS_ENABLED
211 /* The following lock is used for both the list of sources
212 * and the list of poll records
223 GPtrArray *pending_dispatches;
224 gint timeout; /* Timeout for current iteration */
227 GSource *source_list;
228 gint in_check_or_prepare;
230 GPollRec *poll_records, *poll_records_tail;
231 guint n_poll_records;
232 GPollFD *cached_poll_array;
233 guint cached_poll_array_size;
235 #ifdef G_THREADS_ENABLED
237 /* this pipe is used to wake up the main loop when a source is added.
239 gint wake_up_pipe[2];
240 #else /* G_OS_WIN32 */
241 HANDLE wake_up_semaphore;
242 #endif /* G_OS_WIN32 */
245 gboolean poll_waiting;
247 /* Flag indicating whether the set of fd's changed during a poll */
248 gboolean poll_changed;
249 #endif /* G_THREADS_ENABLED */
254 gboolean time_is_fresh;
256 gboolean real_time_is_fresh;
259 struct _GSourceCallback
264 GDestroyNotify notify;
269 GMainContext *context;
274 struct _GTimeoutSource
282 struct _GChildWatchSource
289 #else /* G_OS_WIN32 */
291 gboolean child_exited;
292 #endif /* G_OS_WIN32 */
295 struct _GUnixSignalWatchSource
310 struct _GSourcePrivate
312 GSList *child_sources;
313 GSource *parent_source;
316 #ifdef G_THREADS_ENABLED
317 #define LOCK_CONTEXT(context) g_static_mutex_lock (&context->mutex)
318 #define UNLOCK_CONTEXT(context) g_static_mutex_unlock (&context->mutex)
319 #define G_THREAD_SELF g_thread_self ()
321 #define LOCK_CONTEXT(context) (void)0
322 #define UNLOCK_CONTEXT(context) (void)0
323 #define G_THREAD_SELF NULL
326 #define SOURCE_DESTROYED(source) (((source)->flags & G_HOOK_FLAG_ACTIVE) == 0)
327 #define SOURCE_BLOCKED(source) (((source)->flags & G_HOOK_FLAG_IN_CALL) != 0 && \
328 ((source)->flags & G_SOURCE_CAN_RECURSE) == 0)
330 #define SOURCE_UNREF(source, context) \
332 if ((source)->ref_count > 1) \
333 (source)->ref_count--; \
335 g_source_unref_internal ((source), (context), TRUE); \
339 /* Forward declarations */
341 static void g_source_unref_internal (GSource *source,
342 GMainContext *context,
344 static void g_source_destroy_internal (GSource *source,
345 GMainContext *context,
347 static void g_source_set_priority_unlocked (GSource *source,
348 GMainContext *context,
350 static void g_main_context_poll (GMainContext *context,
355 static void g_main_context_add_poll_unlocked (GMainContext *context,
358 static void g_main_context_remove_poll_unlocked (GMainContext *context,
360 static void g_main_context_wakeup_unlocked (GMainContext *context);
362 static void _g_main_wake_up_all_contexts (void);
364 static gboolean g_timeout_prepare (GSource *source,
366 static gboolean g_timeout_check (GSource *source);
367 static gboolean g_timeout_dispatch (GSource *source,
368 GSourceFunc callback,
370 static gboolean g_child_watch_prepare (GSource *source,
372 static gboolean g_child_watch_check (GSource *source);
373 static gboolean g_child_watch_dispatch (GSource *source,
374 GSourceFunc callback,
377 static gpointer unix_signal_helper_thread (gpointer data) G_GNUC_NORETURN;
378 static void g_unix_signal_handler (int signum);
379 static gboolean g_unix_signal_watch_prepare (GSource *source,
381 static gboolean g_unix_signal_watch_check (GSource *source);
382 static gboolean g_unix_signal_watch_dispatch (GSource *source,
383 GSourceFunc callback,
385 static void g_unix_signal_watch_finalize (GSource *source);
387 static gboolean g_idle_prepare (GSource *source,
389 static gboolean g_idle_check (GSource *source);
390 static gboolean g_idle_dispatch (GSource *source,
391 GSourceFunc callback,
394 G_LOCK_DEFINE_STATIC (main_loop);
395 static GMainContext *default_main_context;
396 static GSList *main_contexts_without_pipe = NULL;
400 /* The UNIX signal pipe contains a single byte specifying which
401 * signal was received.
403 #define _UNIX_SIGNAL_PIPE_SIGCHLD_CHAR 'C'
404 #define _UNIX_SIGNAL_PIPE_SIGHUP_CHAR 'H'
405 #define _UNIX_SIGNAL_PIPE_SIGINT_CHAR 'I'
406 #define _UNIX_SIGNAL_PIPE_SIGTERM_CHAR 'T'
407 /* Guards all the data below */
408 G_LOCK_DEFINE_STATIC (unix_signal_lock);
410 UNIX_SIGNAL_UNINITIALIZED = 0,
411 UNIX_SIGNAL_INITIALIZED_SINGLE,
412 UNIX_SIGNAL_INITIALIZED_THREADED
414 static gint unix_signal_init_state = UNIX_SIGNAL_UNINITIALIZED;
416 /* These are only used in the UNIX_SIGNAL_INITIALIZED_SINGLE case */
417 gboolean sighup_delivered : 1;
418 gboolean sigint_delivered : 1;
419 gboolean sigterm_delivered : 1;
421 static sigset_t unix_signal_mask;
422 static UnixSignalState unix_signal_state;
423 static gint unix_signal_wake_up_pipe[2];
424 GSList *unix_signal_watches;
426 /* Not guarded ( FIXME should it be? ) */
427 static gint child_watch_count = 1;
429 static GSourceFuncs g_unix_signal_funcs =
431 g_unix_signal_watch_prepare,
432 g_unix_signal_watch_check,
433 g_unix_signal_watch_dispatch,
434 g_unix_signal_watch_finalize
436 #endif /* !G_OS_WIN32 */
437 G_LOCK_DEFINE_STATIC (main_context_list);
438 static GSList *main_context_list = NULL;
440 GSourceFuncs g_timeout_funcs =
448 GSourceFuncs g_child_watch_funcs =
450 g_child_watch_prepare,
452 g_child_watch_dispatch,
456 GSourceFuncs g_idle_funcs =
465 * g_main_context_ref:
466 * @context: a #GMainContext
468 * Increases the reference count on a #GMainContext object by one.
470 * Returns: the @context that was passed in (since 2.6)
473 g_main_context_ref (GMainContext *context)
475 g_return_val_if_fail (context != NULL, NULL);
476 g_return_val_if_fail (g_atomic_int_get (&context->ref_count) > 0, NULL);
478 g_atomic_int_inc (&context->ref_count);
484 poll_rec_list_free (GMainContext *context,
487 g_slice_free_chain (GPollRec, list, next);
491 * g_main_context_unref:
492 * @context: a #GMainContext
494 * Decreases the reference count on a #GMainContext object by one. If
495 * the result is zero, free the context and free all associated memory.
498 g_main_context_unref (GMainContext *context)
501 g_return_if_fail (context != NULL);
502 g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
504 if (!g_atomic_int_dec_and_test (&context->ref_count))
507 G_LOCK (main_context_list);
508 main_context_list = g_slist_remove (main_context_list, context);
509 G_UNLOCK (main_context_list);
511 source = context->source_list;
514 GSource *next = source->next;
515 g_source_destroy_internal (source, context, FALSE);
519 #ifdef G_THREADS_ENABLED
520 g_static_mutex_free (&context->mutex);
523 g_ptr_array_free (context->pending_dispatches, TRUE);
524 g_free (context->cached_poll_array);
526 poll_rec_list_free (context, context->poll_records);
528 #ifdef G_THREADS_ENABLED
529 if (g_thread_supported())
532 close (context->wake_up_pipe[0]);
533 close (context->wake_up_pipe[1]);
535 CloseHandle (context->wake_up_semaphore);
539 main_contexts_without_pipe = g_slist_remove (main_contexts_without_pipe,
542 if (context->cond != NULL)
543 g_cond_free (context->cond);
549 #ifdef G_THREADS_ENABLED
551 g_main_context_init_pipe (GMainContext *context)
553 GError *error = NULL;
556 if (context->wake_up_pipe[0] != -1)
559 if (!g_unix_open_pipe (context->wake_up_pipe, FD_CLOEXEC, &error))
560 g_error ("Cannot create pipe main loop wake-up: %s", error->message);
562 context->wake_up_rec.fd = context->wake_up_pipe[0];
563 context->wake_up_rec.events = G_IO_IN;
565 if (context->wake_up_semaphore != NULL)
567 context->wake_up_semaphore = CreateSemaphore (NULL, 0, 100, NULL);
568 if (context->wake_up_semaphore == NULL)
569 g_error ("Cannot create wake-up semaphore: %s",
570 g_win32_error_message (GetLastError ()));
571 context->wake_up_rec.fd = (gintptr) context->wake_up_semaphore;
572 context->wake_up_rec.events = G_IO_IN;
574 if (_g_main_poll_debug)
575 g_print ("wake-up semaphore: %p\n", context->wake_up_semaphore);
577 g_main_context_add_poll_unlocked (context, 0, &context->wake_up_rec);
581 _g_main_thread_init (void)
583 GSList *curr = main_contexts_without_pipe;
586 g_main_context_init_pipe ((GMainContext *)curr->data);
589 g_slist_free (main_contexts_without_pipe);
590 main_contexts_without_pipe = NULL;
592 #endif /* G_THREADS_ENABLED */
595 * g_main_context_new:
597 * Creates a new #GMainContext structure.
599 * Return value: the new #GMainContext
602 g_main_context_new (void)
604 GMainContext *context = g_new0 (GMainContext, 1);
606 #ifdef G_MAIN_POLL_DEBUG
608 static gboolean beenhere = FALSE;
612 if (getenv ("G_MAIN_POLL_DEBUG") != NULL)
613 _g_main_poll_debug = TRUE;
619 #ifdef G_THREADS_ENABLED
620 g_static_mutex_init (&context->mutex);
622 context->owner = NULL;
623 context->waiters = NULL;
626 context->wake_up_pipe[0] = -1;
627 context->wake_up_pipe[1] = -1;
629 context->wake_up_semaphore = NULL;
633 context->ref_count = 1;
635 context->next_id = 1;
637 context->source_list = NULL;
639 context->poll_func = g_poll;
641 context->cached_poll_array = NULL;
642 context->cached_poll_array_size = 0;
644 context->pending_dispatches = g_ptr_array_new ();
646 context->time_is_fresh = FALSE;
647 context->real_time_is_fresh = FALSE;
649 #ifdef G_THREADS_ENABLED
650 if (g_thread_supported ())
651 g_main_context_init_pipe (context);
653 main_contexts_without_pipe = g_slist_prepend (main_contexts_without_pipe,
657 G_LOCK (main_context_list);
658 main_context_list = g_slist_append (main_context_list, context);
660 #ifdef G_MAIN_POLL_DEBUG
661 if (_g_main_poll_debug)
662 g_print ("created context=%p\n", context);
665 G_UNLOCK (main_context_list);
671 * g_main_context_default:
673 * Returns the global default main context. This is the main context
674 * used for main loop functions when a main loop is not explicitly
675 * specified, and corresponds to the "main" main loop. See also
676 * g_main_context_get_thread_default().
678 * Return value: the global default main context.
681 g_main_context_default (void)
687 if (!default_main_context)
689 default_main_context = g_main_context_new ();
690 #ifdef G_MAIN_POLL_DEBUG
691 if (_g_main_poll_debug)
692 g_print ("default context=%p\n", default_main_context);
696 G_UNLOCK (main_loop);
698 return default_main_context;
701 static GStaticPrivate thread_context_stack = G_STATIC_PRIVATE_INIT;
704 free_context_stack (gpointer data)
706 GQueue *stack = data;
707 GMainContext *context;
709 while (!g_queue_is_empty (stack))
711 context = g_queue_pop_head (stack);
712 g_main_context_release (context);
714 g_main_context_unref (context);
716 g_queue_free (stack);
720 * g_main_context_push_thread_default:
721 * @context: a #GMainContext, or %NULL for the global default context
723 * Acquires @context and sets it as the thread-default context for the
724 * current thread. This will cause certain asynchronous operations
725 * (such as most <link linkend="gio">gio</link>-based I/O) which are
726 * started in this thread to run under @context and deliver their
727 * results to its main loop, rather than running under the global
728 * default context in the main thread. Note that calling this function
729 * changes the context returned by
730 * g_main_context_get_thread_default(), <emphasis>not</emphasis> the
731 * one returned by g_main_context_default(), so it does not affect the
732 * context used by functions like g_idle_add().
734 * Normally you would call this function shortly after creating a new
735 * thread, passing it a #GMainContext which will be run by a
736 * #GMainLoop in that thread, to set a new default context for all
737 * async operations in that thread. (In this case, you don't need to
738 * ever call g_main_context_pop_thread_default().) In some cases
739 * however, you may want to schedule a single operation in a
740 * non-default context, or temporarily use a non-default context in
741 * the main thread. In that case, you can wrap the call to the
742 * asynchronous operation inside a
743 * g_main_context_push_thread_default() /
744 * g_main_context_pop_thread_default() pair, but it is up to you to
745 * ensure that no other asynchronous operations accidentally get
746 * started while the non-default context is active.
748 * Beware that libraries that predate this function may not correctly
749 * handle being used from a thread with a thread-default context. Eg,
750 * see g_file_supports_thread_contexts().
755 g_main_context_push_thread_default (GMainContext *context)
758 gboolean acquired_context;
760 acquired_context = g_main_context_acquire (context);
761 g_return_if_fail (acquired_context);
763 if (context == g_main_context_default ())
766 g_main_context_ref (context);
768 stack = g_static_private_get (&thread_context_stack);
771 stack = g_queue_new ();
772 g_static_private_set (&thread_context_stack, stack,
776 g_queue_push_head (stack, context);
780 * g_main_context_pop_thread_default:
781 * @context: a #GMainContext object, or %NULL
783 * Pops @context off the thread-default context stack (verifying that
784 * it was on the top of the stack).
789 g_main_context_pop_thread_default (GMainContext *context)
793 if (context == g_main_context_default ())
796 stack = g_static_private_get (&thread_context_stack);
798 g_return_if_fail (stack != NULL);
799 g_return_if_fail (g_queue_peek_head (stack) == context);
801 g_queue_pop_head (stack);
803 g_main_context_release (context);
805 g_main_context_unref (context);
809 * g_main_context_get_thread_default:
811 * Gets the thread-default #GMainContext for this thread. Asynchronous
812 * operations that want to be able to be run in contexts other than
813 * the default one should call this method to get a #GMainContext to
814 * add their #GSource<!-- -->s to. (Note that even in single-threaded
815 * programs applications may sometimes want to temporarily push a
816 * non-default context, so it is not safe to assume that this will
817 * always return %NULL if threads are not initialized.)
819 * Returns: the thread-default #GMainContext, or %NULL if the
820 * thread-default context is the global default context.
825 g_main_context_get_thread_default (void)
829 stack = g_static_private_get (&thread_context_stack);
831 return g_queue_peek_head (stack);
836 /* Hooks for adding to the main loop */
840 * @source_funcs: structure containing functions that implement
841 * the sources behavior.
842 * @struct_size: size of the #GSource structure to create.
844 * Creates a new #GSource structure. The size is specified to
845 * allow creating structures derived from #GSource that contain
846 * additional data. The size passed in must be at least
847 * <literal>sizeof (GSource)</literal>.
849 * The source will not initially be associated with any #GMainContext
850 * and must be added to one with g_source_attach() before it will be
853 * Return value: the newly-created #GSource.
856 g_source_new (GSourceFuncs *source_funcs,
861 g_return_val_if_fail (source_funcs != NULL, NULL);
862 g_return_val_if_fail (struct_size >= sizeof (GSource), NULL);
864 source = (GSource*) g_malloc0 (struct_size);
866 source->source_funcs = source_funcs;
867 source->ref_count = 1;
869 source->priority = G_PRIORITY_DEFAULT;
871 source->flags = G_HOOK_FLAG_ACTIVE;
873 /* NULL/0 initialization for all other fields */
878 /* Holds context's lock
881 g_source_list_add (GSource *source,
882 GMainContext *context)
884 GSource *tmp_source, *last_source;
886 if (source->priv && source->priv->parent_source)
888 /* Put the source immediately before its parent */
889 tmp_source = source->priv->parent_source;
890 last_source = source->priv->parent_source->prev;
895 tmp_source = context->source_list;
896 while (tmp_source && tmp_source->priority <= source->priority)
898 last_source = tmp_source;
899 tmp_source = tmp_source->next;
903 source->next = tmp_source;
905 tmp_source->prev = source;
907 source->prev = last_source;
909 last_source->next = source;
911 context->source_list = source;
914 /* Holds context's lock
917 g_source_list_remove (GSource *source,
918 GMainContext *context)
921 source->prev->next = source->next;
923 context->source_list = source->next;
926 source->next->prev = source->prev;
933 g_source_attach_unlocked (GSource *source,
934 GMainContext *context)
939 source->context = context;
940 result = source->source_id = context->next_id++;
943 g_source_list_add (source, context);
945 tmp_list = source->poll_fds;
948 g_main_context_add_poll_unlocked (context, source->priority, tmp_list->data);
949 tmp_list = tmp_list->next;
954 tmp_list = source->priv->child_sources;
957 g_source_attach_unlocked (tmp_list->data, context);
958 tmp_list = tmp_list->next;
967 * @source: a #GSource
968 * @context: a #GMainContext (if %NULL, the default context will be used)
970 * Adds a #GSource to a @context so that it will be executed within
971 * that context. Remove it by calling g_source_destroy().
973 * Return value: the ID (greater than 0) for the source within the
977 g_source_attach (GSource *source,
978 GMainContext *context)
982 g_return_val_if_fail (source->context == NULL, 0);
983 g_return_val_if_fail (!SOURCE_DESTROYED (source), 0);
986 context = g_main_context_default ();
988 LOCK_CONTEXT (context);
990 result = g_source_attach_unlocked (source, context);
992 #ifdef G_THREADS_ENABLED
993 /* Now wake up the main loop if it is waiting in the poll() */
994 g_main_context_wakeup_unlocked (context);
997 UNLOCK_CONTEXT (context);
1003 g_source_destroy_internal (GSource *source,
1004 GMainContext *context,
1008 LOCK_CONTEXT (context);
1010 if (!SOURCE_DESTROYED (source))
1013 gpointer old_cb_data;
1014 GSourceCallbackFuncs *old_cb_funcs;
1016 source->flags &= ~G_HOOK_FLAG_ACTIVE;
1018 old_cb_data = source->callback_data;
1019 old_cb_funcs = source->callback_funcs;
1021 source->callback_data = NULL;
1022 source->callback_funcs = NULL;
1026 UNLOCK_CONTEXT (context);
1027 old_cb_funcs->unref (old_cb_data);
1028 LOCK_CONTEXT (context);
1031 if (!SOURCE_BLOCKED (source))
1033 tmp_list = source->poll_fds;
1036 g_main_context_remove_poll_unlocked (context, tmp_list->data);
1037 tmp_list = tmp_list->next;
1041 if (source->priv && source->priv->child_sources)
1043 /* This is safe because even if a child_source finalizer or
1044 * closure notify tried to modify source->priv->child_sources
1045 * from outside the lock, it would fail since
1046 * SOURCE_DESTROYED(source) is now TRUE.
1048 tmp_list = source->priv->child_sources;
1051 g_source_destroy_internal (tmp_list->data, context, TRUE);
1052 g_source_unref_internal (tmp_list->data, context, TRUE);
1053 tmp_list = tmp_list->next;
1055 g_slist_free (source->priv->child_sources);
1056 source->priv->child_sources = NULL;
1059 g_source_unref_internal (source, context, TRUE);
1063 UNLOCK_CONTEXT (context);
1068 * @source: a #GSource
1070 * Removes a source from its #GMainContext, if any, and mark it as
1071 * destroyed. The source cannot be subsequently added to another
1075 g_source_destroy (GSource *source)
1077 GMainContext *context;
1079 g_return_if_fail (source != NULL);
1081 context = source->context;
1084 g_source_destroy_internal (source, context, FALSE);
1086 source->flags &= ~G_HOOK_FLAG_ACTIVE;
1091 * @source: a #GSource
1093 * Returns the numeric ID for a particular source. The ID of a source
1094 * is a positive integer which is unique within a particular main loop
1095 * context. The reverse
1096 * mapping from ID to source is done by g_main_context_find_source_by_id().
1098 * Return value: the ID (greater than 0) for the source
1101 g_source_get_id (GSource *source)
1105 g_return_val_if_fail (source != NULL, 0);
1106 g_return_val_if_fail (source->context != NULL, 0);
1108 LOCK_CONTEXT (source->context);
1109 result = source->source_id;
1110 UNLOCK_CONTEXT (source->context);
1116 * g_source_get_context:
1117 * @source: a #GSource
1119 * Gets the #GMainContext with which the source is associated.
1120 * Calling this function on a destroyed source is an error.
1122 * Return value: the #GMainContext with which the source is associated,
1123 * or %NULL if the context has not yet been added
1127 g_source_get_context (GSource *source)
1129 g_return_val_if_fail (!SOURCE_DESTROYED (source), NULL);
1131 return source->context;
1135 * g_source_add_poll:
1136 * @source:a #GSource
1137 * @fd: a #GPollFD structure holding information about a file
1138 * descriptor to watch.
1140 * Adds a file descriptor to the set of file descriptors polled for
1141 * this source. This is usually combined with g_source_new() to add an
1142 * event source. The event source's check function will typically test
1143 * the @revents field in the #GPollFD struct and return %TRUE if events need
1147 g_source_add_poll (GSource *source,
1150 GMainContext *context;
1152 g_return_if_fail (source != NULL);
1153 g_return_if_fail (fd != NULL);
1154 g_return_if_fail (!SOURCE_DESTROYED (source));
1156 context = source->context;
1159 LOCK_CONTEXT (context);
1161 source->poll_fds = g_slist_prepend (source->poll_fds, fd);
1165 if (!SOURCE_BLOCKED (source))
1166 g_main_context_add_poll_unlocked (context, source->priority, fd);
1167 UNLOCK_CONTEXT (context);
1172 * g_source_remove_poll:
1173 * @source:a #GSource
1174 * @fd: a #GPollFD structure previously passed to g_source_add_poll().
1176 * Removes a file descriptor from the set of file descriptors polled for
1180 g_source_remove_poll (GSource *source,
1183 GMainContext *context;
1185 g_return_if_fail (source != NULL);
1186 g_return_if_fail (fd != NULL);
1187 g_return_if_fail (!SOURCE_DESTROYED (source));
1189 context = source->context;
1192 LOCK_CONTEXT (context);
1194 source->poll_fds = g_slist_remove (source->poll_fds, fd);
1198 if (!SOURCE_BLOCKED (source))
1199 g_main_context_remove_poll_unlocked (context, fd);
1200 UNLOCK_CONTEXT (context);
1205 * g_source_add_child_source:
1206 * @source:a #GSource
1207 * @child_source: a second #GSource that @source should "poll"
1209 * Adds @child_source to @source as a "polled" source; when @source is
1210 * added to a #GMainContext, @child_source will be automatically added
1211 * with the same priority, when @child_source is triggered, it will
1212 * cause @source to dispatch (in addition to calling its own
1213 * callback), and when @source is destroyed, it will destroy
1214 * @child_source as well. (@source will also still be dispatched if
1215 * its own prepare/check functions indicate that it is ready.)
1217 * If you don't need @child_source to do anything on its own when it
1218 * triggers, you can call g_source_set_dummy_callback() on it to set a
1219 * callback that does nothing (except return %TRUE if appropriate).
1221 * @source will hold a reference on @child_source while @child_source
1222 * is attached to it.
1227 g_source_add_child_source (GSource *source,
1228 GSource *child_source)
1230 GMainContext *context;
1232 g_return_if_fail (source != NULL);
1233 g_return_if_fail (child_source != NULL);
1234 g_return_if_fail (!SOURCE_DESTROYED (source));
1235 g_return_if_fail (!SOURCE_DESTROYED (child_source));
1236 g_return_if_fail (child_source->context == NULL);
1237 g_return_if_fail (child_source->priv == NULL || child_source->priv->parent_source == NULL);
1239 context = source->context;
1242 LOCK_CONTEXT (context);
1245 source->priv = g_slice_new0 (GSourcePrivate);
1246 if (!child_source->priv)
1247 child_source->priv = g_slice_new0 (GSourcePrivate);
1249 source->priv->child_sources = g_slist_prepend (source->priv->child_sources,
1250 g_source_ref (child_source));
1251 child_source->priv->parent_source = source;
1252 g_source_set_priority_unlocked (child_source, context, source->priority);
1256 UNLOCK_CONTEXT (context);
1257 g_source_attach (child_source, context);
1262 * g_source_remove_child_source:
1263 * @source:a #GSource
1264 * @child_source: a #GSource previously passed to
1265 * g_source_add_child_source().
1267 * Detaches @child_source from @source and destroys it.
1272 g_source_remove_child_source (GSource *source,
1273 GSource *child_source)
1275 GMainContext *context;
1277 g_return_if_fail (source != NULL);
1278 g_return_if_fail (child_source != NULL);
1279 g_return_if_fail (child_source->priv != NULL && child_source->priv->parent_source == source);
1280 g_return_if_fail (!SOURCE_DESTROYED (source));
1281 g_return_if_fail (!SOURCE_DESTROYED (child_source));
1283 context = source->context;
1286 LOCK_CONTEXT (context);
1288 source->priv->child_sources = g_slist_remove (source->priv->child_sources, child_source);
1289 g_source_destroy_internal (child_source, context, TRUE);
1290 g_source_unref_internal (child_source, context, TRUE);
1293 UNLOCK_CONTEXT (context);
1297 * g_source_set_callback_indirect:
1298 * @source: the source
1299 * @callback_data: pointer to callback data "object"
1300 * @callback_funcs: functions for reference counting @callback_data
1301 * and getting the callback and data
1303 * Sets the callback function storing the data as a refcounted callback
1304 * "object". This is used internally. Note that calling
1305 * g_source_set_callback_indirect() assumes
1306 * an initial reference count on @callback_data, and thus
1307 * @callback_funcs->unref will eventually be called once more
1308 * than @callback_funcs->ref.
1311 g_source_set_callback_indirect (GSource *source,
1312 gpointer callback_data,
1313 GSourceCallbackFuncs *callback_funcs)
1315 GMainContext *context;
1316 gpointer old_cb_data;
1317 GSourceCallbackFuncs *old_cb_funcs;
1319 g_return_if_fail (source != NULL);
1320 g_return_if_fail (callback_funcs != NULL || callback_data == NULL);
1322 context = source->context;
1325 LOCK_CONTEXT (context);
1327 old_cb_data = source->callback_data;
1328 old_cb_funcs = source->callback_funcs;
1330 source->callback_data = callback_data;
1331 source->callback_funcs = callback_funcs;
1334 UNLOCK_CONTEXT (context);
1337 old_cb_funcs->unref (old_cb_data);
1341 g_source_callback_ref (gpointer cb_data)
1343 GSourceCallback *callback = cb_data;
1345 callback->ref_count++;
1350 g_source_callback_unref (gpointer cb_data)
1352 GSourceCallback *callback = cb_data;
1354 callback->ref_count--;
1355 if (callback->ref_count == 0)
1357 if (callback->notify)
1358 callback->notify (callback->data);
1364 g_source_callback_get (gpointer cb_data,
1369 GSourceCallback *callback = cb_data;
1371 *func = callback->func;
1372 *data = callback->data;
1375 static GSourceCallbackFuncs g_source_callback_funcs = {
1376 g_source_callback_ref,
1377 g_source_callback_unref,
1378 g_source_callback_get,
1382 * g_source_set_callback:
1383 * @source: the source
1384 * @func: a callback function
1385 * @data: the data to pass to callback function
1386 * @notify: a function to call when @data is no longer in use, or %NULL.
1388 * Sets the callback function for a source. The callback for a source is
1389 * called from the source's dispatch function.
1391 * The exact type of @func depends on the type of source; ie. you
1392 * should not count on @func being called with @data as its first
1395 * Typically, you won't use this function. Instead use functions specific
1396 * to the type of source you are using.
1399 g_source_set_callback (GSource *source,
1402 GDestroyNotify notify)
1404 GSourceCallback *new_callback;
1406 g_return_if_fail (source != NULL);
1408 new_callback = g_new (GSourceCallback, 1);
1410 new_callback->ref_count = 1;
1411 new_callback->func = func;
1412 new_callback->data = data;
1413 new_callback->notify = notify;
1415 g_source_set_callback_indirect (source, new_callback, &g_source_callback_funcs);
1420 * g_source_set_funcs:
1421 * @source: a #GSource
1422 * @funcs: the new #GSourceFuncs
1424 * Sets the source functions (can be used to override
1425 * default implementations) of an unattached source.
1430 g_source_set_funcs (GSource *source,
1431 GSourceFuncs *funcs)
1433 g_return_if_fail (source != NULL);
1434 g_return_if_fail (source->context == NULL);
1435 g_return_if_fail (source->ref_count > 0);
1436 g_return_if_fail (funcs != NULL);
1438 source->source_funcs = funcs;
1442 g_source_set_priority_unlocked (GSource *source,
1443 GMainContext *context,
1448 source->priority = priority;
1452 /* Remove the source from the context's source and then
1453 * add it back so it is sorted in the correct place
1455 g_source_list_remove (source, source->context);
1456 g_source_list_add (source, source->context);
1458 if (!SOURCE_BLOCKED (source))
1460 tmp_list = source->poll_fds;
1463 g_main_context_remove_poll_unlocked (context, tmp_list->data);
1464 g_main_context_add_poll_unlocked (context, priority, tmp_list->data);
1466 tmp_list = tmp_list->next;
1471 if (source->priv && source->priv->child_sources)
1473 tmp_list = source->priv->child_sources;
1476 g_source_set_priority_unlocked (tmp_list->data, context, priority);
1477 tmp_list = tmp_list->next;
1483 * g_source_set_priority:
1484 * @source: a #GSource
1485 * @priority: the new priority.
1487 * Sets the priority of a source. While the main loop is being run, a
1488 * source will be dispatched if it is ready to be dispatched and no
1489 * sources at a higher (numerically smaller) priority are ready to be
1493 g_source_set_priority (GSource *source,
1496 GMainContext *context;
1498 g_return_if_fail (source != NULL);
1500 context = source->context;
1503 LOCK_CONTEXT (context);
1504 g_source_set_priority_unlocked (source, context, priority);
1506 UNLOCK_CONTEXT (source->context);
1510 * g_source_get_priority:
1511 * @source: a #GSource
1513 * Gets the priority of a source.
1515 * Return value: the priority of the source
1518 g_source_get_priority (GSource *source)
1520 g_return_val_if_fail (source != NULL, 0);
1522 return source->priority;
1526 * g_source_set_can_recurse:
1527 * @source: a #GSource
1528 * @can_recurse: whether recursion is allowed for this source
1530 * Sets whether a source can be called recursively. If @can_recurse is
1531 * %TRUE, then while the source is being dispatched then this source
1532 * will be processed normally. Otherwise, all processing of this
1533 * source is blocked until the dispatch function returns.
1536 g_source_set_can_recurse (GSource *source,
1537 gboolean can_recurse)
1539 GMainContext *context;
1541 g_return_if_fail (source != NULL);
1543 context = source->context;
1546 LOCK_CONTEXT (context);
1549 source->flags |= G_SOURCE_CAN_RECURSE;
1551 source->flags &= ~G_SOURCE_CAN_RECURSE;
1554 UNLOCK_CONTEXT (context);
1558 * g_source_get_can_recurse:
1559 * @source: a #GSource
1561 * Checks whether a source is allowed to be called recursively.
1562 * see g_source_set_can_recurse().
1564 * Return value: whether recursion is allowed.
1567 g_source_get_can_recurse (GSource *source)
1569 g_return_val_if_fail (source != NULL, FALSE);
1571 return (source->flags & G_SOURCE_CAN_RECURSE) != 0;
1576 * g_source_set_name:
1577 * @source: a #GSource
1578 * @name: debug name for the source
1580 * Sets a name for the source, used in debugging and profiling.
1581 * The name defaults to #NULL.
1583 * The source name should describe in a human-readable way
1584 * what the source does. For example, "X11 event queue"
1585 * or "GTK+ repaint idle handler" or whatever it is.
1587 * It is permitted to call this function multiple times, but is not
1588 * recommended due to the potential performance impact. For example,
1589 * one could change the name in the "check" function of a #GSourceFuncs
1590 * to include details like the event type in the source name.
1595 g_source_set_name (GSource *source,
1598 g_return_if_fail (source != NULL);
1600 /* setting back to NULL is allowed, just because it's
1601 * weird if get_name can return NULL but you can't
1605 g_free (source->name);
1606 source->name = g_strdup (name);
1610 * g_source_get_name:
1611 * @source: a #GSource
1613 * Gets a name for the source, used in debugging and profiling.
1614 * The name may be #NULL if it has never been set with
1615 * g_source_set_name().
1617 * Return value: the name of the source
1621 g_source_get_name (GSource *source)
1623 g_return_val_if_fail (source != NULL, NULL);
1625 return source->name;
1629 * g_source_set_name_by_id:
1630 * @tag: a #GSource ID
1631 * @name: debug name for the source
1633 * Sets the name of a source using its ID.
1635 * This is a convenience utility to set source names from the return
1636 * value of g_idle_add(), g_timeout_add(), etc.
1641 g_source_set_name_by_id (guint tag,
1646 g_return_if_fail (tag > 0);
1648 source = g_main_context_find_source_by_id (NULL, tag);
1652 g_source_set_name (source, name);
1658 * @source: a #GSource
1660 * Increases the reference count on a source by one.
1662 * Return value: @source
1665 g_source_ref (GSource *source)
1667 GMainContext *context;
1669 g_return_val_if_fail (source != NULL, NULL);
1671 context = source->context;
1674 LOCK_CONTEXT (context);
1676 source->ref_count++;
1679 UNLOCK_CONTEXT (context);
1684 /* g_source_unref() but possible to call within context lock
1687 g_source_unref_internal (GSource *source,
1688 GMainContext *context,
1691 gpointer old_cb_data = NULL;
1692 GSourceCallbackFuncs *old_cb_funcs = NULL;
1694 g_return_if_fail (source != NULL);
1696 if (!have_lock && context)
1697 LOCK_CONTEXT (context);
1699 source->ref_count--;
1700 if (source->ref_count == 0)
1702 old_cb_data = source->callback_data;
1703 old_cb_funcs = source->callback_funcs;
1705 source->callback_data = NULL;
1706 source->callback_funcs = NULL;
1710 if (!SOURCE_DESTROYED (source))
1711 g_warning (G_STRLOC ": ref_count == 0, but source was still attached to a context!");
1712 g_source_list_remove (source, context);
1715 if (source->source_funcs->finalize)
1718 UNLOCK_CONTEXT (context);
1719 source->source_funcs->finalize (source);
1721 LOCK_CONTEXT (context);
1724 g_free (source->name);
1725 source->name = NULL;
1727 g_slist_free (source->poll_fds);
1728 source->poll_fds = NULL;
1732 g_slice_free (GSourcePrivate, source->priv);
1733 source->priv = NULL;
1739 if (!have_lock && context)
1740 UNLOCK_CONTEXT (context);
1745 UNLOCK_CONTEXT (context);
1747 old_cb_funcs->unref (old_cb_data);
1750 LOCK_CONTEXT (context);
1756 * @source: a #GSource
1758 * Decreases the reference count of a source by one. If the
1759 * resulting reference count is zero the source and associated
1760 * memory will be destroyed.
1763 g_source_unref (GSource *source)
1765 g_return_if_fail (source != NULL);
1767 g_source_unref_internal (source, source->context, FALSE);
1771 * g_main_context_find_source_by_id:
1772 * @context: a #GMainContext (if %NULL, the default context will be used)
1773 * @source_id: the source ID, as returned by g_source_get_id().
1775 * Finds a #GSource given a pair of context and ID.
1777 * Return value: the #GSource if found, otherwise, %NULL
1780 g_main_context_find_source_by_id (GMainContext *context,
1785 g_return_val_if_fail (source_id > 0, NULL);
1787 if (context == NULL)
1788 context = g_main_context_default ();
1790 LOCK_CONTEXT (context);
1792 source = context->source_list;
1795 if (!SOURCE_DESTROYED (source) &&
1796 source->source_id == source_id)
1798 source = source->next;
1801 UNLOCK_CONTEXT (context);
1807 * g_main_context_find_source_by_funcs_user_data:
1808 * @context: a #GMainContext (if %NULL, the default context will be used).
1809 * @funcs: the @source_funcs passed to g_source_new().
1810 * @user_data: the user data from the callback.
1812 * Finds a source with the given source functions and user data. If
1813 * multiple sources exist with the same source function and user data,
1814 * the first one found will be returned.
1816 * Return value: the source, if one was found, otherwise %NULL
1819 g_main_context_find_source_by_funcs_user_data (GMainContext *context,
1820 GSourceFuncs *funcs,
1825 g_return_val_if_fail (funcs != NULL, NULL);
1827 if (context == NULL)
1828 context = g_main_context_default ();
1830 LOCK_CONTEXT (context);
1832 source = context->source_list;
1835 if (!SOURCE_DESTROYED (source) &&
1836 source->source_funcs == funcs &&
1837 source->callback_funcs)
1839 GSourceFunc callback;
1840 gpointer callback_data;
1842 source->callback_funcs->get (source->callback_data, source, &callback, &callback_data);
1844 if (callback_data == user_data)
1847 source = source->next;
1850 UNLOCK_CONTEXT (context);
1856 * g_main_context_find_source_by_user_data:
1857 * @context: a #GMainContext
1858 * @user_data: the user_data for the callback.
1860 * Finds a source with the given user data for the callback. If
1861 * multiple sources exist with the same user data, the first
1862 * one found will be returned.
1864 * Return value: the source, if one was found, otherwise %NULL
1867 g_main_context_find_source_by_user_data (GMainContext *context,
1872 if (context == NULL)
1873 context = g_main_context_default ();
1875 LOCK_CONTEXT (context);
1877 source = context->source_list;
1880 if (!SOURCE_DESTROYED (source) &&
1881 source->callback_funcs)
1883 GSourceFunc callback;
1884 gpointer callback_data = NULL;
1886 source->callback_funcs->get (source->callback_data, source, &callback, &callback_data);
1888 if (callback_data == user_data)
1891 source = source->next;
1894 UNLOCK_CONTEXT (context);
1901 * @tag: the ID of the source to remove.
1903 * Removes the source with the given id from the default main context.
1905 * a #GSource is given by g_source_get_id(), or will be returned by the
1906 * functions g_source_attach(), g_idle_add(), g_idle_add_full(),
1907 * g_timeout_add(), g_timeout_add_full(), g_child_watch_add(),
1908 * g_child_watch_add_full(), g_io_add_watch(), and g_io_add_watch_full().
1910 * See also g_source_destroy(). You must use g_source_destroy() for sources
1911 * added to a non-default main context.
1913 * Return value: %TRUE if the source was found and removed.
1916 g_source_remove (guint tag)
1920 g_return_val_if_fail (tag > 0, FALSE);
1922 source = g_main_context_find_source_by_id (NULL, tag);
1924 g_source_destroy (source);
1926 return source != NULL;
1930 * g_source_remove_by_user_data:
1931 * @user_data: the user_data for the callback.
1933 * Removes a source from the default main loop context given the user
1934 * data for the callback. If multiple sources exist with the same user
1935 * data, only one will be destroyed.
1937 * Return value: %TRUE if a source was found and removed.
1940 g_source_remove_by_user_data (gpointer user_data)
1944 source = g_main_context_find_source_by_user_data (NULL, user_data);
1947 g_source_destroy (source);
1955 * g_source_remove_by_funcs_user_data:
1956 * @funcs: The @source_funcs passed to g_source_new()
1957 * @user_data: the user data for the callback
1959 * Removes a source from the default main loop context given the
1960 * source functions and user data. If multiple sources exist with the
1961 * same source functions and user data, only one will be destroyed.
1963 * Return value: %TRUE if a source was found and removed.
1966 g_source_remove_by_funcs_user_data (GSourceFuncs *funcs,
1971 g_return_val_if_fail (funcs != NULL, FALSE);
1973 source = g_main_context_find_source_by_funcs_user_data (NULL, funcs, user_data);
1976 g_source_destroy (source);
1984 * g_get_current_time:
1985 * @result: #GTimeVal structure in which to store current time.
1987 * Equivalent to the UNIX gettimeofday() function, but portable.
1989 * You may find g_get_real_time() to be more convenient.
1992 g_get_current_time (GTimeVal *result)
1997 g_return_if_fail (result != NULL);
1999 /*this is required on alpha, there the timeval structs are int's
2000 not longs and a cast only would fail horribly*/
2001 gettimeofday (&r, NULL);
2002 result->tv_sec = r.tv_sec;
2003 result->tv_usec = r.tv_usec;
2008 g_return_if_fail (result != NULL);
2010 GetSystemTimeAsFileTime (&ft);
2011 memmove (&time64, &ft, sizeof (FILETIME));
2013 /* Convert from 100s of nanoseconds since 1601-01-01
2014 * to Unix epoch. Yes, this is Y2038 unsafe.
2016 time64 -= G_GINT64_CONSTANT (116444736000000000);
2019 result->tv_sec = time64 / 1000000;
2020 result->tv_usec = time64 % 1000000;
2027 * Queries the system wall-clock time.
2029 * This call is functionally equivalent to g_get_current_time() except
2030 * that the return value is often more convenient than dealing with a
2033 * You should only use this call if you are actually interested in the real
2034 * wall-clock time. g_get_monotonic_time() is probably more useful for
2035 * measuring intervals.
2037 * Returns: the number of microseconds since January 1, 1970 UTC.
2042 g_get_real_time (void)
2046 g_get_current_time (&tv);
2048 return (((gint64) tv.tv_sec) * 1000000) + tv.tv_usec;
2052 * g_get_monotonic_time:
2054 * Queries the system monotonic time, if available.
2056 * On POSIX systems with clock_gettime() and %CLOCK_MONOTONIC this call
2057 * is a very shallow wrapper for that. Otherwise, we make a best effort
2058 * that probably involves returning the wall clock time (with at least
2059 * microsecond accuracy, subject to the limitations of the OS kernel).
2061 * Note that, on Windows, "limitations of the OS kernel" is a rather
2062 * substantial statement. Depending on the configuration of the system,
2063 * the wall clock time is updated as infrequently as 64 times a second
2064 * (which is approximately every 16ms).
2066 * Returns: the monotonic time, in microseconds
2071 g_get_monotonic_time (void)
2073 #ifdef HAVE_CLOCK_GETTIME
2074 /* librt clock_gettime() is our first choice */
2076 static int clockid = CLOCK_REALTIME;
2079 #ifdef HAVE_MONOTONIC_CLOCK
2080 /* We have to check if we actually have monotonic clock support.
2082 * There is no thread safety issue here since there is no harm if we
2086 static gboolean checked;
2088 if G_UNLIKELY (!checked)
2090 if (sysconf (_SC_MONOTONIC_CLOCK) >= 0)
2091 clockid = CLOCK_MONOTONIC;
2097 clock_gettime (clockid, &ts);
2099 /* In theory monotonic time can have any epoch.
2101 * glib presently assumes the following:
2103 * 1) The epoch comes some time after the birth of Jesus of Nazareth, but
2104 * not more than 10000 years later.
2106 * 2) The current time also falls sometime within this range.
2108 * These two reasonable assumptions leave us with a maximum deviation from
2109 * the epoch of 10000 years, or 315569520000000000 seconds.
2111 * If we restrict ourselves to this range then the number of microseconds
2112 * will always fit well inside the constraints of a int64 (by a factor of
2115 * If you actually hit the following assertion, probably you should file a
2116 * bug against your operating system for being excessively silly.
2118 g_assert (G_GINT64_CONSTANT (-315569520000000000) < ts.tv_sec &&
2119 ts.tv_sec < G_GINT64_CONSTANT (315569520000000000));
2121 return (((gint64) ts.tv_sec) * 1000000) + (ts.tv_nsec / 1000);
2124 /* It may look like we are discarding accuracy on Windows (since its
2125 * current time is expressed in 100s of nanoseconds) but according to
2126 * many sources, the time is only updated 64 times per second, so
2127 * microsecond accuracy is more than enough.
2132 g_get_current_time (&tv);
2134 return (((gint64) tv.tv_sec) * 1000000) + tv.tv_usec;
2140 g_main_dispatch_free (gpointer dispatch)
2142 g_slice_free (GMainDispatch, dispatch);
2145 /* Running the main loop */
2147 static GMainDispatch *
2150 static GStaticPrivate depth_private = G_STATIC_PRIVATE_INIT;
2151 GMainDispatch *dispatch = g_static_private_get (&depth_private);
2154 dispatch = g_slice_new0 (GMainDispatch);
2155 g_static_private_set (&depth_private, dispatch, g_main_dispatch_free);
2164 * Returns the depth of the stack of calls to
2165 * g_main_context_dispatch() on any #GMainContext in the current thread.
2166 * That is, when called from the toplevel, it gives 0. When
2167 * called from within a callback from g_main_context_iteration()
2168 * (or g_main_loop_run(), etc.) it returns 1. When called from within
2169 * a callback to a recursive call to g_main_context_iteration(),
2170 * it returns 2. And so forth.
2172 * This function is useful in a situation like the following:
2173 * Imagine an extremely simple "garbage collected" system.
2176 * static GList *free_list;
2179 * allocate_memory (gsize size)
2181 * gpointer result = g_malloc (size);
2182 * free_list = g_list_prepend (free_list, result);
2187 * free_allocated_memory (void)
2190 * for (l = free_list; l; l = l->next);
2192 * g_list_free (free_list);
2200 * g_main_context_iteration (NULL, TRUE);
2201 * free_allocated_memory();
2205 * This works from an application, however, if you want to do the same
2206 * thing from a library, it gets more difficult, since you no longer
2207 * control the main loop. You might think you can simply use an idle
2208 * function to make the call to free_allocated_memory(), but that
2209 * doesn't work, since the idle function could be called from a
2210 * recursive callback. This can be fixed by using g_main_depth()
2214 * allocate_memory (gsize size)
2216 * FreeListBlock *block = g_new (FreeListBlock, 1);
2217 * block->mem = g_malloc (size);
2218 * block->depth = g_main_depth ();
2219 * free_list = g_list_prepend (free_list, block);
2220 * return block->mem;
2224 * free_allocated_memory (void)
2228 * int depth = g_main_depth ();
2229 * for (l = free_list; l; );
2231 * GList *next = l->next;
2232 * FreeListBlock *block = l->data;
2233 * if (block->depth > depth)
2235 * g_free (block->mem);
2237 * free_list = g_list_delete_link (free_list, l);
2245 * There is a temptation to use g_main_depth() to solve
2246 * problems with reentrancy. For instance, while waiting for data
2247 * to be received from the network in response to a menu item,
2248 * the menu item might be selected again. It might seem that
2249 * one could make the menu item's callback return immediately
2250 * and do nothing if g_main_depth() returns a value greater than 1.
2251 * However, this should be avoided since the user then sees selecting
2252 * the menu item do nothing. Furthermore, you'll find yourself adding
2253 * these checks all over your code, since there are doubtless many,
2254 * many things that the user could do. Instead, you can use the
2255 * following techniques:
2260 * Use gtk_widget_set_sensitive() or modal dialogs to prevent
2261 * the user from interacting with elements while the main
2262 * loop is recursing.
2267 * Avoid main loop recursion in situations where you can't handle
2268 * arbitrary callbacks. Instead, structure your code so that you
2269 * simply return to the main loop and then get called again when
2270 * there is more work to do.
2275 * Return value: The main loop recursion level in the current thread
2280 GMainDispatch *dispatch = get_dispatch ();
2281 return dispatch->depth;
2285 * g_main_current_source:
2287 * Returns the currently firing source for this thread.
2289 * Return value: The currently firing source or %NULL.
2294 g_main_current_source (void)
2296 GMainDispatch *dispatch = get_dispatch ();
2297 return dispatch->dispatching_sources ? dispatch->dispatching_sources->data : NULL;
2301 * g_source_is_destroyed:
2302 * @source: a #GSource
2304 * Returns whether @source has been destroyed.
2306 * This is important when you operate upon your objects
2307 * from within idle handlers, but may have freed the object
2308 * before the dispatch of your idle handler.
2312 * idle_callback (gpointer data)
2314 * SomeWidget *self = data;
2316 * GDK_THREADS_ENTER (<!-- -->);
2317 * /<!-- -->* do stuff with self *<!-- -->/
2318 * self->idle_id = 0;
2319 * GDK_THREADS_LEAVE (<!-- -->);
2325 * some_widget_do_stuff_later (SomeWidget *self)
2327 * self->idle_id = g_idle_add (idle_callback, self);
2331 * some_widget_finalize (GObject *object)
2333 * SomeWidget *self = SOME_WIDGET (object);
2335 * if (self->idle_id)
2336 * g_source_remove (self->idle_id);
2338 * G_OBJECT_CLASS (parent_class)->finalize (object);
2342 * This will fail in a multi-threaded application if the
2343 * widget is destroyed before the idle handler fires due
2344 * to the use after free in the callback. A solution, to
2345 * this particular problem, is to check to if the source
2346 * has already been destroy within the callback.
2350 * idle_callback (gpointer data)
2352 * SomeWidget *self = data;
2354 * GDK_THREADS_ENTER ();
2355 * if (!g_source_is_destroyed (g_main_current_source ()))
2357 * /<!-- -->* do stuff with self *<!-- -->/
2359 * GDK_THREADS_LEAVE ();
2365 * Return value: %TRUE if the source has been destroyed
2370 g_source_is_destroyed (GSource *source)
2372 return SOURCE_DESTROYED (source);
2375 /* Temporarily remove all this source's file descriptors from the
2376 * poll(), so that if data comes available for one of the file descriptors
2377 * we don't continually spin in the poll()
2379 /* HOLDS: source->context's lock */
2381 block_source (GSource *source)
2385 g_return_if_fail (!SOURCE_BLOCKED (source));
2387 tmp_list = source->poll_fds;
2390 g_main_context_remove_poll_unlocked (source->context, tmp_list->data);
2391 tmp_list = tmp_list->next;
2395 /* HOLDS: source->context's lock */
2397 unblock_source (GSource *source)
2401 g_return_if_fail (!SOURCE_BLOCKED (source)); /* Source already unblocked */
2402 g_return_if_fail (!SOURCE_DESTROYED (source));
2404 tmp_list = source->poll_fds;
2407 g_main_context_add_poll_unlocked (source->context, source->priority, tmp_list->data);
2408 tmp_list = tmp_list->next;
2412 /* HOLDS: context's lock */
2414 g_main_dispatch (GMainContext *context)
2416 GMainDispatch *current = get_dispatch ();
2419 for (i = 0; i < context->pending_dispatches->len; i++)
2421 GSource *source = context->pending_dispatches->pdata[i];
2423 context->pending_dispatches->pdata[i] = NULL;
2426 source->flags &= ~G_SOURCE_READY;
2428 if (!SOURCE_DESTROYED (source))
2430 gboolean was_in_call;
2431 gpointer user_data = NULL;
2432 GSourceFunc callback = NULL;
2433 GSourceCallbackFuncs *cb_funcs;
2435 gboolean need_destroy;
2437 gboolean (*dispatch) (GSource *,
2440 GSList current_source_link;
2442 dispatch = source->source_funcs->dispatch;
2443 cb_funcs = source->callback_funcs;
2444 cb_data = source->callback_data;
2447 cb_funcs->ref (cb_data);
2449 if ((source->flags & G_SOURCE_CAN_RECURSE) == 0)
2450 block_source (source);
2452 was_in_call = source->flags & G_HOOK_FLAG_IN_CALL;
2453 source->flags |= G_HOOK_FLAG_IN_CALL;
2456 cb_funcs->get (cb_data, source, &callback, &user_data);
2458 UNLOCK_CONTEXT (context);
2461 /* The on-stack allocation of the GSList is unconventional, but
2462 * we know that the lifetime of the link is bounded to this
2463 * function as the link is kept in a thread specific list and
2464 * not manipulated outside of this function and its descendants.
2465 * Avoiding the overhead of a g_slist_alloc() is useful as many
2466 * applications do little more than dispatch events.
2468 * This is a performance hack - do not revert to g_slist_prepend()!
2470 current_source_link.data = source;
2471 current_source_link.next = current->dispatching_sources;
2472 current->dispatching_sources = ¤t_source_link;
2473 need_destroy = ! dispatch (source,
2476 g_assert (current->dispatching_sources == ¤t_source_link);
2477 current->dispatching_sources = current_source_link.next;
2481 cb_funcs->unref (cb_data);
2483 LOCK_CONTEXT (context);
2486 source->flags &= ~G_HOOK_FLAG_IN_CALL;
2488 if ((source->flags & G_SOURCE_CAN_RECURSE) == 0 &&
2489 !SOURCE_DESTROYED (source))
2490 unblock_source (source);
2492 /* Note: this depends on the fact that we can't switch
2493 * sources from one main context to another
2495 if (need_destroy && !SOURCE_DESTROYED (source))
2497 g_assert (source->context == context);
2498 g_source_destroy_internal (source, context, TRUE);
2502 SOURCE_UNREF (source, context);
2505 g_ptr_array_set_size (context->pending_dispatches, 0);
2508 /* Holds context's lock */
2509 static inline GSource *
2510 next_valid_source (GMainContext *context,
2513 GSource *new_source = source ? source->next : context->source_list;
2517 if (!SOURCE_DESTROYED (new_source))
2519 new_source->ref_count++;
2523 new_source = new_source->next;
2527 SOURCE_UNREF (source, context);
2533 * g_main_context_acquire:
2534 * @context: a #GMainContext
2536 * Tries to become the owner of the specified context.
2537 * If some other thread is the owner of the context,
2538 * returns %FALSE immediately. Ownership is properly
2539 * recursive: the owner can require ownership again
2540 * and will release ownership when g_main_context_release()
2541 * is called as many times as g_main_context_acquire().
2543 * You must be the owner of a context before you
2544 * can call g_main_context_prepare(), g_main_context_query(),
2545 * g_main_context_check(), g_main_context_dispatch().
2547 * Return value: %TRUE if the operation succeeded, and
2548 * this thread is now the owner of @context.
2551 g_main_context_acquire (GMainContext *context)
2553 #ifdef G_THREADS_ENABLED
2554 gboolean result = FALSE;
2555 GThread *self = G_THREAD_SELF;
2557 if (context == NULL)
2558 context = g_main_context_default ();
2560 LOCK_CONTEXT (context);
2562 if (!context->owner)
2564 context->owner = self;
2565 g_assert (context->owner_count == 0);
2568 if (context->owner == self)
2570 context->owner_count++;
2574 UNLOCK_CONTEXT (context);
2577 #else /* !G_THREADS_ENABLED */
2579 #endif /* G_THREADS_ENABLED */
2583 * g_main_context_release:
2584 * @context: a #GMainContext
2586 * Releases ownership of a context previously acquired by this thread
2587 * with g_main_context_acquire(). If the context was acquired multiple
2588 * times, the ownership will be released only when g_main_context_release()
2589 * is called as many times as it was acquired.
2592 g_main_context_release (GMainContext *context)
2594 #ifdef G_THREADS_ENABLED
2595 if (context == NULL)
2596 context = g_main_context_default ();
2598 LOCK_CONTEXT (context);
2600 context->owner_count--;
2601 if (context->owner_count == 0)
2603 context->owner = NULL;
2605 if (context->waiters)
2607 GMainWaiter *waiter = context->waiters->data;
2608 gboolean loop_internal_waiter =
2609 (waiter->mutex == g_static_mutex_get_mutex (&context->mutex));
2610 context->waiters = g_slist_delete_link (context->waiters,
2612 if (!loop_internal_waiter)
2613 g_mutex_lock (waiter->mutex);
2615 g_cond_signal (waiter->cond);
2617 if (!loop_internal_waiter)
2618 g_mutex_unlock (waiter->mutex);
2622 UNLOCK_CONTEXT (context);
2623 #endif /* G_THREADS_ENABLED */
2627 * g_main_context_wait:
2628 * @context: a #GMainContext
2629 * @cond: a condition variable
2630 * @mutex: a mutex, currently held
2632 * Tries to become the owner of the specified context,
2633 * as with g_main_context_acquire(). But if another thread
2634 * is the owner, atomically drop @mutex and wait on @cond until
2635 * that owner releases ownership or until @cond is signaled, then
2636 * try again (once) to become the owner.
2638 * Return value: %TRUE if the operation succeeded, and
2639 * this thread is now the owner of @context.
2642 g_main_context_wait (GMainContext *context,
2646 #ifdef G_THREADS_ENABLED
2647 gboolean result = FALSE;
2648 GThread *self = G_THREAD_SELF;
2649 gboolean loop_internal_waiter;
2651 if (context == NULL)
2652 context = g_main_context_default ();
2654 loop_internal_waiter = (mutex == g_static_mutex_get_mutex (&context->mutex));
2656 if (!loop_internal_waiter)
2657 LOCK_CONTEXT (context);
2659 if (context->owner && context->owner != self)
2664 waiter.mutex = mutex;
2666 context->waiters = g_slist_append (context->waiters, &waiter);
2668 if (!loop_internal_waiter)
2669 UNLOCK_CONTEXT (context);
2670 g_cond_wait (cond, mutex);
2671 if (!loop_internal_waiter)
2672 LOCK_CONTEXT (context);
2674 context->waiters = g_slist_remove (context->waiters, &waiter);
2677 if (!context->owner)
2679 context->owner = self;
2680 g_assert (context->owner_count == 0);
2683 if (context->owner == self)
2685 context->owner_count++;
2689 if (!loop_internal_waiter)
2690 UNLOCK_CONTEXT (context);
2693 #else /* !G_THREADS_ENABLED */
2695 #endif /* G_THREADS_ENABLED */
2699 * g_main_context_prepare:
2700 * @context: a #GMainContext
2701 * @priority: location to store priority of highest priority
2702 * source already ready.
2704 * Prepares to poll sources within a main loop. The resulting information
2705 * for polling is determined by calling g_main_context_query ().
2707 * Return value: %TRUE if some source is ready to be dispatched
2711 g_main_context_prepare (GMainContext *context,
2716 gint current_priority = G_MAXINT;
2719 if (context == NULL)
2720 context = g_main_context_default ();
2722 LOCK_CONTEXT (context);
2724 context->time_is_fresh = FALSE;
2725 context->real_time_is_fresh = FALSE;
2727 if (context->in_check_or_prepare)
2729 g_warning ("g_main_context_prepare() called recursively from within a source's check() or "
2730 "prepare() member.");
2731 UNLOCK_CONTEXT (context);
2735 #ifdef G_THREADS_ENABLED
2736 if (context->poll_waiting)
2738 g_warning("g_main_context_prepare(): main loop already active in another thread");
2739 UNLOCK_CONTEXT (context);
2743 context->poll_waiting = TRUE;
2744 #endif /* G_THREADS_ENABLED */
2747 /* If recursing, finish up current dispatch, before starting over */
2748 if (context->pending_dispatches)
2751 g_main_dispatch (context, ¤t_time);
2753 UNLOCK_CONTEXT (context);
2758 /* If recursing, clear list of pending dispatches */
2760 for (i = 0; i < context->pending_dispatches->len; i++)
2762 if (context->pending_dispatches->pdata[i])
2763 SOURCE_UNREF ((GSource *)context->pending_dispatches->pdata[i], context);
2765 g_ptr_array_set_size (context->pending_dispatches, 0);
2767 /* Prepare all sources */
2769 context->timeout = -1;
2771 source = next_valid_source (context, NULL);
2774 gint source_timeout = -1;
2776 if ((n_ready > 0) && (source->priority > current_priority))
2778 SOURCE_UNREF (source, context);
2781 if (SOURCE_BLOCKED (source))
2784 if (!(source->flags & G_SOURCE_READY))
2787 gboolean (*prepare) (GSource *source,
2790 prepare = source->source_funcs->prepare;
2791 context->in_check_or_prepare++;
2792 UNLOCK_CONTEXT (context);
2794 result = (*prepare) (source, &source_timeout);
2796 LOCK_CONTEXT (context);
2797 context->in_check_or_prepare--;
2801 GSource *ready_source = source;
2803 while (ready_source)
2805 ready_source->flags |= G_SOURCE_READY;
2806 ready_source = ready_source->priv ? ready_source->priv->parent_source : NULL;
2811 if (source->flags & G_SOURCE_READY)
2814 current_priority = source->priority;
2815 context->timeout = 0;
2818 if (source_timeout >= 0)
2820 if (context->timeout < 0)
2821 context->timeout = source_timeout;
2823 context->timeout = MIN (context->timeout, source_timeout);
2827 source = next_valid_source (context, source);
2830 UNLOCK_CONTEXT (context);
2833 *priority = current_priority;
2835 return (n_ready > 0);
2839 * g_main_context_query:
2840 * @context: a #GMainContext
2841 * @max_priority: maximum priority source to check
2842 * @timeout_: location to store timeout to be used in polling
2843 * @fds: location to store #GPollFD records that need to be polled.
2844 * @n_fds: length of @fds.
2846 * Determines information necessary to poll this main loop.
2848 * Return value: the number of records actually stored in @fds,
2849 * or, if more than @n_fds records need to be stored, the number
2850 * of records that need to be stored.
2853 g_main_context_query (GMainContext *context,
2862 LOCK_CONTEXT (context);
2864 pollrec = context->poll_records;
2866 while (pollrec && max_priority >= pollrec->priority)
2868 /* We need to include entries with fd->events == 0 in the array because
2869 * otherwise if the application changes fd->events behind our back and
2870 * makes it non-zero, we'll be out of sync when we check the fds[] array.
2871 * (Changing fd->events after adding an FD wasn't an anticipated use of
2872 * this API, but it occurs in practice.) */
2875 fds[n_poll].fd = pollrec->fd->fd;
2876 /* In direct contradiction to the Unix98 spec, IRIX runs into
2877 * difficulty if you pass in POLLERR, POLLHUP or POLLNVAL
2878 * flags in the events field of the pollfd while it should
2879 * just ignoring them. So we mask them out here.
2881 fds[n_poll].events = pollrec->fd->events & ~(G_IO_ERR|G_IO_HUP|G_IO_NVAL);
2882 fds[n_poll].revents = 0;
2885 pollrec = pollrec->next;
2889 #ifdef G_THREADS_ENABLED
2890 context->poll_changed = FALSE;
2895 *timeout = context->timeout;
2898 context->time_is_fresh = FALSE;
2899 context->real_time_is_fresh = FALSE;
2903 UNLOCK_CONTEXT (context);
2909 * g_main_context_check:
2910 * @context: a #GMainContext
2911 * @max_priority: the maximum numerical priority of sources to check
2912 * @fds: array of #GPollFD's that was passed to the last call to
2913 * g_main_context_query()
2914 * @n_fds: return value of g_main_context_query()
2916 * Passes the results of polling back to the main loop.
2918 * Return value: %TRUE if some sources are ready to be dispatched.
2921 g_main_context_check (GMainContext *context,
2931 LOCK_CONTEXT (context);
2933 if (context->in_check_or_prepare)
2935 g_warning ("g_main_context_check() called recursively from within a source's check() or "
2936 "prepare() member.");
2937 UNLOCK_CONTEXT (context);
2941 #ifdef G_THREADS_ENABLED
2942 if (!context->poll_waiting)
2946 read (context->wake_up_pipe[0], &a, 1);
2950 context->poll_waiting = FALSE;
2952 /* If the set of poll file descriptors changed, bail out
2953 * and let the main loop rerun
2955 if (context->poll_changed)
2957 UNLOCK_CONTEXT (context);
2960 #endif /* G_THREADS_ENABLED */
2962 pollrec = context->poll_records;
2966 if (pollrec->fd->events)
2967 pollrec->fd->revents = fds[i].revents;
2969 pollrec = pollrec->next;
2973 source = next_valid_source (context, NULL);
2976 if ((n_ready > 0) && (source->priority > max_priority))
2978 SOURCE_UNREF (source, context);
2981 if (SOURCE_BLOCKED (source))
2984 if (!(source->flags & G_SOURCE_READY))
2987 gboolean (*check) (GSource *source);
2989 check = source->source_funcs->check;
2991 context->in_check_or_prepare++;
2992 UNLOCK_CONTEXT (context);
2994 result = (*check) (source);
2996 LOCK_CONTEXT (context);
2997 context->in_check_or_prepare--;
3001 GSource *ready_source = source;
3003 while (ready_source)
3005 ready_source->flags |= G_SOURCE_READY;
3006 ready_source = ready_source->priv ? ready_source->priv->parent_source : NULL;
3011 if (source->flags & G_SOURCE_READY)
3013 source->ref_count++;
3014 g_ptr_array_add (context->pending_dispatches, source);
3018 /* never dispatch sources with less priority than the first
3019 * one we choose to dispatch
3021 max_priority = source->priority;
3025 source = next_valid_source (context, source);
3028 UNLOCK_CONTEXT (context);
3034 * g_main_context_dispatch:
3035 * @context: a #GMainContext
3037 * Dispatches all pending sources.
3040 g_main_context_dispatch (GMainContext *context)
3042 LOCK_CONTEXT (context);
3044 if (context->pending_dispatches->len > 0)
3046 g_main_dispatch (context);
3049 UNLOCK_CONTEXT (context);
3052 /* HOLDS context lock */
3054 g_main_context_iterate (GMainContext *context,
3061 gboolean some_ready;
3062 gint nfds, allocated_nfds;
3063 GPollFD *fds = NULL;
3065 UNLOCK_CONTEXT (context);
3067 #ifdef G_THREADS_ENABLED
3068 if (!g_main_context_acquire (context))
3070 gboolean got_ownership;
3072 LOCK_CONTEXT (context);
3074 g_return_val_if_fail (g_thread_supported (), FALSE);
3080 context->cond = g_cond_new ();
3082 got_ownership = g_main_context_wait (context,
3084 g_static_mutex_get_mutex (&context->mutex));
3090 LOCK_CONTEXT (context);
3091 #endif /* G_THREADS_ENABLED */
3093 if (!context->cached_poll_array)
3095 context->cached_poll_array_size = context->n_poll_records;
3096 context->cached_poll_array = g_new (GPollFD, context->n_poll_records);
3099 allocated_nfds = context->cached_poll_array_size;
3100 fds = context->cached_poll_array;
3102 UNLOCK_CONTEXT (context);
3104 g_main_context_prepare (context, &max_priority);
3106 while ((nfds = g_main_context_query (context, max_priority, &timeout, fds,
3107 allocated_nfds)) > allocated_nfds)
3109 LOCK_CONTEXT (context);
3111 context->cached_poll_array_size = allocated_nfds = nfds;
3112 context->cached_poll_array = fds = g_new (GPollFD, nfds);
3113 UNLOCK_CONTEXT (context);
3119 g_main_context_poll (context, timeout, max_priority, fds, nfds);
3121 some_ready = g_main_context_check (context, max_priority, fds, nfds);
3124 g_main_context_dispatch (context);
3126 #ifdef G_THREADS_ENABLED
3127 g_main_context_release (context);
3128 #endif /* G_THREADS_ENABLED */
3130 LOCK_CONTEXT (context);
3136 * g_main_context_pending:
3137 * @context: a #GMainContext (if %NULL, the default context will be used)
3139 * Checks if any sources have pending events for the given context.
3141 * Return value: %TRUE if events are pending.
3144 g_main_context_pending (GMainContext *context)
3149 context = g_main_context_default();
3151 LOCK_CONTEXT (context);
3152 retval = g_main_context_iterate (context, FALSE, FALSE, G_THREAD_SELF);
3153 UNLOCK_CONTEXT (context);
3159 * g_main_context_iteration:
3160 * @context: a #GMainContext (if %NULL, the default context will be used)
3161 * @may_block: whether the call may block.
3163 * Runs a single iteration for the given main loop. This involves
3164 * checking to see if any event sources are ready to be processed,
3165 * then if no events sources are ready and @may_block is %TRUE, waiting
3166 * for a source to become ready, then dispatching the highest priority
3167 * events sources that are ready. Otherwise, if @may_block is %FALSE
3168 * sources are not waited to become ready, only those highest priority
3169 * events sources will be dispatched (if any), that are ready at this
3170 * given moment without further waiting.
3172 * Note that even when @may_block is %TRUE, it is still possible for
3173 * g_main_context_iteration() to return %FALSE, since the the wait may
3174 * be interrupted for other reasons than an event source becoming ready.
3176 * Return value: %TRUE if events were dispatched.
3179 g_main_context_iteration (GMainContext *context, gboolean may_block)
3184 context = g_main_context_default();
3186 LOCK_CONTEXT (context);
3187 retval = g_main_context_iterate (context, may_block, TRUE, G_THREAD_SELF);
3188 UNLOCK_CONTEXT (context);
3195 * @context: (allow-none): a #GMainContext (if %NULL, the default context will be used).
3196 * @is_running: set to %TRUE to indicate that the loop is running. This
3197 * is not very important since calling g_main_loop_run() will set this to
3200 * Creates a new #GMainLoop structure.
3202 * Return value: a new #GMainLoop.
3205 g_main_loop_new (GMainContext *context,
3206 gboolean is_running)
3211 context = g_main_context_default();
3213 g_main_context_ref (context);
3215 loop = g_new0 (GMainLoop, 1);
3216 loop->context = context;
3217 loop->is_running = is_running != FALSE;
3218 loop->ref_count = 1;
3225 * @loop: a #GMainLoop
3227 * Increases the reference count on a #GMainLoop object by one.
3229 * Return value: @loop
3232 g_main_loop_ref (GMainLoop *loop)
3234 g_return_val_if_fail (loop != NULL, NULL);
3235 g_return_val_if_fail (g_atomic_int_get (&loop->ref_count) > 0, NULL);
3237 g_atomic_int_inc (&loop->ref_count);
3243 * g_main_loop_unref:
3244 * @loop: a #GMainLoop
3246 * Decreases the reference count on a #GMainLoop object by one. If
3247 * the result is zero, free the loop and free all associated memory.
3250 g_main_loop_unref (GMainLoop *loop)
3252 g_return_if_fail (loop != NULL);
3253 g_return_if_fail (g_atomic_int_get (&loop->ref_count) > 0);
3255 if (!g_atomic_int_dec_and_test (&loop->ref_count))
3258 g_main_context_unref (loop->context);
3264 * @loop: a #GMainLoop
3266 * Runs a main loop until g_main_loop_quit() is called on the loop.
3267 * If this is called for the thread of the loop's #GMainContext,
3268 * it will process events from the loop, otherwise it will
3272 g_main_loop_run (GMainLoop *loop)
3274 GThread *self = G_THREAD_SELF;
3276 g_return_if_fail (loop != NULL);
3277 g_return_if_fail (g_atomic_int_get (&loop->ref_count) > 0);
3279 #ifdef G_THREADS_ENABLED
3280 if (!g_main_context_acquire (loop->context))
3282 gboolean got_ownership = FALSE;
3284 /* Another thread owns this context */
3285 if (!g_thread_supported ())
3287 g_warning ("g_main_loop_run() was called from second thread but "
3288 "g_thread_init() was never called.");
3292 LOCK_CONTEXT (loop->context);
3294 g_atomic_int_inc (&loop->ref_count);
3296 if (!loop->is_running)
3297 loop->is_running = TRUE;
3299 if (!loop->context->cond)
3300 loop->context->cond = g_cond_new ();
3302 while (loop->is_running && !got_ownership)
3303 got_ownership = g_main_context_wait (loop->context,
3304 loop->context->cond,
3305 g_static_mutex_get_mutex (&loop->context->mutex));
3307 if (!loop->is_running)
3309 UNLOCK_CONTEXT (loop->context);
3311 g_main_context_release (loop->context);
3312 g_main_loop_unref (loop);
3316 g_assert (got_ownership);
3319 LOCK_CONTEXT (loop->context);
3320 #endif /* G_THREADS_ENABLED */
3322 if (loop->context->in_check_or_prepare)
3324 g_warning ("g_main_loop_run(): called recursively from within a source's "
3325 "check() or prepare() member, iteration not possible.");
3329 g_atomic_int_inc (&loop->ref_count);
3330 loop->is_running = TRUE;
3331 while (loop->is_running)
3332 g_main_context_iterate (loop->context, TRUE, TRUE, self);
3334 UNLOCK_CONTEXT (loop->context);
3336 #ifdef G_THREADS_ENABLED
3337 g_main_context_release (loop->context);
3338 #endif /* G_THREADS_ENABLED */
3340 g_main_loop_unref (loop);
3345 * @loop: a #GMainLoop
3347 * Stops a #GMainLoop from running. Any calls to g_main_loop_run()
3348 * for the loop will return.
3350 * Note that sources that have already been dispatched when
3351 * g_main_loop_quit() is called will still be executed.
3354 g_main_loop_quit (GMainLoop *loop)
3356 g_return_if_fail (loop != NULL);
3357 g_return_if_fail (g_atomic_int_get (&loop->ref_count) > 0);
3359 LOCK_CONTEXT (loop->context);
3360 loop->is_running = FALSE;
3361 g_main_context_wakeup_unlocked (loop->context);
3363 #ifdef G_THREADS_ENABLED
3364 if (loop->context->cond)
3365 g_cond_broadcast (loop->context->cond);
3366 #endif /* G_THREADS_ENABLED */
3368 UNLOCK_CONTEXT (loop->context);
3372 * g_main_loop_is_running:
3373 * @loop: a #GMainLoop.
3375 * Checks to see if the main loop is currently being run via g_main_loop_run().
3377 * Return value: %TRUE if the mainloop is currently being run.
3380 g_main_loop_is_running (GMainLoop *loop)
3382 g_return_val_if_fail (loop != NULL, FALSE);
3383 g_return_val_if_fail (g_atomic_int_get (&loop->ref_count) > 0, FALSE);
3385 return loop->is_running;
3389 * g_main_loop_get_context:
3390 * @loop: a #GMainLoop.
3392 * Returns the #GMainContext of @loop.
3394 * Return value: the #GMainContext of @loop
3397 g_main_loop_get_context (GMainLoop *loop)
3399 g_return_val_if_fail (loop != NULL, NULL);
3400 g_return_val_if_fail (g_atomic_int_get (&loop->ref_count) > 0, NULL);
3402 return loop->context;
3405 /* HOLDS: context's lock */
3407 g_main_context_poll (GMainContext *context,
3413 #ifdef G_MAIN_POLL_DEBUG
3419 GPollFunc poll_func;
3421 if (n_fds || timeout != 0)
3423 #ifdef G_MAIN_POLL_DEBUG
3424 if (_g_main_poll_debug)
3426 g_print ("polling context=%p n=%d timeout=%d\n",
3427 context, n_fds, timeout);
3428 poll_timer = g_timer_new ();
3432 LOCK_CONTEXT (context);
3434 poll_func = context->poll_func;
3436 UNLOCK_CONTEXT (context);
3437 if ((*poll_func) (fds, n_fds, timeout) < 0 && errno != EINTR)
3440 g_warning ("poll(2) failed due to: %s.",
3441 g_strerror (errno));
3443 /* If g_poll () returns -1, it has already called g_warning() */
3447 #ifdef G_MAIN_POLL_DEBUG
3448 if (_g_main_poll_debug)
3450 LOCK_CONTEXT (context);
3452 g_print ("g_main_poll(%d) timeout: %d - elapsed %12.10f seconds",
3455 g_timer_elapsed (poll_timer, NULL));
3456 g_timer_destroy (poll_timer);
3457 pollrec = context->poll_records;
3459 while (pollrec != NULL)
3464 if (fds[i].fd == pollrec->fd->fd &&
3465 pollrec->fd->events &&
3468 g_print (" [" G_POLLFD_FORMAT " :", fds[i].fd);
3469 if (fds[i].revents & G_IO_IN)
3471 if (fds[i].revents & G_IO_OUT)
3473 if (fds[i].revents & G_IO_PRI)
3475 if (fds[i].revents & G_IO_ERR)
3477 if (fds[i].revents & G_IO_HUP)
3479 if (fds[i].revents & G_IO_NVAL)
3485 pollrec = pollrec->next;
3489 UNLOCK_CONTEXT (context);
3492 } /* if (n_fds || timeout != 0) */
3496 * g_main_context_add_poll:
3497 * @context: a #GMainContext (or %NULL for the default context)
3498 * @fd: a #GPollFD structure holding information about a file
3499 * descriptor to watch.
3500 * @priority: the priority for this file descriptor which should be
3501 * the same as the priority used for g_source_attach() to ensure that the
3502 * file descriptor is polled whenever the results may be needed.
3504 * Adds a file descriptor to the set of file descriptors polled for
3505 * this context. This will very seldomly be used directly. Instead
3506 * a typical event source will use g_source_add_poll() instead.
3509 g_main_context_add_poll (GMainContext *context,
3514 context = g_main_context_default ();
3516 g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
3517 g_return_if_fail (fd);
3519 LOCK_CONTEXT (context);
3520 g_main_context_add_poll_unlocked (context, priority, fd);
3521 UNLOCK_CONTEXT (context);
3524 /* HOLDS: main_loop_lock */
3526 g_main_context_add_poll_unlocked (GMainContext *context,
3530 GPollRec *prevrec, *nextrec;
3531 GPollRec *newrec = g_slice_new (GPollRec);
3533 /* This file descriptor may be checked before we ever poll */
3536 newrec->priority = priority;
3538 prevrec = context->poll_records_tail;
3540 while (prevrec && priority < prevrec->priority)
3543 prevrec = prevrec->prev;
3547 prevrec->next = newrec;
3549 context->poll_records = newrec;
3551 newrec->prev = prevrec;
3552 newrec->next = nextrec;
3555 nextrec->prev = newrec;
3557 context->poll_records_tail = newrec;
3559 context->n_poll_records++;
3561 #ifdef G_THREADS_ENABLED
3562 context->poll_changed = TRUE;
3564 /* Now wake up the main loop if it is waiting in the poll() */
3565 g_main_context_wakeup_unlocked (context);
3570 * g_main_context_remove_poll:
3571 * @context:a #GMainContext
3572 * @fd: a #GPollFD descriptor previously added with g_main_context_add_poll()
3574 * Removes file descriptor from the set of file descriptors to be
3575 * polled for a particular context.
3578 g_main_context_remove_poll (GMainContext *context,
3582 context = g_main_context_default ();
3584 g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
3585 g_return_if_fail (fd);
3587 LOCK_CONTEXT (context);
3588 g_main_context_remove_poll_unlocked (context, fd);
3589 UNLOCK_CONTEXT (context);
3593 g_main_context_remove_poll_unlocked (GMainContext *context,
3596 GPollRec *pollrec, *prevrec, *nextrec;
3599 pollrec = context->poll_records;
3603 nextrec = pollrec->next;
3604 if (pollrec->fd == fd)
3606 if (prevrec != NULL)
3607 prevrec->next = nextrec;
3609 context->poll_records = nextrec;
3611 if (nextrec != NULL)
3612 nextrec->prev = prevrec;
3614 context->poll_records_tail = prevrec;
3616 g_slice_free (GPollRec, pollrec);
3618 context->n_poll_records--;
3625 #ifdef G_THREADS_ENABLED
3626 context->poll_changed = TRUE;
3628 /* Now wake up the main loop if it is waiting in the poll() */
3629 g_main_context_wakeup_unlocked (context);
3634 * g_source_get_current_time:
3635 * @source: a #GSource
3636 * @timeval: #GTimeVal structure in which to store current time.
3638 * Gets the "current time" to be used when checking
3639 * this source. The advantage of calling this function over
3640 * calling g_get_current_time() directly is that when
3641 * checking multiple sources, GLib can cache a single value
3642 * instead of having to repeatedly get the system time.
3644 * Deprecated: 2.28: use g_source_get_time() instead
3647 g_source_get_current_time (GSource *source,
3650 GMainContext *context;
3652 g_return_if_fail (source->context != NULL);
3654 context = source->context;
3656 LOCK_CONTEXT (context);
3658 if (!context->real_time_is_fresh)
3660 context->real_time = g_get_real_time ();
3661 context->real_time_is_fresh = TRUE;
3664 timeval->tv_sec = context->real_time / 1000000;
3665 timeval->tv_usec = context->real_time % 1000000;
3667 UNLOCK_CONTEXT (context);
3671 * g_source_get_time:
3672 * @source: a #GSource
3674 * Gets the time to be used when checking this source. The advantage of
3675 * calling this function over calling g_get_monotonic_time() directly is
3676 * that when checking multiple sources, GLib can cache a single value
3677 * instead of having to repeatedly get the system monotonic time.
3679 * The time here is the system monotonic time, if available, or some
3680 * other reasonable alternative otherwise. See g_get_monotonic_time().
3682 * Returns: the monotonic time in microseconds
3687 g_source_get_time (GSource *source)
3689 GMainContext *context;
3692 g_return_val_if_fail (source->context != NULL, 0);
3694 context = source->context;
3696 LOCK_CONTEXT (context);
3698 if (!context->time_is_fresh)
3700 context->time = g_get_monotonic_time ();
3701 context->time_is_fresh = TRUE;
3704 result = context->time;
3706 UNLOCK_CONTEXT (context);
3712 * g_main_context_set_poll_func:
3713 * @context: a #GMainContext
3714 * @func: the function to call to poll all file descriptors
3716 * Sets the function to use to handle polling of file descriptors. It
3717 * will be used instead of the poll() system call
3718 * (or GLib's replacement function, which is used where
3719 * poll() isn't available).
3721 * This function could possibly be used to integrate the GLib event
3722 * loop with an external event loop.
3725 g_main_context_set_poll_func (GMainContext *context,
3729 context = g_main_context_default ();
3731 g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
3733 LOCK_CONTEXT (context);
3736 context->poll_func = func;
3738 context->poll_func = g_poll;
3740 UNLOCK_CONTEXT (context);
3744 * g_main_context_get_poll_func:
3745 * @context: a #GMainContext
3747 * Gets the poll function set by g_main_context_set_poll_func().
3749 * Return value: the poll function
3752 g_main_context_get_poll_func (GMainContext *context)
3757 context = g_main_context_default ();
3759 g_return_val_if_fail (g_atomic_int_get (&context->ref_count) > 0, NULL);
3761 LOCK_CONTEXT (context);
3762 result = context->poll_func;
3763 UNLOCK_CONTEXT (context);
3769 _g_main_wake_up_all_contexts (void)
3773 /* We were woken up. Wake up all other contexts in all other threads */
3774 G_LOCK (main_context_list);
3775 for (list = main_context_list; list; list = list->next)
3777 GMainContext *context;
3779 context = list->data;
3780 if (g_atomic_int_get (&context->ref_count) > 0)
3781 /* Due to racing conditions we can find ref_count == 0, in
3782 * that case, however, the context is still not destroyed
3783 * and no poll can be active, otherwise the ref_count
3786 g_main_context_wakeup (context);
3788 G_UNLOCK (main_context_list);
3792 /* HOLDS: context's lock */
3793 /* Wake the main loop up from a poll() */
3795 g_main_context_wakeup_unlocked (GMainContext *context)
3797 #ifdef G_THREADS_ENABLED
3798 if (g_thread_supported() && context->poll_waiting)
3800 context->poll_waiting = FALSE;
3802 write (context->wake_up_pipe[1], "A", 1);
3804 ReleaseSemaphore (context->wake_up_semaphore, 1, NULL);
3811 * g_main_context_wakeup:
3812 * @context: a #GMainContext
3814 * If @context is currently waiting in a poll(), interrupt
3815 * the poll(), and continue the iteration process.
3818 g_main_context_wakeup (GMainContext *context)
3821 context = g_main_context_default ();
3823 g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
3825 LOCK_CONTEXT (context);
3826 g_main_context_wakeup_unlocked (context);
3827 UNLOCK_CONTEXT (context);
3831 * g_main_context_is_owner:
3832 * @context: a #GMainContext
3834 * Determines whether this thread holds the (recursive)
3835 * ownership of this #GMaincontext. This is useful to
3836 * know before waiting on another thread that may be
3837 * blocking to get ownership of @context.
3839 * Returns: %TRUE if current thread is owner of @context.
3844 g_main_context_is_owner (GMainContext *context)
3849 context = g_main_context_default ();
3851 #ifdef G_THREADS_ENABLED
3852 LOCK_CONTEXT (context);
3853 is_owner = context->owner == G_THREAD_SELF;
3854 UNLOCK_CONTEXT (context);
3865 g_timeout_set_expiration (GTimeoutSource *timeout_source,
3866 gint64 current_time)
3868 timeout_source->expiration = current_time +
3869 (guint64) timeout_source->interval * 1000;
3871 if (timeout_source->seconds)
3874 static gint timer_perturb = -1;
3876 if (timer_perturb == -1)
3879 * we want a per machine/session unique 'random' value; try the dbus
3880 * address first, that has a UUID in it. If there is no dbus, use the
3881 * hostname for hashing.
3883 const char *session_bus_address = g_getenv ("DBUS_SESSION_BUS_ADDRESS");
3884 if (!session_bus_address)
3885 session_bus_address = g_getenv ("HOSTNAME");
3886 if (session_bus_address)
3887 timer_perturb = ABS ((gint) g_str_hash (session_bus_address)) % 1000000;
3892 /* We want the microseconds part of the timeout to land on the
3893 * 'timer_perturb' mark, but we need to make sure we don't try to
3894 * set the timeout in the past. We do this by ensuring that we
3895 * always only *increase* the expiration time by adding a full
3896 * second in the case that the microsecond portion decreases.
3898 timeout_source->expiration -= timer_perturb;
3900 remainder = timeout_source->expiration % 1000000;
3901 if (remainder >= 1000000/4)
3902 timeout_source->expiration += 1000000;
3904 timeout_source->expiration -= remainder;
3905 timeout_source->expiration += timer_perturb;
3910 g_timeout_prepare (GSource *source,
3913 GTimeoutSource *timeout_source = (GTimeoutSource *) source;
3914 gint64 now = g_source_get_time (source);
3916 if (now < timeout_source->expiration)
3918 /* Round up to ensure that we don't try again too early */
3919 *timeout = (timeout_source->expiration - now + 999) / 1000;
3928 g_timeout_check (GSource *source)
3930 GTimeoutSource *timeout_source = (GTimeoutSource *) source;
3931 gint64 now = g_source_get_time (source);
3933 return timeout_source->expiration <= now;
3937 g_timeout_dispatch (GSource *source,
3938 GSourceFunc callback,
3941 GTimeoutSource *timeout_source = (GTimeoutSource *)source;
3946 g_warning ("Timeout source dispatched without callback\n"
3947 "You must call g_source_set_callback().");
3951 again = callback (user_data);
3954 g_timeout_set_expiration (timeout_source, g_source_get_time (source));
3960 * g_timeout_source_new:
3961 * @interval: the timeout interval in milliseconds.
3963 * Creates a new timeout source.
3965 * The source will not initially be associated with any #GMainContext
3966 * and must be added to one with g_source_attach() before it will be
3969 * Return value: the newly-created timeout source
3972 g_timeout_source_new (guint interval)
3974 GSource *source = g_source_new (&g_timeout_funcs, sizeof (GTimeoutSource));
3975 GTimeoutSource *timeout_source = (GTimeoutSource *)source;
3977 timeout_source->interval = interval;
3978 g_timeout_set_expiration (timeout_source, g_get_monotonic_time ());
3984 * g_timeout_source_new_seconds:
3985 * @interval: the timeout interval in seconds
3987 * Creates a new timeout source.
3989 * The source will not initially be associated with any #GMainContext
3990 * and must be added to one with g_source_attach() before it will be
3993 * The scheduling granularity/accuracy of this timeout source will be
3996 * Return value: the newly-created timeout source
4001 g_timeout_source_new_seconds (guint interval)
4003 GSource *source = g_source_new (&g_timeout_funcs, sizeof (GTimeoutSource));
4004 GTimeoutSource *timeout_source = (GTimeoutSource *)source;
4006 timeout_source->interval = 1000 * interval;
4007 timeout_source->seconds = TRUE;
4009 g_timeout_set_expiration (timeout_source, g_get_monotonic_time ());
4016 * g_timeout_add_full:
4017 * @priority: the priority of the timeout source. Typically this will be in
4018 * the range between #G_PRIORITY_DEFAULT and #G_PRIORITY_HIGH.
4019 * @interval: the time between calls to the function, in milliseconds
4020 * (1/1000ths of a second)
4021 * @function: function to call
4022 * @data: data to pass to @function
4023 * @notify: function to call when the timeout is removed, or %NULL
4025 * Sets a function to be called at regular intervals, with the given
4026 * priority. The function is called repeatedly until it returns
4027 * %FALSE, at which point the timeout is automatically destroyed and
4028 * the function will not be called again. The @notify function is
4029 * called when the timeout is destroyed. The first call to the
4030 * function will be at the end of the first @interval.
4032 * Note that timeout functions may be delayed, due to the processing of other
4033 * event sources. Thus they should not be relied on for precise timing.
4034 * After each call to the timeout function, the time of the next
4035 * timeout is recalculated based on the current time and the given interval
4036 * (it does not try to 'catch up' time lost in delays).
4038 * This internally creates a main loop source using g_timeout_source_new()
4039 * and attaches it to the main loop context using g_source_attach(). You can
4040 * do these steps manually if you need greater control.
4042 * Return value: the ID (greater than 0) of the event source.
4043 * Rename to: g_timeout_add
4046 g_timeout_add_full (gint priority,
4048 GSourceFunc function,
4050 GDestroyNotify notify)
4055 g_return_val_if_fail (function != NULL, 0);
4057 source = g_timeout_source_new (interval);
4059 if (priority != G_PRIORITY_DEFAULT)
4060 g_source_set_priority (source, priority);
4062 g_source_set_callback (source, function, data, notify);
4063 id = g_source_attach (source, NULL);
4064 g_source_unref (source);
4071 * @interval: the time between calls to the function, in milliseconds
4072 * (1/1000ths of a second)
4073 * @function: function to call
4074 * @data: data to pass to @function
4076 * Sets a function to be called at regular intervals, with the default
4077 * priority, #G_PRIORITY_DEFAULT. The function is called repeatedly
4078 * until it returns %FALSE, at which point the timeout is automatically
4079 * destroyed and the function will not be called again. The first call
4080 * to the function will be at the end of the first @interval.
4082 * Note that timeout functions may be delayed, due to the processing of other
4083 * event sources. Thus they should not be relied on for precise timing.
4084 * After each call to the timeout function, the time of the next
4085 * timeout is recalculated based on the current time and the given interval
4086 * (it does not try to 'catch up' time lost in delays).
4088 * If you want to have a timer in the "seconds" range and do not care
4089 * about the exact time of the first call of the timer, use the
4090 * g_timeout_add_seconds() function; this function allows for more
4091 * optimizations and more efficient system power usage.
4093 * This internally creates a main loop source using g_timeout_source_new()
4094 * and attaches it to the main loop context using g_source_attach(). You can
4095 * do these steps manually if you need greater control.
4097 * Return value: the ID (greater than 0) of the event source.
4100 g_timeout_add (guint32 interval,
4101 GSourceFunc function,
4104 return g_timeout_add_full (G_PRIORITY_DEFAULT,
4105 interval, function, data, NULL);
4109 * g_timeout_add_seconds_full:
4110 * @priority: the priority of the timeout source. Typically this will be in
4111 * the range between #G_PRIORITY_DEFAULT and #G_PRIORITY_HIGH.
4112 * @interval: the time between calls to the function, in seconds
4113 * @function: function to call
4114 * @data: data to pass to @function
4115 * @notify: function to call when the timeout is removed, or %NULL
4117 * Sets a function to be called at regular intervals, with @priority.
4118 * The function is called repeatedly until it returns %FALSE, at which
4119 * point the timeout is automatically destroyed and the function will
4120 * not be called again.
4122 * Unlike g_timeout_add(), this function operates at whole second granularity.
4123 * The initial starting point of the timer is determined by the implementation
4124 * and the implementation is expected to group multiple timers together so that
4125 * they fire all at the same time.
4126 * To allow this grouping, the @interval to the first timer is rounded
4127 * and can deviate up to one second from the specified interval.
4128 * Subsequent timer iterations will generally run at the specified interval.
4130 * Note that timeout functions may be delayed, due to the processing of other
4131 * event sources. Thus they should not be relied on for precise timing.
4132 * After each call to the timeout function, the time of the next
4133 * timeout is recalculated based on the current time and the given @interval
4135 * If you want timing more precise than whole seconds, use g_timeout_add()
4138 * The grouping of timers to fire at the same time results in a more power
4139 * and CPU efficient behavior so if your timer is in multiples of seconds
4140 * and you don't require the first timer exactly one second from now, the
4141 * use of g_timeout_add_seconds() is preferred over g_timeout_add().
4143 * This internally creates a main loop source using
4144 * g_timeout_source_new_seconds() and attaches it to the main loop context
4145 * using g_source_attach(). You can do these steps manually if you need
4148 * Return value: the ID (greater than 0) of the event source.
4151 * Rename to: g_timeout_add_seconds
4154 g_timeout_add_seconds_full (gint priority,
4156 GSourceFunc function,
4158 GDestroyNotify notify)
4163 g_return_val_if_fail (function != NULL, 0);
4165 source = g_timeout_source_new_seconds (interval);
4167 if (priority != G_PRIORITY_DEFAULT)
4168 g_source_set_priority (source, priority);
4170 g_source_set_callback (source, function, data, notify);
4171 id = g_source_attach (source, NULL);
4172 g_source_unref (source);
4178 * g_timeout_add_seconds:
4179 * @interval: the time between calls to the function, in seconds
4180 * @function: function to call
4181 * @data: data to pass to @function
4183 * Sets a function to be called at regular intervals with the default
4184 * priority, #G_PRIORITY_DEFAULT. The function is called repeatedly until
4185 * it returns %FALSE, at which point the timeout is automatically destroyed
4186 * and the function will not be called again.
4188 * This internally creates a main loop source using
4189 * g_timeout_source_new_seconds() and attaches it to the main loop context
4190 * using g_source_attach(). You can do these steps manually if you need
4191 * greater control. Also see g_timeout_add_seconds_full().
4193 * Note that the first call of the timer may not be precise for timeouts
4194 * of one second. If you need finer precision and have such a timeout,
4195 * you may want to use g_timeout_add() instead.
4197 * Return value: the ID (greater than 0) of the event source.
4202 g_timeout_add_seconds (guint interval,
4203 GSourceFunc function,
4206 g_return_val_if_fail (function != NULL, 0);
4208 return g_timeout_add_seconds_full (G_PRIORITY_DEFAULT, interval, function, data, NULL);
4211 /* Child watch functions */
4216 g_child_watch_prepare (GSource *source,
4225 g_child_watch_check (GSource *source)
4227 GChildWatchSource *child_watch_source;
4228 gboolean child_exited;
4230 child_watch_source = (GChildWatchSource *) source;
4232 child_exited = child_watch_source->poll.revents & G_IO_IN;
4239 * Note: We do _not_ check for the special value of STILL_ACTIVE
4240 * since we know that the process has exited and doing so runs into
4241 * problems if the child process "happens to return STILL_ACTIVE(259)"
4242 * as Microsoft's Platform SDK puts it.
4244 if (!GetExitCodeProcess (child_watch_source->pid, &child_status))
4246 gchar *emsg = g_win32_error_message (GetLastError ());
4247 g_warning (G_STRLOC ": GetExitCodeProcess() failed: %s", emsg);
4250 child_watch_source->child_status = -1;
4253 child_watch_source->child_status = child_status;
4256 return child_exited;
4259 #else /* G_OS_WIN32 */
4262 check_for_child_exited (GSource *source)
4264 GChildWatchSource *child_watch_source;
4267 /* protect against another SIGCHLD in the middle of this call */
4268 count = child_watch_count;
4270 child_watch_source = (GChildWatchSource *) source;
4272 if (child_watch_source->child_exited)
4275 if (child_watch_source->count < count)
4279 if (waitpid (child_watch_source->pid, &child_status, WNOHANG) > 0)
4281 child_watch_source->child_status = child_status;
4282 child_watch_source->child_exited = TRUE;
4284 child_watch_source->count = count;
4287 return child_watch_source->child_exited;
4291 g_child_watch_prepare (GSource *source,
4296 return check_for_child_exited (source);
4300 g_child_watch_check (GSource *source)
4302 return check_for_child_exited (source);
4306 check_for_signal_delivery (GSource *source)
4308 GUnixSignalWatchSource *unix_signal_source = (GUnixSignalWatchSource*) source;
4311 G_LOCK (unix_signal_lock);
4312 if (unix_signal_init_state == UNIX_SIGNAL_INITIALIZED_SINGLE)
4314 switch (unix_signal_source->signum)
4317 delivered = unix_signal_state.sighup_delivered;
4320 delivered = unix_signal_state.sigint_delivered;
4323 delivered = unix_signal_state.sigterm_delivered;
4326 g_assert_not_reached ();
4333 g_assert (unix_signal_init_state == UNIX_SIGNAL_INITIALIZED_THREADED);
4334 delivered = unix_signal_source->pending;
4336 G_UNLOCK (unix_signal_lock);
4342 g_unix_signal_watch_prepare (GSource *source,
4347 return check_for_signal_delivery (source);
4351 g_unix_signal_watch_check (GSource *source)
4353 return check_for_signal_delivery (source);
4357 g_unix_signal_watch_dispatch (GSource *source,
4358 GSourceFunc callback,
4361 GUnixSignalWatchSource *unix_signal_source;
4363 unix_signal_source = (GUnixSignalWatchSource *) source;
4367 g_warning ("Unix signal source dispatched without callback\n"
4368 "You must call g_source_set_callback().");
4372 (callback) (user_data);
4374 G_LOCK (unix_signal_lock);
4375 if (unix_signal_init_state == UNIX_SIGNAL_INITIALIZED_SINGLE)
4377 switch (unix_signal_source->signum)
4380 unix_signal_state.sighup_delivered = FALSE;
4383 unix_signal_state.sigint_delivered = FALSE;
4386 unix_signal_state.sigterm_delivered = FALSE;
4392 g_assert (unix_signal_init_state == UNIX_SIGNAL_INITIALIZED_THREADED);
4393 unix_signal_source->pending = FALSE;
4395 G_UNLOCK (unix_signal_lock);
4401 ensure_unix_signal_handler_installed_unlocked (int signum)
4403 struct sigaction action;
4404 GError *error = NULL;
4406 if (unix_signal_init_state == UNIX_SIGNAL_UNINITIALIZED)
4408 sigemptyset (&unix_signal_mask);
4411 if (unix_signal_init_state == UNIX_SIGNAL_UNINITIALIZED
4412 || unix_signal_init_state == UNIX_SIGNAL_INITIALIZED_SINGLE)
4414 if (!g_thread_supported ())
4416 /* There is nothing to do for initializing in the non-threaded
4419 if (unix_signal_init_state == UNIX_SIGNAL_UNINITIALIZED)
4420 unix_signal_init_state = UNIX_SIGNAL_INITIALIZED_SINGLE;
4424 if (!g_unix_open_pipe (unix_signal_wake_up_pipe, FD_CLOEXEC, &error))
4425 g_error ("Cannot create UNIX signal wake up pipe: %s\n", error->message);
4426 g_unix_set_fd_nonblocking (unix_signal_wake_up_pipe[1], TRUE, NULL);
4428 /* We create a helper thread that polls on the wakeup pipe indefinitely */
4429 if (g_thread_create (unix_signal_helper_thread, NULL, FALSE, &error) == NULL)
4430 g_error ("Cannot create a thread to monitor UNIX signals: %s\n", error->message);
4432 unix_signal_init_state = UNIX_SIGNAL_INITIALIZED_THREADED;
4436 if (sigismember (&unix_signal_mask, signum))
4439 sigaddset (&unix_signal_mask, signum);
4441 action.sa_handler = g_unix_signal_handler;
4442 sigemptyset (&action.sa_mask);
4443 action.sa_flags = SA_RESTART | SA_NOCLDSTOP;
4444 sigaction (signum, &action, NULL);
4448 _g_main_create_unix_signal_watch (int signum)
4451 GUnixSignalWatchSource *unix_signal_source;
4453 source = g_source_new (&g_unix_signal_funcs, sizeof (GUnixSignalWatchSource));
4454 unix_signal_source = (GUnixSignalWatchSource *) source;
4456 unix_signal_source->signum = signum;
4457 unix_signal_source->pending = FALSE;
4459 G_LOCK (unix_signal_lock);
4460 ensure_unix_signal_handler_installed_unlocked (signum);
4461 unix_signal_watches = g_slist_prepend (unix_signal_watches, unix_signal_source);
4462 G_UNLOCK (unix_signal_lock);
4468 g_unix_signal_watch_finalize (GSource *source)
4470 G_LOCK (unix_signal_lock);
4471 unix_signal_watches = g_slist_remove (unix_signal_watches, source);
4472 G_UNLOCK (unix_signal_lock);
4475 #endif /* G_OS_WIN32 */
4478 g_child_watch_dispatch (GSource *source,
4479 GSourceFunc callback,
4482 GChildWatchSource *child_watch_source;
4483 GChildWatchFunc child_watch_callback = (GChildWatchFunc) callback;
4485 child_watch_source = (GChildWatchSource *) source;
4489 g_warning ("Child watch source dispatched without callback\n"
4490 "You must call g_source_set_callback().");
4494 (child_watch_callback) (child_watch_source->pid, child_watch_source->child_status, user_data);
4496 /* We never keep a child watch source around as the child is gone */
4503 g_unix_signal_handler (int signum)
4505 if (signum == SIGCHLD)
4506 child_watch_count ++;
4508 if (unix_signal_init_state == UNIX_SIGNAL_INITIALIZED_THREADED)
4514 buf[0] = _UNIX_SIGNAL_PIPE_SIGCHLD_CHAR;
4517 buf[0] = _UNIX_SIGNAL_PIPE_SIGHUP_CHAR;
4520 buf[0] = _UNIX_SIGNAL_PIPE_SIGINT_CHAR;
4523 buf[0] = _UNIX_SIGNAL_PIPE_SIGTERM_CHAR;
4526 /* Shouldn't happen */
4529 write (unix_signal_wake_up_pipe[1], buf, 1);
4533 /* We count on the signal interrupting the poll in the same thread. */
4537 /* Nothing to do - the handler will call waitpid() */
4540 unix_signal_state.sighup_delivered = TRUE;
4543 unix_signal_state.sigint_delivered = TRUE;
4546 unix_signal_state.sigterm_delivered = TRUE;
4549 g_assert_not_reached ();
4556 deliver_unix_signal (int signum)
4559 g_assert (signum == SIGHUP || signum == SIGINT || signum == SIGTERM);
4561 G_LOCK (unix_signal_lock);
4562 for (iter = unix_signal_watches; iter; iter = iter->next)
4564 GUnixSignalWatchSource *source = iter->data;
4566 if (source->signum != signum)
4569 source->pending = TRUE;
4571 G_UNLOCK (unix_signal_lock);
4575 * This thread is created whenever anything in GLib needs
4576 * to deal with UNIX signals; at present, just SIGCHLD
4577 * from g_child_watch_source_new().
4579 * Note: We could eventually make this thread a more public interface
4580 * and allow e.g. GDBus to use it instead of its own worker thread.
4583 unix_signal_helper_thread (gpointer data)
4588 ssize_t i, bytes_read;
4589 gboolean sigterm_received = FALSE;
4590 gboolean sigint_received = FALSE;
4591 gboolean sighup_received = FALSE;
4593 bytes_read = read (unix_signal_wake_up_pipe[0], b, sizeof (b));
4596 g_warning ("Failed to read from child watch wake up pipe: %s",
4598 /* Not much we can do here sanely; just wait a second and hope
4601 g_usleep (G_USEC_PER_SEC);
4604 for (i = 0; i < bytes_read; i++)
4608 case _UNIX_SIGNAL_PIPE_SIGCHLD_CHAR:
4609 /* The child watch source will call waitpid() in its
4610 * prepare() and check() methods; however, we don't
4611 * know which pid exited, so we need to wake up
4612 * all contexts. Note: actually we could get the pid
4613 * from the "siginfo_t" via the handler, but to pass
4614 * that info down the pipe would require a more structured
4615 * data stream (as opposed to a single byte).
4618 case _UNIX_SIGNAL_PIPE_SIGTERM_CHAR:
4619 sigterm_received = TRUE;
4621 case _UNIX_SIGNAL_PIPE_SIGHUP_CHAR:
4622 sighup_received = TRUE;
4624 case _UNIX_SIGNAL_PIPE_SIGINT_CHAR:
4625 sigint_received = TRUE;
4628 g_warning ("Invalid char '%c' read from child watch pipe", b[i]);
4631 if (sigterm_received)
4632 deliver_unix_signal (SIGTERM);
4633 if (sigint_received)
4634 deliver_unix_signal (SIGINT);
4635 if (sighup_received)
4636 deliver_unix_signal (SIGHUP);
4637 _g_main_wake_up_all_contexts ();
4643 g_child_watch_source_init (void)
4645 G_LOCK (unix_signal_lock);
4646 ensure_unix_signal_handler_installed_unlocked (SIGCHLD);
4647 G_UNLOCK (unix_signal_lock);
4650 #endif /* !G_OS_WIN32 */
4653 * g_child_watch_source_new:
4654 * @pid: process to watch. On POSIX the pid of a child process. On
4655 * Windows a handle for a process (which doesn't have to be a child).
4657 * Creates a new child_watch source.
4659 * The source will not initially be associated with any #GMainContext
4660 * and must be added to one with g_source_attach() before it will be
4663 * Note that child watch sources can only be used in conjunction with
4664 * <literal>g_spawn...</literal> when the %G_SPAWN_DO_NOT_REAP_CHILD
4667 * Note that on platforms where #GPid must be explicitly closed
4668 * (see g_spawn_close_pid()) @pid must not be closed while the
4669 * source is still active. Typically, you will want to call
4670 * g_spawn_close_pid() in the callback function for the source.
4672 * Note further that using g_child_watch_source_new() is not
4673 * compatible with calling <literal>waitpid(-1)</literal> in
4674 * the application. Calling waitpid() for individual pids will
4677 * Return value: the newly-created child watch source
4682 g_child_watch_source_new (GPid pid)
4684 GSource *source = g_source_new (&g_child_watch_funcs, sizeof (GChildWatchSource));
4685 GChildWatchSource *child_watch_source = (GChildWatchSource *)source;
4688 child_watch_source->poll.fd = (gintptr) pid;
4689 child_watch_source->poll.events = G_IO_IN;
4691 g_source_add_poll (source, &child_watch_source->poll);
4692 #else /* G_OS_WIN32 */
4693 g_child_watch_source_init ();
4694 #endif /* G_OS_WIN32 */
4696 child_watch_source->pid = pid;
4702 * g_child_watch_add_full:
4703 * @priority: the priority of the idle source. Typically this will be in the
4704 * range between #G_PRIORITY_DEFAULT_IDLE and #G_PRIORITY_HIGH_IDLE.
4705 * @pid: process to watch. On POSIX the pid of a child process. On
4706 * Windows a handle for a process (which doesn't have to be a child).
4707 * @function: function to call
4708 * @data: data to pass to @function
4709 * @notify: function to call when the idle is removed, or %NULL
4711 * Sets a function to be called when the child indicated by @pid
4712 * exits, at the priority @priority.
4714 * If you obtain @pid from g_spawn_async() or g_spawn_async_with_pipes()
4715 * you will need to pass #G_SPAWN_DO_NOT_REAP_CHILD as flag to
4716 * the spawn function for the child watching to work.
4718 * Note that on platforms where #GPid must be explicitly closed
4719 * (see g_spawn_close_pid()) @pid must not be closed while the
4720 * source is still active. Typically, you will want to call
4721 * g_spawn_close_pid() in the callback function for the source.
4723 * GLib supports only a single callback per process id.
4725 * This internally creates a main loop source using
4726 * g_child_watch_source_new() and attaches it to the main loop context
4727 * using g_source_attach(). You can do these steps manually if you
4728 * need greater control.
4730 * Return value: the ID (greater than 0) of the event source.
4733 * Rename to: g_child_watch_add
4736 g_child_watch_add_full (gint priority,
4738 GChildWatchFunc function,
4740 GDestroyNotify notify)
4745 g_return_val_if_fail (function != NULL, 0);
4747 source = g_child_watch_source_new (pid);
4749 if (priority != G_PRIORITY_DEFAULT)
4750 g_source_set_priority (source, priority);
4752 g_source_set_callback (source, (GSourceFunc) function, data, notify);
4753 id = g_source_attach (source, NULL);
4754 g_source_unref (source);
4760 * g_child_watch_add:
4761 * @pid: process id to watch. On POSIX the pid of a child process. On
4762 * Windows a handle for a process (which doesn't have to be a child).
4763 * @function: function to call
4764 * @data: data to pass to @function
4766 * Sets a function to be called when the child indicated by @pid
4767 * exits, at a default priority, #G_PRIORITY_DEFAULT.
4769 * If you obtain @pid from g_spawn_async() or g_spawn_async_with_pipes()
4770 * you will need to pass #G_SPAWN_DO_NOT_REAP_CHILD as flag to
4771 * the spawn function for the child watching to work.
4773 * Note that on platforms where #GPid must be explicitly closed
4774 * (see g_spawn_close_pid()) @pid must not be closed while the
4775 * source is still active. Typically, you will want to call
4776 * g_spawn_close_pid() in the callback function for the source.
4778 * GLib supports only a single callback per process id.
4780 * This internally creates a main loop source using
4781 * g_child_watch_source_new() and attaches it to the main loop context
4782 * using g_source_attach(). You can do these steps manually if you
4783 * need greater control.
4785 * Return value: the ID (greater than 0) of the event source.
4790 g_child_watch_add (GPid pid,
4791 GChildWatchFunc function,
4794 return g_child_watch_add_full (G_PRIORITY_DEFAULT, pid, function, data, NULL);
4798 /* Idle functions */
4801 g_idle_prepare (GSource *source,
4810 g_idle_check (GSource *source)
4816 g_idle_dispatch (GSource *source,
4817 GSourceFunc callback,
4822 g_warning ("Idle source dispatched without callback\n"
4823 "You must call g_source_set_callback().");
4827 return callback (user_data);
4831 * g_idle_source_new:
4833 * Creates a new idle source.
4835 * The source will not initially be associated with any #GMainContext
4836 * and must be added to one with g_source_attach() before it will be
4837 * executed. Note that the default priority for idle sources is
4838 * %G_PRIORITY_DEFAULT_IDLE, as compared to other sources which
4839 * have a default priority of %G_PRIORITY_DEFAULT.
4841 * Return value: the newly-created idle source
4844 g_idle_source_new (void)
4848 source = g_source_new (&g_idle_funcs, sizeof (GSource));
4849 g_source_set_priority (source, G_PRIORITY_DEFAULT_IDLE);
4856 * @priority: the priority of the idle source. Typically this will be in the
4857 * range between #G_PRIORITY_DEFAULT_IDLE and #G_PRIORITY_HIGH_IDLE.
4858 * @function: function to call
4859 * @data: data to pass to @function
4860 * @notify: function to call when the idle is removed, or %NULL
4862 * Adds a function to be called whenever there are no higher priority
4863 * events pending. If the function returns %FALSE it is automatically
4864 * removed from the list of event sources and will not be called again.
4866 * This internally creates a main loop source using g_idle_source_new()
4867 * and attaches it to the main loop context using g_source_attach().
4868 * You can do these steps manually if you need greater control.
4870 * Return value: the ID (greater than 0) of the event source.
4871 * Rename to: g_idle_add
4874 g_idle_add_full (gint priority,
4875 GSourceFunc function,
4877 GDestroyNotify notify)
4882 g_return_val_if_fail (function != NULL, 0);
4884 source = g_idle_source_new ();
4886 if (priority != G_PRIORITY_DEFAULT_IDLE)
4887 g_source_set_priority (source, priority);
4889 g_source_set_callback (source, function, data, notify);
4890 id = g_source_attach (source, NULL);
4891 g_source_unref (source);
4898 * @function: function to call
4899 * @data: data to pass to @function.
4901 * Adds a function to be called whenever there are no higher priority
4902 * events pending to the default main loop. The function is given the
4903 * default idle priority, #G_PRIORITY_DEFAULT_IDLE. If the function
4904 * returns %FALSE it is automatically removed from the list of event
4905 * sources and will not be called again.
4907 * This internally creates a main loop source using g_idle_source_new()
4908 * and attaches it to the main loop context using g_source_attach().
4909 * You can do these steps manually if you need greater control.
4911 * Return value: the ID (greater than 0) of the event source.
4914 g_idle_add (GSourceFunc function,
4917 return g_idle_add_full (G_PRIORITY_DEFAULT_IDLE, function, data, NULL);
4921 * g_idle_remove_by_data:
4922 * @data: the data for the idle source's callback.
4924 * Removes the idle function with the given data.
4926 * Return value: %TRUE if an idle source was found and removed.
4929 g_idle_remove_by_data (gpointer data)
4931 return g_source_remove_by_funcs_user_data (&g_idle_funcs, data);
4935 * g_main_context_invoke:
4936 * @context: a #GMainContext, or %NULL
4937 * @function: function to call
4938 * @data: data to pass to @function
4940 * Invokes a function in such a way that @context is owned during the
4941 * invocation of @function.
4943 * If @context is %NULL then the global default main context — as
4944 * returned by g_main_context_default() — is used.
4946 * If @context is owned by the current thread, @function is called
4947 * directly. Otherwise, if @context is the thread-default main context
4948 * of the current thread and g_main_context_acquire() succeeds, then
4949 * @function is called and g_main_context_release() is called
4952 * In any other case, an idle source is created to call @function and
4953 * that source is attached to @context (presumably to be run in another
4954 * thread). The idle source is attached with #G_PRIORITY_DEFAULT
4955 * priority. If you want a different priority, use
4956 * g_main_context_invoke_full().
4958 * Note that, as with normal idle functions, @function should probably
4959 * return %FALSE. If it returns %TRUE, it will be continuously run in a
4960 * loop (and may prevent this call from returning).
4965 g_main_context_invoke (GMainContext *context,
4966 GSourceFunc function,
4969 g_main_context_invoke_full (context,
4971 function, data, NULL);
4975 * g_main_context_invoke_full:
4976 * @context: a #GMainContext, or %NULL
4977 * @priority: the priority at which to run @function
4978 * @function: function to call
4979 * @data: data to pass to @function
4980 * @notify: a function to call when @data is no longer in use, or %NULL.
4982 * Invokes a function in such a way that @context is owned during the
4983 * invocation of @function.
4985 * This function is the same as g_main_context_invoke() except that it
4986 * lets you specify the priority incase @function ends up being
4987 * scheduled as an idle and also lets you give a #GDestroyNotify for @data.
4989 * @notify should not assume that it is called from any particular
4990 * thread or with any particular context acquired.
4995 g_main_context_invoke_full (GMainContext *context,
4997 GSourceFunc function,
4999 GDestroyNotify notify)
5001 g_return_if_fail (function != NULL);
5004 context = g_main_context_default ();
5006 if (g_main_context_is_owner (context))
5008 while (function (data));
5015 GMainContext *thread_default;
5017 thread_default = g_main_context_get_thread_default ();
5019 if (!thread_default)
5020 thread_default = g_main_context_default ();
5022 if (thread_default == context && g_main_context_acquire (context))
5024 while (function (data));
5026 g_main_context_release (context);
5035 source = g_idle_source_new ();
5036 g_source_set_priority (source, priority);
5037 g_source_set_callback (source, function, data, notify);
5038 g_source_attach (source, context);
5039 g_source_unref (source);