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;
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
309 struct _GSourcePrivate
311 GSList *child_sources;
312 GSource *parent_source;
315 #ifdef G_THREADS_ENABLED
316 #define LOCK_CONTEXT(context) g_static_mutex_lock (&context->mutex)
317 #define UNLOCK_CONTEXT(context) g_static_mutex_unlock (&context->mutex)
318 #define G_THREAD_SELF g_thread_self ()
320 #define LOCK_CONTEXT(context) (void)0
321 #define UNLOCK_CONTEXT(context) (void)0
322 #define G_THREAD_SELF NULL
325 #define SOURCE_DESTROYED(source) (((source)->flags & G_HOOK_FLAG_ACTIVE) == 0)
326 #define SOURCE_BLOCKED(source) (((source)->flags & G_HOOK_FLAG_IN_CALL) != 0 && \
327 ((source)->flags & G_SOURCE_CAN_RECURSE) == 0)
329 #define SOURCE_UNREF(source, context) \
331 if ((source)->ref_count > 1) \
332 (source)->ref_count--; \
334 g_source_unref_internal ((source), (context), TRUE); \
338 /* Forward declarations */
340 static void g_source_unref_internal (GSource *source,
341 GMainContext *context,
343 static void g_source_destroy_internal (GSource *source,
344 GMainContext *context,
346 static void g_source_set_priority_unlocked (GSource *source,
347 GMainContext *context,
349 static void g_main_context_poll (GMainContext *context,
354 static void g_main_context_add_poll_unlocked (GMainContext *context,
357 static void g_main_context_remove_poll_unlocked (GMainContext *context,
359 static void g_main_context_wakeup_unlocked (GMainContext *context);
361 static void _g_main_wake_up_all_contexts (void);
363 static gboolean g_timeout_prepare (GSource *source,
365 static gboolean g_timeout_check (GSource *source);
366 static gboolean g_timeout_dispatch (GSource *source,
367 GSourceFunc callback,
369 static gboolean g_child_watch_prepare (GSource *source,
371 static gboolean g_child_watch_check (GSource *source);
372 static gboolean g_child_watch_dispatch (GSource *source,
373 GSourceFunc callback,
376 static gpointer unix_signal_helper_thread (gpointer data) G_GNUC_NORETURN;
377 static void g_unix_signal_handler (int signum);
378 static gboolean g_unix_signal_watch_prepare (GSource *source,
380 static gboolean g_unix_signal_watch_check (GSource *source);
381 static gboolean g_unix_signal_watch_dispatch (GSource *source,
382 GSourceFunc callback,
384 static void g_unix_signal_watch_finalize (GSource *source);
386 static gboolean g_idle_prepare (GSource *source,
388 static gboolean g_idle_check (GSource *source);
389 static gboolean g_idle_dispatch (GSource *source,
390 GSourceFunc callback,
393 G_LOCK_DEFINE_STATIC (main_loop);
394 static GMainContext *default_main_context;
395 static GSList *main_contexts_without_pipe = NULL;
399 /* The UNIX signal pipe contains a single byte specifying which
400 * signal was received.
402 #define _UNIX_SIGNAL_PIPE_SIGCHLD_CHAR 'C'
403 #define _UNIX_SIGNAL_PIPE_SIGHUP_CHAR 'H'
404 #define _UNIX_SIGNAL_PIPE_SIGINT_CHAR 'I'
405 #define _UNIX_SIGNAL_PIPE_SIGTERM_CHAR 'T'
406 /* Guards all the data below */
407 G_LOCK_DEFINE_STATIC (unix_signal_lock);
409 UNIX_SIGNAL_UNINITIALIZED = 0,
410 UNIX_SIGNAL_INITIALIZED_SINGLE,
411 UNIX_SIGNAL_INITIALIZED_THREADED
413 static gint unix_signal_init_state = UNIX_SIGNAL_UNINITIALIZED;
415 gboolean sigchld_handler_installed : 1;
416 gboolean sighup_handler_installed : 1;
417 gboolean sigint_handler_installed : 1;
418 gboolean sigterm_handler_installed : 1;
420 /* These are only used in the UNIX_SIGNAL_INITIALIZED_SINGLE case */
421 gboolean sighup_delivered : 1;
422 gboolean sigint_delivered : 1;
423 gboolean sigterm_delivered : 1;
425 static UnixSignalState unix_signal_state;
426 static gint unix_signal_wake_up_pipe[2];
427 GSList *unix_signal_watches;
429 /* Not guarded ( FIXME should it be? ) */
430 static gint child_watch_count = 1;
432 static GSourceFuncs g_unix_signal_funcs =
434 g_unix_signal_watch_prepare,
435 g_unix_signal_watch_check,
436 g_unix_signal_watch_dispatch,
437 g_unix_signal_watch_finalize
439 #endif /* !G_OS_WIN32 */
440 G_LOCK_DEFINE_STATIC (main_context_list);
441 static GSList *main_context_list = NULL;
443 GSourceFuncs g_timeout_funcs =
451 GSourceFuncs g_child_watch_funcs =
453 g_child_watch_prepare,
455 g_child_watch_dispatch,
459 GSourceFuncs g_idle_funcs =
468 * g_main_context_ref:
469 * @context: a #GMainContext
471 * Increases the reference count on a #GMainContext object by one.
473 * Returns: the @context that was passed in (since 2.6)
476 g_main_context_ref (GMainContext *context)
478 g_return_val_if_fail (context != NULL, NULL);
479 g_return_val_if_fail (g_atomic_int_get (&context->ref_count) > 0, NULL);
481 g_atomic_int_inc (&context->ref_count);
487 poll_rec_list_free (GMainContext *context,
490 g_slice_free_chain (GPollRec, list, next);
494 * g_main_context_unref:
495 * @context: a #GMainContext
497 * Decreases the reference count on a #GMainContext object by one. If
498 * the result is zero, free the context and free all associated memory.
501 g_main_context_unref (GMainContext *context)
504 g_return_if_fail (context != NULL);
505 g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
507 if (!g_atomic_int_dec_and_test (&context->ref_count))
510 G_LOCK (main_context_list);
511 main_context_list = g_slist_remove (main_context_list, context);
512 G_UNLOCK (main_context_list);
514 source = context->source_list;
517 GSource *next = source->next;
518 g_source_destroy_internal (source, context, FALSE);
522 #ifdef G_THREADS_ENABLED
523 g_static_mutex_free (&context->mutex);
526 g_ptr_array_free (context->pending_dispatches, TRUE);
527 g_free (context->cached_poll_array);
529 poll_rec_list_free (context, context->poll_records);
531 #ifdef G_THREADS_ENABLED
532 if (g_thread_supported())
535 close (context->wake_up_pipe[0]);
536 close (context->wake_up_pipe[1]);
538 CloseHandle (context->wake_up_semaphore);
542 main_contexts_without_pipe = g_slist_remove (main_contexts_without_pipe,
545 if (context->cond != NULL)
546 g_cond_free (context->cond);
552 #ifdef G_THREADS_ENABLED
554 g_main_context_init_pipe (GMainContext *context)
556 GError *error = NULL;
559 if (context->wake_up_pipe[0] != -1)
562 if (!g_unix_open_pipe (context->wake_up_pipe, FD_CLOEXEC, &error))
563 g_error ("Cannot create pipe main loop wake-up: %s", error->message);
565 context->wake_up_rec.fd = context->wake_up_pipe[0];
566 context->wake_up_rec.events = G_IO_IN;
568 if (context->wake_up_semaphore != NULL)
570 context->wake_up_semaphore = CreateSemaphore (NULL, 0, 100, NULL);
571 if (context->wake_up_semaphore == NULL)
572 g_error ("Cannot create wake-up semaphore: %s",
573 g_win32_error_message (GetLastError ()));
574 context->wake_up_rec.fd = (gintptr) context->wake_up_semaphore;
575 context->wake_up_rec.events = G_IO_IN;
577 if (_g_main_poll_debug)
578 g_print ("wake-up semaphore: %p\n", context->wake_up_semaphore);
580 g_main_context_add_poll_unlocked (context, 0, &context->wake_up_rec);
584 _g_main_thread_init (void)
586 GSList *curr = main_contexts_without_pipe;
589 g_main_context_init_pipe ((GMainContext *)curr->data);
592 g_slist_free (main_contexts_without_pipe);
593 main_contexts_without_pipe = NULL;
595 #endif /* G_THREADS_ENABLED */
598 * g_main_context_new:
600 * Creates a new #GMainContext structure.
602 * Return value: the new #GMainContext
605 g_main_context_new (void)
607 GMainContext *context = g_new0 (GMainContext, 1);
609 #ifdef G_MAIN_POLL_DEBUG
611 static gboolean beenhere = FALSE;
615 if (getenv ("G_MAIN_POLL_DEBUG") != NULL)
616 _g_main_poll_debug = TRUE;
622 #ifdef G_THREADS_ENABLED
623 g_static_mutex_init (&context->mutex);
625 context->owner = NULL;
626 context->waiters = NULL;
629 context->wake_up_pipe[0] = -1;
630 context->wake_up_pipe[1] = -1;
632 context->wake_up_semaphore = NULL;
636 context->ref_count = 1;
638 context->next_id = 1;
640 context->source_list = NULL;
642 context->poll_func = g_poll;
644 context->cached_poll_array = NULL;
645 context->cached_poll_array_size = 0;
647 context->pending_dispatches = g_ptr_array_new ();
649 context->time_is_fresh = FALSE;
650 context->real_time_is_fresh = FALSE;
652 #ifdef G_THREADS_ENABLED
653 if (g_thread_supported ())
654 g_main_context_init_pipe (context);
656 main_contexts_without_pipe = g_slist_prepend (main_contexts_without_pipe,
660 G_LOCK (main_context_list);
661 main_context_list = g_slist_append (main_context_list, context);
663 #ifdef G_MAIN_POLL_DEBUG
664 if (_g_main_poll_debug)
665 g_print ("created context=%p\n", context);
668 G_UNLOCK (main_context_list);
674 * g_main_context_default:
676 * Returns the global default main context. This is the main context
677 * used for main loop functions when a main loop is not explicitly
678 * specified, and corresponds to the "main" main loop. See also
679 * g_main_context_get_thread_default().
681 * Return value: the global default main context.
684 g_main_context_default (void)
690 if (!default_main_context)
692 default_main_context = g_main_context_new ();
693 #ifdef G_MAIN_POLL_DEBUG
694 if (_g_main_poll_debug)
695 g_print ("default context=%p\n", default_main_context);
699 G_UNLOCK (main_loop);
701 return default_main_context;
704 static GStaticPrivate thread_context_stack = G_STATIC_PRIVATE_INIT;
707 free_context_stack (gpointer data)
709 GQueue *stack = data;
710 GMainContext *context;
712 while (!g_queue_is_empty (stack))
714 context = g_queue_pop_head (stack);
715 g_main_context_release (context);
717 g_main_context_unref (context);
719 g_queue_free (stack);
723 * g_main_context_push_thread_default:
724 * @context: a #GMainContext, or %NULL for the global default context
726 * Acquires @context and sets it as the thread-default context for the
727 * current thread. This will cause certain asynchronous operations
728 * (such as most <link linkend="gio">gio</link>-based I/O) which are
729 * started in this thread to run under @context and deliver their
730 * results to its main loop, rather than running under the global
731 * default context in the main thread. Note that calling this function
732 * changes the context returned by
733 * g_main_context_get_thread_default(), <emphasis>not</emphasis> the
734 * one returned by g_main_context_default(), so it does not affect the
735 * context used by functions like g_idle_add().
737 * Normally you would call this function shortly after creating a new
738 * thread, passing it a #GMainContext which will be run by a
739 * #GMainLoop in that thread, to set a new default context for all
740 * async operations in that thread. (In this case, you don't need to
741 * ever call g_main_context_pop_thread_default().) In some cases
742 * however, you may want to schedule a single operation in a
743 * non-default context, or temporarily use a non-default context in
744 * the main thread. In that case, you can wrap the call to the
745 * asynchronous operation inside a
746 * g_main_context_push_thread_default() /
747 * g_main_context_pop_thread_default() pair, but it is up to you to
748 * ensure that no other asynchronous operations accidentally get
749 * started while the non-default context is active.
751 * Beware that libraries that predate this function may not correctly
752 * handle being used from a thread with a thread-default context. Eg,
753 * see g_file_supports_thread_contexts().
758 g_main_context_push_thread_default (GMainContext *context)
761 gboolean acquired_context;
763 acquired_context = g_main_context_acquire (context);
764 g_return_if_fail (acquired_context);
766 if (context == g_main_context_default ())
769 g_main_context_ref (context);
771 stack = g_static_private_get (&thread_context_stack);
774 stack = g_queue_new ();
775 g_static_private_set (&thread_context_stack, stack,
779 g_queue_push_head (stack, context);
783 * g_main_context_pop_thread_default:
784 * @context: a #GMainContext object, or %NULL
786 * Pops @context off the thread-default context stack (verifying that
787 * it was on the top of the stack).
792 g_main_context_pop_thread_default (GMainContext *context)
796 if (context == g_main_context_default ())
799 stack = g_static_private_get (&thread_context_stack);
801 g_return_if_fail (stack != NULL);
802 g_return_if_fail (g_queue_peek_head (stack) == context);
804 g_queue_pop_head (stack);
806 g_main_context_release (context);
808 g_main_context_unref (context);
812 * g_main_context_get_thread_default:
814 * Gets the thread-default #GMainContext for this thread. Asynchronous
815 * operations that want to be able to be run in contexts other than
816 * the default one should call this method to get a #GMainContext to
817 * add their #GSource<!-- -->s to. (Note that even in single-threaded
818 * programs applications may sometimes want to temporarily push a
819 * non-default context, so it is not safe to assume that this will
820 * always return %NULL if threads are not initialized.)
822 * Returns: the thread-default #GMainContext, or %NULL if the
823 * thread-default context is the global default context.
828 g_main_context_get_thread_default (void)
832 stack = g_static_private_get (&thread_context_stack);
834 return g_queue_peek_head (stack);
839 /* Hooks for adding to the main loop */
843 * @source_funcs: structure containing functions that implement
844 * the sources behavior.
845 * @struct_size: size of the #GSource structure to create.
847 * Creates a new #GSource structure. The size is specified to
848 * allow creating structures derived from #GSource that contain
849 * additional data. The size passed in must be at least
850 * <literal>sizeof (GSource)</literal>.
852 * The source will not initially be associated with any #GMainContext
853 * and must be added to one with g_source_attach() before it will be
856 * Return value: the newly-created #GSource.
859 g_source_new (GSourceFuncs *source_funcs,
864 g_return_val_if_fail (source_funcs != NULL, NULL);
865 g_return_val_if_fail (struct_size >= sizeof (GSource), NULL);
867 source = (GSource*) g_malloc0 (struct_size);
869 source->source_funcs = source_funcs;
870 source->ref_count = 1;
872 source->priority = G_PRIORITY_DEFAULT;
874 source->flags = G_HOOK_FLAG_ACTIVE;
876 /* NULL/0 initialization for all other fields */
881 /* Holds context's lock
884 g_source_list_add (GSource *source,
885 GMainContext *context)
887 GSource *tmp_source, *last_source;
889 if (source->priv && source->priv->parent_source)
891 /* Put the source immediately before its parent */
892 tmp_source = source->priv->parent_source;
893 last_source = source->priv->parent_source->prev;
898 tmp_source = context->source_list;
899 while (tmp_source && tmp_source->priority <= source->priority)
901 last_source = tmp_source;
902 tmp_source = tmp_source->next;
906 source->next = tmp_source;
908 tmp_source->prev = source;
910 source->prev = last_source;
912 last_source->next = source;
914 context->source_list = source;
917 /* Holds context's lock
920 g_source_list_remove (GSource *source,
921 GMainContext *context)
924 source->prev->next = source->next;
926 context->source_list = source->next;
929 source->next->prev = source->prev;
936 g_source_attach_unlocked (GSource *source,
937 GMainContext *context)
942 source->context = context;
943 result = source->source_id = context->next_id++;
946 g_source_list_add (source, context);
948 tmp_list = source->poll_fds;
951 g_main_context_add_poll_unlocked (context, source->priority, tmp_list->data);
952 tmp_list = tmp_list->next;
957 tmp_list = source->priv->child_sources;
960 g_source_attach_unlocked (tmp_list->data, context);
961 tmp_list = tmp_list->next;
970 * @source: a #GSource
971 * @context: a #GMainContext (if %NULL, the default context will be used)
973 * Adds a #GSource to a @context so that it will be executed within
974 * that context. Remove it by calling g_source_destroy().
976 * Return value: the ID (greater than 0) for the source within the
980 g_source_attach (GSource *source,
981 GMainContext *context)
985 g_return_val_if_fail (source->context == NULL, 0);
986 g_return_val_if_fail (!SOURCE_DESTROYED (source), 0);
989 context = g_main_context_default ();
991 LOCK_CONTEXT (context);
993 result = g_source_attach_unlocked (source, context);
995 #ifdef G_THREADS_ENABLED
996 /* Now wake up the main loop if it is waiting in the poll() */
997 g_main_context_wakeup_unlocked (context);
1000 UNLOCK_CONTEXT (context);
1006 g_source_destroy_internal (GSource *source,
1007 GMainContext *context,
1011 LOCK_CONTEXT (context);
1013 if (!SOURCE_DESTROYED (source))
1016 gpointer old_cb_data;
1017 GSourceCallbackFuncs *old_cb_funcs;
1019 source->flags &= ~G_HOOK_FLAG_ACTIVE;
1021 old_cb_data = source->callback_data;
1022 old_cb_funcs = source->callback_funcs;
1024 source->callback_data = NULL;
1025 source->callback_funcs = NULL;
1029 UNLOCK_CONTEXT (context);
1030 old_cb_funcs->unref (old_cb_data);
1031 LOCK_CONTEXT (context);
1034 if (!SOURCE_BLOCKED (source))
1036 tmp_list = source->poll_fds;
1039 g_main_context_remove_poll_unlocked (context, tmp_list->data);
1040 tmp_list = tmp_list->next;
1044 if (source->priv && source->priv->child_sources)
1046 /* This is safe because even if a child_source finalizer or
1047 * closure notify tried to modify source->priv->child_sources
1048 * from outside the lock, it would fail since
1049 * SOURCE_DESTROYED(source) is now TRUE.
1051 tmp_list = source->priv->child_sources;
1054 g_source_destroy_internal (tmp_list->data, context, TRUE);
1055 g_source_unref_internal (tmp_list->data, context, TRUE);
1056 tmp_list = tmp_list->next;
1058 g_slist_free (source->priv->child_sources);
1059 source->priv->child_sources = NULL;
1062 g_source_unref_internal (source, context, TRUE);
1066 UNLOCK_CONTEXT (context);
1071 * @source: a #GSource
1073 * Removes a source from its #GMainContext, if any, and mark it as
1074 * destroyed. The source cannot be subsequently added to another
1078 g_source_destroy (GSource *source)
1080 GMainContext *context;
1082 g_return_if_fail (source != NULL);
1084 context = source->context;
1087 g_source_destroy_internal (source, context, FALSE);
1089 source->flags &= ~G_HOOK_FLAG_ACTIVE;
1094 * @source: a #GSource
1096 * Returns the numeric ID for a particular source. The ID of a source
1097 * is a positive integer which is unique within a particular main loop
1098 * context. The reverse
1099 * mapping from ID to source is done by g_main_context_find_source_by_id().
1101 * Return value: the ID (greater than 0) for the source
1104 g_source_get_id (GSource *source)
1108 g_return_val_if_fail (source != NULL, 0);
1109 g_return_val_if_fail (source->context != NULL, 0);
1111 LOCK_CONTEXT (source->context);
1112 result = source->source_id;
1113 UNLOCK_CONTEXT (source->context);
1119 * g_source_get_context:
1120 * @source: a #GSource
1122 * Gets the #GMainContext with which the source is associated.
1123 * Calling this function on a destroyed source is an error.
1125 * Return value: the #GMainContext with which the source is associated,
1126 * or %NULL if the context has not yet been added
1130 g_source_get_context (GSource *source)
1132 g_return_val_if_fail (!SOURCE_DESTROYED (source), NULL);
1134 return source->context;
1138 * g_source_add_poll:
1139 * @source:a #GSource
1140 * @fd: a #GPollFD structure holding information about a file
1141 * descriptor to watch.
1143 * Adds a file descriptor to the set of file descriptors polled for
1144 * this source. This is usually combined with g_source_new() to add an
1145 * event source. The event source's check function will typically test
1146 * the @revents field in the #GPollFD struct and return %TRUE if events need
1150 g_source_add_poll (GSource *source,
1153 GMainContext *context;
1155 g_return_if_fail (source != NULL);
1156 g_return_if_fail (fd != NULL);
1157 g_return_if_fail (!SOURCE_DESTROYED (source));
1159 context = source->context;
1162 LOCK_CONTEXT (context);
1164 source->poll_fds = g_slist_prepend (source->poll_fds, fd);
1168 if (!SOURCE_BLOCKED (source))
1169 g_main_context_add_poll_unlocked (context, source->priority, fd);
1170 UNLOCK_CONTEXT (context);
1175 * g_source_remove_poll:
1176 * @source:a #GSource
1177 * @fd: a #GPollFD structure previously passed to g_source_add_poll().
1179 * Removes a file descriptor from the set of file descriptors polled for
1183 g_source_remove_poll (GSource *source,
1186 GMainContext *context;
1188 g_return_if_fail (source != NULL);
1189 g_return_if_fail (fd != NULL);
1190 g_return_if_fail (!SOURCE_DESTROYED (source));
1192 context = source->context;
1195 LOCK_CONTEXT (context);
1197 source->poll_fds = g_slist_remove (source->poll_fds, fd);
1201 if (!SOURCE_BLOCKED (source))
1202 g_main_context_remove_poll_unlocked (context, fd);
1203 UNLOCK_CONTEXT (context);
1208 * g_source_add_child_source:
1209 * @source:a #GSource
1210 * @child_source: a second #GSource that @source should "poll"
1212 * Adds @child_source to @source as a "polled" source; when @source is
1213 * added to a #GMainContext, @child_source will be automatically added
1214 * with the same priority, when @child_source is triggered, it will
1215 * cause @source to dispatch (in addition to calling its own
1216 * callback), and when @source is destroyed, it will destroy
1217 * @child_source as well. (@source will also still be dispatched if
1218 * its own prepare/check functions indicate that it is ready.)
1220 * If you don't need @child_source to do anything on its own when it
1221 * triggers, you can call g_source_set_dummy_callback() on it to set a
1222 * callback that does nothing (except return %TRUE if appropriate).
1224 * @source will hold a reference on @child_source while @child_source
1225 * is attached to it.
1230 g_source_add_child_source (GSource *source,
1231 GSource *child_source)
1233 GMainContext *context;
1235 g_return_if_fail (source != NULL);
1236 g_return_if_fail (child_source != NULL);
1237 g_return_if_fail (!SOURCE_DESTROYED (source));
1238 g_return_if_fail (!SOURCE_DESTROYED (child_source));
1239 g_return_if_fail (child_source->context == NULL);
1240 g_return_if_fail (child_source->priv == NULL || child_source->priv->parent_source == NULL);
1242 context = source->context;
1245 LOCK_CONTEXT (context);
1248 source->priv = g_slice_new0 (GSourcePrivate);
1249 if (!child_source->priv)
1250 child_source->priv = g_slice_new0 (GSourcePrivate);
1252 source->priv->child_sources = g_slist_prepend (source->priv->child_sources,
1253 g_source_ref (child_source));
1254 child_source->priv->parent_source = source;
1255 g_source_set_priority_unlocked (child_source, context, source->priority);
1259 UNLOCK_CONTEXT (context);
1260 g_source_attach (child_source, context);
1265 * g_source_remove_child_source:
1266 * @source:a #GSource
1267 * @child_source: a #GSource previously passed to
1268 * g_source_add_child_source().
1270 * Detaches @child_source from @source and destroys it.
1275 g_source_remove_child_source (GSource *source,
1276 GSource *child_source)
1278 GMainContext *context;
1280 g_return_if_fail (source != NULL);
1281 g_return_if_fail (child_source != NULL);
1282 g_return_if_fail (child_source->priv != NULL && child_source->priv->parent_source == source);
1283 g_return_if_fail (!SOURCE_DESTROYED (source));
1284 g_return_if_fail (!SOURCE_DESTROYED (child_source));
1286 context = source->context;
1289 LOCK_CONTEXT (context);
1291 source->priv->child_sources = g_slist_remove (source->priv->child_sources, child_source);
1292 g_source_destroy_internal (child_source, context, TRUE);
1293 g_source_unref_internal (child_source, context, TRUE);
1296 UNLOCK_CONTEXT (context);
1300 * g_source_set_callback_indirect:
1301 * @source: the source
1302 * @callback_data: pointer to callback data "object"
1303 * @callback_funcs: functions for reference counting @callback_data
1304 * and getting the callback and data
1306 * Sets the callback function storing the data as a refcounted callback
1307 * "object". This is used internally. Note that calling
1308 * g_source_set_callback_indirect() assumes
1309 * an initial reference count on @callback_data, and thus
1310 * @callback_funcs->unref will eventually be called once more
1311 * than @callback_funcs->ref.
1314 g_source_set_callback_indirect (GSource *source,
1315 gpointer callback_data,
1316 GSourceCallbackFuncs *callback_funcs)
1318 GMainContext *context;
1319 gpointer old_cb_data;
1320 GSourceCallbackFuncs *old_cb_funcs;
1322 g_return_if_fail (source != NULL);
1323 g_return_if_fail (callback_funcs != NULL || callback_data == NULL);
1325 context = source->context;
1328 LOCK_CONTEXT (context);
1330 old_cb_data = source->callback_data;
1331 old_cb_funcs = source->callback_funcs;
1333 source->callback_data = callback_data;
1334 source->callback_funcs = callback_funcs;
1337 UNLOCK_CONTEXT (context);
1340 old_cb_funcs->unref (old_cb_data);
1344 g_source_callback_ref (gpointer cb_data)
1346 GSourceCallback *callback = cb_data;
1348 callback->ref_count++;
1353 g_source_callback_unref (gpointer cb_data)
1355 GSourceCallback *callback = cb_data;
1357 callback->ref_count--;
1358 if (callback->ref_count == 0)
1360 if (callback->notify)
1361 callback->notify (callback->data);
1367 g_source_callback_get (gpointer cb_data,
1372 GSourceCallback *callback = cb_data;
1374 *func = callback->func;
1375 *data = callback->data;
1378 static GSourceCallbackFuncs g_source_callback_funcs = {
1379 g_source_callback_ref,
1380 g_source_callback_unref,
1381 g_source_callback_get,
1385 * g_source_set_callback:
1386 * @source: the source
1387 * @func: a callback function
1388 * @data: the data to pass to callback function
1389 * @notify: a function to call when @data is no longer in use, or %NULL.
1391 * Sets the callback function for a source. The callback for a source is
1392 * called from the source's dispatch function.
1394 * The exact type of @func depends on the type of source; ie. you
1395 * should not count on @func being called with @data as its first
1398 * Typically, you won't use this function. Instead use functions specific
1399 * to the type of source you are using.
1402 g_source_set_callback (GSource *source,
1405 GDestroyNotify notify)
1407 GSourceCallback *new_callback;
1409 g_return_if_fail (source != NULL);
1411 new_callback = g_new (GSourceCallback, 1);
1413 new_callback->ref_count = 1;
1414 new_callback->func = func;
1415 new_callback->data = data;
1416 new_callback->notify = notify;
1418 g_source_set_callback_indirect (source, new_callback, &g_source_callback_funcs);
1423 * g_source_set_funcs:
1424 * @source: a #GSource
1425 * @funcs: the new #GSourceFuncs
1427 * Sets the source functions (can be used to override
1428 * default implementations) of an unattached source.
1433 g_source_set_funcs (GSource *source,
1434 GSourceFuncs *funcs)
1436 g_return_if_fail (source != NULL);
1437 g_return_if_fail (source->context == NULL);
1438 g_return_if_fail (source->ref_count > 0);
1439 g_return_if_fail (funcs != NULL);
1441 source->source_funcs = funcs;
1445 g_source_set_priority_unlocked (GSource *source,
1446 GMainContext *context,
1451 source->priority = priority;
1455 /* Remove the source from the context's source and then
1456 * add it back so it is sorted in the correct place
1458 g_source_list_remove (source, source->context);
1459 g_source_list_add (source, source->context);
1461 if (!SOURCE_BLOCKED (source))
1463 tmp_list = source->poll_fds;
1466 g_main_context_remove_poll_unlocked (context, tmp_list->data);
1467 g_main_context_add_poll_unlocked (context, priority, tmp_list->data);
1469 tmp_list = tmp_list->next;
1474 if (source->priv && source->priv->child_sources)
1476 tmp_list = source->priv->child_sources;
1479 g_source_set_priority_unlocked (tmp_list->data, context, priority);
1480 tmp_list = tmp_list->next;
1486 * g_source_set_priority:
1487 * @source: a #GSource
1488 * @priority: the new priority.
1490 * Sets the priority of a source. While the main loop is being run, a
1491 * source will be dispatched if it is ready to be dispatched and no
1492 * sources at a higher (numerically smaller) priority are ready to be
1496 g_source_set_priority (GSource *source,
1499 GMainContext *context;
1501 g_return_if_fail (source != NULL);
1503 context = source->context;
1506 LOCK_CONTEXT (context);
1507 g_source_set_priority_unlocked (source, context, priority);
1509 UNLOCK_CONTEXT (source->context);
1513 * g_source_get_priority:
1514 * @source: a #GSource
1516 * Gets the priority of a source.
1518 * Return value: the priority of the source
1521 g_source_get_priority (GSource *source)
1523 g_return_val_if_fail (source != NULL, 0);
1525 return source->priority;
1529 * g_source_set_can_recurse:
1530 * @source: a #GSource
1531 * @can_recurse: whether recursion is allowed for this source
1533 * Sets whether a source can be called recursively. If @can_recurse is
1534 * %TRUE, then while the source is being dispatched then this source
1535 * will be processed normally. Otherwise, all processing of this
1536 * source is blocked until the dispatch function returns.
1539 g_source_set_can_recurse (GSource *source,
1540 gboolean can_recurse)
1542 GMainContext *context;
1544 g_return_if_fail (source != NULL);
1546 context = source->context;
1549 LOCK_CONTEXT (context);
1552 source->flags |= G_SOURCE_CAN_RECURSE;
1554 source->flags &= ~G_SOURCE_CAN_RECURSE;
1557 UNLOCK_CONTEXT (context);
1561 * g_source_get_can_recurse:
1562 * @source: a #GSource
1564 * Checks whether a source is allowed to be called recursively.
1565 * see g_source_set_can_recurse().
1567 * Return value: whether recursion is allowed.
1570 g_source_get_can_recurse (GSource *source)
1572 g_return_val_if_fail (source != NULL, FALSE);
1574 return (source->flags & G_SOURCE_CAN_RECURSE) != 0;
1579 * g_source_set_name:
1580 * @source: a #GSource
1581 * @name: debug name for the source
1583 * Sets a name for the source, used in debugging and profiling.
1584 * The name defaults to #NULL.
1586 * The source name should describe in a human-readable way
1587 * what the source does. For example, "X11 event queue"
1588 * or "GTK+ repaint idle handler" or whatever it is.
1590 * It is permitted to call this function multiple times, but is not
1591 * recommended due to the potential performance impact. For example,
1592 * one could change the name in the "check" function of a #GSourceFuncs
1593 * to include details like the event type in the source name.
1598 g_source_set_name (GSource *source,
1601 g_return_if_fail (source != NULL);
1603 /* setting back to NULL is allowed, just because it's
1604 * weird if get_name can return NULL but you can't
1608 g_free (source->name);
1609 source->name = g_strdup (name);
1613 * g_source_get_name:
1614 * @source: a #GSource
1616 * Gets a name for the source, used in debugging and profiling.
1617 * The name may be #NULL if it has never been set with
1618 * g_source_set_name().
1620 * Return value: the name of the source
1623 G_CONST_RETURN char*
1624 g_source_get_name (GSource *source)
1626 g_return_val_if_fail (source != NULL, NULL);
1628 return source->name;
1632 * g_source_set_name_by_id:
1633 * @tag: a #GSource ID
1634 * @name: debug name for the source
1636 * Sets the name of a source using its ID.
1638 * This is a convenience utility to set source names from the return
1639 * value of g_idle_add(), g_timeout_add(), etc.
1644 g_source_set_name_by_id (guint tag,
1649 g_return_if_fail (tag > 0);
1651 source = g_main_context_find_source_by_id (NULL, tag);
1655 g_source_set_name (source, name);
1661 * @source: a #GSource
1663 * Increases the reference count on a source by one.
1665 * Return value: @source
1668 g_source_ref (GSource *source)
1670 GMainContext *context;
1672 g_return_val_if_fail (source != NULL, NULL);
1674 context = source->context;
1677 LOCK_CONTEXT (context);
1679 source->ref_count++;
1682 UNLOCK_CONTEXT (context);
1687 /* g_source_unref() but possible to call within context lock
1690 g_source_unref_internal (GSource *source,
1691 GMainContext *context,
1694 gpointer old_cb_data = NULL;
1695 GSourceCallbackFuncs *old_cb_funcs = NULL;
1697 g_return_if_fail (source != NULL);
1699 if (!have_lock && context)
1700 LOCK_CONTEXT (context);
1702 source->ref_count--;
1703 if (source->ref_count == 0)
1705 old_cb_data = source->callback_data;
1706 old_cb_funcs = source->callback_funcs;
1708 source->callback_data = NULL;
1709 source->callback_funcs = NULL;
1713 if (!SOURCE_DESTROYED (source))
1714 g_warning (G_STRLOC ": ref_count == 0, but source was still attached to a context!");
1715 g_source_list_remove (source, context);
1718 if (source->source_funcs->finalize)
1721 UNLOCK_CONTEXT (context);
1722 source->source_funcs->finalize (source);
1724 LOCK_CONTEXT (context);
1727 g_free (source->name);
1728 source->name = NULL;
1730 g_slist_free (source->poll_fds);
1731 source->poll_fds = NULL;
1735 g_slice_free (GSourcePrivate, source->priv);
1736 source->priv = NULL;
1742 if (!have_lock && context)
1743 UNLOCK_CONTEXT (context);
1748 UNLOCK_CONTEXT (context);
1750 old_cb_funcs->unref (old_cb_data);
1753 LOCK_CONTEXT (context);
1759 * @source: a #GSource
1761 * Decreases the reference count of a source by one. If the
1762 * resulting reference count is zero the source and associated
1763 * memory will be destroyed.
1766 g_source_unref (GSource *source)
1768 g_return_if_fail (source != NULL);
1770 g_source_unref_internal (source, source->context, FALSE);
1774 * g_main_context_find_source_by_id:
1775 * @context: a #GMainContext (if %NULL, the default context will be used)
1776 * @source_id: the source ID, as returned by g_source_get_id().
1778 * Finds a #GSource given a pair of context and ID.
1780 * Return value: the #GSource if found, otherwise, %NULL
1783 g_main_context_find_source_by_id (GMainContext *context,
1788 g_return_val_if_fail (source_id > 0, NULL);
1790 if (context == NULL)
1791 context = g_main_context_default ();
1793 LOCK_CONTEXT (context);
1795 source = context->source_list;
1798 if (!SOURCE_DESTROYED (source) &&
1799 source->source_id == source_id)
1801 source = source->next;
1804 UNLOCK_CONTEXT (context);
1810 * g_main_context_find_source_by_funcs_user_data:
1811 * @context: a #GMainContext (if %NULL, the default context will be used).
1812 * @funcs: the @source_funcs passed to g_source_new().
1813 * @user_data: the user data from the callback.
1815 * Finds a source with the given source functions and user data. If
1816 * multiple sources exist with the same source function and user data,
1817 * the first one found will be returned.
1819 * Return value: the source, if one was found, otherwise %NULL
1822 g_main_context_find_source_by_funcs_user_data (GMainContext *context,
1823 GSourceFuncs *funcs,
1828 g_return_val_if_fail (funcs != NULL, NULL);
1830 if (context == NULL)
1831 context = g_main_context_default ();
1833 LOCK_CONTEXT (context);
1835 source = context->source_list;
1838 if (!SOURCE_DESTROYED (source) &&
1839 source->source_funcs == funcs &&
1840 source->callback_funcs)
1842 GSourceFunc callback;
1843 gpointer callback_data;
1845 source->callback_funcs->get (source->callback_data, source, &callback, &callback_data);
1847 if (callback_data == user_data)
1850 source = source->next;
1853 UNLOCK_CONTEXT (context);
1859 * g_main_context_find_source_by_user_data:
1860 * @context: a #GMainContext
1861 * @user_data: the user_data for the callback.
1863 * Finds a source with the given user data for the callback. If
1864 * multiple sources exist with the same user data, the first
1865 * one found will be returned.
1867 * Return value: the source, if one was found, otherwise %NULL
1870 g_main_context_find_source_by_user_data (GMainContext *context,
1875 if (context == NULL)
1876 context = g_main_context_default ();
1878 LOCK_CONTEXT (context);
1880 source = context->source_list;
1883 if (!SOURCE_DESTROYED (source) &&
1884 source->callback_funcs)
1886 GSourceFunc callback;
1887 gpointer callback_data = NULL;
1889 source->callback_funcs->get (source->callback_data, source, &callback, &callback_data);
1891 if (callback_data == user_data)
1894 source = source->next;
1897 UNLOCK_CONTEXT (context);
1904 * @tag: the ID of the source to remove.
1906 * Removes the source with the given id from the default main context.
1908 * a #GSource is given by g_source_get_id(), or will be returned by the
1909 * functions g_source_attach(), g_idle_add(), g_idle_add_full(),
1910 * g_timeout_add(), g_timeout_add_full(), g_child_watch_add(),
1911 * g_child_watch_add_full(), g_io_add_watch(), and g_io_add_watch_full().
1913 * See also g_source_destroy(). You must use g_source_destroy() for sources
1914 * added to a non-default main context.
1916 * Return value: %TRUE if the source was found and removed.
1919 g_source_remove (guint tag)
1923 g_return_val_if_fail (tag > 0, FALSE);
1925 source = g_main_context_find_source_by_id (NULL, tag);
1927 g_source_destroy (source);
1929 return source != NULL;
1933 * g_source_remove_by_user_data:
1934 * @user_data: the user_data for the callback.
1936 * Removes a source from the default main loop context given the user
1937 * data for the callback. If multiple sources exist with the same user
1938 * data, only one will be destroyed.
1940 * Return value: %TRUE if a source was found and removed.
1943 g_source_remove_by_user_data (gpointer user_data)
1947 source = g_main_context_find_source_by_user_data (NULL, user_data);
1950 g_source_destroy (source);
1958 * g_source_remove_by_funcs_user_data:
1959 * @funcs: The @source_funcs passed to g_source_new()
1960 * @user_data: the user data for the callback
1962 * Removes a source from the default main loop context given the
1963 * source functions and user data. If multiple sources exist with the
1964 * same source functions and user data, only one will be destroyed.
1966 * Return value: %TRUE if a source was found and removed.
1969 g_source_remove_by_funcs_user_data (GSourceFuncs *funcs,
1974 g_return_val_if_fail (funcs != NULL, FALSE);
1976 source = g_main_context_find_source_by_funcs_user_data (NULL, funcs, user_data);
1979 g_source_destroy (source);
1987 * g_get_current_time:
1988 * @result: #GTimeVal structure in which to store current time.
1990 * Equivalent to the UNIX gettimeofday() function, but portable.
1992 * You may find g_get_real_time() to be more convenient.
1995 g_get_current_time (GTimeVal *result)
2000 g_return_if_fail (result != NULL);
2002 /*this is required on alpha, there the timeval structs are int's
2003 not longs and a cast only would fail horribly*/
2004 gettimeofday (&r, NULL);
2005 result->tv_sec = r.tv_sec;
2006 result->tv_usec = r.tv_usec;
2011 g_return_if_fail (result != NULL);
2013 GetSystemTimeAsFileTime (&ft);
2014 memmove (&time64, &ft, sizeof (FILETIME));
2016 /* Convert from 100s of nanoseconds since 1601-01-01
2017 * to Unix epoch. Yes, this is Y2038 unsafe.
2019 time64 -= G_GINT64_CONSTANT (116444736000000000);
2022 result->tv_sec = time64 / 1000000;
2023 result->tv_usec = time64 % 1000000;
2030 * Queries the system wall-clock time.
2032 * This call is functionally equivalent to g_get_current_time() except
2033 * that the return value is often more convenient than dealing with a
2036 * You should only use this call if you are actually interested in the real
2037 * wall-clock time. g_get_monotonic_time() is probably more useful for
2038 * measuring intervals.
2040 * Returns: the number of microseconds since January 1, 1970 UTC.
2045 g_get_real_time (void)
2049 g_get_current_time (&tv);
2051 return (((gint64) tv.tv_sec) * 1000000) + tv.tv_usec;
2055 * g_get_monotonic_time:
2057 * Queries the system monotonic time, if available.
2059 * On POSIX systems with clock_gettime() and %CLOCK_MONOTONIC this call
2060 * is a very shallow wrapper for that. Otherwise, we make a best effort
2061 * that probably involves returning the wall clock time (with at least
2062 * microsecond accuracy, subject to the limitations of the OS kernel).
2064 * Note that, on Windows, "limitations of the OS kernel" is a rather
2065 * substantial statement. Depending on the configuration of the system,
2066 * the wall clock time is updated as infrequently as 64 times a second
2067 * (which is approximately every 16ms).
2069 * Returns: the monotonic time, in microseconds
2074 g_get_monotonic_time (void)
2076 #ifdef HAVE_CLOCK_GETTIME
2077 /* librt clock_gettime() is our first choice */
2079 static int clockid = CLOCK_REALTIME;
2082 #ifdef HAVE_MONOTONIC_CLOCK
2083 /* We have to check if we actually have monotonic clock support.
2085 * There is no thread safety issue here since there is no harm if we
2089 static gboolean checked;
2091 if G_UNLIKELY (!checked)
2093 if (sysconf (_SC_MONOTONIC_CLOCK) >= 0)
2094 clockid = CLOCK_MONOTONIC;
2100 clock_gettime (clockid, &ts);
2102 /* In theory monotonic time can have any epoch.
2104 * glib presently assumes the following:
2106 * 1) The epoch comes some time after the birth of Jesus of Nazareth, but
2107 * not more than 10000 years later.
2109 * 2) The current time also falls sometime within this range.
2111 * These two reasonable assumptions leave us with a maximum deviation from
2112 * the epoch of 10000 years, or 315569520000000000 seconds.
2114 * If we restrict ourselves to this range then the number of microseconds
2115 * will always fit well inside the constraints of a int64 (by a factor of
2118 * If you actually hit the following assertion, probably you should file a
2119 * bug against your operating system for being excessively silly.
2121 g_assert (G_GINT64_CONSTANT (-315569520000000000) < ts.tv_sec &&
2122 ts.tv_sec < G_GINT64_CONSTANT (315569520000000000));
2124 return (((gint64) ts.tv_sec) * 1000000) + (ts.tv_nsec / 1000);
2127 /* It may look like we are discarding accuracy on Windows (since its
2128 * current time is expressed in 100s of nanoseconds) but according to
2129 * many sources, the time is only updated 64 times per second, so
2130 * microsecond accuracy is more than enough.
2135 g_get_current_time (&tv);
2137 return (((gint64) tv.tv_sec) * 1000000) + tv.tv_usec;
2143 g_main_dispatch_free (gpointer dispatch)
2145 g_slice_free (GMainDispatch, dispatch);
2148 /* Running the main loop */
2150 static GMainDispatch *
2153 static GStaticPrivate depth_private = G_STATIC_PRIVATE_INIT;
2154 GMainDispatch *dispatch = g_static_private_get (&depth_private);
2157 dispatch = g_slice_new0 (GMainDispatch);
2158 g_static_private_set (&depth_private, dispatch, g_main_dispatch_free);
2167 * Returns the depth of the stack of calls to
2168 * g_main_context_dispatch() on any #GMainContext in the current thread.
2169 * That is, when called from the toplevel, it gives 0. When
2170 * called from within a callback from g_main_context_iteration()
2171 * (or g_main_loop_run(), etc.) it returns 1. When called from within
2172 * a callback to a recursive call to g_main_context_iteration(),
2173 * it returns 2. And so forth.
2175 * This function is useful in a situation like the following:
2176 * Imagine an extremely simple "garbage collected" system.
2179 * static GList *free_list;
2182 * allocate_memory (gsize size)
2184 * gpointer result = g_malloc (size);
2185 * free_list = g_list_prepend (free_list, result);
2190 * free_allocated_memory (void)
2193 * for (l = free_list; l; l = l->next);
2195 * g_list_free (free_list);
2203 * g_main_context_iteration (NULL, TRUE);
2204 * free_allocated_memory();
2208 * This works from an application, however, if you want to do the same
2209 * thing from a library, it gets more difficult, since you no longer
2210 * control the main loop. You might think you can simply use an idle
2211 * function to make the call to free_allocated_memory(), but that
2212 * doesn't work, since the idle function could be called from a
2213 * recursive callback. This can be fixed by using g_main_depth()
2217 * allocate_memory (gsize size)
2219 * FreeListBlock *block = g_new (FreeListBlock, 1);
2220 * block->mem = g_malloc (size);
2221 * block->depth = g_main_depth ();
2222 * free_list = g_list_prepend (free_list, block);
2223 * return block->mem;
2227 * free_allocated_memory (void)
2231 * int depth = g_main_depth ();
2232 * for (l = free_list; l; );
2234 * GList *next = l->next;
2235 * FreeListBlock *block = l->data;
2236 * if (block->depth > depth)
2238 * g_free (block->mem);
2240 * free_list = g_list_delete_link (free_list, l);
2248 * There is a temptation to use g_main_depth() to solve
2249 * problems with reentrancy. For instance, while waiting for data
2250 * to be received from the network in response to a menu item,
2251 * the menu item might be selected again. It might seem that
2252 * one could make the menu item's callback return immediately
2253 * and do nothing if g_main_depth() returns a value greater than 1.
2254 * However, this should be avoided since the user then sees selecting
2255 * the menu item do nothing. Furthermore, you'll find yourself adding
2256 * these checks all over your code, since there are doubtless many,
2257 * many things that the user could do. Instead, you can use the
2258 * following techniques:
2263 * Use gtk_widget_set_sensitive() or modal dialogs to prevent
2264 * the user from interacting with elements while the main
2265 * loop is recursing.
2270 * Avoid main loop recursion in situations where you can't handle
2271 * arbitrary callbacks. Instead, structure your code so that you
2272 * simply return to the main loop and then get called again when
2273 * there is more work to do.
2278 * Return value: The main loop recursion level in the current thread
2283 GMainDispatch *dispatch = get_dispatch ();
2284 return dispatch->depth;
2288 * g_main_current_source:
2290 * Returns the currently firing source for this thread.
2292 * Return value: The currently firing source or %NULL.
2297 g_main_current_source (void)
2299 GMainDispatch *dispatch = get_dispatch ();
2300 return dispatch->dispatching_sources ? dispatch->dispatching_sources->data : NULL;
2304 * g_source_is_destroyed:
2305 * @source: a #GSource
2307 * Returns whether @source has been destroyed.
2309 * This is important when you operate upon your objects
2310 * from within idle handlers, but may have freed the object
2311 * before the dispatch of your idle handler.
2315 * idle_callback (gpointer data)
2317 * SomeWidget *self = data;
2319 * GDK_THREADS_ENTER (<!-- -->);
2320 * /<!-- -->* do stuff with self *<!-- -->/
2321 * self->idle_id = 0;
2322 * GDK_THREADS_LEAVE (<!-- -->);
2328 * some_widget_do_stuff_later (SomeWidget *self)
2330 * self->idle_id = g_idle_add (idle_callback, self);
2334 * some_widget_finalize (GObject *object)
2336 * SomeWidget *self = SOME_WIDGET (object);
2338 * if (self->idle_id)
2339 * g_source_remove (self->idle_id);
2341 * G_OBJECT_CLASS (parent_class)->finalize (object);
2345 * This will fail in a multi-threaded application if the
2346 * widget is destroyed before the idle handler fires due
2347 * to the use after free in the callback. A solution, to
2348 * this particular problem, is to check to if the source
2349 * has already been destroy within the callback.
2353 * idle_callback (gpointer data)
2355 * SomeWidget *self = data;
2357 * GDK_THREADS_ENTER ();
2358 * if (!g_source_is_destroyed (g_main_current_source ()))
2360 * /<!-- -->* do stuff with self *<!-- -->/
2362 * GDK_THREADS_LEAVE ();
2368 * Return value: %TRUE if the source has been destroyed
2373 g_source_is_destroyed (GSource *source)
2375 return SOURCE_DESTROYED (source);
2378 /* Temporarily remove all this source's file descriptors from the
2379 * poll(), so that if data comes available for one of the file descriptors
2380 * we don't continually spin in the poll()
2382 /* HOLDS: source->context's lock */
2384 block_source (GSource *source)
2388 g_return_if_fail (!SOURCE_BLOCKED (source));
2390 tmp_list = source->poll_fds;
2393 g_main_context_remove_poll_unlocked (source->context, tmp_list->data);
2394 tmp_list = tmp_list->next;
2398 /* HOLDS: source->context's lock */
2400 unblock_source (GSource *source)
2404 g_return_if_fail (!SOURCE_BLOCKED (source)); /* Source already unblocked */
2405 g_return_if_fail (!SOURCE_DESTROYED (source));
2407 tmp_list = source->poll_fds;
2410 g_main_context_add_poll_unlocked (source->context, source->priority, tmp_list->data);
2411 tmp_list = tmp_list->next;
2415 /* HOLDS: context's lock */
2417 g_main_dispatch (GMainContext *context)
2419 GMainDispatch *current = get_dispatch ();
2422 for (i = 0; i < context->pending_dispatches->len; i++)
2424 GSource *source = context->pending_dispatches->pdata[i];
2426 context->pending_dispatches->pdata[i] = NULL;
2429 source->flags &= ~G_SOURCE_READY;
2431 if (!SOURCE_DESTROYED (source))
2433 gboolean was_in_call;
2434 gpointer user_data = NULL;
2435 GSourceFunc callback = NULL;
2436 GSourceCallbackFuncs *cb_funcs;
2438 gboolean need_destroy;
2440 gboolean (*dispatch) (GSource *,
2443 GSList current_source_link;
2445 dispatch = source->source_funcs->dispatch;
2446 cb_funcs = source->callback_funcs;
2447 cb_data = source->callback_data;
2450 cb_funcs->ref (cb_data);
2452 if ((source->flags & G_SOURCE_CAN_RECURSE) == 0)
2453 block_source (source);
2455 was_in_call = source->flags & G_HOOK_FLAG_IN_CALL;
2456 source->flags |= G_HOOK_FLAG_IN_CALL;
2459 cb_funcs->get (cb_data, source, &callback, &user_data);
2461 UNLOCK_CONTEXT (context);
2464 /* The on-stack allocation of the GSList is unconventional, but
2465 * we know that the lifetime of the link is bounded to this
2466 * function as the link is kept in a thread specific list and
2467 * not manipulated outside of this function and its descendants.
2468 * Avoiding the overhead of a g_slist_alloc() is useful as many
2469 * applications do little more than dispatch events.
2471 * This is a performance hack - do not revert to g_slist_prepend()!
2473 current_source_link.data = source;
2474 current_source_link.next = current->dispatching_sources;
2475 current->dispatching_sources = ¤t_source_link;
2476 need_destroy = ! dispatch (source,
2479 g_assert (current->dispatching_sources == ¤t_source_link);
2480 current->dispatching_sources = current_source_link.next;
2484 cb_funcs->unref (cb_data);
2486 LOCK_CONTEXT (context);
2489 source->flags &= ~G_HOOK_FLAG_IN_CALL;
2491 if ((source->flags & G_SOURCE_CAN_RECURSE) == 0 &&
2492 !SOURCE_DESTROYED (source))
2493 unblock_source (source);
2495 /* Note: this depends on the fact that we can't switch
2496 * sources from one main context to another
2498 if (need_destroy && !SOURCE_DESTROYED (source))
2500 g_assert (source->context == context);
2501 g_source_destroy_internal (source, context, TRUE);
2505 SOURCE_UNREF (source, context);
2508 g_ptr_array_set_size (context->pending_dispatches, 0);
2511 /* Holds context's lock */
2512 static inline GSource *
2513 next_valid_source (GMainContext *context,
2516 GSource *new_source = source ? source->next : context->source_list;
2520 if (!SOURCE_DESTROYED (new_source))
2522 new_source->ref_count++;
2526 new_source = new_source->next;
2530 SOURCE_UNREF (source, context);
2536 * g_main_context_acquire:
2537 * @context: a #GMainContext
2539 * Tries to become the owner of the specified context.
2540 * If some other thread is the owner of the context,
2541 * returns %FALSE immediately. Ownership is properly
2542 * recursive: the owner can require ownership again
2543 * and will release ownership when g_main_context_release()
2544 * is called as many times as g_main_context_acquire().
2546 * You must be the owner of a context before you
2547 * can call g_main_context_prepare(), g_main_context_query(),
2548 * g_main_context_check(), g_main_context_dispatch().
2550 * Return value: %TRUE if the operation succeeded, and
2551 * this thread is now the owner of @context.
2554 g_main_context_acquire (GMainContext *context)
2556 #ifdef G_THREADS_ENABLED
2557 gboolean result = FALSE;
2558 GThread *self = G_THREAD_SELF;
2560 if (context == NULL)
2561 context = g_main_context_default ();
2563 LOCK_CONTEXT (context);
2565 if (!context->owner)
2567 context->owner = self;
2568 g_assert (context->owner_count == 0);
2571 if (context->owner == self)
2573 context->owner_count++;
2577 UNLOCK_CONTEXT (context);
2580 #else /* !G_THREADS_ENABLED */
2582 #endif /* G_THREADS_ENABLED */
2586 * g_main_context_release:
2587 * @context: a #GMainContext
2589 * Releases ownership of a context previously acquired by this thread
2590 * with g_main_context_acquire(). If the context was acquired multiple
2591 * times, the ownership will be released only when g_main_context_release()
2592 * is called as many times as it was acquired.
2595 g_main_context_release (GMainContext *context)
2597 #ifdef G_THREADS_ENABLED
2598 if (context == NULL)
2599 context = g_main_context_default ();
2601 LOCK_CONTEXT (context);
2603 context->owner_count--;
2604 if (context->owner_count == 0)
2606 context->owner = NULL;
2608 if (context->waiters)
2610 GMainWaiter *waiter = context->waiters->data;
2611 gboolean loop_internal_waiter =
2612 (waiter->mutex == g_static_mutex_get_mutex (&context->mutex));
2613 context->waiters = g_slist_delete_link (context->waiters,
2615 if (!loop_internal_waiter)
2616 g_mutex_lock (waiter->mutex);
2618 g_cond_signal (waiter->cond);
2620 if (!loop_internal_waiter)
2621 g_mutex_unlock (waiter->mutex);
2625 UNLOCK_CONTEXT (context);
2626 #endif /* G_THREADS_ENABLED */
2630 * g_main_context_wait:
2631 * @context: a #GMainContext
2632 * @cond: a condition variable
2633 * @mutex: a mutex, currently held
2635 * Tries to become the owner of the specified context,
2636 * as with g_main_context_acquire(). But if another thread
2637 * is the owner, atomically drop @mutex and wait on @cond until
2638 * that owner releases ownership or until @cond is signaled, then
2639 * try again (once) to become the owner.
2641 * Return value: %TRUE if the operation succeeded, and
2642 * this thread is now the owner of @context.
2645 g_main_context_wait (GMainContext *context,
2649 #ifdef G_THREADS_ENABLED
2650 gboolean result = FALSE;
2651 GThread *self = G_THREAD_SELF;
2652 gboolean loop_internal_waiter;
2654 if (context == NULL)
2655 context = g_main_context_default ();
2657 loop_internal_waiter = (mutex == g_static_mutex_get_mutex (&context->mutex));
2659 if (!loop_internal_waiter)
2660 LOCK_CONTEXT (context);
2662 if (context->owner && context->owner != self)
2667 waiter.mutex = mutex;
2669 context->waiters = g_slist_append (context->waiters, &waiter);
2671 if (!loop_internal_waiter)
2672 UNLOCK_CONTEXT (context);
2673 g_cond_wait (cond, mutex);
2674 if (!loop_internal_waiter)
2675 LOCK_CONTEXT (context);
2677 context->waiters = g_slist_remove (context->waiters, &waiter);
2680 if (!context->owner)
2682 context->owner = self;
2683 g_assert (context->owner_count == 0);
2686 if (context->owner == self)
2688 context->owner_count++;
2692 if (!loop_internal_waiter)
2693 UNLOCK_CONTEXT (context);
2696 #else /* !G_THREADS_ENABLED */
2698 #endif /* G_THREADS_ENABLED */
2702 * g_main_context_prepare:
2703 * @context: a #GMainContext
2704 * @priority: location to store priority of highest priority
2705 * source already ready.
2707 * Prepares to poll sources within a main loop. The resulting information
2708 * for polling is determined by calling g_main_context_query ().
2710 * Return value: %TRUE if some source is ready to be dispatched
2714 g_main_context_prepare (GMainContext *context,
2719 gint current_priority = G_MAXINT;
2722 if (context == NULL)
2723 context = g_main_context_default ();
2725 LOCK_CONTEXT (context);
2727 context->time_is_fresh = FALSE;
2728 context->real_time_is_fresh = FALSE;
2730 if (context->in_check_or_prepare)
2732 g_warning ("g_main_context_prepare() called recursively from within a source's check() or "
2733 "prepare() member.");
2734 UNLOCK_CONTEXT (context);
2738 #ifdef G_THREADS_ENABLED
2739 if (context->poll_waiting)
2741 g_warning("g_main_context_prepare(): main loop already active in another thread");
2742 UNLOCK_CONTEXT (context);
2746 context->poll_waiting = TRUE;
2747 #endif /* G_THREADS_ENABLED */
2750 /* If recursing, finish up current dispatch, before starting over */
2751 if (context->pending_dispatches)
2754 g_main_dispatch (context, ¤t_time);
2756 UNLOCK_CONTEXT (context);
2761 /* If recursing, clear list of pending dispatches */
2763 for (i = 0; i < context->pending_dispatches->len; i++)
2765 if (context->pending_dispatches->pdata[i])
2766 SOURCE_UNREF ((GSource *)context->pending_dispatches->pdata[i], context);
2768 g_ptr_array_set_size (context->pending_dispatches, 0);
2770 /* Prepare all sources */
2772 context->timeout = -1;
2774 source = next_valid_source (context, NULL);
2777 gint source_timeout = -1;
2779 if ((n_ready > 0) && (source->priority > current_priority))
2781 SOURCE_UNREF (source, context);
2784 if (SOURCE_BLOCKED (source))
2787 if (!(source->flags & G_SOURCE_READY))
2790 gboolean (*prepare) (GSource *source,
2793 prepare = source->source_funcs->prepare;
2794 context->in_check_or_prepare++;
2795 UNLOCK_CONTEXT (context);
2797 result = (*prepare) (source, &source_timeout);
2799 LOCK_CONTEXT (context);
2800 context->in_check_or_prepare--;
2804 GSource *ready_source = source;
2806 while (ready_source)
2808 ready_source->flags |= G_SOURCE_READY;
2809 ready_source = ready_source->priv ? ready_source->priv->parent_source : NULL;
2814 if (source->flags & G_SOURCE_READY)
2817 current_priority = source->priority;
2818 context->timeout = 0;
2821 if (source_timeout >= 0)
2823 if (context->timeout < 0)
2824 context->timeout = source_timeout;
2826 context->timeout = MIN (context->timeout, source_timeout);
2830 source = next_valid_source (context, source);
2833 UNLOCK_CONTEXT (context);
2836 *priority = current_priority;
2838 return (n_ready > 0);
2842 * g_main_context_query:
2843 * @context: a #GMainContext
2844 * @max_priority: maximum priority source to check
2845 * @timeout_: location to store timeout to be used in polling
2846 * @fds: location to store #GPollFD records that need to be polled.
2847 * @n_fds: length of @fds.
2849 * Determines information necessary to poll this main loop.
2851 * Return value: the number of records actually stored in @fds,
2852 * or, if more than @n_fds records need to be stored, the number
2853 * of records that need to be stored.
2856 g_main_context_query (GMainContext *context,
2865 LOCK_CONTEXT (context);
2867 pollrec = context->poll_records;
2869 while (pollrec && max_priority >= pollrec->priority)
2871 /* We need to include entries with fd->events == 0 in the array because
2872 * otherwise if the application changes fd->events behind our back and
2873 * makes it non-zero, we'll be out of sync when we check the fds[] array.
2874 * (Changing fd->events after adding an FD wasn't an anticipated use of
2875 * this API, but it occurs in practice.) */
2878 fds[n_poll].fd = pollrec->fd->fd;
2879 /* In direct contradiction to the Unix98 spec, IRIX runs into
2880 * difficulty if you pass in POLLERR, POLLHUP or POLLNVAL
2881 * flags in the events field of the pollfd while it should
2882 * just ignoring them. So we mask them out here.
2884 fds[n_poll].events = pollrec->fd->events & ~(G_IO_ERR|G_IO_HUP|G_IO_NVAL);
2885 fds[n_poll].revents = 0;
2888 pollrec = pollrec->next;
2892 #ifdef G_THREADS_ENABLED
2893 context->poll_changed = FALSE;
2898 *timeout = context->timeout;
2901 context->time_is_fresh = FALSE;
2902 context->real_time_is_fresh = FALSE;
2906 UNLOCK_CONTEXT (context);
2912 * g_main_context_check:
2913 * @context: a #GMainContext
2914 * @max_priority: the maximum numerical priority of sources to check
2915 * @fds: array of #GPollFD's that was passed to the last call to
2916 * g_main_context_query()
2917 * @n_fds: return value of g_main_context_query()
2919 * Passes the results of polling back to the main loop.
2921 * Return value: %TRUE if some sources are ready to be dispatched.
2924 g_main_context_check (GMainContext *context,
2934 LOCK_CONTEXT (context);
2936 if (context->in_check_or_prepare)
2938 g_warning ("g_main_context_check() called recursively from within a source's check() or "
2939 "prepare() member.");
2940 UNLOCK_CONTEXT (context);
2944 #ifdef G_THREADS_ENABLED
2945 if (!context->poll_waiting)
2949 read (context->wake_up_pipe[0], &a, 1);
2953 context->poll_waiting = FALSE;
2955 /* If the set of poll file descriptors changed, bail out
2956 * and let the main loop rerun
2958 if (context->poll_changed)
2960 UNLOCK_CONTEXT (context);
2963 #endif /* G_THREADS_ENABLED */
2965 pollrec = context->poll_records;
2969 if (pollrec->fd->events)
2970 pollrec->fd->revents = fds[i].revents;
2972 pollrec = pollrec->next;
2976 source = next_valid_source (context, NULL);
2979 if ((n_ready > 0) && (source->priority > max_priority))
2981 SOURCE_UNREF (source, context);
2984 if (SOURCE_BLOCKED (source))
2987 if (!(source->flags & G_SOURCE_READY))
2990 gboolean (*check) (GSource *source);
2992 check = source->source_funcs->check;
2994 context->in_check_or_prepare++;
2995 UNLOCK_CONTEXT (context);
2997 result = (*check) (source);
2999 LOCK_CONTEXT (context);
3000 context->in_check_or_prepare--;
3004 GSource *ready_source = source;
3006 while (ready_source)
3008 ready_source->flags |= G_SOURCE_READY;
3009 ready_source = ready_source->priv ? ready_source->priv->parent_source : NULL;
3014 if (source->flags & G_SOURCE_READY)
3016 source->ref_count++;
3017 g_ptr_array_add (context->pending_dispatches, source);
3021 /* never dispatch sources with less priority than the first
3022 * one we choose to dispatch
3024 max_priority = source->priority;
3028 source = next_valid_source (context, source);
3031 UNLOCK_CONTEXT (context);
3037 * g_main_context_dispatch:
3038 * @context: a #GMainContext
3040 * Dispatches all pending sources.
3043 g_main_context_dispatch (GMainContext *context)
3045 LOCK_CONTEXT (context);
3047 if (context->pending_dispatches->len > 0)
3049 g_main_dispatch (context);
3052 UNLOCK_CONTEXT (context);
3055 /* HOLDS context lock */
3057 g_main_context_iterate (GMainContext *context,
3064 gboolean some_ready;
3065 gint nfds, allocated_nfds;
3066 GPollFD *fds = NULL;
3068 UNLOCK_CONTEXT (context);
3070 #ifdef G_THREADS_ENABLED
3071 if (!g_main_context_acquire (context))
3073 gboolean got_ownership;
3075 LOCK_CONTEXT (context);
3077 g_return_val_if_fail (g_thread_supported (), FALSE);
3083 context->cond = g_cond_new ();
3085 got_ownership = g_main_context_wait (context,
3087 g_static_mutex_get_mutex (&context->mutex));
3093 LOCK_CONTEXT (context);
3094 #endif /* G_THREADS_ENABLED */
3096 if (!context->cached_poll_array)
3098 context->cached_poll_array_size = context->n_poll_records;
3099 context->cached_poll_array = g_new (GPollFD, context->n_poll_records);
3102 allocated_nfds = context->cached_poll_array_size;
3103 fds = context->cached_poll_array;
3105 UNLOCK_CONTEXT (context);
3107 g_main_context_prepare (context, &max_priority);
3109 while ((nfds = g_main_context_query (context, max_priority, &timeout, fds,
3110 allocated_nfds)) > allocated_nfds)
3112 LOCK_CONTEXT (context);
3114 context->cached_poll_array_size = allocated_nfds = nfds;
3115 context->cached_poll_array = fds = g_new (GPollFD, nfds);
3116 UNLOCK_CONTEXT (context);
3122 g_main_context_poll (context, timeout, max_priority, fds, nfds);
3124 some_ready = g_main_context_check (context, max_priority, fds, nfds);
3127 g_main_context_dispatch (context);
3129 #ifdef G_THREADS_ENABLED
3130 g_main_context_release (context);
3131 #endif /* G_THREADS_ENABLED */
3133 LOCK_CONTEXT (context);
3139 * g_main_context_pending:
3140 * @context: a #GMainContext (if %NULL, the default context will be used)
3142 * Checks if any sources have pending events for the given context.
3144 * Return value: %TRUE if events are pending.
3147 g_main_context_pending (GMainContext *context)
3152 context = g_main_context_default();
3154 LOCK_CONTEXT (context);
3155 retval = g_main_context_iterate (context, FALSE, FALSE, G_THREAD_SELF);
3156 UNLOCK_CONTEXT (context);
3162 * g_main_context_iteration:
3163 * @context: a #GMainContext (if %NULL, the default context will be used)
3164 * @may_block: whether the call may block.
3166 * Runs a single iteration for the given main loop. This involves
3167 * checking to see if any event sources are ready to be processed,
3168 * then if no events sources are ready and @may_block is %TRUE, waiting
3169 * for a source to become ready, then dispatching the highest priority
3170 * events sources that are ready. Otherwise, if @may_block is %FALSE
3171 * sources are not waited to become ready, only those highest priority
3172 * events sources will be dispatched (if any), that are ready at this
3173 * given moment without further waiting.
3175 * Note that even when @may_block is %TRUE, it is still possible for
3176 * g_main_context_iteration() to return %FALSE, since the the wait may
3177 * be interrupted for other reasons than an event source becoming ready.
3179 * Return value: %TRUE if events were dispatched.
3182 g_main_context_iteration (GMainContext *context, gboolean may_block)
3187 context = g_main_context_default();
3189 LOCK_CONTEXT (context);
3190 retval = g_main_context_iterate (context, may_block, TRUE, G_THREAD_SELF);
3191 UNLOCK_CONTEXT (context);
3198 * @context: a #GMainContext (if %NULL, the default context will be used).
3199 * @is_running: set to %TRUE to indicate that the loop is running. This
3200 * is not very important since calling g_main_loop_run() will set this to
3203 * Creates a new #GMainLoop structure.
3205 * Return value: a new #GMainLoop.
3208 g_main_loop_new (GMainContext *context,
3209 gboolean is_running)
3214 context = g_main_context_default();
3216 g_main_context_ref (context);
3218 loop = g_new0 (GMainLoop, 1);
3219 loop->context = context;
3220 loop->is_running = is_running != FALSE;
3221 loop->ref_count = 1;
3228 * @loop: a #GMainLoop
3230 * Increases the reference count on a #GMainLoop object by one.
3232 * Return value: @loop
3235 g_main_loop_ref (GMainLoop *loop)
3237 g_return_val_if_fail (loop != NULL, NULL);
3238 g_return_val_if_fail (g_atomic_int_get (&loop->ref_count) > 0, NULL);
3240 g_atomic_int_inc (&loop->ref_count);
3246 * g_main_loop_unref:
3247 * @loop: a #GMainLoop
3249 * Decreases the reference count on a #GMainLoop object by one. If
3250 * the result is zero, free the loop and free all associated memory.
3253 g_main_loop_unref (GMainLoop *loop)
3255 g_return_if_fail (loop != NULL);
3256 g_return_if_fail (g_atomic_int_get (&loop->ref_count) > 0);
3258 if (!g_atomic_int_dec_and_test (&loop->ref_count))
3261 g_main_context_unref (loop->context);
3267 * @loop: a #GMainLoop
3269 * Runs a main loop until g_main_loop_quit() is called on the loop.
3270 * If this is called for the thread of the loop's #GMainContext,
3271 * it will process events from the loop, otherwise it will
3275 g_main_loop_run (GMainLoop *loop)
3277 GThread *self = G_THREAD_SELF;
3279 g_return_if_fail (loop != NULL);
3280 g_return_if_fail (g_atomic_int_get (&loop->ref_count) > 0);
3282 #ifdef G_THREADS_ENABLED
3283 if (!g_main_context_acquire (loop->context))
3285 gboolean got_ownership = FALSE;
3287 /* Another thread owns this context */
3288 if (!g_thread_supported ())
3290 g_warning ("g_main_loop_run() was called from second thread but "
3291 "g_thread_init() was never called.");
3295 LOCK_CONTEXT (loop->context);
3297 g_atomic_int_inc (&loop->ref_count);
3299 if (!loop->is_running)
3300 loop->is_running = TRUE;
3302 if (!loop->context->cond)
3303 loop->context->cond = g_cond_new ();
3305 while (loop->is_running && !got_ownership)
3306 got_ownership = g_main_context_wait (loop->context,
3307 loop->context->cond,
3308 g_static_mutex_get_mutex (&loop->context->mutex));
3310 if (!loop->is_running)
3312 UNLOCK_CONTEXT (loop->context);
3314 g_main_context_release (loop->context);
3315 g_main_loop_unref (loop);
3319 g_assert (got_ownership);
3322 LOCK_CONTEXT (loop->context);
3323 #endif /* G_THREADS_ENABLED */
3325 if (loop->context->in_check_or_prepare)
3327 g_warning ("g_main_loop_run(): called recursively from within a source's "
3328 "check() or prepare() member, iteration not possible.");
3332 g_atomic_int_inc (&loop->ref_count);
3333 loop->is_running = TRUE;
3334 while (loop->is_running)
3335 g_main_context_iterate (loop->context, TRUE, TRUE, self);
3337 UNLOCK_CONTEXT (loop->context);
3339 #ifdef G_THREADS_ENABLED
3340 g_main_context_release (loop->context);
3341 #endif /* G_THREADS_ENABLED */
3343 g_main_loop_unref (loop);
3348 * @loop: a #GMainLoop
3350 * Stops a #GMainLoop from running. Any calls to g_main_loop_run()
3351 * for the loop will return.
3353 * Note that sources that have already been dispatched when
3354 * g_main_loop_quit() is called will still be executed.
3357 g_main_loop_quit (GMainLoop *loop)
3359 g_return_if_fail (loop != NULL);
3360 g_return_if_fail (g_atomic_int_get (&loop->ref_count) > 0);
3362 LOCK_CONTEXT (loop->context);
3363 loop->is_running = FALSE;
3364 g_main_context_wakeup_unlocked (loop->context);
3366 #ifdef G_THREADS_ENABLED
3367 if (loop->context->cond)
3368 g_cond_broadcast (loop->context->cond);
3369 #endif /* G_THREADS_ENABLED */
3371 UNLOCK_CONTEXT (loop->context);
3375 * g_main_loop_is_running:
3376 * @loop: a #GMainLoop.
3378 * Checks to see if the main loop is currently being run via g_main_loop_run().
3380 * Return value: %TRUE if the mainloop is currently being run.
3383 g_main_loop_is_running (GMainLoop *loop)
3385 g_return_val_if_fail (loop != NULL, FALSE);
3386 g_return_val_if_fail (g_atomic_int_get (&loop->ref_count) > 0, FALSE);
3388 return loop->is_running;
3392 * g_main_loop_get_context:
3393 * @loop: a #GMainLoop.
3395 * Returns the #GMainContext of @loop.
3397 * Return value: the #GMainContext of @loop
3400 g_main_loop_get_context (GMainLoop *loop)
3402 g_return_val_if_fail (loop != NULL, NULL);
3403 g_return_val_if_fail (g_atomic_int_get (&loop->ref_count) > 0, NULL);
3405 return loop->context;
3408 /* HOLDS: context's lock */
3410 g_main_context_poll (GMainContext *context,
3416 #ifdef G_MAIN_POLL_DEBUG
3422 GPollFunc poll_func;
3424 if (n_fds || timeout != 0)
3426 #ifdef G_MAIN_POLL_DEBUG
3427 if (_g_main_poll_debug)
3429 g_print ("polling context=%p n=%d timeout=%d\n",
3430 context, n_fds, timeout);
3431 poll_timer = g_timer_new ();
3435 LOCK_CONTEXT (context);
3437 poll_func = context->poll_func;
3439 UNLOCK_CONTEXT (context);
3440 if ((*poll_func) (fds, n_fds, timeout) < 0 && errno != EINTR)
3443 g_warning ("poll(2) failed due to: %s.",
3444 g_strerror (errno));
3446 /* If g_poll () returns -1, it has already called g_warning() */
3450 #ifdef G_MAIN_POLL_DEBUG
3451 if (_g_main_poll_debug)
3453 LOCK_CONTEXT (context);
3455 g_print ("g_main_poll(%d) timeout: %d - elapsed %12.10f seconds",
3458 g_timer_elapsed (poll_timer, NULL));
3459 g_timer_destroy (poll_timer);
3460 pollrec = context->poll_records;
3462 while (pollrec != NULL)
3467 if (fds[i].fd == pollrec->fd->fd &&
3468 pollrec->fd->events &&
3471 g_print (" [" G_POLLFD_FORMAT " :", fds[i].fd);
3472 if (fds[i].revents & G_IO_IN)
3474 if (fds[i].revents & G_IO_OUT)
3476 if (fds[i].revents & G_IO_PRI)
3478 if (fds[i].revents & G_IO_ERR)
3480 if (fds[i].revents & G_IO_HUP)
3482 if (fds[i].revents & G_IO_NVAL)
3488 pollrec = pollrec->next;
3492 UNLOCK_CONTEXT (context);
3495 } /* if (n_fds || timeout != 0) */
3499 * g_main_context_add_poll:
3500 * @context: a #GMainContext (or %NULL for the default context)
3501 * @fd: a #GPollFD structure holding information about a file
3502 * descriptor to watch.
3503 * @priority: the priority for this file descriptor which should be
3504 * the same as the priority used for g_source_attach() to ensure that the
3505 * file descriptor is polled whenever the results may be needed.
3507 * Adds a file descriptor to the set of file descriptors polled for
3508 * this context. This will very seldomly be used directly. Instead
3509 * a typical event source will use g_source_add_poll() instead.
3512 g_main_context_add_poll (GMainContext *context,
3517 context = g_main_context_default ();
3519 g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
3520 g_return_if_fail (fd);
3522 LOCK_CONTEXT (context);
3523 g_main_context_add_poll_unlocked (context, priority, fd);
3524 UNLOCK_CONTEXT (context);
3527 /* HOLDS: main_loop_lock */
3529 g_main_context_add_poll_unlocked (GMainContext *context,
3533 GPollRec *lastrec, *pollrec;
3534 GPollRec *newrec = g_slice_new (GPollRec);
3536 /* This file descriptor may be checked before we ever poll */
3539 newrec->priority = priority;
3542 pollrec = context->poll_records;
3543 while (pollrec && priority >= pollrec->priority)
3546 pollrec = pollrec->next;
3550 lastrec->next = newrec;
3552 context->poll_records = newrec;
3554 newrec->next = pollrec;
3556 context->n_poll_records++;
3558 #ifdef G_THREADS_ENABLED
3559 context->poll_changed = TRUE;
3561 /* Now wake up the main loop if it is waiting in the poll() */
3562 g_main_context_wakeup_unlocked (context);
3567 * g_main_context_remove_poll:
3568 * @context:a #GMainContext
3569 * @fd: a #GPollFD descriptor previously added with g_main_context_add_poll()
3571 * Removes file descriptor from the set of file descriptors to be
3572 * polled for a particular context.
3575 g_main_context_remove_poll (GMainContext *context,
3579 context = g_main_context_default ();
3581 g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
3582 g_return_if_fail (fd);
3584 LOCK_CONTEXT (context);
3585 g_main_context_remove_poll_unlocked (context, fd);
3586 UNLOCK_CONTEXT (context);
3590 g_main_context_remove_poll_unlocked (GMainContext *context,
3593 GPollRec *pollrec, *lastrec;
3596 pollrec = context->poll_records;
3600 if (pollrec->fd == fd)
3602 if (lastrec != NULL)
3603 lastrec->next = pollrec->next;
3605 context->poll_records = pollrec->next;
3607 g_slice_free (GPollRec, pollrec);
3609 context->n_poll_records--;
3613 pollrec = pollrec->next;
3616 #ifdef G_THREADS_ENABLED
3617 context->poll_changed = TRUE;
3619 /* Now wake up the main loop if it is waiting in the poll() */
3620 g_main_context_wakeup_unlocked (context);
3625 * g_source_get_current_time:
3626 * @source: a #GSource
3627 * @timeval: #GTimeVal structure in which to store current time.
3629 * Gets the "current time" to be used when checking
3630 * this source. The advantage of calling this function over
3631 * calling g_get_current_time() directly is that when
3632 * checking multiple sources, GLib can cache a single value
3633 * instead of having to repeatedly get the system time.
3635 * Deprecated: 2.28: use g_source_get_time() instead
3638 g_source_get_current_time (GSource *source,
3641 GMainContext *context;
3643 g_return_if_fail (source->context != NULL);
3645 context = source->context;
3647 LOCK_CONTEXT (context);
3649 if (!context->real_time_is_fresh)
3651 context->real_time = g_get_real_time ();
3652 context->real_time_is_fresh = TRUE;
3655 timeval->tv_sec = context->real_time / 1000000;
3656 timeval->tv_usec = context->real_time % 1000000;
3658 UNLOCK_CONTEXT (context);
3662 * g_source_get_time:
3663 * @source: a #GSource
3665 * Gets the time to be used when checking this source. The advantage of
3666 * calling this function over calling g_get_monotonic_time() directly is
3667 * that when checking multiple sources, GLib can cache a single value
3668 * instead of having to repeatedly get the system monotonic time.
3670 * The time here is the system monotonic time, if available, or some
3671 * other reasonable alternative otherwise. See g_get_monotonic_time().
3673 * Returns: the monotonic time in microseconds
3678 g_source_get_time (GSource *source)
3680 GMainContext *context;
3683 g_return_val_if_fail (source->context != NULL, 0);
3685 context = source->context;
3687 LOCK_CONTEXT (context);
3689 if (!context->time_is_fresh)
3691 context->time = g_get_monotonic_time ();
3692 context->time_is_fresh = TRUE;
3695 result = context->time;
3697 UNLOCK_CONTEXT (context);
3703 * g_main_context_set_poll_func:
3704 * @context: a #GMainContext
3705 * @func: the function to call to poll all file descriptors
3707 * Sets the function to use to handle polling of file descriptors. It
3708 * will be used instead of the poll() system call
3709 * (or GLib's replacement function, which is used where
3710 * poll() isn't available).
3712 * This function could possibly be used to integrate the GLib event
3713 * loop with an external event loop.
3716 g_main_context_set_poll_func (GMainContext *context,
3720 context = g_main_context_default ();
3722 g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
3724 LOCK_CONTEXT (context);
3727 context->poll_func = func;
3729 context->poll_func = g_poll;
3731 UNLOCK_CONTEXT (context);
3735 * g_main_context_get_poll_func:
3736 * @context: a #GMainContext
3738 * Gets the poll function set by g_main_context_set_poll_func().
3740 * Return value: the poll function
3743 g_main_context_get_poll_func (GMainContext *context)
3748 context = g_main_context_default ();
3750 g_return_val_if_fail (g_atomic_int_get (&context->ref_count) > 0, NULL);
3752 LOCK_CONTEXT (context);
3753 result = context->poll_func;
3754 UNLOCK_CONTEXT (context);
3760 _g_main_wake_up_all_contexts (void)
3764 /* We were woken up. Wake up all other contexts in all other threads */
3765 G_LOCK (main_context_list);
3766 for (list = main_context_list; list; list = list->next)
3768 GMainContext *context;
3770 context = list->data;
3771 if (g_atomic_int_get (&context->ref_count) > 0)
3772 /* Due to racing conditions we can find ref_count == 0, in
3773 * that case, however, the context is still not destroyed
3774 * and no poll can be active, otherwise the ref_count
3777 g_main_context_wakeup (context);
3779 G_UNLOCK (main_context_list);
3783 /* HOLDS: context's lock */
3784 /* Wake the main loop up from a poll() */
3786 g_main_context_wakeup_unlocked (GMainContext *context)
3788 #ifdef G_THREADS_ENABLED
3789 if (g_thread_supported() && context->poll_waiting)
3791 context->poll_waiting = FALSE;
3793 write (context->wake_up_pipe[1], "A", 1);
3795 ReleaseSemaphore (context->wake_up_semaphore, 1, NULL);
3802 * g_main_context_wakeup:
3803 * @context: a #GMainContext
3805 * If @context is currently waiting in a poll(), interrupt
3806 * the poll(), and continue the iteration process.
3809 g_main_context_wakeup (GMainContext *context)
3812 context = g_main_context_default ();
3814 g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
3816 LOCK_CONTEXT (context);
3817 g_main_context_wakeup_unlocked (context);
3818 UNLOCK_CONTEXT (context);
3822 * g_main_context_is_owner:
3823 * @context: a #GMainContext
3825 * Determines whether this thread holds the (recursive)
3826 * ownership of this #GMaincontext. This is useful to
3827 * know before waiting on another thread that may be
3828 * blocking to get ownership of @context.
3830 * Returns: %TRUE if current thread is owner of @context.
3835 g_main_context_is_owner (GMainContext *context)
3840 context = g_main_context_default ();
3842 #ifdef G_THREADS_ENABLED
3843 LOCK_CONTEXT (context);
3844 is_owner = context->owner == G_THREAD_SELF;
3845 UNLOCK_CONTEXT (context);
3856 g_timeout_set_expiration (GTimeoutSource *timeout_source,
3857 gint64 current_time)
3859 timeout_source->expiration = current_time +
3860 (guint64) timeout_source->interval * 1000;
3862 if (timeout_source->seconds)
3865 static gint timer_perturb = -1;
3867 if (timer_perturb == -1)
3870 * we want a per machine/session unique 'random' value; try the dbus
3871 * address first, that has a UUID in it. If there is no dbus, use the
3872 * hostname for hashing.
3874 const char *session_bus_address = g_getenv ("DBUS_SESSION_BUS_ADDRESS");
3875 if (!session_bus_address)
3876 session_bus_address = g_getenv ("HOSTNAME");
3877 if (session_bus_address)
3878 timer_perturb = ABS ((gint) g_str_hash (session_bus_address)) % 1000000;
3883 /* We want the microseconds part of the timeout to land on the
3884 * 'timer_perturb' mark, but we need to make sure we don't try to
3885 * set the timeout in the past. We do this by ensuring that we
3886 * always only *increase* the expiration time by adding a full
3887 * second in the case that the microsecond portion decreases.
3889 timeout_source->expiration -= timer_perturb;
3891 remainder = timeout_source->expiration % 1000000;
3892 if (remainder >= 1000000/4)
3893 timeout_source->expiration += 1000000;
3895 timeout_source->expiration -= remainder;
3896 timeout_source->expiration += timer_perturb;
3901 g_timeout_prepare (GSource *source,
3904 GTimeoutSource *timeout_source = (GTimeoutSource *) source;
3905 gint64 now = g_source_get_time (source);
3907 if (now < timeout_source->expiration)
3909 /* Round up to ensure that we don't try again too early */
3910 *timeout = (timeout_source->expiration - now + 999) / 1000;
3919 g_timeout_check (GSource *source)
3921 GTimeoutSource *timeout_source = (GTimeoutSource *) source;
3922 gint64 now = g_source_get_time (source);
3924 return timeout_source->expiration <= now;
3928 g_timeout_dispatch (GSource *source,
3929 GSourceFunc callback,
3932 GTimeoutSource *timeout_source = (GTimeoutSource *)source;
3937 g_warning ("Timeout source dispatched without callback\n"
3938 "You must call g_source_set_callback().");
3942 again = callback (user_data);
3945 g_timeout_set_expiration (timeout_source, g_source_get_time (source));
3951 * g_timeout_source_new:
3952 * @interval: the timeout interval in milliseconds.
3954 * Creates a new timeout source.
3956 * The source will not initially be associated with any #GMainContext
3957 * and must be added to one with g_source_attach() before it will be
3960 * Return value: the newly-created timeout source
3963 g_timeout_source_new (guint interval)
3965 GSource *source = g_source_new (&g_timeout_funcs, sizeof (GTimeoutSource));
3966 GTimeoutSource *timeout_source = (GTimeoutSource *)source;
3968 timeout_source->interval = interval;
3969 g_timeout_set_expiration (timeout_source, g_get_monotonic_time ());
3975 * g_timeout_source_new_seconds:
3976 * @interval: the timeout interval in seconds
3978 * Creates a new timeout source.
3980 * The source will not initially be associated with any #GMainContext
3981 * and must be added to one with g_source_attach() before it will be
3984 * The scheduling granularity/accuracy of this timeout source will be
3987 * Return value: the newly-created timeout source
3992 g_timeout_source_new_seconds (guint interval)
3994 GSource *source = g_source_new (&g_timeout_funcs, sizeof (GTimeoutSource));
3995 GTimeoutSource *timeout_source = (GTimeoutSource *)source;
3997 timeout_source->interval = 1000 * interval;
3998 timeout_source->seconds = TRUE;
4000 g_timeout_set_expiration (timeout_source, g_get_monotonic_time ());
4007 * g_timeout_add_full:
4008 * @priority: the priority of the timeout source. Typically this will be in
4009 * the range between #G_PRIORITY_DEFAULT and #G_PRIORITY_HIGH.
4010 * @interval: the time between calls to the function, in milliseconds
4011 * (1/1000ths of a second)
4012 * @function: function to call
4013 * @data: data to pass to @function
4014 * @notify: function to call when the timeout is removed, or %NULL
4016 * Sets a function to be called at regular intervals, with the given
4017 * priority. The function is called repeatedly until it returns
4018 * %FALSE, at which point the timeout is automatically destroyed and
4019 * the function will not be called again. The @notify function is
4020 * called when the timeout is destroyed. The first call to the
4021 * function will be at the end of the first @interval.
4023 * Note that timeout functions may be delayed, due to the processing of other
4024 * event sources. Thus they should not be relied on for precise timing.
4025 * After each call to the timeout function, the time of the next
4026 * timeout is recalculated based on the current time and the given interval
4027 * (it does not try to 'catch up' time lost in delays).
4029 * This internally creates a main loop source using g_timeout_source_new()
4030 * and attaches it to the main loop context using g_source_attach(). You can
4031 * do these steps manually if you need greater control.
4033 * Return value: the ID (greater than 0) of the event source.
4036 g_timeout_add_full (gint priority,
4038 GSourceFunc function,
4040 GDestroyNotify notify)
4045 g_return_val_if_fail (function != NULL, 0);
4047 source = g_timeout_source_new (interval);
4049 if (priority != G_PRIORITY_DEFAULT)
4050 g_source_set_priority (source, priority);
4052 g_source_set_callback (source, function, data, notify);
4053 id = g_source_attach (source, NULL);
4054 g_source_unref (source);
4061 * @interval: the time between calls to the function, in milliseconds
4062 * (1/1000ths of a second)
4063 * @function: function to call
4064 * @data: data to pass to @function
4066 * Sets a function to be called at regular intervals, with the default
4067 * priority, #G_PRIORITY_DEFAULT. The function is called repeatedly
4068 * until it returns %FALSE, at which point the timeout is automatically
4069 * destroyed and the function will not be called again. The first call
4070 * to the function will be at the end of the first @interval.
4072 * Note that timeout functions may be delayed, due to the processing of other
4073 * event sources. Thus they should not be relied on for precise timing.
4074 * After each call to the timeout function, the time of the next
4075 * timeout is recalculated based on the current time and the given interval
4076 * (it does not try to 'catch up' time lost in delays).
4078 * If you want to have a timer in the "seconds" range and do not care
4079 * about the exact time of the first call of the timer, use the
4080 * g_timeout_add_seconds() function; this function allows for more
4081 * optimizations and more efficient system power usage.
4083 * This internally creates a main loop source using g_timeout_source_new()
4084 * and attaches it to the main loop context using g_source_attach(). You can
4085 * do these steps manually if you need greater control.
4087 * Return value: the ID (greater than 0) of the event source.
4090 g_timeout_add (guint32 interval,
4091 GSourceFunc function,
4094 return g_timeout_add_full (G_PRIORITY_DEFAULT,
4095 interval, function, data, NULL);
4099 * g_timeout_add_seconds_full:
4100 * @priority: the priority of the timeout source. Typically this will be in
4101 * the range between #G_PRIORITY_DEFAULT and #G_PRIORITY_HIGH.
4102 * @interval: the time between calls to the function, in seconds
4103 * @function: function to call
4104 * @data: data to pass to @function
4105 * @notify: function to call when the timeout is removed, or %NULL
4107 * Sets a function to be called at regular intervals, with @priority.
4108 * The function is called repeatedly until it returns %FALSE, at which
4109 * point the timeout is automatically destroyed and the function will
4110 * not be called again.
4112 * Unlike g_timeout_add(), this function operates at whole second granularity.
4113 * The initial starting point of the timer is determined by the implementation
4114 * and the implementation is expected to group multiple timers together so that
4115 * they fire all at the same time.
4116 * To allow this grouping, the @interval to the first timer is rounded
4117 * and can deviate up to one second from the specified interval.
4118 * Subsequent timer iterations will generally run at the specified interval.
4120 * Note that timeout functions may be delayed, due to the processing of other
4121 * event sources. Thus they should not be relied on for precise timing.
4122 * After each call to the timeout function, the time of the next
4123 * timeout is recalculated based on the current time and the given @interval
4125 * If you want timing more precise than whole seconds, use g_timeout_add()
4128 * The grouping of timers to fire at the same time results in a more power
4129 * and CPU efficient behavior so if your timer is in multiples of seconds
4130 * and you don't require the first timer exactly one second from now, the
4131 * use of g_timeout_add_seconds() is preferred over g_timeout_add().
4133 * This internally creates a main loop source using
4134 * g_timeout_source_new_seconds() and attaches it to the main loop context
4135 * using g_source_attach(). You can do these steps manually if you need
4138 * Return value: the ID (greater than 0) of the event source.
4143 g_timeout_add_seconds_full (gint priority,
4145 GSourceFunc function,
4147 GDestroyNotify notify)
4152 g_return_val_if_fail (function != NULL, 0);
4154 source = g_timeout_source_new_seconds (interval);
4156 if (priority != G_PRIORITY_DEFAULT)
4157 g_source_set_priority (source, priority);
4159 g_source_set_callback (source, function, data, notify);
4160 id = g_source_attach (source, NULL);
4161 g_source_unref (source);
4167 * g_timeout_add_seconds:
4168 * @interval: the time between calls to the function, in seconds
4169 * @function: function to call
4170 * @data: data to pass to @function
4172 * Sets a function to be called at regular intervals with the default
4173 * priority, #G_PRIORITY_DEFAULT. The function is called repeatedly until
4174 * it returns %FALSE, at which point the timeout is automatically destroyed
4175 * and the function will not be called again.
4177 * This internally creates a main loop source using
4178 * g_timeout_source_new_seconds() and attaches it to the main loop context
4179 * using g_source_attach(). You can do these steps manually if you need
4180 * greater control. Also see g_timout_add_seconds_full().
4182 * Note that the first call of the timer may not be precise for timeouts
4183 * of one second. If you need finer precision and have such a timeout,
4184 * you may want to use g_timeout_add() instead.
4186 * Return value: the ID (greater than 0) of the event source.
4191 g_timeout_add_seconds (guint interval,
4192 GSourceFunc function,
4195 g_return_val_if_fail (function != NULL, 0);
4197 return g_timeout_add_seconds_full (G_PRIORITY_DEFAULT, interval, function, data, NULL);
4200 /* Child watch functions */
4205 g_child_watch_prepare (GSource *source,
4214 g_child_watch_check (GSource *source)
4216 GChildWatchSource *child_watch_source;
4217 gboolean child_exited;
4219 child_watch_source = (GChildWatchSource *) source;
4221 child_exited = child_watch_source->poll.revents & G_IO_IN;
4228 * Note: We do _not_ check for the special value of STILL_ACTIVE
4229 * since we know that the process has exited and doing so runs into
4230 * problems if the child process "happens to return STILL_ACTIVE(259)"
4231 * as Microsoft's Platform SDK puts it.
4233 if (!GetExitCodeProcess (child_watch_source->pid, &child_status))
4235 gchar *emsg = g_win32_error_message (GetLastError ());
4236 g_warning (G_STRLOC ": GetExitCodeProcess() failed: %s", emsg);
4239 child_watch_source->child_status = -1;
4242 child_watch_source->child_status = child_status;
4245 return child_exited;
4248 #else /* G_OS_WIN32 */
4251 check_for_child_exited (GSource *source)
4253 GChildWatchSource *child_watch_source;
4256 /* protect against another SIGCHLD in the middle of this call */
4257 count = child_watch_count;
4259 child_watch_source = (GChildWatchSource *) source;
4261 if (child_watch_source->child_exited)
4264 if (child_watch_source->count < count)
4268 if (waitpid (child_watch_source->pid, &child_status, WNOHANG) > 0)
4270 child_watch_source->child_status = child_status;
4271 child_watch_source->child_exited = TRUE;
4273 child_watch_source->count = count;
4276 return child_watch_source->child_exited;
4280 g_child_watch_prepare (GSource *source,
4285 return check_for_child_exited (source);
4289 g_child_watch_check (GSource *source)
4291 return check_for_child_exited (source);
4295 check_for_signal_delivery (GSource *source)
4297 GUnixSignalWatchSource *unix_signal_source = (GUnixSignalWatchSource*) source;
4300 G_LOCK (unix_signal_lock);
4301 if (unix_signal_init_state == UNIX_SIGNAL_INITIALIZED_SINGLE)
4303 switch (unix_signal_source->signum)
4306 delivered = unix_signal_state.sighup_delivered;
4309 delivered = unix_signal_state.sigint_delivered;
4312 delivered = unix_signal_state.sigterm_delivered;
4315 g_assert_not_reached ();
4322 g_assert (unix_signal_init_state == UNIX_SIGNAL_INITIALIZED_THREADED);
4323 delivered = unix_signal_source->pending;
4325 G_UNLOCK (unix_signal_lock);
4331 g_unix_signal_watch_prepare (GSource *source,
4336 return check_for_signal_delivery (source);
4340 g_unix_signal_watch_check (GSource *source)
4342 return check_for_signal_delivery (source);
4346 g_unix_signal_watch_dispatch (GSource *source,
4347 GSourceFunc callback,
4350 GUnixSignalWatchSource *unix_signal_source;
4352 unix_signal_source = (GUnixSignalWatchSource *) source;
4356 g_warning ("Unix signal source dispatched without callback\n"
4357 "You must call g_source_set_callback().");
4361 (callback) (user_data);
4363 G_LOCK (unix_signal_lock);
4364 if (unix_signal_init_state == UNIX_SIGNAL_INITIALIZED_SINGLE)
4366 switch (unix_signal_source->signum)
4369 unix_signal_state.sighup_delivered = FALSE;
4372 unix_signal_state.sigint_delivered = FALSE;
4375 unix_signal_state.sigterm_delivered = FALSE;
4381 g_assert (unix_signal_init_state == UNIX_SIGNAL_INITIALIZED_THREADED);
4382 unix_signal_source->pending = FALSE;
4384 G_UNLOCK (unix_signal_lock);
4390 ensure_unix_signal_handler_installed_unlocked (int signum)
4392 struct sigaction action;
4393 GError *error = NULL;
4395 if (unix_signal_init_state == UNIX_SIGNAL_UNINITIALIZED
4396 || unix_signal_init_state == UNIX_SIGNAL_INITIALIZED_SINGLE)
4398 if (!g_thread_supported ())
4400 /* There is nothing to do for initializing in the non-threaded
4403 if (unix_signal_init_state == UNIX_SIGNAL_UNINITIALIZED)
4404 unix_signal_init_state = UNIX_SIGNAL_INITIALIZED_SINGLE;
4408 if (!g_unix_open_pipe (unix_signal_wake_up_pipe, FD_CLOEXEC, &error))
4409 g_error ("Cannot create UNIX signal wake up pipe: %s\n", error->message);
4410 g_unix_set_fd_nonblocking (unix_signal_wake_up_pipe[1], TRUE, NULL);
4412 /* We create a helper thread that polls on the wakeup pipe indefinitely */
4413 if (g_thread_create (unix_signal_helper_thread, NULL, FALSE, &error) == NULL)
4414 g_error ("Cannot create a thread to monitor UNIX signals: %s\n", error->message);
4416 unix_signal_init_state = UNIX_SIGNAL_INITIALIZED_THREADED;
4423 if (unix_signal_state.sigchld_handler_installed)
4425 unix_signal_state.sigchld_handler_installed = TRUE;
4427 if (unix_signal_state.sighup_handler_installed)
4429 unix_signal_state.sighup_handler_installed = TRUE;
4432 if (unix_signal_state.sigint_handler_installed)
4434 unix_signal_state.sigint_handler_installed = TRUE;
4437 if (unix_signal_state.sigterm_handler_installed)
4439 unix_signal_state.sigterm_handler_installed = TRUE;
4443 action.sa_handler = g_unix_signal_handler;
4444 sigemptyset (&action.sa_mask);
4445 action.sa_flags = SA_RESTART | SA_NOCLDSTOP;
4446 sigaction (signum, &action, NULL);
4450 _g_main_create_unix_signal_watch (int signum)
4453 GUnixSignalWatchSource *unix_signal_source;
4455 source = g_source_new (&g_unix_signal_funcs, sizeof (GUnixSignalWatchSource));
4456 unix_signal_source = (GUnixSignalWatchSource *) source;
4458 unix_signal_source->signum = signum;
4459 unix_signal_source->pending = FALSE;
4461 G_LOCK (unix_signal_lock);
4462 ensure_unix_signal_handler_installed_unlocked (signum);
4463 unix_signal_watches = g_slist_prepend (unix_signal_watches, unix_signal_source);
4464 G_UNLOCK (unix_signal_lock);
4470 g_unix_signal_watch_finalize (GSource *source)
4472 G_LOCK (unix_signal_lock);
4473 unix_signal_watches = g_slist_remove (unix_signal_watches, source);
4474 G_UNLOCK (unix_signal_lock);
4477 #endif /* G_OS_WIN32 */
4480 g_child_watch_dispatch (GSource *source,
4481 GSourceFunc callback,
4484 GChildWatchSource *child_watch_source;
4485 GChildWatchFunc child_watch_callback = (GChildWatchFunc) callback;
4487 child_watch_source = (GChildWatchSource *) source;
4491 g_warning ("Child watch source dispatched without callback\n"
4492 "You must call g_source_set_callback().");
4496 (child_watch_callback) (child_watch_source->pid, child_watch_source->child_status, user_data);
4498 /* We never keep a child watch source around as the child is gone */
4505 g_unix_signal_handler (int signum)
4507 if (signum == SIGCHLD)
4508 child_watch_count ++;
4510 if (unix_signal_init_state == UNIX_SIGNAL_INITIALIZED_THREADED)
4516 buf[0] = _UNIX_SIGNAL_PIPE_SIGCHLD_CHAR;
4519 buf[0] = _UNIX_SIGNAL_PIPE_SIGHUP_CHAR;
4522 buf[0] = _UNIX_SIGNAL_PIPE_SIGINT_CHAR;
4525 buf[0] = _UNIX_SIGNAL_PIPE_SIGTERM_CHAR;
4528 /* Shouldn't happen */
4531 write (unix_signal_wake_up_pipe[1], buf, 1);
4535 /* We count on the signal interrupting the poll in the same thread. */
4539 /* Nothing to do - the handler will call waitpid() */
4542 unix_signal_state.sighup_delivered = TRUE;
4545 unix_signal_state.sigint_delivered = TRUE;
4548 unix_signal_state.sigterm_delivered = TRUE;
4551 g_assert_not_reached ();
4558 deliver_unix_signal (int signum)
4561 g_assert (signum == SIGHUP || signum == SIGINT || signum == SIGTERM);
4563 G_LOCK (unix_signal_lock);
4564 for (iter = unix_signal_watches; iter; iter = iter->next)
4566 GUnixSignalWatchSource *source = iter->data;
4568 if (source->signum != signum)
4571 source->pending = TRUE;
4573 G_UNLOCK (unix_signal_lock);
4577 * This thread is created whenever anything in GLib needs
4578 * to deal with UNIX signals; at present, just SIGCHLD
4579 * from g_child_watch_source_new().
4581 * Note: We could eventually make this thread a more public interface
4582 * and allow e.g. GDBus to use it instead of its own worker thread.
4585 unix_signal_helper_thread (gpointer data)
4590 ssize_t i, bytes_read;
4591 gboolean sigterm_received = FALSE;
4592 gboolean sigint_received = FALSE;
4593 gboolean sighup_received = FALSE;
4595 bytes_read = read (unix_signal_wake_up_pipe[0], b, sizeof (b));
4598 g_warning ("Failed to read from child watch wake up pipe: %s",
4600 /* Not much we can do here sanely; just wait a second and hope
4603 g_usleep (G_USEC_PER_SEC);
4606 for (i = 0; i < bytes_read; i++)
4610 case _UNIX_SIGNAL_PIPE_SIGCHLD_CHAR:
4611 /* The child watch source will call waitpid() in its
4612 * prepare() and check() methods; however, we don't
4613 * know which pid exited, so we need to wake up
4614 * all contexts. Note: actually we could get the pid
4615 * from the "siginfo_t" via the handler, but to pass
4616 * that info down the pipe would require a more structured
4617 * data stream (as opposed to a single byte).
4620 case _UNIX_SIGNAL_PIPE_SIGTERM_CHAR:
4621 sigterm_received = TRUE;
4623 case _UNIX_SIGNAL_PIPE_SIGHUP_CHAR:
4624 sighup_received = TRUE;
4626 case _UNIX_SIGNAL_PIPE_SIGINT_CHAR:
4627 sigint_received = TRUE;
4630 g_warning ("Invalid char '%c' read from child watch pipe", b[i]);
4633 if (sigterm_received)
4634 deliver_unix_signal (SIGTERM);
4635 if (sigint_received)
4636 deliver_unix_signal (SIGINT);
4637 if (sighup_received)
4638 deliver_unix_signal (SIGHUP);
4639 _g_main_wake_up_all_contexts ();
4645 g_child_watch_source_init (void)
4647 G_LOCK (unix_signal_lock);
4648 ensure_unix_signal_handler_installed_unlocked (SIGCHLD);
4649 G_UNLOCK (unix_signal_lock);
4652 #endif /* !G_OS_WIN32 */
4655 * g_child_watch_source_new:
4656 * @pid: process to watch. On POSIX the pid of a child process. On
4657 * Windows a handle for a process (which doesn't have to be a child).
4659 * Creates a new child_watch source.
4661 * The source will not initially be associated with any #GMainContext
4662 * and must be added to one with g_source_attach() before it will be
4665 * Note that child watch sources can only be used in conjunction with
4666 * <literal>g_spawn...</literal> when the %G_SPAWN_DO_NOT_REAP_CHILD
4669 * Note that on platforms where #GPid must be explicitly closed
4670 * (see g_spawn_close_pid()) @pid must not be closed while the
4671 * source is still active. Typically, you will want to call
4672 * g_spawn_close_pid() in the callback function for the source.
4674 * Note further that using g_child_watch_source_new() is not
4675 * compatible with calling <literal>waitpid(-1)</literal> in
4676 * the application. Calling waitpid() for individual pids will
4679 * Return value: the newly-created child watch source
4684 g_child_watch_source_new (GPid pid)
4686 GSource *source = g_source_new (&g_child_watch_funcs, sizeof (GChildWatchSource));
4687 GChildWatchSource *child_watch_source = (GChildWatchSource *)source;
4690 child_watch_source->poll.fd = (gintptr) pid;
4691 child_watch_source->poll.events = G_IO_IN;
4693 g_source_add_poll (source, &child_watch_source->poll);
4694 #else /* G_OS_WIN32 */
4695 g_child_watch_source_init ();
4696 #endif /* G_OS_WIN32 */
4698 child_watch_source->pid = pid;
4704 * g_child_watch_add_full:
4705 * @priority: the priority of the idle source. Typically this will be in the
4706 * range between #G_PRIORITY_DEFAULT_IDLE and #G_PRIORITY_HIGH_IDLE.
4707 * @pid: process to watch. On POSIX the pid of a child process. On
4708 * Windows a handle for a process (which doesn't have to be a child).
4709 * @function: function to call
4710 * @data: data to pass to @function
4711 * @notify: function to call when the idle is removed, or %NULL
4713 * Sets a function to be called when the child indicated by @pid
4714 * exits, at the priority @priority.
4716 * If you obtain @pid from g_spawn_async() or g_spawn_async_with_pipes()
4717 * you will need to pass #G_SPAWN_DO_NOT_REAP_CHILD as flag to
4718 * the spawn function for the child watching to work.
4720 * Note that on platforms where #GPid must be explicitly closed
4721 * (see g_spawn_close_pid()) @pid must not be closed while the
4722 * source is still active. Typically, you will want to call
4723 * g_spawn_close_pid() in the callback function for the source.
4725 * GLib supports only a single callback per process id.
4727 * This internally creates a main loop source using
4728 * g_child_watch_source_new() and attaches it to the main loop context
4729 * using g_source_attach(). You can do these steps manually if you
4730 * need greater control.
4732 * Return value: the ID (greater than 0) of the event source.
4737 g_child_watch_add_full (gint priority,
4739 GChildWatchFunc function,
4741 GDestroyNotify notify)
4746 g_return_val_if_fail (function != NULL, 0);
4748 source = g_child_watch_source_new (pid);
4750 if (priority != G_PRIORITY_DEFAULT)
4751 g_source_set_priority (source, priority);
4753 g_source_set_callback (source, (GSourceFunc) function, data, notify);
4754 id = g_source_attach (source, NULL);
4755 g_source_unref (source);
4761 * g_child_watch_add:
4762 * @pid: process id to watch. On POSIX the pid of a child process. On
4763 * Windows a handle for a process (which doesn't have to be a child).
4764 * @function: function to call
4765 * @data: data to pass to @function
4767 * Sets a function to be called when the child indicated by @pid
4768 * exits, at a default priority, #G_PRIORITY_DEFAULT.
4770 * If you obtain @pid from g_spawn_async() or g_spawn_async_with_pipes()
4771 * you will need to pass #G_SPAWN_DO_NOT_REAP_CHILD as flag to
4772 * the spawn function for the child watching to work.
4774 * Note that on platforms where #GPid must be explicitly closed
4775 * (see g_spawn_close_pid()) @pid must not be closed while the
4776 * source is still active. Typically, you will want to call
4777 * g_spawn_close_pid() in the callback function for the source.
4779 * GLib supports only a single callback per process id.
4781 * This internally creates a main loop source using
4782 * g_child_watch_source_new() and attaches it to the main loop context
4783 * using g_source_attach(). You can do these steps manually if you
4784 * need greater control.
4786 * Return value: the ID (greater than 0) of the event source.
4791 g_child_watch_add (GPid pid,
4792 GChildWatchFunc function,
4795 return g_child_watch_add_full (G_PRIORITY_DEFAULT, pid, function, data, NULL);
4799 /* Idle functions */
4802 g_idle_prepare (GSource *source,
4811 g_idle_check (GSource *source)
4817 g_idle_dispatch (GSource *source,
4818 GSourceFunc callback,
4823 g_warning ("Idle source dispatched without callback\n"
4824 "You must call g_source_set_callback().");
4828 return callback (user_data);
4832 * g_idle_source_new:
4834 * Creates a new idle source.
4836 * The source will not initially be associated with any #GMainContext
4837 * and must be added to one with g_source_attach() before it will be
4838 * executed. Note that the default priority for idle sources is
4839 * %G_PRIORITY_DEFAULT_IDLE, as compared to other sources which
4840 * have a default priority of %G_PRIORITY_DEFAULT.
4842 * Return value: the newly-created idle source
4845 g_idle_source_new (void)
4849 source = g_source_new (&g_idle_funcs, sizeof (GSource));
4850 g_source_set_priority (source, G_PRIORITY_DEFAULT_IDLE);
4857 * @priority: the priority of the idle source. Typically this will be in the
4858 * range between #G_PRIORITY_DEFAULT_IDLE and #G_PRIORITY_HIGH_IDLE.
4859 * @function: function to call
4860 * @data: data to pass to @function
4861 * @notify: function to call when the idle is removed, or %NULL
4863 * Adds a function to be called whenever there are no higher priority
4864 * events pending. If the function returns %FALSE it is automatically
4865 * removed from the list of event sources and will not be called again.
4867 * This internally creates a main loop source using g_idle_source_new()
4868 * and attaches it to the main loop context using g_source_attach().
4869 * You can do these steps manually if you need greater control.
4871 * Return value: the ID (greater than 0) of the event source.
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);