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"
54 #include <sys/eventfd.h>
59 #include <sys/types.h>
62 #ifdef HAVE_SYS_TIME_H
64 #endif /* HAVE_SYS_TIME_H */
67 #endif /* HAVE_UNISTD_H */
74 #endif /* G_OS_WIN32 */
77 #include <sys/socket.h>
79 #endif /* G_OS_BEOS */
84 #include "giochannel.h"
88 #include "gstrfuncs.h"
89 #include "gtestutils.h"
95 #ifdef G_MAIN_POLL_DEBUG
100 #include "gmain-internal.h"
101 #include "glib-private.h"
105 * @title: The Main Event Loop
106 * @short_description: manages all available sources of events
108 * The main event loop manages all the available sources of events for
109 * GLib and GTK+ applications. These events can come from any number of
110 * different types of sources such as file descriptors (plain files,
111 * pipes or sockets) and timeouts. New types of event sources can also
112 * be added using g_source_attach().
114 * To allow multiple independent sets of sources to be handled in
115 * different threads, each source is associated with a #GMainContext.
116 * A GMainContext can only be running in a single thread, but
117 * sources can be added to it and removed from it from other threads.
119 * Each event source is assigned a priority. The default priority,
120 * #G_PRIORITY_DEFAULT, is 0. Values less than 0 denote higher priorities.
121 * Values greater than 0 denote lower priorities. Events from high priority
122 * sources are always processed before events from lower priority sources.
124 * Idle functions can also be added, and assigned a priority. These will
125 * be run whenever no events with a higher priority are ready to be processed.
127 * The #GMainLoop data type represents a main event loop. A GMainLoop is
128 * created with g_main_loop_new(). After adding the initial event sources,
129 * g_main_loop_run() is called. This continuously checks for new events from
130 * each of the event sources and dispatches them. Finally, the processing of
131 * an event from one of the sources leads to a call to g_main_loop_quit() to
132 * exit the main loop, and g_main_loop_run() returns.
134 * It is possible to create new instances of #GMainLoop recursively.
135 * This is often used in GTK+ applications when showing modal dialog
136 * boxes. Note that event sources are associated with a particular
137 * #GMainContext, and will be checked and dispatched for all main
138 * loops associated with that GMainContext.
140 * GTK+ contains wrappers of some of these functions, e.g. gtk_main(),
141 * gtk_main_quit() and gtk_events_pending().
143 * <refsect2><title>Creating new source types</title>
144 * <para>One of the unusual features of the #GMainLoop functionality
145 * is that new types of event source can be created and used in
146 * addition to the builtin type of event source. A new event source
147 * type is used for handling GDK events. A new source type is created
148 * by <firstterm>deriving</firstterm> from the #GSource structure.
149 * The derived type of source is represented by a structure that has
150 * the #GSource structure as a first element, and other elements specific
151 * to the new source type. To create an instance of the new source type,
152 * call g_source_new() passing in the size of the derived structure and
153 * a table of functions. These #GSourceFuncs determine the behavior of
154 * the new source type.</para>
155 * <para>New source types basically interact with the main context
156 * in two ways. Their prepare function in #GSourceFuncs can set a timeout
157 * to determine the maximum amount of time that the main loop will sleep
158 * before checking the source again. In addition, or as well, the source
159 * can add file descriptors to the set that the main context checks using
160 * g_source_add_poll().</para>
162 * <refsect2><title>Customizing the main loop iteration</title>
163 * <para>Single iterations of a #GMainContext can be run with
164 * g_main_context_iteration(). In some cases, more detailed control
165 * of exactly how the details of the main loop work is desired, for
166 * instance, when integrating the #GMainLoop with an external main loop.
167 * In such cases, you can call the component functions of
168 * g_main_context_iteration() directly. These functions are
169 * g_main_context_prepare(), g_main_context_query(),
170 * g_main_context_check() and g_main_context_dispatch().</para>
171 * <para>The operation of these functions can best be seen in terms
172 * of a state diagram, as shown in <xref linkend="mainloop-states"/>.</para>
173 * <figure id="mainloop-states"><title>States of a Main Context</title>
174 * <graphic fileref="mainloop-states.gif" format="GIF"></graphic>
178 * On Unix, the GLib mainloop is incompatible with fork(). Any program
179 * using the mainloop must either exec() or exit() from the child
180 * without returning to the mainloop.
185 typedef struct _GTimeoutSource GTimeoutSource;
186 typedef struct _GChildWatchSource GChildWatchSource;
187 typedef struct _GUnixSignalWatchSource GUnixSignalWatchSource;
188 typedef struct _GPollRec GPollRec;
189 typedef struct _GSourceCallback GSourceCallback;
193 G_SOURCE_READY = 1 << G_HOOK_FLAG_USER_SHIFT,
194 G_SOURCE_CAN_RECURSE = 1 << (G_HOOK_FLAG_USER_SHIFT + 1),
195 G_SOURCE_BLOCKED = 1 << (G_HOOK_FLAG_USER_SHIFT + 2)
198 typedef struct _GMainWaiter GMainWaiter;
206 typedef struct _GMainDispatch GMainDispatch;
208 struct _GMainDispatch
211 GSList *dispatching_sources; /* stack of current sources */
214 #ifdef G_MAIN_POLL_DEBUG
215 gboolean _g_main_poll_debug = FALSE;
220 /* The following lock is used for both the list of sources
221 * and the list of poll records
231 GPtrArray *pending_dispatches;
232 gint timeout; /* Timeout for current iteration */
235 GSource *source_list;
236 gint in_check_or_prepare;
238 GPollRec *poll_records, *poll_records_tail;
239 guint n_poll_records;
240 GPollFD *cached_poll_array;
241 guint cached_poll_array_size;
247 /* Flag indicating whether the set of fd's changed during a poll */
248 gboolean poll_changed;
253 gboolean time_is_fresh;
256 struct _GSourceCallback
261 GDestroyNotify notify;
266 GMainContext *context;
271 struct _GTimeoutSource
279 struct _GChildWatchSource
286 #else /* G_OS_WIN32 */
287 gboolean child_exited;
288 #endif /* G_OS_WIN32 */
291 struct _GUnixSignalWatchSource
306 struct _GSourcePrivate
308 GSList *child_sources;
309 GSource *parent_source;
312 #define LOCK_CONTEXT(context) g_mutex_lock (&context->mutex)
313 #define UNLOCK_CONTEXT(context) g_mutex_unlock (&context->mutex)
314 #define G_THREAD_SELF g_thread_self ()
316 #define SOURCE_DESTROYED(source) (((source)->flags & G_HOOK_FLAG_ACTIVE) == 0)
317 #define SOURCE_BLOCKED(source) (((source)->flags & G_SOURCE_BLOCKED) != 0)
319 #define SOURCE_UNREF(source, context) \
321 if ((source)->ref_count > 1) \
322 (source)->ref_count--; \
324 g_source_unref_internal ((source), (context), TRUE); \
328 /* Forward declarations */
330 static void g_source_unref_internal (GSource *source,
331 GMainContext *context,
333 static void g_source_destroy_internal (GSource *source,
334 GMainContext *context,
336 static void g_source_set_priority_unlocked (GSource *source,
337 GMainContext *context,
339 static void g_main_context_poll (GMainContext *context,
344 static void g_main_context_add_poll_unlocked (GMainContext *context,
347 static void g_main_context_remove_poll_unlocked (GMainContext *context,
350 static gboolean g_timeout_prepare (GSource *source,
352 static gboolean g_timeout_check (GSource *source);
353 static gboolean g_timeout_dispatch (GSource *source,
354 GSourceFunc callback,
356 static gboolean g_child_watch_prepare (GSource *source,
358 static gboolean g_child_watch_check (GSource *source);
359 static gboolean g_child_watch_dispatch (GSource *source,
360 GSourceFunc callback,
362 static void g_child_watch_finalize (GSource *source);
364 static void g_unix_signal_handler (int signum);
365 static gboolean g_unix_signal_watch_prepare (GSource *source,
367 static gboolean g_unix_signal_watch_check (GSource *source);
368 static gboolean g_unix_signal_watch_dispatch (GSource *source,
369 GSourceFunc callback,
371 static void g_unix_signal_watch_finalize (GSource *source);
373 static gboolean g_idle_prepare (GSource *source,
375 static gboolean g_idle_check (GSource *source);
376 static gboolean g_idle_dispatch (GSource *source,
377 GSourceFunc callback,
380 static GMainContext *glib_worker_context;
382 G_LOCK_DEFINE_STATIC (main_loop);
383 static GMainContext *default_main_context;
388 /* UNIX signals work by marking one of these variables then waking the
389 * worker context to check on them and dispatch accordingly.
391 #ifdef HAVE_SIG_ATOMIC_T
392 static volatile sig_atomic_t unix_signal_pending[NSIG];
393 static volatile sig_atomic_t any_unix_signal_pending;
395 static volatile int unix_signal_pending[NSIG];
396 static volatile int any_unix_signal_pending;
399 /* Guards all the data below */
400 G_LOCK_DEFINE_STATIC (unix_signal_lock);
401 static GSList *unix_signal_watches;
402 static GSList *unix_child_watches;
404 static GSourceFuncs g_unix_signal_funcs =
406 g_unix_signal_watch_prepare,
407 g_unix_signal_watch_check,
408 g_unix_signal_watch_dispatch,
409 g_unix_signal_watch_finalize
411 #endif /* !G_OS_WIN32 */
412 G_LOCK_DEFINE_STATIC (main_context_list);
413 static GSList *main_context_list = NULL;
415 GSourceFuncs g_timeout_funcs =
423 GSourceFuncs g_child_watch_funcs =
425 g_child_watch_prepare,
427 g_child_watch_dispatch,
428 g_child_watch_finalize
431 GSourceFuncs g_idle_funcs =
440 * g_main_context_ref:
441 * @context: a #GMainContext
443 * Increases the reference count on a #GMainContext object by one.
445 * Returns: the @context that was passed in (since 2.6)
448 g_main_context_ref (GMainContext *context)
450 g_return_val_if_fail (context != NULL, NULL);
451 g_return_val_if_fail (g_atomic_int_get (&context->ref_count) > 0, NULL);
453 g_atomic_int_inc (&context->ref_count);
459 poll_rec_list_free (GMainContext *context,
462 g_slice_free_chain (GPollRec, list, next);
466 * g_main_context_unref:
467 * @context: a #GMainContext
469 * Decreases the reference count on a #GMainContext object by one. If
470 * the result is zero, free the context and free all associated memory.
473 g_main_context_unref (GMainContext *context)
476 g_return_if_fail (context != NULL);
477 g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
479 if (!g_atomic_int_dec_and_test (&context->ref_count))
482 G_LOCK (main_context_list);
483 main_context_list = g_slist_remove (main_context_list, context);
484 G_UNLOCK (main_context_list);
486 source = context->source_list;
489 GSource *next = source->next;
490 g_source_destroy_internal (source, context, FALSE);
494 g_mutex_clear (&context->mutex);
496 g_ptr_array_free (context->pending_dispatches, TRUE);
497 g_free (context->cached_poll_array);
499 poll_rec_list_free (context, context->poll_records);
501 g_wakeup_free (context->wakeup);
502 g_cond_clear (&context->cond);
508 * g_main_context_new:
510 * Creates a new #GMainContext structure.
512 * Return value: the new #GMainContext
515 g_main_context_new (void)
517 static gsize initialised;
518 GMainContext *context;
520 if (g_once_init_enter (&initialised))
522 #ifdef G_MAIN_POLL_DEBUG
523 if (getenv ("G_MAIN_POLL_DEBUG") != NULL)
524 _g_main_poll_debug = TRUE;
527 g_once_init_leave (&initialised, TRUE);
530 context = g_new0 (GMainContext, 1);
532 g_mutex_init (&context->mutex);
533 g_cond_init (&context->cond);
535 context->owner = NULL;
536 context->waiters = NULL;
538 context->ref_count = 1;
540 context->next_id = 1;
542 context->source_list = NULL;
544 context->poll_func = g_poll;
546 context->cached_poll_array = NULL;
547 context->cached_poll_array_size = 0;
549 context->pending_dispatches = g_ptr_array_new ();
551 context->time_is_fresh = FALSE;
553 context->wakeup = g_wakeup_new ();
554 g_wakeup_get_pollfd (context->wakeup, &context->wake_up_rec);
555 g_main_context_add_poll_unlocked (context, 0, &context->wake_up_rec);
557 G_LOCK (main_context_list);
558 main_context_list = g_slist_append (main_context_list, context);
560 #ifdef G_MAIN_POLL_DEBUG
561 if (_g_main_poll_debug)
562 g_print ("created context=%p\n", context);
565 G_UNLOCK (main_context_list);
571 * g_main_context_default:
573 * Returns the global default main context. This is the main context
574 * used for main loop functions when a main loop is not explicitly
575 * specified, and corresponds to the "main" main loop. See also
576 * g_main_context_get_thread_default().
578 * Return value: (transfer none): the global default main context.
581 g_main_context_default (void)
587 if (!default_main_context)
589 default_main_context = g_main_context_new ();
590 #ifdef G_MAIN_POLL_DEBUG
591 if (_g_main_poll_debug)
592 g_print ("default context=%p\n", default_main_context);
596 G_UNLOCK (main_loop);
598 return default_main_context;
602 free_context (gpointer data)
604 GMainContext *context = data;
606 g_main_context_release (context);
608 g_main_context_unref (context);
612 free_context_stack (gpointer data)
614 g_queue_free_full((GQueue *) data, (GDestroyNotify) free_context);
617 static GPrivate thread_context_stack = G_PRIVATE_INIT (free_context_stack);
620 * g_main_context_push_thread_default:
621 * @context: (allow-none): a #GMainContext, or %NULL for the global default context
623 * Acquires @context and sets it as the thread-default context for the
624 * current thread. This will cause certain asynchronous operations
625 * (such as most <link linkend="gio">gio</link>-based I/O) which are
626 * started in this thread to run under @context and deliver their
627 * results to its main loop, rather than running under the global
628 * default context in the main thread. Note that calling this function
629 * changes the context returned by
630 * g_main_context_get_thread_default(), <emphasis>not</emphasis> the
631 * one returned by g_main_context_default(), so it does not affect the
632 * context used by functions like g_idle_add().
634 * Normally you would call this function shortly after creating a new
635 * thread, passing it a #GMainContext which will be run by a
636 * #GMainLoop in that thread, to set a new default context for all
637 * async operations in that thread. (In this case, you don't need to
638 * ever call g_main_context_pop_thread_default().) In some cases
639 * however, you may want to schedule a single operation in a
640 * non-default context, or temporarily use a non-default context in
641 * the main thread. In that case, you can wrap the call to the
642 * asynchronous operation inside a
643 * g_main_context_push_thread_default() /
644 * g_main_context_pop_thread_default() pair, but it is up to you to
645 * ensure that no other asynchronous operations accidentally get
646 * started while the non-default context is active.
648 * Beware that libraries that predate this function may not correctly
649 * handle being used from a thread with a thread-default context. Eg,
650 * see g_file_supports_thread_contexts().
655 g_main_context_push_thread_default (GMainContext *context)
658 gboolean acquired_context;
660 acquired_context = g_main_context_acquire (context);
661 g_return_if_fail (acquired_context);
663 if (context == g_main_context_default ())
666 g_main_context_ref (context);
668 stack = g_private_get (&thread_context_stack);
671 stack = g_queue_new ();
672 g_private_set (&thread_context_stack, stack);
675 g_queue_push_head (stack, context);
679 * g_main_context_pop_thread_default:
680 * @context: (allow-none): a #GMainContext object, or %NULL
682 * Pops @context off the thread-default context stack (verifying that
683 * it was on the top of the stack).
688 g_main_context_pop_thread_default (GMainContext *context)
692 if (context == g_main_context_default ())
695 stack = g_private_get (&thread_context_stack);
697 g_return_if_fail (stack != NULL);
698 g_return_if_fail (g_queue_peek_head (stack) == context);
700 g_queue_pop_head (stack);
702 g_main_context_release (context);
704 g_main_context_unref (context);
708 * g_main_context_get_thread_default:
710 * Gets the thread-default #GMainContext for this thread. Asynchronous
711 * operations that want to be able to be run in contexts other than
712 * the default one should call this method or
713 * g_main_context_ref_thread_default() to get a #GMainContext to add
714 * their #GSource<!-- -->s to. (Note that even in single-threaded
715 * programs applications may sometimes want to temporarily push a
716 * non-default context, so it is not safe to assume that this will
717 * always return %NULL if you are running in the default thread.)
719 * If you need to hold a reference on the context, use
720 * g_main_context_ref_thread_default() instead.
722 * Returns: (transfer none): the thread-default #GMainContext, or
723 * %NULL if the thread-default context is the global default context.
728 g_main_context_get_thread_default (void)
732 stack = g_private_get (&thread_context_stack);
734 return g_queue_peek_head (stack);
740 * g_main_context_ref_thread_default:
742 * Gets the thread-default #GMainContext for this thread, as with
743 * g_main_context_get_thread_default(), but also adds a reference to
744 * it with g_main_context_ref(). In addition, unlike
745 * g_main_context_get_thread_default(), if the thread-default context
746 * is the global default context, this will return that #GMainContext
747 * (with a ref added to it) rather than returning %NULL.
749 * Returns: (transfer full): the thread-default #GMainContext. Unref
750 * with g_main_context_unref() when you are done with it.
755 g_main_context_ref_thread_default (void)
757 GMainContext *context;
759 context = g_main_context_get_thread_default ();
761 context = g_main_context_default ();
762 return g_main_context_ref (context);
765 /* Hooks for adding to the main loop */
769 * @source_funcs: structure containing functions that implement
770 * the sources behavior.
771 * @struct_size: size of the #GSource structure to create.
773 * Creates a new #GSource structure. The size is specified to
774 * allow creating structures derived from #GSource that contain
775 * additional data. The size passed in must be at least
776 * <literal>sizeof (GSource)</literal>.
778 * The source will not initially be associated with any #GMainContext
779 * and must be added to one with g_source_attach() before it will be
782 * Return value: the newly-created #GSource.
785 g_source_new (GSourceFuncs *source_funcs,
790 g_return_val_if_fail (source_funcs != NULL, NULL);
791 g_return_val_if_fail (struct_size >= sizeof (GSource), NULL);
793 source = (GSource*) g_malloc0 (struct_size);
794 source->priv = g_slice_new0 (GSourcePrivate);
795 source->source_funcs = source_funcs;
796 source->ref_count = 1;
798 source->priority = G_PRIORITY_DEFAULT;
800 source->flags = G_HOOK_FLAG_ACTIVE;
802 /* NULL/0 initialization for all other fields */
807 /* Holds context's lock
810 g_source_list_add (GSource *source,
811 GMainContext *context)
813 GSource *tmp_source, *last_source;
815 if (source->priv->parent_source)
817 /* Put the source immediately before its parent */
818 tmp_source = source->priv->parent_source;
819 last_source = source->priv->parent_source->prev;
824 tmp_source = context->source_list;
825 while (tmp_source && tmp_source->priority <= source->priority)
827 last_source = tmp_source;
828 tmp_source = tmp_source->next;
832 source->next = tmp_source;
834 tmp_source->prev = source;
836 source->prev = last_source;
838 last_source->next = source;
840 context->source_list = source;
843 /* Holds context's lock
846 g_source_list_remove (GSource *source,
847 GMainContext *context)
850 source->prev->next = source->next;
852 context->source_list = source->next;
855 source->next->prev = source->prev;
862 g_source_attach_unlocked (GSource *source,
863 GMainContext *context)
868 source->context = context;
869 result = source->source_id = context->next_id++;
872 g_source_list_add (source, context);
874 tmp_list = source->poll_fds;
877 g_main_context_add_poll_unlocked (context, source->priority, tmp_list->data);
878 tmp_list = tmp_list->next;
881 tmp_list = source->priv->child_sources;
884 g_source_attach_unlocked (tmp_list->data, context);
885 tmp_list = tmp_list->next;
893 * @source: a #GSource
894 * @context: (allow-none): a #GMainContext (if %NULL, the default context will be used)
896 * Adds a #GSource to a @context so that it will be executed within
897 * that context. Remove it by calling g_source_destroy().
899 * Return value: the ID (greater than 0) for the source within the
903 g_source_attach (GSource *source,
904 GMainContext *context)
908 g_return_val_if_fail (source->context == NULL, 0);
909 g_return_val_if_fail (!SOURCE_DESTROYED (source), 0);
912 context = g_main_context_default ();
914 LOCK_CONTEXT (context);
916 result = g_source_attach_unlocked (source, context);
918 /* If another thread has acquired the context, wake it up since it
919 * might be in poll() right now.
921 if (context->owner && context->owner != G_THREAD_SELF)
922 g_wakeup_signal (context->wakeup);
924 UNLOCK_CONTEXT (context);
930 g_source_destroy_internal (GSource *source,
931 GMainContext *context,
935 LOCK_CONTEXT (context);
937 if (!SOURCE_DESTROYED (source))
940 gpointer old_cb_data;
941 GSourceCallbackFuncs *old_cb_funcs;
943 source->flags &= ~G_HOOK_FLAG_ACTIVE;
945 old_cb_data = source->callback_data;
946 old_cb_funcs = source->callback_funcs;
948 source->callback_data = NULL;
949 source->callback_funcs = NULL;
953 UNLOCK_CONTEXT (context);
954 old_cb_funcs->unref (old_cb_data);
955 LOCK_CONTEXT (context);
958 if (!SOURCE_BLOCKED (source))
960 tmp_list = source->poll_fds;
963 g_main_context_remove_poll_unlocked (context, tmp_list->data);
964 tmp_list = tmp_list->next;
968 if (source->priv->child_sources)
970 /* This is safe because even if a child_source finalizer or
971 * closure notify tried to modify source->priv->child_sources
972 * from outside the lock, it would fail since
973 * SOURCE_DESTROYED(source) is now TRUE.
975 tmp_list = source->priv->child_sources;
978 g_source_destroy_internal (tmp_list->data, context, TRUE);
979 g_source_unref_internal (tmp_list->data, context, TRUE);
980 tmp_list = tmp_list->next;
982 g_slist_free (source->priv->child_sources);
983 source->priv->child_sources = NULL;
986 g_source_unref_internal (source, context, TRUE);
990 UNLOCK_CONTEXT (context);
995 * @source: a #GSource
997 * Removes a source from its #GMainContext, if any, and mark it as
998 * destroyed. The source cannot be subsequently added to another
1002 g_source_destroy (GSource *source)
1004 GMainContext *context;
1006 g_return_if_fail (source != NULL);
1008 context = source->context;
1011 g_source_destroy_internal (source, context, FALSE);
1013 source->flags &= ~G_HOOK_FLAG_ACTIVE;
1018 * @source: a #GSource
1020 * Returns the numeric ID for a particular source. The ID of a source
1021 * is a positive integer which is unique within a particular main loop
1022 * context. The reverse
1023 * mapping from ID to source is done by g_main_context_find_source_by_id().
1025 * Return value: the ID (greater than 0) for the source
1028 g_source_get_id (GSource *source)
1032 g_return_val_if_fail (source != NULL, 0);
1033 g_return_val_if_fail (source->context != NULL, 0);
1035 LOCK_CONTEXT (source->context);
1036 result = source->source_id;
1037 UNLOCK_CONTEXT (source->context);
1043 * g_source_get_context:
1044 * @source: a #GSource
1046 * Gets the #GMainContext with which the source is associated.
1047 * Calling this function on a destroyed source is an error.
1049 * Return value: (transfer none) (allow-none): the #GMainContext with which the
1050 * source is associated, or %NULL if the context has not
1051 * yet been added to a source.
1054 g_source_get_context (GSource *source)
1056 g_return_val_if_fail (!SOURCE_DESTROYED (source), NULL);
1058 return source->context;
1062 * g_source_add_poll:
1063 * @source:a #GSource
1064 * @fd: a #GPollFD structure holding information about a file
1065 * descriptor to watch.
1067 * Adds a file descriptor to the set of file descriptors polled for
1068 * this source. This is usually combined with g_source_new() to add an
1069 * event source. The event source's check function will typically test
1070 * the @revents field in the #GPollFD struct and return %TRUE if events need
1074 g_source_add_poll (GSource *source,
1077 GMainContext *context;
1079 g_return_if_fail (source != NULL);
1080 g_return_if_fail (fd != NULL);
1081 g_return_if_fail (!SOURCE_DESTROYED (source));
1083 context = source->context;
1086 LOCK_CONTEXT (context);
1088 source->poll_fds = g_slist_prepend (source->poll_fds, fd);
1092 if (!SOURCE_BLOCKED (source))
1093 g_main_context_add_poll_unlocked (context, source->priority, fd);
1094 UNLOCK_CONTEXT (context);
1099 * g_source_remove_poll:
1100 * @source:a #GSource
1101 * @fd: a #GPollFD structure previously passed to g_source_add_poll().
1103 * Removes a file descriptor from the set of file descriptors polled for
1107 g_source_remove_poll (GSource *source,
1110 GMainContext *context;
1112 g_return_if_fail (source != NULL);
1113 g_return_if_fail (fd != NULL);
1114 g_return_if_fail (!SOURCE_DESTROYED (source));
1116 context = source->context;
1119 LOCK_CONTEXT (context);
1121 source->poll_fds = g_slist_remove (source->poll_fds, fd);
1125 if (!SOURCE_BLOCKED (source))
1126 g_main_context_remove_poll_unlocked (context, fd);
1127 UNLOCK_CONTEXT (context);
1132 * g_source_add_child_source:
1133 * @source:a #GSource
1134 * @child_source: a second #GSource that @source should "poll"
1136 * Adds @child_source to @source as a "polled" source; when @source is
1137 * added to a #GMainContext, @child_source will be automatically added
1138 * with the same priority, when @child_source is triggered, it will
1139 * cause @source to dispatch (in addition to calling its own
1140 * callback), and when @source is destroyed, it will destroy
1141 * @child_source as well. (@source will also still be dispatched if
1142 * its own prepare/check functions indicate that it is ready.)
1144 * If you don't need @child_source to do anything on its own when it
1145 * triggers, you can call g_source_set_dummy_callback() on it to set a
1146 * callback that does nothing (except return %TRUE if appropriate).
1148 * @source will hold a reference on @child_source while @child_source
1149 * is attached to it.
1154 g_source_add_child_source (GSource *source,
1155 GSource *child_source)
1157 GMainContext *context;
1159 g_return_if_fail (source != NULL);
1160 g_return_if_fail (child_source != NULL);
1161 g_return_if_fail (!SOURCE_DESTROYED (source));
1162 g_return_if_fail (!SOURCE_DESTROYED (child_source));
1163 g_return_if_fail (child_source->context == NULL);
1164 g_return_if_fail (child_source->priv->parent_source == NULL);
1166 context = source->context;
1169 LOCK_CONTEXT (context);
1171 source->priv->child_sources = g_slist_prepend (source->priv->child_sources,
1172 g_source_ref (child_source));
1173 child_source->priv->parent_source = source;
1174 g_source_set_priority_unlocked (child_source, NULL, source->priority);
1178 UNLOCK_CONTEXT (context);
1179 g_source_attach (child_source, context);
1184 * g_source_remove_child_source:
1185 * @source:a #GSource
1186 * @child_source: a #GSource previously passed to
1187 * g_source_add_child_source().
1189 * Detaches @child_source from @source and destroys it.
1194 g_source_remove_child_source (GSource *source,
1195 GSource *child_source)
1197 GMainContext *context;
1199 g_return_if_fail (source != NULL);
1200 g_return_if_fail (child_source != NULL);
1201 g_return_if_fail (child_source->priv->parent_source == source);
1202 g_return_if_fail (!SOURCE_DESTROYED (source));
1203 g_return_if_fail (!SOURCE_DESTROYED (child_source));
1205 context = source->context;
1208 LOCK_CONTEXT (context);
1210 source->priv->child_sources = g_slist_remove (source->priv->child_sources, child_source);
1211 g_source_destroy_internal (child_source, context, TRUE);
1212 g_source_unref_internal (child_source, context, TRUE);
1215 UNLOCK_CONTEXT (context);
1219 * g_source_set_callback_indirect:
1220 * @source: the source
1221 * @callback_data: pointer to callback data "object"
1222 * @callback_funcs: functions for reference counting @callback_data
1223 * and getting the callback and data
1225 * Sets the callback function storing the data as a refcounted callback
1226 * "object". This is used internally. Note that calling
1227 * g_source_set_callback_indirect() assumes
1228 * an initial reference count on @callback_data, and thus
1229 * @callback_funcs->unref will eventually be called once more
1230 * than @callback_funcs->ref.
1233 g_source_set_callback_indirect (GSource *source,
1234 gpointer callback_data,
1235 GSourceCallbackFuncs *callback_funcs)
1237 GMainContext *context;
1238 gpointer old_cb_data;
1239 GSourceCallbackFuncs *old_cb_funcs;
1241 g_return_if_fail (source != NULL);
1242 g_return_if_fail (callback_funcs != NULL || callback_data == NULL);
1244 context = source->context;
1247 LOCK_CONTEXT (context);
1249 old_cb_data = source->callback_data;
1250 old_cb_funcs = source->callback_funcs;
1252 source->callback_data = callback_data;
1253 source->callback_funcs = callback_funcs;
1256 UNLOCK_CONTEXT (context);
1259 old_cb_funcs->unref (old_cb_data);
1263 g_source_callback_ref (gpointer cb_data)
1265 GSourceCallback *callback = cb_data;
1267 callback->ref_count++;
1272 g_source_callback_unref (gpointer cb_data)
1274 GSourceCallback *callback = cb_data;
1276 callback->ref_count--;
1277 if (callback->ref_count == 0)
1279 if (callback->notify)
1280 callback->notify (callback->data);
1286 g_source_callback_get (gpointer cb_data,
1291 GSourceCallback *callback = cb_data;
1293 *func = callback->func;
1294 *data = callback->data;
1297 static GSourceCallbackFuncs g_source_callback_funcs = {
1298 g_source_callback_ref,
1299 g_source_callback_unref,
1300 g_source_callback_get,
1304 * g_source_set_callback:
1305 * @source: the source
1306 * @func: a callback function
1307 * @data: the data to pass to callback function
1308 * @notify: (allow-none): a function to call when @data is no longer in use, or %NULL.
1310 * Sets the callback function for a source. The callback for a source is
1311 * called from the source's dispatch function.
1313 * The exact type of @func depends on the type of source; ie. you
1314 * should not count on @func being called with @data as its first
1317 * Typically, you won't use this function. Instead use functions specific
1318 * to the type of source you are using.
1321 g_source_set_callback (GSource *source,
1324 GDestroyNotify notify)
1326 GSourceCallback *new_callback;
1328 g_return_if_fail (source != NULL);
1330 new_callback = g_new (GSourceCallback, 1);
1332 new_callback->ref_count = 1;
1333 new_callback->func = func;
1334 new_callback->data = data;
1335 new_callback->notify = notify;
1337 g_source_set_callback_indirect (source, new_callback, &g_source_callback_funcs);
1342 * g_source_set_funcs:
1343 * @source: a #GSource
1344 * @funcs: the new #GSourceFuncs
1346 * Sets the source functions (can be used to override
1347 * default implementations) of an unattached source.
1352 g_source_set_funcs (GSource *source,
1353 GSourceFuncs *funcs)
1355 g_return_if_fail (source != NULL);
1356 g_return_if_fail (source->context == NULL);
1357 g_return_if_fail (source->ref_count > 0);
1358 g_return_if_fail (funcs != NULL);
1360 source->source_funcs = funcs;
1364 g_source_set_priority_unlocked (GSource *source,
1365 GMainContext *context,
1370 source->priority = priority;
1374 /* Remove the source from the context's source and then
1375 * add it back so it is sorted in the correct place
1377 g_source_list_remove (source, source->context);
1378 g_source_list_add (source, source->context);
1380 if (!SOURCE_BLOCKED (source))
1382 tmp_list = source->poll_fds;
1385 g_main_context_remove_poll_unlocked (context, tmp_list->data);
1386 g_main_context_add_poll_unlocked (context, priority, tmp_list->data);
1388 tmp_list = tmp_list->next;
1393 if (source->priv->child_sources)
1395 tmp_list = source->priv->child_sources;
1398 g_source_set_priority_unlocked (tmp_list->data, context, priority);
1399 tmp_list = tmp_list->next;
1405 * g_source_set_priority:
1406 * @source: a #GSource
1407 * @priority: the new priority.
1409 * Sets the priority of a source. While the main loop is being run, a
1410 * source will be dispatched if it is ready to be dispatched and no
1411 * sources at a higher (numerically smaller) priority are ready to be
1415 g_source_set_priority (GSource *source,
1418 GMainContext *context;
1420 g_return_if_fail (source != NULL);
1422 context = source->context;
1425 LOCK_CONTEXT (context);
1426 g_source_set_priority_unlocked (source, context, priority);
1428 UNLOCK_CONTEXT (source->context);
1432 * g_source_get_priority:
1433 * @source: a #GSource
1435 * Gets the priority of a source.
1437 * Return value: the priority of the source
1440 g_source_get_priority (GSource *source)
1442 g_return_val_if_fail (source != NULL, 0);
1444 return source->priority;
1448 * g_source_set_can_recurse:
1449 * @source: a #GSource
1450 * @can_recurse: whether recursion is allowed for this source
1452 * Sets whether a source can be called recursively. If @can_recurse is
1453 * %TRUE, then while the source is being dispatched then this source
1454 * will be processed normally. Otherwise, all processing of this
1455 * source is blocked until the dispatch function returns.
1458 g_source_set_can_recurse (GSource *source,
1459 gboolean can_recurse)
1461 GMainContext *context;
1463 g_return_if_fail (source != NULL);
1465 context = source->context;
1468 LOCK_CONTEXT (context);
1471 source->flags |= G_SOURCE_CAN_RECURSE;
1473 source->flags &= ~G_SOURCE_CAN_RECURSE;
1476 UNLOCK_CONTEXT (context);
1480 * g_source_get_can_recurse:
1481 * @source: a #GSource
1483 * Checks whether a source is allowed to be called recursively.
1484 * see g_source_set_can_recurse().
1486 * Return value: whether recursion is allowed.
1489 g_source_get_can_recurse (GSource *source)
1491 g_return_val_if_fail (source != NULL, FALSE);
1493 return (source->flags & G_SOURCE_CAN_RECURSE) != 0;
1498 * g_source_set_name:
1499 * @source: a #GSource
1500 * @name: debug name for the source
1502 * Sets a name for the source, used in debugging and profiling.
1503 * The name defaults to #NULL.
1505 * The source name should describe in a human-readable way
1506 * what the source does. For example, "X11 event queue"
1507 * or "GTK+ repaint idle handler" or whatever it is.
1509 * It is permitted to call this function multiple times, but is not
1510 * recommended due to the potential performance impact. For example,
1511 * one could change the name in the "check" function of a #GSourceFuncs
1512 * to include details like the event type in the source name.
1517 g_source_set_name (GSource *source,
1520 g_return_if_fail (source != NULL);
1522 /* setting back to NULL is allowed, just because it's
1523 * weird if get_name can return NULL but you can't
1527 g_free (source->name);
1528 source->name = g_strdup (name);
1532 * g_source_get_name:
1533 * @source: a #GSource
1535 * Gets a name for the source, used in debugging and profiling.
1536 * The name may be #NULL if it has never been set with
1537 * g_source_set_name().
1539 * Return value: the name of the source
1543 g_source_get_name (GSource *source)
1545 g_return_val_if_fail (source != NULL, NULL);
1547 return source->name;
1551 * g_source_set_name_by_id:
1552 * @tag: a #GSource ID
1553 * @name: debug name for the source
1555 * Sets the name of a source using its ID.
1557 * This is a convenience utility to set source names from the return
1558 * value of g_idle_add(), g_timeout_add(), etc.
1563 g_source_set_name_by_id (guint tag,
1568 g_return_if_fail (tag > 0);
1570 source = g_main_context_find_source_by_id (NULL, tag);
1574 g_source_set_name (source, name);
1580 * @source: a #GSource
1582 * Increases the reference count on a source by one.
1584 * Return value: @source
1587 g_source_ref (GSource *source)
1589 GMainContext *context;
1591 g_return_val_if_fail (source != NULL, NULL);
1593 context = source->context;
1596 LOCK_CONTEXT (context);
1598 source->ref_count++;
1601 UNLOCK_CONTEXT (context);
1606 /* g_source_unref() but possible to call within context lock
1609 g_source_unref_internal (GSource *source,
1610 GMainContext *context,
1613 gpointer old_cb_data = NULL;
1614 GSourceCallbackFuncs *old_cb_funcs = NULL;
1616 g_return_if_fail (source != NULL);
1618 if (!have_lock && context)
1619 LOCK_CONTEXT (context);
1621 source->ref_count--;
1622 if (source->ref_count == 0)
1624 old_cb_data = source->callback_data;
1625 old_cb_funcs = source->callback_funcs;
1627 source->callback_data = NULL;
1628 source->callback_funcs = NULL;
1632 if (!SOURCE_DESTROYED (source))
1633 g_warning (G_STRLOC ": ref_count == 0, but source was still attached to a context!");
1634 g_source_list_remove (source, context);
1637 if (source->source_funcs->finalize)
1640 UNLOCK_CONTEXT (context);
1641 source->source_funcs->finalize (source);
1643 LOCK_CONTEXT (context);
1646 g_free (source->name);
1647 source->name = NULL;
1649 g_slist_free (source->poll_fds);
1650 source->poll_fds = NULL;
1652 g_slice_free (GSourcePrivate, source->priv);
1653 source->priv = NULL;
1658 if (!have_lock && context)
1659 UNLOCK_CONTEXT (context);
1664 UNLOCK_CONTEXT (context);
1666 old_cb_funcs->unref (old_cb_data);
1669 LOCK_CONTEXT (context);
1675 * @source: a #GSource
1677 * Decreases the reference count of a source by one. If the
1678 * resulting reference count is zero the source and associated
1679 * memory will be destroyed.
1682 g_source_unref (GSource *source)
1684 g_return_if_fail (source != NULL);
1686 g_source_unref_internal (source, source->context, FALSE);
1690 * g_main_context_find_source_by_id:
1691 * @context: (allow-none): a #GMainContext (if %NULL, the default context will be used)
1692 * @source_id: the source ID, as returned by g_source_get_id().
1694 * Finds a #GSource given a pair of context and ID.
1696 * Return value: (transfer none): the #GSource if found, otherwise, %NULL
1699 g_main_context_find_source_by_id (GMainContext *context,
1704 g_return_val_if_fail (source_id > 0, NULL);
1706 if (context == NULL)
1707 context = g_main_context_default ();
1709 LOCK_CONTEXT (context);
1711 source = context->source_list;
1714 if (!SOURCE_DESTROYED (source) &&
1715 source->source_id == source_id)
1717 source = source->next;
1720 UNLOCK_CONTEXT (context);
1726 * g_main_context_find_source_by_funcs_user_data:
1727 * @context: (allow-none): a #GMainContext (if %NULL, the default context will be used).
1728 * @funcs: the @source_funcs passed to g_source_new().
1729 * @user_data: the user data from the callback.
1731 * Finds a source with the given source functions and user data. If
1732 * multiple sources exist with the same source function and user data,
1733 * the first one found will be returned.
1735 * Return value: (transfer none): the source, if one was found, otherwise %NULL
1738 g_main_context_find_source_by_funcs_user_data (GMainContext *context,
1739 GSourceFuncs *funcs,
1744 g_return_val_if_fail (funcs != NULL, NULL);
1746 if (context == NULL)
1747 context = g_main_context_default ();
1749 LOCK_CONTEXT (context);
1751 source = context->source_list;
1754 if (!SOURCE_DESTROYED (source) &&
1755 source->source_funcs == funcs &&
1756 source->callback_funcs)
1758 GSourceFunc callback;
1759 gpointer callback_data;
1761 source->callback_funcs->get (source->callback_data, source, &callback, &callback_data);
1763 if (callback_data == user_data)
1766 source = source->next;
1769 UNLOCK_CONTEXT (context);
1775 * g_main_context_find_source_by_user_data:
1776 * @context: a #GMainContext
1777 * @user_data: the user_data for the callback.
1779 * Finds a source with the given user data for the callback. If
1780 * multiple sources exist with the same user data, the first
1781 * one found will be returned.
1783 * Return value: (transfer none): the source, if one was found, otherwise %NULL
1786 g_main_context_find_source_by_user_data (GMainContext *context,
1791 if (context == NULL)
1792 context = g_main_context_default ();
1794 LOCK_CONTEXT (context);
1796 source = context->source_list;
1799 if (!SOURCE_DESTROYED (source) &&
1800 source->callback_funcs)
1802 GSourceFunc callback;
1803 gpointer callback_data = NULL;
1805 source->callback_funcs->get (source->callback_data, source, &callback, &callback_data);
1807 if (callback_data == user_data)
1810 source = source->next;
1813 UNLOCK_CONTEXT (context);
1820 * @tag: the ID of the source to remove.
1822 * Removes the source with the given id from the default main context.
1824 * a #GSource is given by g_source_get_id(), or will be returned by the
1825 * functions g_source_attach(), g_idle_add(), g_idle_add_full(),
1826 * g_timeout_add(), g_timeout_add_full(), g_child_watch_add(),
1827 * g_child_watch_add_full(), g_io_add_watch(), and g_io_add_watch_full().
1829 * See also g_source_destroy(). You must use g_source_destroy() for sources
1830 * added to a non-default main context.
1832 * Return value: %TRUE if the source was found and removed.
1835 g_source_remove (guint tag)
1839 g_return_val_if_fail (tag > 0, FALSE);
1841 source = g_main_context_find_source_by_id (NULL, tag);
1843 g_source_destroy (source);
1845 return source != NULL;
1849 * g_source_remove_by_user_data:
1850 * @user_data: the user_data for the callback.
1852 * Removes a source from the default main loop context given the user
1853 * data for the callback. If multiple sources exist with the same user
1854 * data, only one will be destroyed.
1856 * Return value: %TRUE if a source was found and removed.
1859 g_source_remove_by_user_data (gpointer user_data)
1863 source = g_main_context_find_source_by_user_data (NULL, user_data);
1866 g_source_destroy (source);
1874 * g_source_remove_by_funcs_user_data:
1875 * @funcs: The @source_funcs passed to g_source_new()
1876 * @user_data: the user data for the callback
1878 * Removes a source from the default main loop context given the
1879 * source functions and user data. If multiple sources exist with the
1880 * same source functions and user data, only one will be destroyed.
1882 * Return value: %TRUE if a source was found and removed.
1885 g_source_remove_by_funcs_user_data (GSourceFuncs *funcs,
1890 g_return_val_if_fail (funcs != NULL, FALSE);
1892 source = g_main_context_find_source_by_funcs_user_data (NULL, funcs, user_data);
1895 g_source_destroy (source);
1903 * g_get_current_time:
1904 * @result: #GTimeVal structure in which to store current time.
1906 * Equivalent to the UNIX gettimeofday() function, but portable.
1908 * You may find g_get_real_time() to be more convenient.
1911 g_get_current_time (GTimeVal *result)
1916 g_return_if_fail (result != NULL);
1918 /*this is required on alpha, there the timeval structs are int's
1919 not longs and a cast only would fail horribly*/
1920 gettimeofday (&r, NULL);
1921 result->tv_sec = r.tv_sec;
1922 result->tv_usec = r.tv_usec;
1927 g_return_if_fail (result != NULL);
1929 GetSystemTimeAsFileTime (&ft);
1930 memmove (&time64, &ft, sizeof (FILETIME));
1932 /* Convert from 100s of nanoseconds since 1601-01-01
1933 * to Unix epoch. Yes, this is Y2038 unsafe.
1935 time64 -= G_GINT64_CONSTANT (116444736000000000);
1938 result->tv_sec = time64 / 1000000;
1939 result->tv_usec = time64 % 1000000;
1946 * Queries the system wall-clock time.
1948 * This call is functionally equivalent to g_get_current_time() except
1949 * that the return value is often more convenient than dealing with a
1952 * You should only use this call if you are actually interested in the real
1953 * wall-clock time. g_get_monotonic_time() is probably more useful for
1954 * measuring intervals.
1956 * Returns: the number of microseconds since January 1, 1970 UTC.
1961 g_get_real_time (void)
1965 g_get_current_time (&tv);
1967 return (((gint64) tv.tv_sec) * 1000000) + tv.tv_usec;
1971 static ULONGLONG (*g_GetTickCount64) (void) = NULL;
1972 static guint32 g_win32_tick_epoch = 0;
1974 G_GNUC_INTERNAL void
1975 g_clock_win32_init (void)
1979 g_GetTickCount64 = NULL;
1980 kernel32 = GetModuleHandle ("KERNEL32.DLL");
1981 if (kernel32 != NULL)
1982 g_GetTickCount64 = (void *) GetProcAddress (kernel32, "GetTickCount64");
1983 g_win32_tick_epoch = ((guint32)GetTickCount()) >> 31;
1988 * g_get_monotonic_time:
1990 * Queries the system monotonic time, if available.
1992 * On POSIX systems with clock_gettime() and <literal>CLOCK_MONOTONIC</literal> this call
1993 * is a very shallow wrapper for that. Otherwise, we make a best effort
1994 * that probably involves returning the wall clock time (with at least
1995 * microsecond accuracy, subject to the limitations of the OS kernel).
1997 * It's important to note that POSIX <literal>CLOCK_MONOTONIC</literal> does
1998 * not count time spent while the machine is suspended.
2000 * On Windows, "limitations of the OS kernel" is a rather substantial
2001 * statement. Depending on the configuration of the system, the wall
2002 * clock time is updated as infrequently as 64 times a second (which
2003 * is approximately every 16ms). Also, on XP (but not on Vista or later)
2004 * the monotonic clock is locally monotonic, but may differ in exact
2005 * value between processes due to timer wrap handling.
2007 * Returns: the monotonic time, in microseconds
2012 g_get_monotonic_time (void)
2014 #ifdef HAVE_CLOCK_GETTIME
2015 /* librt clock_gettime() is our first choice */
2018 #ifdef CLOCK_MONOTONIC
2019 clock_gettime (CLOCK_MONOTONIC, &ts);
2021 clock_gettime (CLOCK_REALTIME, &ts);
2024 /* In theory monotonic time can have any epoch.
2026 * glib presently assumes the following:
2028 * 1) The epoch comes some time after the birth of Jesus of Nazareth, but
2029 * not more than 10000 years later.
2031 * 2) The current time also falls sometime within this range.
2033 * These two reasonable assumptions leave us with a maximum deviation from
2034 * the epoch of 10000 years, or 315569520000000000 seconds.
2036 * If we restrict ourselves to this range then the number of microseconds
2037 * will always fit well inside the constraints of a int64 (by a factor of
2040 * If you actually hit the following assertion, probably you should file a
2041 * bug against your operating system for being excessively silly.
2043 g_assert (G_GINT64_CONSTANT (-315569520000000000) < ts.tv_sec &&
2044 ts.tv_sec < G_GINT64_CONSTANT (315569520000000000));
2046 return (((gint64) ts.tv_sec) * 1000000) + (ts.tv_nsec / 1000);
2048 #elif defined (G_OS_WIN32)
2052 /* There are four sources for the monotonic time on Windows:
2054 * Three are based on a (1 msec accuracy, but only read periodically) clock chip:
2055 * - GetTickCount (GTC)
2056 * 32bit msec counter, updated each ~15msec, wraps in ~50 days
2057 * - GetTickCount64 (GTC64)
2058 * Same as GetTickCount, but extended to 64bit, so no wrap
2059 * Only available in Vista or later
2060 * - timeGetTime (TGT)
2061 * similar to GetTickCount by default: 15msec, 50 day wrap.
2062 * available in winmm.dll (thus known as the multimedia timers)
2063 * However apps can raise the system timer clock frequency using timeBeginPeriod()
2064 * increasing the accuracy up to 1 msec, at a cost in general system performance
2067 * One is based on high precision clocks:
2068 * - QueryPrecisionCounter (QPC)
2069 * This has much higher accuracy, but is not guaranteed monotonic, and
2070 * has lots of complications like clock jumps and different times on different
2071 * CPUs. It also has lower long term accuracy (i.e. it will drift compared to
2072 * the low precision clocks.
2074 * Additionally, the precision available in the timer-based wakeup such as
2075 * MsgWaitForMultipleObjectsEx (which is what the mainloop is based on) is based
2076 * on the TGT resolution, so by default it is ~15msec, but can be increased by apps.
2078 * The QPC timer has too many issues to be used as is. The only way it could be used
2079 * is to use it to interpolate the lower precision clocks. Firefox does something like
2081 * https://bugzilla.mozilla.org/show_bug.cgi?id=363258
2083 * However this seems quite complicated, so we're not doing this right now.
2085 * The approach we take instead is to use the TGT timer, extending it to 64bit
2086 * either by using the GTC64 value, or if that is not available, a process local
2087 * time epoch that we increment when we detect a timer wrap (assumes that we read
2088 * the time at least once every 50 days).
2091 * - We have a globally consistent monotonic clock on Vista and later
2092 * - We have a locally monotonic clock on XP
2093 * - Apps that need higher precision in timeouts and clock reads can call
2094 * timeBeginPeriod() to increase it as much as they want
2097 if (g_GetTickCount64 != NULL)
2099 guint32 ticks_as_32bit;
2101 ticks = g_GetTickCount64 ();
2102 ticks32 = timeGetTime();
2104 /* GTC64 and TGT are sampled at different times, however they
2105 * have the same base and source (msecs since system boot).
2106 * They can differ by as much as -16 to +16 msecs.
2107 * We can't just inject the low bits into the 64bit counter
2108 * as one of the counters can have wrapped in 32bit space and
2109 * the other not. Instead we calculate the signed difference
2110 * in 32bit space and apply that difference to the 64bit counter.
2112 ticks_as_32bit = (guint32)ticks;
2114 /* We could do some 2's complement hack, but we play it safe */
2115 if (ticks32 - ticks_as_32bit <= G_MAXINT32)
2116 ticks += ticks32 - ticks_as_32bit;
2118 ticks -= ticks_as_32bit - ticks32;
2124 epoch = g_atomic_int_get (&g_win32_tick_epoch);
2126 /* Must read ticks after the epoch. Then we're guaranteed
2127 * that the ticks value we read is higher or equal to any
2128 * previous ones that lead to the writing of the epoch.
2130 ticks32 = timeGetTime();
2132 /* We store the MSB of the current time as the LSB
2133 * of the epoch. Comparing these bits lets us detect when
2134 * the 32bit counter has wrapped so we can increase the
2137 * This will work as long as this function is called at
2138 * least once every ~24 days, which is half the wrap time
2139 * of a 32bit msec counter. I think this is pretty likely.
2141 * Note that g_win32_tick_epoch is a process local state,
2142 * so the monotonic clock will not be the same between
2145 if ((ticks32 >> 31) != (epoch & 1))
2148 g_atomic_int_set (&g_win32_tick_epoch, epoch);
2152 ticks = (guint64)ticks32 | ((guint64)epoch) << 31;
2155 return ticks * 1000;
2157 #else /* !HAVE_CLOCK_GETTIME && ! G_OS_WIN32*/
2161 g_get_current_time (&tv);
2163 return (((gint64) tv.tv_sec) * 1000000) + tv.tv_usec;
2168 g_main_dispatch_free (gpointer dispatch)
2170 g_slice_free (GMainDispatch, dispatch);
2173 /* Running the main loop */
2175 static GMainDispatch *
2178 static GPrivate depth_private = G_PRIVATE_INIT (g_main_dispatch_free);
2179 GMainDispatch *dispatch;
2181 dispatch = g_private_get (&depth_private);
2185 dispatch = g_slice_new0 (GMainDispatch);
2186 g_private_set (&depth_private, dispatch);
2195 * Returns the depth of the stack of calls to
2196 * g_main_context_dispatch() on any #GMainContext in the current thread.
2197 * That is, when called from the toplevel, it gives 0. When
2198 * called from within a callback from g_main_context_iteration()
2199 * (or g_main_loop_run(), etc.) it returns 1. When called from within
2200 * a callback to a recursive call to g_main_context_iteration(),
2201 * it returns 2. And so forth.
2203 * This function is useful in a situation like the following:
2204 * Imagine an extremely simple "garbage collected" system.
2207 * static GList *free_list;
2210 * allocate_memory (gsize size)
2212 * gpointer result = g_malloc (size);
2213 * free_list = g_list_prepend (free_list, result);
2218 * free_allocated_memory (void)
2221 * for (l = free_list; l; l = l->next);
2223 * g_list_free (free_list);
2231 * g_main_context_iteration (NULL, TRUE);
2232 * free_allocated_memory();
2236 * This works from an application, however, if you want to do the same
2237 * thing from a library, it gets more difficult, since you no longer
2238 * control the main loop. You might think you can simply use an idle
2239 * function to make the call to free_allocated_memory(), but that
2240 * doesn't work, since the idle function could be called from a
2241 * recursive callback. This can be fixed by using g_main_depth()
2245 * allocate_memory (gsize size)
2247 * FreeListBlock *block = g_new (FreeListBlock, 1);
2248 * block->mem = g_malloc (size);
2249 * block->depth = g_main_depth ();
2250 * free_list = g_list_prepend (free_list, block);
2251 * return block->mem;
2255 * free_allocated_memory (void)
2259 * int depth = g_main_depth ();
2260 * for (l = free_list; l; );
2262 * GList *next = l->next;
2263 * FreeListBlock *block = l->data;
2264 * if (block->depth > depth)
2266 * g_free (block->mem);
2268 * free_list = g_list_delete_link (free_list, l);
2276 * There is a temptation to use g_main_depth() to solve
2277 * problems with reentrancy. For instance, while waiting for data
2278 * to be received from the network in response to a menu item,
2279 * the menu item might be selected again. It might seem that
2280 * one could make the menu item's callback return immediately
2281 * and do nothing if g_main_depth() returns a value greater than 1.
2282 * However, this should be avoided since the user then sees selecting
2283 * the menu item do nothing. Furthermore, you'll find yourself adding
2284 * these checks all over your code, since there are doubtless many,
2285 * many things that the user could do. Instead, you can use the
2286 * following techniques:
2291 * Use gtk_widget_set_sensitive() or modal dialogs to prevent
2292 * the user from interacting with elements while the main
2293 * loop is recursing.
2298 * Avoid main loop recursion in situations where you can't handle
2299 * arbitrary callbacks. Instead, structure your code so that you
2300 * simply return to the main loop and then get called again when
2301 * there is more work to do.
2306 * Return value: The main loop recursion level in the current thread
2311 GMainDispatch *dispatch = get_dispatch ();
2312 return dispatch->depth;
2316 * g_main_current_source:
2318 * Returns the currently firing source for this thread.
2320 * Return value: (transfer none): The currently firing source or %NULL.
2325 g_main_current_source (void)
2327 GMainDispatch *dispatch = get_dispatch ();
2328 return dispatch->dispatching_sources ? dispatch->dispatching_sources->data : NULL;
2332 * g_source_is_destroyed:
2333 * @source: a #GSource
2335 * Returns whether @source has been destroyed.
2337 * This is important when you operate upon your objects
2338 * from within idle handlers, but may have freed the object
2339 * before the dispatch of your idle handler.
2343 * idle_callback (gpointer data)
2345 * SomeWidget *self = data;
2347 * GDK_THREADS_ENTER (<!-- -->);
2348 * /<!-- -->* do stuff with self *<!-- -->/
2349 * self->idle_id = 0;
2350 * GDK_THREADS_LEAVE (<!-- -->);
2352 * return G_SOURCE_REMOVE;
2356 * some_widget_do_stuff_later (SomeWidget *self)
2358 * self->idle_id = g_idle_add (idle_callback, self);
2362 * some_widget_finalize (GObject *object)
2364 * SomeWidget *self = SOME_WIDGET (object);
2366 * if (self->idle_id)
2367 * g_source_remove (self->idle_id);
2369 * G_OBJECT_CLASS (parent_class)->finalize (object);
2373 * This will fail in a multi-threaded application if the
2374 * widget is destroyed before the idle handler fires due
2375 * to the use after free in the callback. A solution, to
2376 * this particular problem, is to check to if the source
2377 * has already been destroy within the callback.
2381 * idle_callback (gpointer data)
2383 * SomeWidget *self = data;
2385 * GDK_THREADS_ENTER ();
2386 * if (!g_source_is_destroyed (g_main_current_source ()))
2388 * /<!-- -->* do stuff with self *<!-- -->/
2390 * GDK_THREADS_LEAVE ();
2396 * Return value: %TRUE if the source has been destroyed
2401 g_source_is_destroyed (GSource *source)
2403 return SOURCE_DESTROYED (source);
2406 /* Temporarily remove all this source's file descriptors from the
2407 * poll(), so that if data comes available for one of the file descriptors
2408 * we don't continually spin in the poll()
2410 /* HOLDS: source->context's lock */
2412 block_source (GSource *source)
2416 g_return_if_fail (!SOURCE_BLOCKED (source));
2418 source->flags |= G_SOURCE_BLOCKED;
2420 tmp_list = source->poll_fds;
2423 g_main_context_remove_poll_unlocked (source->context, tmp_list->data);
2424 tmp_list = tmp_list->next;
2427 if (source->priv && source->priv->child_sources)
2429 tmp_list = source->priv->child_sources;
2432 block_source (tmp_list->data);
2433 tmp_list = tmp_list->next;
2438 /* HOLDS: source->context's lock */
2440 unblock_source (GSource *source)
2444 g_return_if_fail (SOURCE_BLOCKED (source)); /* Source already unblocked */
2445 g_return_if_fail (!SOURCE_DESTROYED (source));
2447 source->flags &= ~G_SOURCE_BLOCKED;
2449 tmp_list = source->poll_fds;
2452 g_main_context_add_poll_unlocked (source->context, source->priority, tmp_list->data);
2453 tmp_list = tmp_list->next;
2456 if (source->priv && source->priv->child_sources)
2458 tmp_list = source->priv->child_sources;
2461 unblock_source (tmp_list->data);
2462 tmp_list = tmp_list->next;
2467 /* HOLDS: context's lock */
2469 g_main_dispatch (GMainContext *context)
2471 GMainDispatch *current = get_dispatch ();
2474 for (i = 0; i < context->pending_dispatches->len; i++)
2476 GSource *source = context->pending_dispatches->pdata[i];
2478 context->pending_dispatches->pdata[i] = NULL;
2481 source->flags &= ~G_SOURCE_READY;
2483 if (!SOURCE_DESTROYED (source))
2485 gboolean was_in_call;
2486 gpointer user_data = NULL;
2487 GSourceFunc callback = NULL;
2488 GSourceCallbackFuncs *cb_funcs;
2490 gboolean need_destroy;
2492 gboolean (*dispatch) (GSource *,
2495 GSList current_source_link;
2497 dispatch = source->source_funcs->dispatch;
2498 cb_funcs = source->callback_funcs;
2499 cb_data = source->callback_data;
2502 cb_funcs->ref (cb_data);
2504 if ((source->flags & G_SOURCE_CAN_RECURSE) == 0)
2505 block_source (source);
2507 was_in_call = source->flags & G_HOOK_FLAG_IN_CALL;
2508 source->flags |= G_HOOK_FLAG_IN_CALL;
2511 cb_funcs->get (cb_data, source, &callback, &user_data);
2513 UNLOCK_CONTEXT (context);
2516 /* The on-stack allocation of the GSList is unconventional, but
2517 * we know that the lifetime of the link is bounded to this
2518 * function as the link is kept in a thread specific list and
2519 * not manipulated outside of this function and its descendants.
2520 * Avoiding the overhead of a g_slist_alloc() is useful as many
2521 * applications do little more than dispatch events.
2523 * This is a performance hack - do not revert to g_slist_prepend()!
2525 current_source_link.data = source;
2526 current_source_link.next = current->dispatching_sources;
2527 current->dispatching_sources = ¤t_source_link;
2528 need_destroy = ! dispatch (source,
2531 g_assert (current->dispatching_sources == ¤t_source_link);
2532 current->dispatching_sources = current_source_link.next;
2536 cb_funcs->unref (cb_data);
2538 LOCK_CONTEXT (context);
2541 source->flags &= ~G_HOOK_FLAG_IN_CALL;
2543 if (SOURCE_BLOCKED (source) && !SOURCE_DESTROYED (source))
2544 unblock_source (source);
2546 /* Note: this depends on the fact that we can't switch
2547 * sources from one main context to another
2549 if (need_destroy && !SOURCE_DESTROYED (source))
2551 g_assert (source->context == context);
2552 g_source_destroy_internal (source, context, TRUE);
2556 SOURCE_UNREF (source, context);
2559 g_ptr_array_set_size (context->pending_dispatches, 0);
2562 /* Holds context's lock */
2563 static inline GSource *
2564 next_valid_source (GMainContext *context,
2567 GSource *new_source = source ? source->next : context->source_list;
2571 if (!SOURCE_DESTROYED (new_source))
2573 new_source->ref_count++;
2577 new_source = new_source->next;
2581 SOURCE_UNREF (source, context);
2587 * g_main_context_acquire:
2588 * @context: a #GMainContext
2590 * Tries to become the owner of the specified context.
2591 * If some other thread is the owner of the context,
2592 * returns %FALSE immediately. Ownership is properly
2593 * recursive: the owner can require ownership again
2594 * and will release ownership when g_main_context_release()
2595 * is called as many times as g_main_context_acquire().
2597 * You must be the owner of a context before you
2598 * can call g_main_context_prepare(), g_main_context_query(),
2599 * g_main_context_check(), g_main_context_dispatch().
2601 * Return value: %TRUE if the operation succeeded, and
2602 * this thread is now the owner of @context.
2605 g_main_context_acquire (GMainContext *context)
2607 gboolean result = FALSE;
2608 GThread *self = G_THREAD_SELF;
2610 if (context == NULL)
2611 context = g_main_context_default ();
2613 LOCK_CONTEXT (context);
2615 if (!context->owner)
2617 context->owner = self;
2618 g_assert (context->owner_count == 0);
2621 if (context->owner == self)
2623 context->owner_count++;
2627 UNLOCK_CONTEXT (context);
2633 * g_main_context_release:
2634 * @context: a #GMainContext
2636 * Releases ownership of a context previously acquired by this thread
2637 * with g_main_context_acquire(). If the context was acquired multiple
2638 * times, the ownership will be released only when g_main_context_release()
2639 * is called as many times as it was acquired.
2642 g_main_context_release (GMainContext *context)
2644 if (context == NULL)
2645 context = g_main_context_default ();
2647 LOCK_CONTEXT (context);
2649 context->owner_count--;
2650 if (context->owner_count == 0)
2652 context->owner = NULL;
2654 if (context->waiters)
2656 GMainWaiter *waiter = context->waiters->data;
2657 gboolean loop_internal_waiter = (waiter->mutex == &context->mutex);
2658 context->waiters = g_slist_delete_link (context->waiters,
2660 if (!loop_internal_waiter)
2661 g_mutex_lock (waiter->mutex);
2663 g_cond_signal (waiter->cond);
2665 if (!loop_internal_waiter)
2666 g_mutex_unlock (waiter->mutex);
2670 UNLOCK_CONTEXT (context);
2674 * g_main_context_wait:
2675 * @context: a #GMainContext
2676 * @cond: a condition variable
2677 * @mutex: a mutex, currently held
2679 * Tries to become the owner of the specified context,
2680 * as with g_main_context_acquire(). But if another thread
2681 * is the owner, atomically drop @mutex and wait on @cond until
2682 * that owner releases ownership or until @cond is signaled, then
2683 * try again (once) to become the owner.
2685 * Return value: %TRUE if the operation succeeded, and
2686 * this thread is now the owner of @context.
2689 g_main_context_wait (GMainContext *context,
2693 gboolean result = FALSE;
2694 GThread *self = G_THREAD_SELF;
2695 gboolean loop_internal_waiter;
2697 if (context == NULL)
2698 context = g_main_context_default ();
2700 loop_internal_waiter = (mutex == &context->mutex);
2702 if (!loop_internal_waiter)
2703 LOCK_CONTEXT (context);
2705 if (context->owner && context->owner != self)
2710 waiter.mutex = mutex;
2712 context->waiters = g_slist_append (context->waiters, &waiter);
2714 if (!loop_internal_waiter)
2715 UNLOCK_CONTEXT (context);
2716 g_cond_wait (cond, mutex);
2717 if (!loop_internal_waiter)
2718 LOCK_CONTEXT (context);
2720 context->waiters = g_slist_remove (context->waiters, &waiter);
2723 if (!context->owner)
2725 context->owner = self;
2726 g_assert (context->owner_count == 0);
2729 if (context->owner == self)
2731 context->owner_count++;
2735 if (!loop_internal_waiter)
2736 UNLOCK_CONTEXT (context);
2742 * g_main_context_prepare:
2743 * @context: a #GMainContext
2744 * @priority: location to store priority of highest priority
2745 * source already ready.
2747 * Prepares to poll sources within a main loop. The resulting information
2748 * for polling is determined by calling g_main_context_query ().
2750 * Return value: %TRUE if some source is ready to be dispatched
2754 g_main_context_prepare (GMainContext *context,
2759 gint current_priority = G_MAXINT;
2762 if (context == NULL)
2763 context = g_main_context_default ();
2765 LOCK_CONTEXT (context);
2767 context->time_is_fresh = FALSE;
2769 if (context->in_check_or_prepare)
2771 g_warning ("g_main_context_prepare() called recursively from within a source's check() or "
2772 "prepare() member.");
2773 UNLOCK_CONTEXT (context);
2778 /* If recursing, finish up current dispatch, before starting over */
2779 if (context->pending_dispatches)
2782 g_main_dispatch (context, ¤t_time);
2784 UNLOCK_CONTEXT (context);
2789 /* If recursing, clear list of pending dispatches */
2791 for (i = 0; i < context->pending_dispatches->len; i++)
2793 if (context->pending_dispatches->pdata[i])
2794 SOURCE_UNREF ((GSource *)context->pending_dispatches->pdata[i], context);
2796 g_ptr_array_set_size (context->pending_dispatches, 0);
2798 /* Prepare all sources */
2800 context->timeout = -1;
2802 source = next_valid_source (context, NULL);
2805 gint source_timeout = -1;
2807 if ((n_ready > 0) && (source->priority > current_priority))
2809 SOURCE_UNREF (source, context);
2812 if (SOURCE_BLOCKED (source))
2815 if (!(source->flags & G_SOURCE_READY))
2818 gboolean (*prepare) (GSource *source,
2821 prepare = source->source_funcs->prepare;
2822 context->in_check_or_prepare++;
2823 UNLOCK_CONTEXT (context);
2825 result = (*prepare) (source, &source_timeout);
2827 LOCK_CONTEXT (context);
2828 context->in_check_or_prepare--;
2832 GSource *ready_source = source;
2834 while (ready_source)
2836 ready_source->flags |= G_SOURCE_READY;
2837 ready_source = ready_source->priv->parent_source;
2842 if (source->flags & G_SOURCE_READY)
2845 current_priority = source->priority;
2846 context->timeout = 0;
2849 if (source_timeout >= 0)
2851 if (context->timeout < 0)
2852 context->timeout = source_timeout;
2854 context->timeout = MIN (context->timeout, source_timeout);
2858 source = next_valid_source (context, source);
2861 UNLOCK_CONTEXT (context);
2864 *priority = current_priority;
2866 return (n_ready > 0);
2870 * g_main_context_query:
2871 * @context: a #GMainContext
2872 * @max_priority: maximum priority source to check
2873 * @timeout_: (out): location to store timeout to be used in polling
2874 * @fds: (out caller-allocates) (array length=n_fds): location to
2875 * store #GPollFD records that need to be polled.
2876 * @n_fds: length of @fds.
2878 * Determines information necessary to poll this main loop.
2880 * Return value: the number of records actually stored in @fds,
2881 * or, if more than @n_fds records need to be stored, the number
2882 * of records that need to be stored.
2885 g_main_context_query (GMainContext *context,
2894 LOCK_CONTEXT (context);
2896 pollrec = context->poll_records;
2898 while (pollrec && max_priority >= pollrec->priority)
2900 /* We need to include entries with fd->events == 0 in the array because
2901 * otherwise if the application changes fd->events behind our back and
2902 * makes it non-zero, we'll be out of sync when we check the fds[] array.
2903 * (Changing fd->events after adding an FD wasn't an anticipated use of
2904 * this API, but it occurs in practice.) */
2907 fds[n_poll].fd = pollrec->fd->fd;
2908 /* In direct contradiction to the Unix98 spec, IRIX runs into
2909 * difficulty if you pass in POLLERR, POLLHUP or POLLNVAL
2910 * flags in the events field of the pollfd while it should
2911 * just ignoring them. So we mask them out here.
2913 fds[n_poll].events = pollrec->fd->events & ~(G_IO_ERR|G_IO_HUP|G_IO_NVAL);
2914 fds[n_poll].revents = 0;
2917 pollrec = pollrec->next;
2921 context->poll_changed = FALSE;
2925 *timeout = context->timeout;
2927 context->time_is_fresh = FALSE;
2930 UNLOCK_CONTEXT (context);
2936 * g_main_context_check:
2937 * @context: a #GMainContext
2938 * @max_priority: the maximum numerical priority of sources to check
2939 * @fds: (array length=n_fds): array of #GPollFD's that was passed to
2940 * the last call to g_main_context_query()
2941 * @n_fds: return value of g_main_context_query()
2943 * Passes the results of polling back to the main loop.
2945 * Return value: %TRUE if some sources are ready to be dispatched.
2948 g_main_context_check (GMainContext *context,
2958 LOCK_CONTEXT (context);
2960 if (context->in_check_or_prepare)
2962 g_warning ("g_main_context_check() called recursively from within a source's check() or "
2963 "prepare() member.");
2964 UNLOCK_CONTEXT (context);
2968 if (context->wake_up_rec.revents)
2969 g_wakeup_acknowledge (context->wakeup);
2971 /* If the set of poll file descriptors changed, bail out
2972 * and let the main loop rerun
2974 if (context->poll_changed)
2976 UNLOCK_CONTEXT (context);
2980 pollrec = context->poll_records;
2984 if (pollrec->fd->events)
2985 pollrec->fd->revents = fds[i].revents;
2987 pollrec = pollrec->next;
2991 source = next_valid_source (context, NULL);
2994 if ((n_ready > 0) && (source->priority > max_priority))
2996 SOURCE_UNREF (source, context);
2999 if (SOURCE_BLOCKED (source))
3002 if (!(source->flags & G_SOURCE_READY))
3005 gboolean (*check) (GSource *source);
3007 check = source->source_funcs->check;
3009 context->in_check_or_prepare++;
3010 UNLOCK_CONTEXT (context);
3012 result = (*check) (source);
3014 LOCK_CONTEXT (context);
3015 context->in_check_or_prepare--;
3019 GSource *ready_source = source;
3021 while (ready_source)
3023 ready_source->flags |= G_SOURCE_READY;
3024 ready_source = ready_source->priv->parent_source;
3029 if (source->flags & G_SOURCE_READY)
3031 source->ref_count++;
3032 g_ptr_array_add (context->pending_dispatches, source);
3036 /* never dispatch sources with less priority than the first
3037 * one we choose to dispatch
3039 max_priority = source->priority;
3043 source = next_valid_source (context, source);
3046 UNLOCK_CONTEXT (context);
3052 * g_main_context_dispatch:
3053 * @context: a #GMainContext
3055 * Dispatches all pending sources.
3058 g_main_context_dispatch (GMainContext *context)
3060 LOCK_CONTEXT (context);
3062 if (context->pending_dispatches->len > 0)
3064 g_main_dispatch (context);
3067 UNLOCK_CONTEXT (context);
3070 /* HOLDS context lock */
3072 g_main_context_iterate (GMainContext *context,
3079 gboolean some_ready;
3080 gint nfds, allocated_nfds;
3081 GPollFD *fds = NULL;
3083 UNLOCK_CONTEXT (context);
3085 if (!g_main_context_acquire (context))
3087 gboolean got_ownership;
3089 LOCK_CONTEXT (context);
3094 got_ownership = g_main_context_wait (context,
3102 LOCK_CONTEXT (context);
3104 if (!context->cached_poll_array)
3106 context->cached_poll_array_size = context->n_poll_records;
3107 context->cached_poll_array = g_new (GPollFD, context->n_poll_records);
3110 allocated_nfds = context->cached_poll_array_size;
3111 fds = context->cached_poll_array;
3113 UNLOCK_CONTEXT (context);
3115 g_main_context_prepare (context, &max_priority);
3117 while ((nfds = g_main_context_query (context, max_priority, &timeout, fds,
3118 allocated_nfds)) > allocated_nfds)
3120 LOCK_CONTEXT (context);
3122 context->cached_poll_array_size = allocated_nfds = nfds;
3123 context->cached_poll_array = fds = g_new (GPollFD, nfds);
3124 UNLOCK_CONTEXT (context);
3130 g_main_context_poll (context, timeout, max_priority, fds, nfds);
3132 some_ready = g_main_context_check (context, max_priority, fds, nfds);
3135 g_main_context_dispatch (context);
3137 g_main_context_release (context);
3139 LOCK_CONTEXT (context);
3145 * g_main_context_pending:
3146 * @context: (allow-none): a #GMainContext (if %NULL, the default context will be used)
3148 * Checks if any sources have pending events for the given context.
3150 * Return value: %TRUE if events are pending.
3153 g_main_context_pending (GMainContext *context)
3158 context = g_main_context_default();
3160 LOCK_CONTEXT (context);
3161 retval = g_main_context_iterate (context, FALSE, FALSE, G_THREAD_SELF);
3162 UNLOCK_CONTEXT (context);
3168 * g_main_context_iteration:
3169 * @context: (allow-none): a #GMainContext (if %NULL, the default context will be used)
3170 * @may_block: whether the call may block.
3172 * Runs a single iteration for the given main loop. This involves
3173 * checking to see if any event sources are ready to be processed,
3174 * then if no events sources are ready and @may_block is %TRUE, waiting
3175 * for a source to become ready, then dispatching the highest priority
3176 * events sources that are ready. Otherwise, if @may_block is %FALSE
3177 * sources are not waited to become ready, only those highest priority
3178 * events sources will be dispatched (if any), that are ready at this
3179 * given moment without further waiting.
3181 * Note that even when @may_block is %TRUE, it is still possible for
3182 * g_main_context_iteration() to return %FALSE, since the the wait may
3183 * be interrupted for other reasons than an event source becoming ready.
3185 * Return value: %TRUE if events were dispatched.
3188 g_main_context_iteration (GMainContext *context, gboolean may_block)
3193 context = g_main_context_default();
3195 LOCK_CONTEXT (context);
3196 retval = g_main_context_iterate (context, may_block, TRUE, G_THREAD_SELF);
3197 UNLOCK_CONTEXT (context);
3204 * @context: (allow-none): a #GMainContext (if %NULL, the default context will be used).
3205 * @is_running: set to %TRUE to indicate that the loop is running. This
3206 * is not very important since calling g_main_loop_run() will set this to
3209 * Creates a new #GMainLoop structure.
3211 * Return value: a new #GMainLoop.
3214 g_main_loop_new (GMainContext *context,
3215 gboolean is_running)
3220 context = g_main_context_default();
3222 g_main_context_ref (context);
3224 loop = g_new0 (GMainLoop, 1);
3225 loop->context = context;
3226 loop->is_running = is_running != FALSE;
3227 loop->ref_count = 1;
3234 * @loop: a #GMainLoop
3236 * Increases the reference count on a #GMainLoop object by one.
3238 * Return value: @loop
3241 g_main_loop_ref (GMainLoop *loop)
3243 g_return_val_if_fail (loop != NULL, NULL);
3244 g_return_val_if_fail (g_atomic_int_get (&loop->ref_count) > 0, NULL);
3246 g_atomic_int_inc (&loop->ref_count);
3252 * g_main_loop_unref:
3253 * @loop: a #GMainLoop
3255 * Decreases the reference count on a #GMainLoop object by one. If
3256 * the result is zero, free the loop and free all associated memory.
3259 g_main_loop_unref (GMainLoop *loop)
3261 g_return_if_fail (loop != NULL);
3262 g_return_if_fail (g_atomic_int_get (&loop->ref_count) > 0);
3264 if (!g_atomic_int_dec_and_test (&loop->ref_count))
3267 g_main_context_unref (loop->context);
3273 * @loop: a #GMainLoop
3275 * Runs a main loop until g_main_loop_quit() is called on the loop.
3276 * If this is called for the thread of the loop's #GMainContext,
3277 * it will process events from the loop, otherwise it will
3281 g_main_loop_run (GMainLoop *loop)
3283 GThread *self = G_THREAD_SELF;
3285 g_return_if_fail (loop != NULL);
3286 g_return_if_fail (g_atomic_int_get (&loop->ref_count) > 0);
3288 if (!g_main_context_acquire (loop->context))
3290 gboolean got_ownership = FALSE;
3292 /* Another thread owns this context */
3293 LOCK_CONTEXT (loop->context);
3295 g_atomic_int_inc (&loop->ref_count);
3297 if (!loop->is_running)
3298 loop->is_running = TRUE;
3300 while (loop->is_running && !got_ownership)
3301 got_ownership = g_main_context_wait (loop->context,
3302 &loop->context->cond,
3303 &loop->context->mutex);
3305 if (!loop->is_running)
3307 UNLOCK_CONTEXT (loop->context);
3309 g_main_context_release (loop->context);
3310 g_main_loop_unref (loop);
3314 g_assert (got_ownership);
3317 LOCK_CONTEXT (loop->context);
3319 if (loop->context->in_check_or_prepare)
3321 g_warning ("g_main_loop_run(): called recursively from within a source's "
3322 "check() or prepare() member, iteration not possible.");
3326 g_atomic_int_inc (&loop->ref_count);
3327 loop->is_running = TRUE;
3328 while (loop->is_running)
3329 g_main_context_iterate (loop->context, TRUE, TRUE, self);
3331 UNLOCK_CONTEXT (loop->context);
3333 g_main_context_release (loop->context);
3335 g_main_loop_unref (loop);
3340 * @loop: a #GMainLoop
3342 * Stops a #GMainLoop from running. Any calls to g_main_loop_run()
3343 * for the loop will return.
3345 * Note that sources that have already been dispatched when
3346 * g_main_loop_quit() is called will still be executed.
3349 g_main_loop_quit (GMainLoop *loop)
3351 g_return_if_fail (loop != NULL);
3352 g_return_if_fail (g_atomic_int_get (&loop->ref_count) > 0);
3354 LOCK_CONTEXT (loop->context);
3355 loop->is_running = FALSE;
3356 g_wakeup_signal (loop->context->wakeup);
3358 g_cond_broadcast (&loop->context->cond);
3360 UNLOCK_CONTEXT (loop->context);
3364 * g_main_loop_is_running:
3365 * @loop: a #GMainLoop.
3367 * Checks to see if the main loop is currently being run via g_main_loop_run().
3369 * Return value: %TRUE if the mainloop is currently being run.
3372 g_main_loop_is_running (GMainLoop *loop)
3374 g_return_val_if_fail (loop != NULL, FALSE);
3375 g_return_val_if_fail (g_atomic_int_get (&loop->ref_count) > 0, FALSE);
3377 return loop->is_running;
3381 * g_main_loop_get_context:
3382 * @loop: a #GMainLoop.
3384 * Returns the #GMainContext of @loop.
3386 * Return value: (transfer none): the #GMainContext of @loop
3389 g_main_loop_get_context (GMainLoop *loop)
3391 g_return_val_if_fail (loop != NULL, NULL);
3392 g_return_val_if_fail (g_atomic_int_get (&loop->ref_count) > 0, NULL);
3394 return loop->context;
3397 /* HOLDS: context's lock */
3399 g_main_context_poll (GMainContext *context,
3405 #ifdef G_MAIN_POLL_DEBUG
3411 GPollFunc poll_func;
3413 if (n_fds || timeout != 0)
3415 #ifdef G_MAIN_POLL_DEBUG
3416 if (_g_main_poll_debug)
3418 g_print ("polling context=%p n=%d timeout=%d\n",
3419 context, n_fds, timeout);
3420 poll_timer = g_timer_new ();
3424 LOCK_CONTEXT (context);
3426 poll_func = context->poll_func;
3428 UNLOCK_CONTEXT (context);
3429 if ((*poll_func) (fds, n_fds, timeout) < 0 && errno != EINTR)
3432 g_warning ("poll(2) failed due to: %s.",
3433 g_strerror (errno));
3435 /* If g_poll () returns -1, it has already called g_warning() */
3439 #ifdef G_MAIN_POLL_DEBUG
3440 if (_g_main_poll_debug)
3442 LOCK_CONTEXT (context);
3444 g_print ("g_main_poll(%d) timeout: %d - elapsed %12.10f seconds",
3447 g_timer_elapsed (poll_timer, NULL));
3448 g_timer_destroy (poll_timer);
3449 pollrec = context->poll_records;
3451 while (pollrec != NULL)
3456 if (fds[i].fd == pollrec->fd->fd &&
3457 pollrec->fd->events &&
3460 g_print (" [" G_POLLFD_FORMAT " :", fds[i].fd);
3461 if (fds[i].revents & G_IO_IN)
3463 if (fds[i].revents & G_IO_OUT)
3465 if (fds[i].revents & G_IO_PRI)
3467 if (fds[i].revents & G_IO_ERR)
3469 if (fds[i].revents & G_IO_HUP)
3471 if (fds[i].revents & G_IO_NVAL)
3477 pollrec = pollrec->next;
3481 UNLOCK_CONTEXT (context);
3484 } /* if (n_fds || timeout != 0) */
3488 * g_main_context_add_poll:
3489 * @context: (allow-none): a #GMainContext (or %NULL for the default context)
3490 * @fd: a #GPollFD structure holding information about a file
3491 * descriptor to watch.
3492 * @priority: the priority for this file descriptor which should be
3493 * the same as the priority used for g_source_attach() to ensure that the
3494 * file descriptor is polled whenever the results may be needed.
3496 * Adds a file descriptor to the set of file descriptors polled for
3497 * this context. This will very seldom be used directly. Instead
3498 * a typical event source will use g_source_add_poll() instead.
3501 g_main_context_add_poll (GMainContext *context,
3506 context = g_main_context_default ();
3508 g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
3509 g_return_if_fail (fd);
3511 LOCK_CONTEXT (context);
3512 g_main_context_add_poll_unlocked (context, priority, fd);
3513 UNLOCK_CONTEXT (context);
3516 /* HOLDS: main_loop_lock */
3518 g_main_context_add_poll_unlocked (GMainContext *context,
3522 GPollRec *prevrec, *nextrec;
3523 GPollRec *newrec = g_slice_new (GPollRec);
3525 /* This file descriptor may be checked before we ever poll */
3528 newrec->priority = priority;
3530 prevrec = context->poll_records_tail;
3532 while (prevrec && priority < prevrec->priority)
3535 prevrec = prevrec->prev;
3539 prevrec->next = newrec;
3541 context->poll_records = newrec;
3543 newrec->prev = prevrec;
3544 newrec->next = nextrec;
3547 nextrec->prev = newrec;
3549 context->poll_records_tail = newrec;
3551 context->n_poll_records++;
3553 context->poll_changed = TRUE;
3555 /* Now wake up the main loop if it is waiting in the poll() */
3556 g_wakeup_signal (context->wakeup);
3560 * g_main_context_remove_poll:
3561 * @context:a #GMainContext
3562 * @fd: a #GPollFD descriptor previously added with g_main_context_add_poll()
3564 * Removes file descriptor from the set of file descriptors to be
3565 * polled for a particular context.
3568 g_main_context_remove_poll (GMainContext *context,
3572 context = g_main_context_default ();
3574 g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
3575 g_return_if_fail (fd);
3577 LOCK_CONTEXT (context);
3578 g_main_context_remove_poll_unlocked (context, fd);
3579 UNLOCK_CONTEXT (context);
3583 g_main_context_remove_poll_unlocked (GMainContext *context,
3586 GPollRec *pollrec, *prevrec, *nextrec;
3589 pollrec = context->poll_records;
3593 nextrec = pollrec->next;
3594 if (pollrec->fd == fd)
3596 if (prevrec != NULL)
3597 prevrec->next = nextrec;
3599 context->poll_records = nextrec;
3601 if (nextrec != NULL)
3602 nextrec->prev = prevrec;
3604 context->poll_records_tail = prevrec;
3606 g_slice_free (GPollRec, pollrec);
3608 context->n_poll_records--;
3615 context->poll_changed = TRUE;
3617 /* Now wake up the main loop if it is waiting in the poll() */
3618 g_wakeup_signal (context->wakeup);
3622 * g_source_get_current_time:
3623 * @source: a #GSource
3624 * @timeval: #GTimeVal structure in which to store current time.
3626 * This function ignores @source and is otherwise the same as
3627 * g_get_current_time().
3629 * Deprecated: 2.28: use g_source_get_time() instead
3632 g_source_get_current_time (GSource *source,
3635 g_get_current_time (timeval);
3639 * g_source_get_time:
3640 * @source: a #GSource
3642 * Gets the time to be used when checking this source. The advantage of
3643 * calling this function over calling g_get_monotonic_time() directly is
3644 * that when checking multiple sources, GLib can cache a single value
3645 * instead of having to repeatedly get the system monotonic time.
3647 * The time here is the system monotonic time, if available, or some
3648 * other reasonable alternative otherwise. See g_get_monotonic_time().
3650 * Returns: the monotonic time in microseconds
3655 g_source_get_time (GSource *source)
3657 GMainContext *context;
3660 g_return_val_if_fail (source->context != NULL, 0);
3662 context = source->context;
3664 LOCK_CONTEXT (context);
3666 if (!context->time_is_fresh)
3668 context->time = g_get_monotonic_time ();
3669 context->time_is_fresh = TRUE;
3672 result = context->time;
3674 UNLOCK_CONTEXT (context);
3680 * g_main_context_set_poll_func:
3681 * @context: a #GMainContext
3682 * @func: the function to call to poll all file descriptors
3684 * Sets the function to use to handle polling of file descriptors. It
3685 * will be used instead of the poll() system call
3686 * (or GLib's replacement function, which is used where
3687 * poll() isn't available).
3689 * This function could possibly be used to integrate the GLib event
3690 * loop with an external event loop.
3693 g_main_context_set_poll_func (GMainContext *context,
3697 context = g_main_context_default ();
3699 g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
3701 LOCK_CONTEXT (context);
3704 context->poll_func = func;
3706 context->poll_func = g_poll;
3708 UNLOCK_CONTEXT (context);
3712 * g_main_context_get_poll_func:
3713 * @context: a #GMainContext
3715 * Gets the poll function set by g_main_context_set_poll_func().
3717 * Return value: the poll function
3720 g_main_context_get_poll_func (GMainContext *context)
3725 context = g_main_context_default ();
3727 g_return_val_if_fail (g_atomic_int_get (&context->ref_count) > 0, NULL);
3729 LOCK_CONTEXT (context);
3730 result = context->poll_func;
3731 UNLOCK_CONTEXT (context);
3737 * g_main_context_wakeup:
3738 * @context: a #GMainContext
3740 * If @context is currently waiting in a poll(), interrupt
3741 * the poll(), and continue the iteration process.
3744 g_main_context_wakeup (GMainContext *context)
3747 context = g_main_context_default ();
3749 g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
3751 g_wakeup_signal (context->wakeup);
3755 * g_main_context_is_owner:
3756 * @context: a #GMainContext
3758 * Determines whether this thread holds the (recursive)
3759 * ownership of this #GMainContext. This is useful to
3760 * know before waiting on another thread that may be
3761 * blocking to get ownership of @context.
3763 * Returns: %TRUE if current thread is owner of @context.
3768 g_main_context_is_owner (GMainContext *context)
3773 context = g_main_context_default ();
3775 LOCK_CONTEXT (context);
3776 is_owner = context->owner == G_THREAD_SELF;
3777 UNLOCK_CONTEXT (context);
3785 g_timeout_set_expiration (GTimeoutSource *timeout_source,
3786 gint64 current_time)
3788 timeout_source->expiration = current_time +
3789 (guint64) timeout_source->interval * 1000;
3791 if (timeout_source->seconds)
3794 static gint timer_perturb = -1;
3796 if (timer_perturb == -1)
3799 * we want a per machine/session unique 'random' value; try the dbus
3800 * address first, that has a UUID in it. If there is no dbus, use the
3801 * hostname for hashing.
3803 const char *session_bus_address = g_getenv ("DBUS_SESSION_BUS_ADDRESS");
3804 if (!session_bus_address)
3805 session_bus_address = g_getenv ("HOSTNAME");
3806 if (session_bus_address)
3807 timer_perturb = ABS ((gint) g_str_hash (session_bus_address)) % 1000000;
3812 /* We want the microseconds part of the timeout to land on the
3813 * 'timer_perturb' mark, but we need to make sure we don't try to
3814 * set the timeout in the past. We do this by ensuring that we
3815 * always only *increase* the expiration time by adding a full
3816 * second in the case that the microsecond portion decreases.
3818 timeout_source->expiration -= timer_perturb;
3820 remainder = timeout_source->expiration % 1000000;
3821 if (remainder >= 1000000/4)
3822 timeout_source->expiration += 1000000;
3824 timeout_source->expiration -= remainder;
3825 timeout_source->expiration += timer_perturb;
3830 g_timeout_prepare (GSource *source,
3833 GTimeoutSource *timeout_source = (GTimeoutSource *) source;
3834 gint64 now = g_source_get_time (source);
3836 if (now < timeout_source->expiration)
3838 /* Round up to ensure that we don't try again too early */
3839 *timeout = (timeout_source->expiration - now + 999) / 1000;
3848 g_timeout_check (GSource *source)
3850 GTimeoutSource *timeout_source = (GTimeoutSource *) source;
3851 gint64 now = g_source_get_time (source);
3853 return timeout_source->expiration <= now;
3857 g_timeout_dispatch (GSource *source,
3858 GSourceFunc callback,
3861 GTimeoutSource *timeout_source = (GTimeoutSource *)source;
3866 g_warning ("Timeout source dispatched without callback\n"
3867 "You must call g_source_set_callback().");
3871 again = callback (user_data);
3874 g_timeout_set_expiration (timeout_source, g_source_get_time (source));
3880 * g_timeout_source_new:
3881 * @interval: the timeout interval in milliseconds.
3883 * Creates a new timeout source.
3885 * The source will not initially be associated with any #GMainContext
3886 * and must be added to one with g_source_attach() before it will be
3889 * The interval given is in terms of monotonic time, not wall clock
3890 * time. See g_get_monotonic_time().
3892 * Return value: the newly-created timeout source
3895 g_timeout_source_new (guint interval)
3897 GSource *source = g_source_new (&g_timeout_funcs, sizeof (GTimeoutSource));
3898 GTimeoutSource *timeout_source = (GTimeoutSource *)source;
3900 timeout_source->interval = interval;
3901 g_timeout_set_expiration (timeout_source, g_get_monotonic_time ());
3907 * g_timeout_source_new_seconds:
3908 * @interval: the timeout interval in seconds
3910 * Creates a new timeout source.
3912 * The source will not initially be associated with any #GMainContext
3913 * and must be added to one with g_source_attach() before it will be
3916 * The scheduling granularity/accuracy of this timeout source will be
3919 * The interval given in terms of monotonic time, not wall clock time.
3920 * See g_get_monotonic_time().
3922 * Return value: the newly-created timeout source
3927 g_timeout_source_new_seconds (guint interval)
3929 GSource *source = g_source_new (&g_timeout_funcs, sizeof (GTimeoutSource));
3930 GTimeoutSource *timeout_source = (GTimeoutSource *)source;
3932 timeout_source->interval = 1000 * interval;
3933 timeout_source->seconds = TRUE;
3935 g_timeout_set_expiration (timeout_source, g_get_monotonic_time ());
3942 * g_timeout_add_full:
3943 * @priority: the priority of the timeout source. Typically this will be in
3944 * the range between #G_PRIORITY_DEFAULT and #G_PRIORITY_HIGH.
3945 * @interval: the time between calls to the function, in milliseconds
3946 * (1/1000ths of a second)
3947 * @function: function to call
3948 * @data: data to pass to @function
3949 * @notify: (allow-none): function to call when the timeout is removed, or %NULL
3951 * Sets a function to be called at regular intervals, with the given
3952 * priority. The function is called repeatedly until it returns
3953 * %FALSE, at which point the timeout is automatically destroyed and
3954 * the function will not be called again. The @notify function is
3955 * called when the timeout is destroyed. The first call to the
3956 * function will be at the end of the first @interval.
3958 * Note that timeout functions may be delayed, due to the processing of other
3959 * event sources. Thus they should not be relied on for precise timing.
3960 * After each call to the timeout function, the time of the next
3961 * timeout is recalculated based on the current time and the given interval
3962 * (it does not try to 'catch up' time lost in delays).
3964 * This internally creates a main loop source using g_timeout_source_new()
3965 * and attaches it to the main loop context using g_source_attach(). You can
3966 * do these steps manually if you need greater control.
3968 * The interval given in terms of monotonic time, not wall clock time.
3969 * See g_get_monotonic_time().
3971 * Return value: the ID (greater than 0) of the event source.
3972 * Rename to: g_timeout_add
3975 g_timeout_add_full (gint priority,
3977 GSourceFunc function,
3979 GDestroyNotify notify)
3984 g_return_val_if_fail (function != NULL, 0);
3986 source = g_timeout_source_new (interval);
3988 if (priority != G_PRIORITY_DEFAULT)
3989 g_source_set_priority (source, priority);
3991 g_source_set_callback (source, function, data, notify);
3992 id = g_source_attach (source, NULL);
3993 g_source_unref (source);
4000 * @interval: the time between calls to the function, in milliseconds
4001 * (1/1000ths of a second)
4002 * @function: function to call
4003 * @data: data to pass to @function
4005 * Sets a function to be called at regular intervals, with the default
4006 * priority, #G_PRIORITY_DEFAULT. The function is called repeatedly
4007 * until it returns %FALSE, at which point the timeout is automatically
4008 * destroyed and the function will not be called again. The first call
4009 * to the function will be at the end of the first @interval.
4011 * Note that timeout functions may be delayed, due to the processing of other
4012 * event sources. Thus they should not be relied on for precise timing.
4013 * After each call to the timeout function, the time of the next
4014 * timeout is recalculated based on the current time and the given interval
4015 * (it does not try to 'catch up' time lost in delays).
4017 * If you want to have a timer in the "seconds" range and do not care
4018 * about the exact time of the first call of the timer, use the
4019 * g_timeout_add_seconds() function; this function allows for more
4020 * optimizations and more efficient system power usage.
4022 * This internally creates a main loop source using g_timeout_source_new()
4023 * and attaches it to the main loop context using g_source_attach(). You can
4024 * do these steps manually if you need greater control.
4026 * The interval given is in terms of monotonic time, not wall clock
4027 * time. See g_get_monotonic_time().
4029 * Return value: the ID (greater than 0) of the event source.
4032 g_timeout_add (guint32 interval,
4033 GSourceFunc function,
4036 return g_timeout_add_full (G_PRIORITY_DEFAULT,
4037 interval, function, data, NULL);
4041 * g_timeout_add_seconds_full:
4042 * @priority: the priority of the timeout source. Typically this will be in
4043 * the range between #G_PRIORITY_DEFAULT and #G_PRIORITY_HIGH.
4044 * @interval: the time between calls to the function, in seconds
4045 * @function: function to call
4046 * @data: data to pass to @function
4047 * @notify: (allow-none): function to call when the timeout is removed, or %NULL
4049 * Sets a function to be called at regular intervals, with @priority.
4050 * The function is called repeatedly until it returns %FALSE, at which
4051 * point the timeout is automatically destroyed and the function will
4052 * not be called again.
4054 * Unlike g_timeout_add(), this function operates at whole second granularity.
4055 * The initial starting point of the timer is determined by the implementation
4056 * and the implementation is expected to group multiple timers together so that
4057 * they fire all at the same time.
4058 * To allow this grouping, the @interval to the first timer is rounded
4059 * and can deviate up to one second from the specified interval.
4060 * Subsequent timer iterations will generally run at the specified interval.
4062 * Note that timeout functions may be delayed, due to the processing of other
4063 * event sources. Thus they should not be relied on for precise timing.
4064 * After each call to the timeout function, the time of the next
4065 * timeout is recalculated based on the current time and the given @interval
4067 * If you want timing more precise than whole seconds, use g_timeout_add()
4070 * The grouping of timers to fire at the same time results in a more power
4071 * and CPU efficient behavior so if your timer is in multiples of seconds
4072 * and you don't require the first timer exactly one second from now, the
4073 * use of g_timeout_add_seconds() is preferred over g_timeout_add().
4075 * This internally creates a main loop source using
4076 * g_timeout_source_new_seconds() and attaches it to the main loop context
4077 * using g_source_attach(). You can do these steps manually if you need
4080 * The interval given is in terms of monotonic time, not wall clock
4081 * time. See g_get_monotonic_time().
4083 * Return value: the ID (greater than 0) of the event source.
4085 * Rename to: g_timeout_add_seconds
4089 g_timeout_add_seconds_full (gint priority,
4091 GSourceFunc function,
4093 GDestroyNotify notify)
4098 g_return_val_if_fail (function != NULL, 0);
4100 source = g_timeout_source_new_seconds (interval);
4102 if (priority != G_PRIORITY_DEFAULT)
4103 g_source_set_priority (source, priority);
4105 g_source_set_callback (source, function, data, notify);
4106 id = g_source_attach (source, NULL);
4107 g_source_unref (source);
4113 * g_timeout_add_seconds:
4114 * @interval: the time between calls to the function, in seconds
4115 * @function: function to call
4116 * @data: data to pass to @function
4118 * Sets a function to be called at regular intervals with the default
4119 * priority, #G_PRIORITY_DEFAULT. The function is called repeatedly until
4120 * it returns %FALSE, at which point the timeout is automatically destroyed
4121 * and the function will not be called again.
4123 * This internally creates a main loop source using
4124 * g_timeout_source_new_seconds() and attaches it to the main loop context
4125 * using g_source_attach(). You can do these steps manually if you need
4126 * greater control. Also see g_timeout_add_seconds_full().
4128 * Note that the first call of the timer may not be precise for timeouts
4129 * of one second. If you need finer precision and have such a timeout,
4130 * you may want to use g_timeout_add() instead.
4132 * The interval given is in terms of monotonic time, not wall clock
4133 * time. See g_get_monotonic_time().
4135 * Return value: the ID (greater than 0) of the event source.
4140 g_timeout_add_seconds (guint interval,
4141 GSourceFunc function,
4144 g_return_val_if_fail (function != NULL, 0);
4146 return g_timeout_add_seconds_full (G_PRIORITY_DEFAULT, interval, function, data, NULL);
4149 /* Child watch functions */
4154 g_child_watch_prepare (GSource *source,
4162 g_child_watch_check (GSource *source)
4164 GChildWatchSource *child_watch_source;
4165 gboolean child_exited;
4167 child_watch_source = (GChildWatchSource *) source;
4169 child_exited = child_watch_source->poll.revents & G_IO_IN;
4176 * Note: We do _not_ check for the special value of STILL_ACTIVE
4177 * since we know that the process has exited and doing so runs into
4178 * problems if the child process "happens to return STILL_ACTIVE(259)"
4179 * as Microsoft's Platform SDK puts it.
4181 if (!GetExitCodeProcess (child_watch_source->pid, &child_status))
4183 gchar *emsg = g_win32_error_message (GetLastError ());
4184 g_warning (G_STRLOC ": GetExitCodeProcess() failed: %s", emsg);
4187 child_watch_source->child_status = -1;
4190 child_watch_source->child_status = child_status;
4193 return child_exited;
4197 g_child_watch_finalize (GSource *source)
4201 #else /* G_OS_WIN32 */
4204 wake_source (GSource *source)
4206 GMainContext *context;
4208 /* This should be thread-safe:
4210 * - if the source is currently being added to a context, that
4211 * context will be woken up anyway
4213 * - if the source is currently being destroyed, we simply need not
4216 * - the memory for the source will remain valid until after the
4217 * source finalize function was called (which would remove the
4218 * source from the global list which we are currently holding the
4221 * - the GMainContext will either be NULL or point to a live
4224 * - the GMainContext will remain valid since we hold the
4225 * main_context_list lock
4227 * Since we are holding a lot of locks here, don't try to enter any
4228 * more GMainContext functions for fear of dealock -- just hit the
4229 * GWakeup and run. Even if that's safe now, it could easily become
4230 * unsafe with some very minor changes in the future, and signal
4231 * handling is not the most well-tested codepath.
4233 G_LOCK(main_context_list);
4234 context = source->context;
4236 g_wakeup_signal (context->wakeup);
4237 G_UNLOCK(main_context_list);
4241 dispatch_unix_signals (void)
4245 /* clear this first incase another one arrives while we're processing */
4246 any_unix_signal_pending = FALSE;
4248 G_LOCK(unix_signal_lock);
4250 /* handle GChildWatchSource instances */
4251 if (unix_signal_pending[SIGCHLD])
4253 unix_signal_pending[SIGCHLD] = FALSE;
4255 /* The only way we can do this is to scan all of the children.
4257 * The docs promise that we will not reap children that we are not
4258 * explicitly watching, so that ties our hands from calling
4259 * waitpid(-1). We also can't use siginfo's si_pid field since if
4260 * multiple SIGCHLD arrive at the same time, one of them can be
4261 * dropped (since a given UNIX signal can only be pending once).
4263 for (node = unix_child_watches; node; node = node->next)
4265 GChildWatchSource *source = node->data;
4267 if (!source->child_exited)
4269 if (waitpid (source->pid, &source->child_status, WNOHANG) > 0)
4271 source->child_exited = TRUE;
4273 wake_source ((GSource *) source);
4279 /* handle GUnixSignalWatchSource instances */
4280 for (node = unix_signal_watches; node; node = node->next)
4282 GUnixSignalWatchSource *source = node->data;
4284 if (!source->pending)
4286 if (unix_signal_pending[source->signum])
4288 unix_signal_pending[source->signum] = FALSE;
4289 source->pending = TRUE;
4291 wake_source ((GSource *) source);
4296 G_UNLOCK(unix_signal_lock);
4300 g_child_watch_prepare (GSource *source,
4303 GChildWatchSource *child_watch_source;
4305 child_watch_source = (GChildWatchSource *) source;
4307 return child_watch_source->child_exited;
4311 g_child_watch_check (GSource *source)
4313 GChildWatchSource *child_watch_source;
4315 child_watch_source = (GChildWatchSource *) source;
4317 return child_watch_source->child_exited;
4321 g_unix_signal_watch_prepare (GSource *source,
4324 GUnixSignalWatchSource *unix_signal_source;
4326 unix_signal_source = (GUnixSignalWatchSource *) source;
4328 return unix_signal_source->pending;
4332 g_unix_signal_watch_check (GSource *source)
4334 GUnixSignalWatchSource *unix_signal_source;
4336 unix_signal_source = (GUnixSignalWatchSource *) source;
4338 return unix_signal_source->pending;
4342 g_unix_signal_watch_dispatch (GSource *source,
4343 GSourceFunc callback,
4346 GUnixSignalWatchSource *unix_signal_source;
4348 unix_signal_source = (GUnixSignalWatchSource *) source;
4352 g_warning ("Unix signal source dispatched without callback\n"
4353 "You must call g_source_set_callback().");
4357 (callback) (user_data);
4359 unix_signal_source->pending = FALSE;
4365 ensure_unix_signal_handler_installed_unlocked (int signum)
4367 static sigset_t installed_signal_mask;
4368 static gboolean initialized;
4369 struct sigaction action;
4373 sigemptyset (&installed_signal_mask);
4374 g_get_worker_context ();
4378 if (sigismember (&installed_signal_mask, signum))
4381 sigaddset (&installed_signal_mask, signum);
4383 action.sa_handler = g_unix_signal_handler;
4384 sigemptyset (&action.sa_mask);
4385 action.sa_flags = SA_RESTART | SA_NOCLDSTOP;
4386 sigaction (signum, &action, NULL);
4390 _g_main_create_unix_signal_watch (int signum)
4393 GUnixSignalWatchSource *unix_signal_source;
4395 source = g_source_new (&g_unix_signal_funcs, sizeof (GUnixSignalWatchSource));
4396 unix_signal_source = (GUnixSignalWatchSource *) source;
4398 unix_signal_source->signum = signum;
4399 unix_signal_source->pending = FALSE;
4401 G_LOCK (unix_signal_lock);
4402 ensure_unix_signal_handler_installed_unlocked (signum);
4403 unix_signal_watches = g_slist_prepend (unix_signal_watches, unix_signal_source);
4404 if (unix_signal_pending[signum])
4405 unix_signal_source->pending = TRUE;
4406 unix_signal_pending[signum] = FALSE;
4407 G_UNLOCK (unix_signal_lock);
4413 g_unix_signal_watch_finalize (GSource *source)
4415 G_LOCK (unix_signal_lock);
4416 unix_signal_watches = g_slist_remove (unix_signal_watches, source);
4417 G_UNLOCK (unix_signal_lock);
4421 g_child_watch_finalize (GSource *source)
4423 G_LOCK (unix_signal_lock);
4424 unix_child_watches = g_slist_remove (unix_child_watches, source);
4425 G_UNLOCK (unix_signal_lock);
4428 #endif /* G_OS_WIN32 */
4431 g_child_watch_dispatch (GSource *source,
4432 GSourceFunc callback,
4435 GChildWatchSource *child_watch_source;
4436 GChildWatchFunc child_watch_callback = (GChildWatchFunc) callback;
4438 child_watch_source = (GChildWatchSource *) source;
4442 g_warning ("Child watch source dispatched without callback\n"
4443 "You must call g_source_set_callback().");
4447 (child_watch_callback) (child_watch_source->pid, child_watch_source->child_status, user_data);
4449 /* We never keep a child watch source around as the child is gone */
4456 g_unix_signal_handler (int signum)
4458 unix_signal_pending[signum] = TRUE;
4459 any_unix_signal_pending = TRUE;
4461 g_wakeup_signal (glib_worker_context->wakeup);
4464 #endif /* !G_OS_WIN32 */
4467 * g_child_watch_source_new:
4468 * @pid: process to watch. On POSIX the pid of a child process. On
4469 * Windows a handle for a process (which doesn't have to be a child).
4471 * Creates a new child_watch source.
4473 * The source will not initially be associated with any #GMainContext
4474 * and must be added to one with g_source_attach() before it will be
4477 * Note that child watch sources can only be used in conjunction with
4478 * <literal>g_spawn...</literal> when the %G_SPAWN_DO_NOT_REAP_CHILD
4481 * Note that on platforms where #GPid must be explicitly closed
4482 * (see g_spawn_close_pid()) @pid must not be closed while the
4483 * source is still active. Typically, you will want to call
4484 * g_spawn_close_pid() in the callback function for the source.
4486 * Note further that using g_child_watch_source_new() is not
4487 * compatible with calling <literal>waitpid(-1)</literal> in
4488 * the application. Calling waitpid() for individual pids will
4491 * Return value: the newly-created child watch source
4496 g_child_watch_source_new (GPid pid)
4498 GSource *source = g_source_new (&g_child_watch_funcs, sizeof (GChildWatchSource));
4499 GChildWatchSource *child_watch_source = (GChildWatchSource *)source;
4501 child_watch_source->pid = pid;
4504 child_watch_source->poll.fd = (gintptr) pid;
4505 child_watch_source->poll.events = G_IO_IN;
4507 g_source_add_poll (source, &child_watch_source->poll);
4508 #else /* G_OS_WIN32 */
4509 G_LOCK (unix_signal_lock);
4510 ensure_unix_signal_handler_installed_unlocked (SIGCHLD);
4511 unix_child_watches = g_slist_prepend (unix_child_watches, child_watch_source);
4512 if (waitpid (pid, &child_watch_source->child_status, WNOHANG) > 0)
4513 child_watch_source->child_exited = TRUE;
4514 G_UNLOCK (unix_signal_lock);
4515 #endif /* G_OS_WIN32 */
4521 * g_child_watch_add_full:
4522 * @priority: the priority of the idle source. Typically this will be in the
4523 * range between #G_PRIORITY_DEFAULT_IDLE and #G_PRIORITY_HIGH_IDLE.
4524 * @pid: process to watch. On POSIX the pid of a child process. On
4525 * Windows a handle for a process (which doesn't have to be a child).
4526 * @function: function to call
4527 * @data: data to pass to @function
4528 * @notify: (allow-none): function to call when the idle is removed, or %NULL
4530 * Sets a function to be called when the child indicated by @pid
4531 * exits, at the priority @priority.
4533 * If you obtain @pid from g_spawn_async() or g_spawn_async_with_pipes()
4534 * you will need to pass #G_SPAWN_DO_NOT_REAP_CHILD as flag to
4535 * the spawn function for the child watching to work.
4537 * Note that on platforms where #GPid must be explicitly closed
4538 * (see g_spawn_close_pid()) @pid must not be closed while the
4539 * source is still active. Typically, you will want to call
4540 * g_spawn_close_pid() in the callback function for the source.
4542 * GLib supports only a single callback per process id.
4544 * This internally creates a main loop source using
4545 * g_child_watch_source_new() and attaches it to the main loop context
4546 * using g_source_attach(). You can do these steps manually if you
4547 * need greater control.
4549 * Return value: the ID (greater than 0) of the event source.
4551 * Rename to: g_child_watch_add
4555 g_child_watch_add_full (gint priority,
4557 GChildWatchFunc function,
4559 GDestroyNotify notify)
4564 g_return_val_if_fail (function != NULL, 0);
4566 source = g_child_watch_source_new (pid);
4568 if (priority != G_PRIORITY_DEFAULT)
4569 g_source_set_priority (source, priority);
4571 g_source_set_callback (source, (GSourceFunc) function, data, notify);
4572 id = g_source_attach (source, NULL);
4573 g_source_unref (source);
4579 * g_child_watch_add:
4580 * @pid: process id to watch. On POSIX the pid of a child process. On
4581 * Windows a handle for a process (which doesn't have to be a child).
4582 * @function: function to call
4583 * @data: data to pass to @function
4585 * Sets a function to be called when the child indicated by @pid
4586 * exits, at a default priority, #G_PRIORITY_DEFAULT.
4588 * If you obtain @pid from g_spawn_async() or g_spawn_async_with_pipes()
4589 * you will need to pass #G_SPAWN_DO_NOT_REAP_CHILD as flag to
4590 * the spawn function for the child watching to work.
4592 * Note that on platforms where #GPid must be explicitly closed
4593 * (see g_spawn_close_pid()) @pid must not be closed while the
4594 * source is still active. Typically, you will want to call
4595 * g_spawn_close_pid() in the callback function for the source.
4597 * GLib supports only a single callback per process id.
4599 * This internally creates a main loop source using
4600 * g_child_watch_source_new() and attaches it to the main loop context
4601 * using g_source_attach(). You can do these steps manually if you
4602 * need greater control.
4604 * Return value: the ID (greater than 0) of the event source.
4609 g_child_watch_add (GPid pid,
4610 GChildWatchFunc function,
4613 return g_child_watch_add_full (G_PRIORITY_DEFAULT, pid, function, data, NULL);
4617 /* Idle functions */
4620 g_idle_prepare (GSource *source,
4629 g_idle_check (GSource *source)
4635 g_idle_dispatch (GSource *source,
4636 GSourceFunc callback,
4641 g_warning ("Idle source dispatched without callback\n"
4642 "You must call g_source_set_callback().");
4646 return callback (user_data);
4650 * g_idle_source_new:
4652 * Creates a new idle source.
4654 * The source will not initially be associated with any #GMainContext
4655 * and must be added to one with g_source_attach() before it will be
4656 * executed. Note that the default priority for idle sources is
4657 * %G_PRIORITY_DEFAULT_IDLE, as compared to other sources which
4658 * have a default priority of %G_PRIORITY_DEFAULT.
4660 * Return value: the newly-created idle source
4663 g_idle_source_new (void)
4667 source = g_source_new (&g_idle_funcs, sizeof (GSource));
4668 g_source_set_priority (source, G_PRIORITY_DEFAULT_IDLE);
4675 * @priority: the priority of the idle source. Typically this will be in the
4676 * range between #G_PRIORITY_DEFAULT_IDLE and #G_PRIORITY_HIGH_IDLE.
4677 * @function: function to call
4678 * @data: data to pass to @function
4679 * @notify: (allow-none): function to call when the idle is removed, or %NULL
4681 * Adds a function to be called whenever there are no higher priority
4682 * events pending. If the function returns %FALSE it is automatically
4683 * removed from the list of event sources and will not be called again.
4685 * This internally creates a main loop source using g_idle_source_new()
4686 * and attaches it to the main loop context using g_source_attach().
4687 * You can do these steps manually if you need greater control.
4689 * Return value: the ID (greater than 0) of the event source.
4690 * Rename to: g_idle_add
4693 g_idle_add_full (gint priority,
4694 GSourceFunc function,
4696 GDestroyNotify notify)
4701 g_return_val_if_fail (function != NULL, 0);
4703 source = g_idle_source_new ();
4705 if (priority != G_PRIORITY_DEFAULT_IDLE)
4706 g_source_set_priority (source, priority);
4708 g_source_set_callback (source, function, data, notify);
4709 id = g_source_attach (source, NULL);
4710 g_source_unref (source);
4717 * @function: function to call
4718 * @data: data to pass to @function.
4720 * Adds a function to be called whenever there are no higher priority
4721 * events pending to the default main loop. The function is given the
4722 * default idle priority, #G_PRIORITY_DEFAULT_IDLE. If the function
4723 * returns %FALSE it is automatically removed from the list of event
4724 * sources and will not be called again.
4726 * This internally creates a main loop source using g_idle_source_new()
4727 * and attaches it to the main loop context using g_source_attach().
4728 * You can do these steps manually if you need greater control.
4730 * Return value: the ID (greater than 0) of the event source.
4733 g_idle_add (GSourceFunc function,
4736 return g_idle_add_full (G_PRIORITY_DEFAULT_IDLE, function, data, NULL);
4740 * g_idle_remove_by_data:
4741 * @data: the data for the idle source's callback.
4743 * Removes the idle function with the given data.
4745 * Return value: %TRUE if an idle source was found and removed.
4748 g_idle_remove_by_data (gpointer data)
4750 return g_source_remove_by_funcs_user_data (&g_idle_funcs, data);
4754 * g_main_context_invoke:
4755 * @context: (allow-none): a #GMainContext, or %NULL
4756 * @function: function to call
4757 * @data: data to pass to @function
4759 * Invokes a function in such a way that @context is owned during the
4760 * invocation of @function.
4762 * If @context is %NULL then the global default main context — as
4763 * returned by g_main_context_default() — is used.
4765 * If @context is owned by the current thread, @function is called
4766 * directly. Otherwise, if @context is the thread-default main context
4767 * of the current thread and g_main_context_acquire() succeeds, then
4768 * @function is called and g_main_context_release() is called
4771 * In any other case, an idle source is created to call @function and
4772 * that source is attached to @context (presumably to be run in another
4773 * thread). The idle source is attached with #G_PRIORITY_DEFAULT
4774 * priority. If you want a different priority, use
4775 * g_main_context_invoke_full().
4777 * Note that, as with normal idle functions, @function should probably
4778 * return %FALSE. If it returns %TRUE, it will be continuously run in a
4779 * loop (and may prevent this call from returning).
4784 g_main_context_invoke (GMainContext *context,
4785 GSourceFunc function,
4788 g_main_context_invoke_full (context,
4790 function, data, NULL);
4794 * g_main_context_invoke_full:
4795 * @context: (allow-none): a #GMainContext, or %NULL
4796 * @priority: the priority at which to run @function
4797 * @function: function to call
4798 * @data: data to pass to @function
4799 * @notify: (allow-none): a function to call when @data is no longer in use, or %NULL.
4801 * Invokes a function in such a way that @context is owned during the
4802 * invocation of @function.
4804 * This function is the same as g_main_context_invoke() except that it
4805 * lets you specify the priority incase @function ends up being
4806 * scheduled as an idle and also lets you give a #GDestroyNotify for @data.
4808 * @notify should not assume that it is called from any particular
4809 * thread or with any particular context acquired.
4814 g_main_context_invoke_full (GMainContext *context,
4816 GSourceFunc function,
4818 GDestroyNotify notify)
4820 g_return_if_fail (function != NULL);
4823 context = g_main_context_default ();
4825 if (g_main_context_is_owner (context))
4827 while (function (data));
4834 GMainContext *thread_default;
4836 thread_default = g_main_context_get_thread_default ();
4838 if (!thread_default)
4839 thread_default = g_main_context_default ();
4841 if (thread_default == context && g_main_context_acquire (context))
4843 while (function (data));
4845 g_main_context_release (context);
4854 source = g_idle_source_new ();
4855 g_source_set_priority (source, priority);
4856 g_source_set_callback (source, function, data, notify);
4857 g_source_attach (source, context);
4858 g_source_unref (source);
4864 glib_worker_main (gpointer data)
4868 g_main_context_iteration (glib_worker_context, TRUE);
4871 if (any_unix_signal_pending)
4872 dispatch_unix_signals ();
4876 return NULL; /* worst GCC warning message ever... */
4880 g_get_worker_context (void)
4882 static gsize initialised;
4884 if (g_once_init_enter (&initialised))
4886 /* mask all signals in the worker thread */
4892 pthread_sigmask (SIG_SETMASK, &all, &prev_mask);
4894 glib_worker_context = g_main_context_new ();
4895 g_thread_new ("gmain", glib_worker_main, NULL);
4897 pthread_sigmask (SIG_SETMASK, &prev_mask, NULL);
4899 g_once_init_leave (&initialised, TRUE);
4902 return glib_worker_context;