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 _GSourceList GSourceList;
202 GSource *head, *tail;
206 typedef struct _GMainWaiter GMainWaiter;
214 typedef struct _GMainDispatch GMainDispatch;
216 struct _GMainDispatch
219 GSList *dispatching_sources; /* stack of current sources */
222 #ifdef G_MAIN_POLL_DEBUG
223 gboolean _g_main_poll_debug = FALSE;
228 /* The following lock is used for both the list of sources
229 * and the list of poll records
239 GPtrArray *pending_dispatches;
240 gint timeout; /* Timeout for current iteration */
244 gint in_check_or_prepare;
246 GPollRec *poll_records, *poll_records_tail;
247 guint n_poll_records;
248 GPollFD *cached_poll_array;
249 guint cached_poll_array_size;
255 /* Flag indicating whether the set of fd's changed during a poll */
256 gboolean poll_changed;
261 gboolean time_is_fresh;
264 struct _GSourceCallback
269 GDestroyNotify notify;
274 GMainContext *context;
279 struct _GTimeoutSource
287 struct _GChildWatchSource
294 #else /* G_OS_WIN32 */
295 gboolean child_exited;
296 #endif /* G_OS_WIN32 */
299 struct _GUnixSignalWatchSource
314 struct _GSourcePrivate
316 GSList *child_sources;
317 GSource *parent_source;
320 typedef struct _GSourceIter
322 GMainContext *context;
328 #define LOCK_CONTEXT(context) g_mutex_lock (&context->mutex)
329 #define UNLOCK_CONTEXT(context) g_mutex_unlock (&context->mutex)
330 #define G_THREAD_SELF g_thread_self ()
332 #define SOURCE_DESTROYED(source) (((source)->flags & G_HOOK_FLAG_ACTIVE) == 0)
333 #define SOURCE_BLOCKED(source) (((source)->flags & G_SOURCE_BLOCKED) != 0)
335 #define SOURCE_UNREF(source, context) \
337 if ((source)->ref_count > 1) \
338 (source)->ref_count--; \
340 g_source_unref_internal ((source), (context), TRUE); \
344 /* Forward declarations */
346 static void g_source_unref_internal (GSource *source,
347 GMainContext *context,
349 static void g_source_destroy_internal (GSource *source,
350 GMainContext *context,
352 static void g_source_set_priority_unlocked (GSource *source,
353 GMainContext *context,
355 static void g_main_context_poll (GMainContext *context,
360 static void g_main_context_add_poll_unlocked (GMainContext *context,
363 static void g_main_context_remove_poll_unlocked (GMainContext *context,
366 static void g_source_iter_init (GSourceIter *iter,
367 GMainContext *context,
368 gboolean may_modify);
369 static gboolean g_source_iter_next (GSourceIter *iter,
371 static void g_source_iter_clear (GSourceIter *iter);
373 static gboolean g_timeout_prepare (GSource *source,
375 static gboolean g_timeout_check (GSource *source);
376 static gboolean g_timeout_dispatch (GSource *source,
377 GSourceFunc callback,
379 static gboolean g_child_watch_prepare (GSource *source,
381 static gboolean g_child_watch_check (GSource *source);
382 static gboolean g_child_watch_dispatch (GSource *source,
383 GSourceFunc callback,
385 static void g_child_watch_finalize (GSource *source);
387 static void g_unix_signal_handler (int signum);
388 static gboolean g_unix_signal_watch_prepare (GSource *source,
390 static gboolean g_unix_signal_watch_check (GSource *source);
391 static gboolean g_unix_signal_watch_dispatch (GSource *source,
392 GSourceFunc callback,
394 static void g_unix_signal_watch_finalize (GSource *source);
396 static gboolean g_idle_prepare (GSource *source,
398 static gboolean g_idle_check (GSource *source);
399 static gboolean g_idle_dispatch (GSource *source,
400 GSourceFunc callback,
403 static void block_source (GSource *source);
405 static GMainContext *glib_worker_context;
407 G_LOCK_DEFINE_STATIC (main_loop);
408 static GMainContext *default_main_context;
413 /* UNIX signals work by marking one of these variables then waking the
414 * worker context to check on them and dispatch accordingly.
416 #ifdef HAVE_SIG_ATOMIC_T
417 static volatile sig_atomic_t unix_signal_pending[NSIG];
418 static volatile sig_atomic_t any_unix_signal_pending;
420 static volatile int unix_signal_pending[NSIG];
421 static volatile int any_unix_signal_pending;
424 /* Guards all the data below */
425 G_LOCK_DEFINE_STATIC (unix_signal_lock);
426 static GSList *unix_signal_watches;
427 static GSList *unix_child_watches;
429 static GSourceFuncs g_unix_signal_funcs =
431 g_unix_signal_watch_prepare,
432 g_unix_signal_watch_check,
433 g_unix_signal_watch_dispatch,
434 g_unix_signal_watch_finalize
436 #endif /* !G_OS_WIN32 */
437 G_LOCK_DEFINE_STATIC (main_context_list);
438 static GSList *main_context_list = NULL;
440 GSourceFuncs g_timeout_funcs =
448 GSourceFuncs g_child_watch_funcs =
450 g_child_watch_prepare,
452 g_child_watch_dispatch,
453 g_child_watch_finalize
456 GSourceFuncs g_idle_funcs =
465 * g_main_context_ref:
466 * @context: a #GMainContext
468 * Increases the reference count on a #GMainContext object by one.
470 * Returns: the @context that was passed in (since 2.6)
473 g_main_context_ref (GMainContext *context)
475 g_return_val_if_fail (context != NULL, NULL);
476 g_return_val_if_fail (g_atomic_int_get (&context->ref_count) > 0, NULL);
478 g_atomic_int_inc (&context->ref_count);
484 poll_rec_list_free (GMainContext *context,
487 g_slice_free_chain (GPollRec, list, next);
491 * g_main_context_unref:
492 * @context: a #GMainContext
494 * Decreases the reference count on a #GMainContext object by one. If
495 * the result is zero, free the context and free all associated memory.
498 g_main_context_unref (GMainContext *context)
503 g_return_if_fail (context != NULL);
504 g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
506 if (!g_atomic_int_dec_and_test (&context->ref_count))
509 G_LOCK (main_context_list);
510 main_context_list = g_slist_remove (main_context_list, context);
511 G_UNLOCK (main_context_list);
513 g_source_iter_init (&iter, context, TRUE);
514 while (g_source_iter_next (&iter, &source))
515 g_source_destroy_internal (source, context, FALSE);
517 g_mutex_clear (&context->mutex);
519 g_ptr_array_free (context->pending_dispatches, TRUE);
520 g_free (context->cached_poll_array);
522 poll_rec_list_free (context, context->poll_records);
524 g_wakeup_free (context->wakeup);
525 g_cond_clear (&context->cond);
531 * g_main_context_new:
533 * Creates a new #GMainContext structure.
535 * Return value: the new #GMainContext
538 g_main_context_new (void)
540 static gsize initialised;
541 GMainContext *context;
543 if (g_once_init_enter (&initialised))
545 #ifdef G_MAIN_POLL_DEBUG
546 if (getenv ("G_MAIN_POLL_DEBUG") != NULL)
547 _g_main_poll_debug = TRUE;
550 g_once_init_leave (&initialised, TRUE);
553 context = g_new0 (GMainContext, 1);
555 g_mutex_init (&context->mutex);
556 g_cond_init (&context->cond);
558 context->owner = NULL;
559 context->waiters = NULL;
561 context->ref_count = 1;
563 context->next_id = 1;
565 context->source_lists = NULL;
567 context->poll_func = g_poll;
569 context->cached_poll_array = NULL;
570 context->cached_poll_array_size = 0;
572 context->pending_dispatches = g_ptr_array_new ();
574 context->time_is_fresh = FALSE;
576 context->wakeup = g_wakeup_new ();
577 g_wakeup_get_pollfd (context->wakeup, &context->wake_up_rec);
578 g_main_context_add_poll_unlocked (context, 0, &context->wake_up_rec);
580 G_LOCK (main_context_list);
581 main_context_list = g_slist_append (main_context_list, context);
583 #ifdef G_MAIN_POLL_DEBUG
584 if (_g_main_poll_debug)
585 g_print ("created context=%p\n", context);
588 G_UNLOCK (main_context_list);
594 * g_main_context_default:
596 * Returns the global default main context. This is the main context
597 * used for main loop functions when a main loop is not explicitly
598 * specified, and corresponds to the "main" main loop. See also
599 * g_main_context_get_thread_default().
601 * Return value: (transfer none): the global default main context.
604 g_main_context_default (void)
610 if (!default_main_context)
612 default_main_context = g_main_context_new ();
613 #ifdef G_MAIN_POLL_DEBUG
614 if (_g_main_poll_debug)
615 g_print ("default context=%p\n", default_main_context);
619 G_UNLOCK (main_loop);
621 return default_main_context;
625 free_context (gpointer data)
627 GMainContext *context = data;
629 g_main_context_release (context);
631 g_main_context_unref (context);
635 free_context_stack (gpointer data)
637 g_queue_free_full((GQueue *) data, (GDestroyNotify) free_context);
640 static GPrivate thread_context_stack = G_PRIVATE_INIT (free_context_stack);
643 * g_main_context_push_thread_default:
644 * @context: (allow-none): a #GMainContext, or %NULL for the global default context
646 * Acquires @context and sets it as the thread-default context for the
647 * current thread. This will cause certain asynchronous operations
648 * (such as most <link linkend="gio">gio</link>-based I/O) which are
649 * started in this thread to run under @context and deliver their
650 * results to its main loop, rather than running under the global
651 * default context in the main thread. Note that calling this function
652 * changes the context returned by
653 * g_main_context_get_thread_default(), <emphasis>not</emphasis> the
654 * one returned by g_main_context_default(), so it does not affect the
655 * context used by functions like g_idle_add().
657 * Normally you would call this function shortly after creating a new
658 * thread, passing it a #GMainContext which will be run by a
659 * #GMainLoop in that thread, to set a new default context for all
660 * async operations in that thread. (In this case, you don't need to
661 * ever call g_main_context_pop_thread_default().) In some cases
662 * however, you may want to schedule a single operation in a
663 * non-default context, or temporarily use a non-default context in
664 * the main thread. In that case, you can wrap the call to the
665 * asynchronous operation inside a
666 * g_main_context_push_thread_default() /
667 * g_main_context_pop_thread_default() pair, but it is up to you to
668 * ensure that no other asynchronous operations accidentally get
669 * started while the non-default context is active.
671 * Beware that libraries that predate this function may not correctly
672 * handle being used from a thread with a thread-default context. Eg,
673 * see g_file_supports_thread_contexts().
678 g_main_context_push_thread_default (GMainContext *context)
681 gboolean acquired_context;
683 acquired_context = g_main_context_acquire (context);
684 g_return_if_fail (acquired_context);
686 if (context == g_main_context_default ())
689 g_main_context_ref (context);
691 stack = g_private_get (&thread_context_stack);
694 stack = g_queue_new ();
695 g_private_set (&thread_context_stack, stack);
698 g_queue_push_head (stack, context);
702 * g_main_context_pop_thread_default:
703 * @context: (allow-none): a #GMainContext object, or %NULL
705 * Pops @context off the thread-default context stack (verifying that
706 * it was on the top of the stack).
711 g_main_context_pop_thread_default (GMainContext *context)
715 if (context == g_main_context_default ())
718 stack = g_private_get (&thread_context_stack);
720 g_return_if_fail (stack != NULL);
721 g_return_if_fail (g_queue_peek_head (stack) == context);
723 g_queue_pop_head (stack);
725 g_main_context_release (context);
727 g_main_context_unref (context);
731 * g_main_context_get_thread_default:
733 * Gets the thread-default #GMainContext for this thread. Asynchronous
734 * operations that want to be able to be run in contexts other than
735 * the default one should call this method or
736 * g_main_context_ref_thread_default() to get a #GMainContext to add
737 * their #GSource<!-- -->s to. (Note that even in single-threaded
738 * programs applications may sometimes want to temporarily push a
739 * non-default context, so it is not safe to assume that this will
740 * always return %NULL if you are running in the default thread.)
742 * If you need to hold a reference on the context, use
743 * g_main_context_ref_thread_default() instead.
745 * Returns: (transfer none): the thread-default #GMainContext, or
746 * %NULL if the thread-default context is the global default context.
751 g_main_context_get_thread_default (void)
755 stack = g_private_get (&thread_context_stack);
757 return g_queue_peek_head (stack);
763 * g_main_context_ref_thread_default:
765 * Gets the thread-default #GMainContext for this thread, as with
766 * g_main_context_get_thread_default(), but also adds a reference to
767 * it with g_main_context_ref(). In addition, unlike
768 * g_main_context_get_thread_default(), if the thread-default context
769 * is the global default context, this will return that #GMainContext
770 * (with a ref added to it) rather than returning %NULL.
772 * Returns: (transfer full): the thread-default #GMainContext. Unref
773 * with g_main_context_unref() when you are done with it.
778 g_main_context_ref_thread_default (void)
780 GMainContext *context;
782 context = g_main_context_get_thread_default ();
784 context = g_main_context_default ();
785 return g_main_context_ref (context);
788 /* Hooks for adding to the main loop */
792 * @source_funcs: structure containing functions that implement
793 * the sources behavior.
794 * @struct_size: size of the #GSource structure to create.
796 * Creates a new #GSource structure. The size is specified to
797 * allow creating structures derived from #GSource that contain
798 * additional data. The size passed in must be at least
799 * <literal>sizeof (GSource)</literal>.
801 * The source will not initially be associated with any #GMainContext
802 * and must be added to one with g_source_attach() before it will be
805 * Return value: the newly-created #GSource.
808 g_source_new (GSourceFuncs *source_funcs,
813 g_return_val_if_fail (source_funcs != NULL, NULL);
814 g_return_val_if_fail (struct_size >= sizeof (GSource), NULL);
816 source = (GSource*) g_malloc0 (struct_size);
817 source->priv = g_slice_new0 (GSourcePrivate);
818 source->source_funcs = source_funcs;
819 source->ref_count = 1;
821 source->priority = G_PRIORITY_DEFAULT;
823 source->flags = G_HOOK_FLAG_ACTIVE;
825 /* NULL/0 initialization for all other fields */
830 /* Holds context's lock */
832 g_source_iter_init (GSourceIter *iter,
833 GMainContext *context,
836 iter->context = context;
837 iter->current_list = NULL;
839 iter->may_modify = may_modify;
842 /* Holds context's lock */
844 g_source_iter_next (GSourceIter *iter, GSource **source)
846 GSource *next_source;
849 next_source = iter->source->next;
855 if (iter->current_list)
856 iter->current_list = iter->current_list->next;
858 iter->current_list = iter->context->source_lists;
860 if (iter->current_list)
862 GSourceList *source_list = iter->current_list->data;
864 next_source = source_list->head;
868 /* Note: unreffing iter->source could potentially cause its
869 * GSourceList to be removed from source_lists (if iter->source is
870 * the only source in its list, and it is destroyed), so we have to
871 * keep it reffed until after we advance iter->current_list, above.
874 if (iter->source && iter->may_modify)
875 SOURCE_UNREF (iter->source, iter->context);
876 iter->source = next_source;
877 if (iter->source && iter->may_modify)
878 iter->source->ref_count++;
880 *source = iter->source;
881 return *source != NULL;
884 /* Holds context's lock. Only necessary to call if you broke out of
885 * the g_source_iter_next() loop early.
888 g_source_iter_clear (GSourceIter *iter)
890 if (iter->source && iter->may_modify)
892 SOURCE_UNREF (iter->source, iter->context);
897 /* Holds context's lock
900 find_source_list_for_priority (GMainContext *context,
905 GSourceList *source_list;
908 for (iter = context->source_lists; iter != NULL; last = iter, iter = iter->next)
910 source_list = iter->data;
912 if (source_list->priority == priority)
915 if (source_list->priority > priority)
920 source_list = g_slice_new0 (GSourceList);
921 source_list->priority = priority;
922 context->source_lists = g_list_insert_before (context->source_lists,
932 source_list = g_slice_new0 (GSourceList);
933 source_list->priority = priority;
936 context->source_lists = g_list_append (NULL, source_list);
939 /* This just appends source_list to the end of
940 * context->source_lists without having to walk the list again.
942 last = g_list_append (last, source_list);
947 /* Holds context's lock
950 source_add_to_context (GSource *source,
951 GMainContext *context)
953 GSourceList *source_list;
954 GSource *prev, *next;
956 source_list = find_source_list_for_priority (context, source->priority, TRUE);
958 if (source->priv->parent_source)
960 g_assert (source_list->head != NULL);
962 /* Put the source immediately before its parent */
963 prev = source->priv->parent_source->prev;
964 next = source->priv->parent_source;
968 prev = source_list->tail;
976 source_list->tail = source;
982 source_list->head = source;
985 /* Holds context's lock
988 source_remove_from_context (GSource *source,
989 GMainContext *context)
991 GSourceList *source_list;
993 source_list = find_source_list_for_priority (context, source->priority, FALSE);
994 g_return_if_fail (source_list != NULL);
997 source->prev->next = source->next;
999 source_list->head = source->next;
1002 source->next->prev = source->prev;
1004 source_list->tail = source->prev;
1006 source->prev = NULL;
1007 source->next = NULL;
1009 if (source_list->head == NULL)
1011 context->source_lists = g_list_remove (context->source_lists, source_list);
1012 g_slice_free (GSourceList, source_list);
1017 g_source_attach_unlocked (GSource *source,
1018 GMainContext *context)
1023 source->context = context;
1024 result = source->source_id = context->next_id++;
1026 source->ref_count++;
1027 source_add_to_context (source, context);
1029 tmp_list = source->poll_fds;
1032 g_main_context_add_poll_unlocked (context, source->priority, tmp_list->data);
1033 tmp_list = tmp_list->next;
1036 tmp_list = source->priv->child_sources;
1039 g_source_attach_unlocked (tmp_list->data, context);
1040 tmp_list = tmp_list->next;
1048 * @source: a #GSource
1049 * @context: (allow-none): a #GMainContext (if %NULL, the default context will be used)
1051 * Adds a #GSource to a @context so that it will be executed within
1052 * that context. Remove it by calling g_source_destroy().
1054 * Return value: the ID (greater than 0) for the source within the
1058 g_source_attach (GSource *source,
1059 GMainContext *context)
1063 g_return_val_if_fail (source->context == NULL, 0);
1064 g_return_val_if_fail (!SOURCE_DESTROYED (source), 0);
1067 context = g_main_context_default ();
1069 LOCK_CONTEXT (context);
1071 result = g_source_attach_unlocked (source, context);
1073 /* If another thread has acquired the context, wake it up since it
1074 * might be in poll() right now.
1076 if (context->owner && context->owner != G_THREAD_SELF)
1077 g_wakeup_signal (context->wakeup);
1079 UNLOCK_CONTEXT (context);
1085 g_source_destroy_internal (GSource *source,
1086 GMainContext *context,
1090 LOCK_CONTEXT (context);
1092 if (!SOURCE_DESTROYED (source))
1095 gpointer old_cb_data;
1096 GSourceCallbackFuncs *old_cb_funcs;
1098 source->flags &= ~G_HOOK_FLAG_ACTIVE;
1100 old_cb_data = source->callback_data;
1101 old_cb_funcs = source->callback_funcs;
1103 source->callback_data = NULL;
1104 source->callback_funcs = NULL;
1108 UNLOCK_CONTEXT (context);
1109 old_cb_funcs->unref (old_cb_data);
1110 LOCK_CONTEXT (context);
1113 if (!SOURCE_BLOCKED (source))
1115 tmp_list = source->poll_fds;
1118 g_main_context_remove_poll_unlocked (context, tmp_list->data);
1119 tmp_list = tmp_list->next;
1123 if (source->priv->child_sources)
1125 /* This is safe because even if a child_source finalizer or
1126 * closure notify tried to modify source->priv->child_sources
1127 * from outside the lock, it would fail since
1128 * SOURCE_DESTROYED(source) is now TRUE.
1130 tmp_list = source->priv->child_sources;
1133 g_source_destroy_internal (tmp_list->data, context, TRUE);
1134 g_source_unref_internal (tmp_list->data, context, TRUE);
1135 tmp_list = tmp_list->next;
1137 g_slist_free (source->priv->child_sources);
1138 source->priv->child_sources = NULL;
1141 g_source_unref_internal (source, context, TRUE);
1145 UNLOCK_CONTEXT (context);
1150 * @source: a #GSource
1152 * Removes a source from its #GMainContext, if any, and mark it as
1153 * destroyed. The source cannot be subsequently added to another
1157 g_source_destroy (GSource *source)
1159 GMainContext *context;
1161 g_return_if_fail (source != NULL);
1163 context = source->context;
1166 g_source_destroy_internal (source, context, FALSE);
1168 source->flags &= ~G_HOOK_FLAG_ACTIVE;
1173 * @source: a #GSource
1175 * Returns the numeric ID for a particular source. The ID of a source
1176 * is a positive integer which is unique within a particular main loop
1177 * context. The reverse
1178 * mapping from ID to source is done by g_main_context_find_source_by_id().
1180 * Return value: the ID (greater than 0) for the source
1183 g_source_get_id (GSource *source)
1187 g_return_val_if_fail (source != NULL, 0);
1188 g_return_val_if_fail (source->context != NULL, 0);
1190 LOCK_CONTEXT (source->context);
1191 result = source->source_id;
1192 UNLOCK_CONTEXT (source->context);
1198 * g_source_get_context:
1199 * @source: a #GSource
1201 * Gets the #GMainContext with which the source is associated.
1202 * Calling this function on a destroyed source is an error.
1204 * Return value: (transfer none) (allow-none): the #GMainContext with which the
1205 * source is associated, or %NULL if the context has not
1206 * yet been added to a source.
1209 g_source_get_context (GSource *source)
1211 g_return_val_if_fail (!SOURCE_DESTROYED (source), NULL);
1213 return source->context;
1217 * g_source_add_poll:
1218 * @source:a #GSource
1219 * @fd: a #GPollFD structure holding information about a file
1220 * descriptor to watch.
1222 * Adds a file descriptor to the set of file descriptors polled for
1223 * this source. This is usually combined with g_source_new() to add an
1224 * event source. The event source's check function will typically test
1225 * the @revents field in the #GPollFD struct and return %TRUE if events need
1229 g_source_add_poll (GSource *source,
1232 GMainContext *context;
1234 g_return_if_fail (source != NULL);
1235 g_return_if_fail (fd != NULL);
1236 g_return_if_fail (!SOURCE_DESTROYED (source));
1238 context = source->context;
1241 LOCK_CONTEXT (context);
1243 source->poll_fds = g_slist_prepend (source->poll_fds, fd);
1247 if (!SOURCE_BLOCKED (source))
1248 g_main_context_add_poll_unlocked (context, source->priority, fd);
1249 UNLOCK_CONTEXT (context);
1254 * g_source_remove_poll:
1255 * @source:a #GSource
1256 * @fd: a #GPollFD structure previously passed to g_source_add_poll().
1258 * Removes a file descriptor from the set of file descriptors polled for
1262 g_source_remove_poll (GSource *source,
1265 GMainContext *context;
1267 g_return_if_fail (source != NULL);
1268 g_return_if_fail (fd != NULL);
1269 g_return_if_fail (!SOURCE_DESTROYED (source));
1271 context = source->context;
1274 LOCK_CONTEXT (context);
1276 source->poll_fds = g_slist_remove (source->poll_fds, fd);
1280 if (!SOURCE_BLOCKED (source))
1281 g_main_context_remove_poll_unlocked (context, fd);
1282 UNLOCK_CONTEXT (context);
1287 * g_source_add_child_source:
1288 * @source:a #GSource
1289 * @child_source: a second #GSource that @source should "poll"
1291 * Adds @child_source to @source as a "polled" source; when @source is
1292 * added to a #GMainContext, @child_source will be automatically added
1293 * with the same priority, when @child_source is triggered, it will
1294 * cause @source to dispatch (in addition to calling its own
1295 * callback), and when @source is destroyed, it will destroy
1296 * @child_source as well. (@source will also still be dispatched if
1297 * its own prepare/check functions indicate that it is ready.)
1299 * If you don't need @child_source to do anything on its own when it
1300 * triggers, you can call g_source_set_dummy_callback() on it to set a
1301 * callback that does nothing (except return %TRUE if appropriate).
1303 * @source will hold a reference on @child_source while @child_source
1304 * is attached to it.
1309 g_source_add_child_source (GSource *source,
1310 GSource *child_source)
1312 GMainContext *context;
1314 g_return_if_fail (source != NULL);
1315 g_return_if_fail (child_source != NULL);
1316 g_return_if_fail (!SOURCE_DESTROYED (source));
1317 g_return_if_fail (!SOURCE_DESTROYED (child_source));
1318 g_return_if_fail (child_source->context == NULL);
1319 g_return_if_fail (child_source->priv->parent_source == NULL);
1321 context = source->context;
1324 LOCK_CONTEXT (context);
1326 source->priv->child_sources = g_slist_prepend (source->priv->child_sources,
1327 g_source_ref (child_source));
1328 child_source->priv->parent_source = source;
1329 g_source_set_priority_unlocked (child_source, NULL, source->priority);
1330 if (SOURCE_BLOCKED (source))
1331 block_source (child_source);
1335 UNLOCK_CONTEXT (context);
1336 g_source_attach (child_source, context);
1341 * g_source_remove_child_source:
1342 * @source:a #GSource
1343 * @child_source: a #GSource previously passed to
1344 * g_source_add_child_source().
1346 * Detaches @child_source from @source and destroys it.
1351 g_source_remove_child_source (GSource *source,
1352 GSource *child_source)
1354 GMainContext *context;
1356 g_return_if_fail (source != NULL);
1357 g_return_if_fail (child_source != NULL);
1358 g_return_if_fail (child_source->priv->parent_source == source);
1359 g_return_if_fail (!SOURCE_DESTROYED (source));
1360 g_return_if_fail (!SOURCE_DESTROYED (child_source));
1362 context = source->context;
1365 LOCK_CONTEXT (context);
1367 source->priv->child_sources = g_slist_remove (source->priv->child_sources, child_source);
1368 g_source_destroy_internal (child_source, context, TRUE);
1369 g_source_unref_internal (child_source, context, TRUE);
1372 UNLOCK_CONTEXT (context);
1376 * g_source_set_callback_indirect:
1377 * @source: the source
1378 * @callback_data: pointer to callback data "object"
1379 * @callback_funcs: functions for reference counting @callback_data
1380 * and getting the callback and data
1382 * Sets the callback function storing the data as a refcounted callback
1383 * "object". This is used internally. Note that calling
1384 * g_source_set_callback_indirect() assumes
1385 * an initial reference count on @callback_data, and thus
1386 * @callback_funcs->unref will eventually be called once more
1387 * than @callback_funcs->ref.
1390 g_source_set_callback_indirect (GSource *source,
1391 gpointer callback_data,
1392 GSourceCallbackFuncs *callback_funcs)
1394 GMainContext *context;
1395 gpointer old_cb_data;
1396 GSourceCallbackFuncs *old_cb_funcs;
1398 g_return_if_fail (source != NULL);
1399 g_return_if_fail (callback_funcs != NULL || callback_data == NULL);
1401 context = source->context;
1404 LOCK_CONTEXT (context);
1406 old_cb_data = source->callback_data;
1407 old_cb_funcs = source->callback_funcs;
1409 source->callback_data = callback_data;
1410 source->callback_funcs = callback_funcs;
1413 UNLOCK_CONTEXT (context);
1416 old_cb_funcs->unref (old_cb_data);
1420 g_source_callback_ref (gpointer cb_data)
1422 GSourceCallback *callback = cb_data;
1424 callback->ref_count++;
1429 g_source_callback_unref (gpointer cb_data)
1431 GSourceCallback *callback = cb_data;
1433 callback->ref_count--;
1434 if (callback->ref_count == 0)
1436 if (callback->notify)
1437 callback->notify (callback->data);
1443 g_source_callback_get (gpointer cb_data,
1448 GSourceCallback *callback = cb_data;
1450 *func = callback->func;
1451 *data = callback->data;
1454 static GSourceCallbackFuncs g_source_callback_funcs = {
1455 g_source_callback_ref,
1456 g_source_callback_unref,
1457 g_source_callback_get,
1461 * g_source_set_callback:
1462 * @source: the source
1463 * @func: a callback function
1464 * @data: the data to pass to callback function
1465 * @notify: (allow-none): a function to call when @data is no longer in use, or %NULL.
1467 * Sets the callback function for a source. The callback for a source is
1468 * called from the source's dispatch function.
1470 * The exact type of @func depends on the type of source; ie. you
1471 * should not count on @func being called with @data as its first
1474 * Typically, you won't use this function. Instead use functions specific
1475 * to the type of source you are using.
1478 g_source_set_callback (GSource *source,
1481 GDestroyNotify notify)
1483 GSourceCallback *new_callback;
1485 g_return_if_fail (source != NULL);
1487 new_callback = g_new (GSourceCallback, 1);
1489 new_callback->ref_count = 1;
1490 new_callback->func = func;
1491 new_callback->data = data;
1492 new_callback->notify = notify;
1494 g_source_set_callback_indirect (source, new_callback, &g_source_callback_funcs);
1499 * g_source_set_funcs:
1500 * @source: a #GSource
1501 * @funcs: the new #GSourceFuncs
1503 * Sets the source functions (can be used to override
1504 * default implementations) of an unattached source.
1509 g_source_set_funcs (GSource *source,
1510 GSourceFuncs *funcs)
1512 g_return_if_fail (source != NULL);
1513 g_return_if_fail (source->context == NULL);
1514 g_return_if_fail (source->ref_count > 0);
1515 g_return_if_fail (funcs != NULL);
1517 source->source_funcs = funcs;
1521 g_source_set_priority_unlocked (GSource *source,
1522 GMainContext *context,
1527 g_return_if_fail (source->priv->parent_source == NULL ||
1528 source->priv->parent_source->priority == priority);
1532 /* Remove the source from the context's source and then
1533 * add it back after so it is sorted in the correct place
1535 source_remove_from_context (source, source->context);
1538 source->priority = priority;
1542 source_add_to_context (source, source->context);
1544 if (!SOURCE_BLOCKED (source))
1546 tmp_list = source->poll_fds;
1549 g_main_context_remove_poll_unlocked (context, tmp_list->data);
1550 g_main_context_add_poll_unlocked (context, priority, tmp_list->data);
1552 tmp_list = tmp_list->next;
1557 if (source->priv->child_sources)
1559 tmp_list = source->priv->child_sources;
1562 g_source_set_priority_unlocked (tmp_list->data, context, priority);
1563 tmp_list = tmp_list->next;
1569 * g_source_set_priority:
1570 * @source: a #GSource
1571 * @priority: the new priority.
1573 * Sets the priority of a source. While the main loop is being run, a
1574 * source will be dispatched if it is ready to be dispatched and no
1575 * sources at a higher (numerically smaller) priority are ready to be
1579 g_source_set_priority (GSource *source,
1582 GMainContext *context;
1584 g_return_if_fail (source != NULL);
1586 context = source->context;
1589 LOCK_CONTEXT (context);
1590 g_source_set_priority_unlocked (source, context, priority);
1592 UNLOCK_CONTEXT (source->context);
1596 * g_source_get_priority:
1597 * @source: a #GSource
1599 * Gets the priority of a source.
1601 * Return value: the priority of the source
1604 g_source_get_priority (GSource *source)
1606 g_return_val_if_fail (source != NULL, 0);
1608 return source->priority;
1612 * g_source_set_can_recurse:
1613 * @source: a #GSource
1614 * @can_recurse: whether recursion is allowed for this source
1616 * Sets whether a source can be called recursively. If @can_recurse is
1617 * %TRUE, then while the source is being dispatched then this source
1618 * will be processed normally. Otherwise, all processing of this
1619 * source is blocked until the dispatch function returns.
1622 g_source_set_can_recurse (GSource *source,
1623 gboolean can_recurse)
1625 GMainContext *context;
1627 g_return_if_fail (source != NULL);
1629 context = source->context;
1632 LOCK_CONTEXT (context);
1635 source->flags |= G_SOURCE_CAN_RECURSE;
1637 source->flags &= ~G_SOURCE_CAN_RECURSE;
1640 UNLOCK_CONTEXT (context);
1644 * g_source_get_can_recurse:
1645 * @source: a #GSource
1647 * Checks whether a source is allowed to be called recursively.
1648 * see g_source_set_can_recurse().
1650 * Return value: whether recursion is allowed.
1653 g_source_get_can_recurse (GSource *source)
1655 g_return_val_if_fail (source != NULL, FALSE);
1657 return (source->flags & G_SOURCE_CAN_RECURSE) != 0;
1662 * g_source_set_name:
1663 * @source: a #GSource
1664 * @name: debug name for the source
1666 * Sets a name for the source, used in debugging and profiling.
1667 * The name defaults to #NULL.
1669 * The source name should describe in a human-readable way
1670 * what the source does. For example, "X11 event queue"
1671 * or "GTK+ repaint idle handler" or whatever it is.
1673 * It is permitted to call this function multiple times, but is not
1674 * recommended due to the potential performance impact. For example,
1675 * one could change the name in the "check" function of a #GSourceFuncs
1676 * to include details like the event type in the source name.
1681 g_source_set_name (GSource *source,
1684 g_return_if_fail (source != NULL);
1686 /* setting back to NULL is allowed, just because it's
1687 * weird if get_name can return NULL but you can't
1691 g_free (source->name);
1692 source->name = g_strdup (name);
1696 * g_source_get_name:
1697 * @source: a #GSource
1699 * Gets a name for the source, used in debugging and profiling.
1700 * The name may be #NULL if it has never been set with
1701 * g_source_set_name().
1703 * Return value: the name of the source
1707 g_source_get_name (GSource *source)
1709 g_return_val_if_fail (source != NULL, NULL);
1711 return source->name;
1715 * g_source_set_name_by_id:
1716 * @tag: a #GSource ID
1717 * @name: debug name for the source
1719 * Sets the name of a source using its ID.
1721 * This is a convenience utility to set source names from the return
1722 * value of g_idle_add(), g_timeout_add(), etc.
1727 g_source_set_name_by_id (guint tag,
1732 g_return_if_fail (tag > 0);
1734 source = g_main_context_find_source_by_id (NULL, tag);
1738 g_source_set_name (source, name);
1744 * @source: a #GSource
1746 * Increases the reference count on a source by one.
1748 * Return value: @source
1751 g_source_ref (GSource *source)
1753 GMainContext *context;
1755 g_return_val_if_fail (source != NULL, NULL);
1757 context = source->context;
1760 LOCK_CONTEXT (context);
1762 source->ref_count++;
1765 UNLOCK_CONTEXT (context);
1770 /* g_source_unref() but possible to call within context lock
1773 g_source_unref_internal (GSource *source,
1774 GMainContext *context,
1777 gpointer old_cb_data = NULL;
1778 GSourceCallbackFuncs *old_cb_funcs = NULL;
1780 g_return_if_fail (source != NULL);
1782 if (!have_lock && context)
1783 LOCK_CONTEXT (context);
1785 source->ref_count--;
1786 if (source->ref_count == 0)
1788 old_cb_data = source->callback_data;
1789 old_cb_funcs = source->callback_funcs;
1791 source->callback_data = NULL;
1792 source->callback_funcs = NULL;
1796 if (!SOURCE_DESTROYED (source))
1797 g_warning (G_STRLOC ": ref_count == 0, but source was still attached to a context!");
1798 source_remove_from_context (source, context);
1801 if (source->source_funcs->finalize)
1804 UNLOCK_CONTEXT (context);
1805 source->source_funcs->finalize (source);
1807 LOCK_CONTEXT (context);
1810 g_free (source->name);
1811 source->name = NULL;
1813 g_slist_free (source->poll_fds);
1814 source->poll_fds = NULL;
1816 g_slice_free (GSourcePrivate, source->priv);
1817 source->priv = NULL;
1822 if (!have_lock && context)
1823 UNLOCK_CONTEXT (context);
1828 UNLOCK_CONTEXT (context);
1830 old_cb_funcs->unref (old_cb_data);
1833 LOCK_CONTEXT (context);
1839 * @source: a #GSource
1841 * Decreases the reference count of a source by one. If the
1842 * resulting reference count is zero the source and associated
1843 * memory will be destroyed.
1846 g_source_unref (GSource *source)
1848 g_return_if_fail (source != NULL);
1850 g_source_unref_internal (source, source->context, FALSE);
1854 * g_main_context_find_source_by_id:
1855 * @context: (allow-none): a #GMainContext (if %NULL, the default context will be used)
1856 * @source_id: the source ID, as returned by g_source_get_id().
1858 * Finds a #GSource given a pair of context and ID.
1860 * Return value: (transfer none): the #GSource if found, otherwise, %NULL
1863 g_main_context_find_source_by_id (GMainContext *context,
1869 g_return_val_if_fail (source_id > 0, NULL);
1871 if (context == NULL)
1872 context = g_main_context_default ();
1874 LOCK_CONTEXT (context);
1876 g_source_iter_init (&iter, context, FALSE);
1877 while (g_source_iter_next (&iter, &source))
1879 if (!SOURCE_DESTROYED (source) &&
1880 source->source_id == source_id)
1883 g_source_iter_clear (&iter);
1885 UNLOCK_CONTEXT (context);
1891 * g_main_context_find_source_by_funcs_user_data:
1892 * @context: (allow-none): a #GMainContext (if %NULL, the default context will be used).
1893 * @funcs: the @source_funcs passed to g_source_new().
1894 * @user_data: the user data from the callback.
1896 * Finds a source with the given source functions and user data. If
1897 * multiple sources exist with the same source function and user data,
1898 * the first one found will be returned.
1900 * Return value: (transfer none): the source, if one was found, otherwise %NULL
1903 g_main_context_find_source_by_funcs_user_data (GMainContext *context,
1904 GSourceFuncs *funcs,
1910 g_return_val_if_fail (funcs != NULL, NULL);
1912 if (context == NULL)
1913 context = g_main_context_default ();
1915 LOCK_CONTEXT (context);
1917 g_source_iter_init (&iter, context, FALSE);
1918 while (g_source_iter_next (&iter, &source))
1920 if (!SOURCE_DESTROYED (source) &&
1921 source->source_funcs == funcs &&
1922 source->callback_funcs)
1924 GSourceFunc callback;
1925 gpointer callback_data;
1927 source->callback_funcs->get (source->callback_data, source, &callback, &callback_data);
1929 if (callback_data == user_data)
1933 g_source_iter_clear (&iter);
1935 UNLOCK_CONTEXT (context);
1941 * g_main_context_find_source_by_user_data:
1942 * @context: a #GMainContext
1943 * @user_data: the user_data for the callback.
1945 * Finds a source with the given user data for the callback. If
1946 * multiple sources exist with the same user data, the first
1947 * one found will be returned.
1949 * Return value: (transfer none): the source, if one was found, otherwise %NULL
1952 g_main_context_find_source_by_user_data (GMainContext *context,
1958 if (context == NULL)
1959 context = g_main_context_default ();
1961 LOCK_CONTEXT (context);
1963 g_source_iter_init (&iter, context, FALSE);
1964 while (g_source_iter_next (&iter, &source))
1966 if (!SOURCE_DESTROYED (source) &&
1967 source->callback_funcs)
1969 GSourceFunc callback;
1970 gpointer callback_data = NULL;
1972 source->callback_funcs->get (source->callback_data, source, &callback, &callback_data);
1974 if (callback_data == user_data)
1978 g_source_iter_clear (&iter);
1980 UNLOCK_CONTEXT (context);
1987 * @tag: the ID of the source to remove.
1989 * Removes the source with the given id from the default main context.
1991 * a #GSource is given by g_source_get_id(), or will be returned by the
1992 * functions g_source_attach(), g_idle_add(), g_idle_add_full(),
1993 * g_timeout_add(), g_timeout_add_full(), g_child_watch_add(),
1994 * g_child_watch_add_full(), g_io_add_watch(), and g_io_add_watch_full().
1996 * See also g_source_destroy(). You must use g_source_destroy() for sources
1997 * added to a non-default main context.
1999 * Return value: %TRUE if the source was found and removed.
2002 g_source_remove (guint tag)
2006 g_return_val_if_fail (tag > 0, FALSE);
2008 source = g_main_context_find_source_by_id (NULL, tag);
2010 g_source_destroy (source);
2012 return source != NULL;
2016 * g_source_remove_by_user_data:
2017 * @user_data: the user_data for the callback.
2019 * Removes a source from the default main loop context given the user
2020 * data for the callback. If multiple sources exist with the same user
2021 * data, only one will be destroyed.
2023 * Return value: %TRUE if a source was found and removed.
2026 g_source_remove_by_user_data (gpointer user_data)
2030 source = g_main_context_find_source_by_user_data (NULL, user_data);
2033 g_source_destroy (source);
2041 * g_source_remove_by_funcs_user_data:
2042 * @funcs: The @source_funcs passed to g_source_new()
2043 * @user_data: the user data for the callback
2045 * Removes a source from the default main loop context given the
2046 * source functions and user data. If multiple sources exist with the
2047 * same source functions and user data, only one will be destroyed.
2049 * Return value: %TRUE if a source was found and removed.
2052 g_source_remove_by_funcs_user_data (GSourceFuncs *funcs,
2057 g_return_val_if_fail (funcs != NULL, FALSE);
2059 source = g_main_context_find_source_by_funcs_user_data (NULL, funcs, user_data);
2062 g_source_destroy (source);
2070 * g_get_current_time:
2071 * @result: #GTimeVal structure in which to store current time.
2073 * Equivalent to the UNIX gettimeofday() function, but portable.
2075 * You may find g_get_real_time() to be more convenient.
2078 g_get_current_time (GTimeVal *result)
2083 g_return_if_fail (result != NULL);
2085 /*this is required on alpha, there the timeval structs are int's
2086 not longs and a cast only would fail horribly*/
2087 gettimeofday (&r, NULL);
2088 result->tv_sec = r.tv_sec;
2089 result->tv_usec = r.tv_usec;
2094 g_return_if_fail (result != NULL);
2096 GetSystemTimeAsFileTime (&ft);
2097 memmove (&time64, &ft, sizeof (FILETIME));
2099 /* Convert from 100s of nanoseconds since 1601-01-01
2100 * to Unix epoch. Yes, this is Y2038 unsafe.
2102 time64 -= G_GINT64_CONSTANT (116444736000000000);
2105 result->tv_sec = time64 / 1000000;
2106 result->tv_usec = time64 % 1000000;
2113 * Queries the system wall-clock time.
2115 * This call is functionally equivalent to g_get_current_time() except
2116 * that the return value is often more convenient than dealing with a
2119 * You should only use this call if you are actually interested in the real
2120 * wall-clock time. g_get_monotonic_time() is probably more useful for
2121 * measuring intervals.
2123 * Returns: the number of microseconds since January 1, 1970 UTC.
2128 g_get_real_time (void)
2132 g_get_current_time (&tv);
2134 return (((gint64) tv.tv_sec) * 1000000) + tv.tv_usec;
2138 static ULONGLONG (*g_GetTickCount64) (void) = NULL;
2139 static guint32 g_win32_tick_epoch = 0;
2141 G_GNUC_INTERNAL void
2142 g_clock_win32_init (void)
2146 g_GetTickCount64 = NULL;
2147 kernel32 = GetModuleHandle ("KERNEL32.DLL");
2148 if (kernel32 != NULL)
2149 g_GetTickCount64 = (void *) GetProcAddress (kernel32, "GetTickCount64");
2150 g_win32_tick_epoch = ((guint32)GetTickCount()) >> 31;
2155 * g_get_monotonic_time:
2157 * Queries the system monotonic time, if available.
2159 * On POSIX systems with clock_gettime() and <literal>CLOCK_MONOTONIC</literal> this call
2160 * is a very shallow wrapper for that. Otherwise, we make a best effort
2161 * that probably involves returning the wall clock time (with at least
2162 * microsecond accuracy, subject to the limitations of the OS kernel).
2164 * It's important to note that POSIX <literal>CLOCK_MONOTONIC</literal> does
2165 * not count time spent while the machine is suspended.
2167 * On Windows, "limitations of the OS kernel" is a rather substantial
2168 * statement. Depending on the configuration of the system, the wall
2169 * clock time is updated as infrequently as 64 times a second (which
2170 * is approximately every 16ms). Also, on XP (but not on Vista or later)
2171 * the monotonic clock is locally monotonic, but may differ in exact
2172 * value between processes due to timer wrap handling.
2174 * Returns: the monotonic time, in microseconds
2179 g_get_monotonic_time (void)
2181 #ifdef HAVE_CLOCK_GETTIME
2182 /* librt clock_gettime() is our first choice */
2185 #ifdef CLOCK_MONOTONIC
2186 clock_gettime (CLOCK_MONOTONIC, &ts);
2188 clock_gettime (CLOCK_REALTIME, &ts);
2191 /* In theory monotonic time can have any epoch.
2193 * glib presently assumes the following:
2195 * 1) The epoch comes some time after the birth of Jesus of Nazareth, but
2196 * not more than 10000 years later.
2198 * 2) The current time also falls sometime within this range.
2200 * These two reasonable assumptions leave us with a maximum deviation from
2201 * the epoch of 10000 years, or 315569520000000000 seconds.
2203 * If we restrict ourselves to this range then the number of microseconds
2204 * will always fit well inside the constraints of a int64 (by a factor of
2207 * If you actually hit the following assertion, probably you should file a
2208 * bug against your operating system for being excessively silly.
2210 g_assert (G_GINT64_CONSTANT (-315569520000000000) < ts.tv_sec &&
2211 ts.tv_sec < G_GINT64_CONSTANT (315569520000000000));
2213 return (((gint64) ts.tv_sec) * 1000000) + (ts.tv_nsec / 1000);
2215 #elif defined (G_OS_WIN32)
2219 /* There are four sources for the monotonic time on Windows:
2221 * Three are based on a (1 msec accuracy, but only read periodically) clock chip:
2222 * - GetTickCount (GTC)
2223 * 32bit msec counter, updated each ~15msec, wraps in ~50 days
2224 * - GetTickCount64 (GTC64)
2225 * Same as GetTickCount, but extended to 64bit, so no wrap
2226 * Only available in Vista or later
2227 * - timeGetTime (TGT)
2228 * similar to GetTickCount by default: 15msec, 50 day wrap.
2229 * available in winmm.dll (thus known as the multimedia timers)
2230 * However apps can raise the system timer clock frequency using timeBeginPeriod()
2231 * increasing the accuracy up to 1 msec, at a cost in general system performance
2234 * One is based on high precision clocks:
2235 * - QueryPrecisionCounter (QPC)
2236 * This has much higher accuracy, but is not guaranteed monotonic, and
2237 * has lots of complications like clock jumps and different times on different
2238 * CPUs. It also has lower long term accuracy (i.e. it will drift compared to
2239 * the low precision clocks.
2241 * Additionally, the precision available in the timer-based wakeup such as
2242 * MsgWaitForMultipleObjectsEx (which is what the mainloop is based on) is based
2243 * on the TGT resolution, so by default it is ~15msec, but can be increased by apps.
2245 * The QPC timer has too many issues to be used as is. The only way it could be used
2246 * is to use it to interpolate the lower precision clocks. Firefox does something like
2248 * https://bugzilla.mozilla.org/show_bug.cgi?id=363258
2250 * However this seems quite complicated, so we're not doing this right now.
2252 * The approach we take instead is to use the TGT timer, extending it to 64bit
2253 * either by using the GTC64 value, or if that is not available, a process local
2254 * time epoch that we increment when we detect a timer wrap (assumes that we read
2255 * the time at least once every 50 days).
2258 * - We have a globally consistent monotonic clock on Vista and later
2259 * - We have a locally monotonic clock on XP
2260 * - Apps that need higher precision in timeouts and clock reads can call
2261 * timeBeginPeriod() to increase it as much as they want
2264 if (g_GetTickCount64 != NULL)
2266 guint32 ticks_as_32bit;
2268 ticks = g_GetTickCount64 ();
2269 ticks32 = timeGetTime();
2271 /* GTC64 and TGT are sampled at different times, however they
2272 * have the same base and source (msecs since system boot).
2273 * They can differ by as much as -16 to +16 msecs.
2274 * We can't just inject the low bits into the 64bit counter
2275 * as one of the counters can have wrapped in 32bit space and
2276 * the other not. Instead we calculate the signed difference
2277 * in 32bit space and apply that difference to the 64bit counter.
2279 ticks_as_32bit = (guint32)ticks;
2281 /* We could do some 2's complement hack, but we play it safe */
2282 if (ticks32 - ticks_as_32bit <= G_MAXINT32)
2283 ticks += ticks32 - ticks_as_32bit;
2285 ticks -= ticks_as_32bit - ticks32;
2291 epoch = g_atomic_int_get (&g_win32_tick_epoch);
2293 /* Must read ticks after the epoch. Then we're guaranteed
2294 * that the ticks value we read is higher or equal to any
2295 * previous ones that lead to the writing of the epoch.
2297 ticks32 = timeGetTime();
2299 /* We store the MSB of the current time as the LSB
2300 * of the epoch. Comparing these bits lets us detect when
2301 * the 32bit counter has wrapped so we can increase the
2304 * This will work as long as this function is called at
2305 * least once every ~24 days, which is half the wrap time
2306 * of a 32bit msec counter. I think this is pretty likely.
2308 * Note that g_win32_tick_epoch is a process local state,
2309 * so the monotonic clock will not be the same between
2312 if ((ticks32 >> 31) != (epoch & 1))
2315 g_atomic_int_set (&g_win32_tick_epoch, epoch);
2319 ticks = (guint64)ticks32 | ((guint64)epoch) << 31;
2322 return ticks * 1000;
2324 #else /* !HAVE_CLOCK_GETTIME && ! G_OS_WIN32*/
2328 g_get_current_time (&tv);
2330 return (((gint64) tv.tv_sec) * 1000000) + tv.tv_usec;
2335 g_main_dispatch_free (gpointer dispatch)
2337 g_slice_free (GMainDispatch, dispatch);
2340 /* Running the main loop */
2342 static GMainDispatch *
2345 static GPrivate depth_private = G_PRIVATE_INIT (g_main_dispatch_free);
2346 GMainDispatch *dispatch;
2348 dispatch = g_private_get (&depth_private);
2352 dispatch = g_slice_new0 (GMainDispatch);
2353 g_private_set (&depth_private, dispatch);
2362 * Returns the depth of the stack of calls to
2363 * g_main_context_dispatch() on any #GMainContext in the current thread.
2364 * That is, when called from the toplevel, it gives 0. When
2365 * called from within a callback from g_main_context_iteration()
2366 * (or g_main_loop_run(), etc.) it returns 1. When called from within
2367 * a callback to a recursive call to g_main_context_iteration(),
2368 * it returns 2. And so forth.
2370 * This function is useful in a situation like the following:
2371 * Imagine an extremely simple "garbage collected" system.
2374 * static GList *free_list;
2377 * allocate_memory (gsize size)
2379 * gpointer result = g_malloc (size);
2380 * free_list = g_list_prepend (free_list, result);
2385 * free_allocated_memory (void)
2388 * for (l = free_list; l; l = l->next);
2390 * g_list_free (free_list);
2398 * g_main_context_iteration (NULL, TRUE);
2399 * free_allocated_memory();
2403 * This works from an application, however, if you want to do the same
2404 * thing from a library, it gets more difficult, since you no longer
2405 * control the main loop. You might think you can simply use an idle
2406 * function to make the call to free_allocated_memory(), but that
2407 * doesn't work, since the idle function could be called from a
2408 * recursive callback. This can be fixed by using g_main_depth()
2412 * allocate_memory (gsize size)
2414 * FreeListBlock *block = g_new (FreeListBlock, 1);
2415 * block->mem = g_malloc (size);
2416 * block->depth = g_main_depth ();
2417 * free_list = g_list_prepend (free_list, block);
2418 * return block->mem;
2422 * free_allocated_memory (void)
2426 * int depth = g_main_depth ();
2427 * for (l = free_list; l; );
2429 * GList *next = l->next;
2430 * FreeListBlock *block = l->data;
2431 * if (block->depth > depth)
2433 * g_free (block->mem);
2435 * free_list = g_list_delete_link (free_list, l);
2443 * There is a temptation to use g_main_depth() to solve
2444 * problems with reentrancy. For instance, while waiting for data
2445 * to be received from the network in response to a menu item,
2446 * the menu item might be selected again. It might seem that
2447 * one could make the menu item's callback return immediately
2448 * and do nothing if g_main_depth() returns a value greater than 1.
2449 * However, this should be avoided since the user then sees selecting
2450 * the menu item do nothing. Furthermore, you'll find yourself adding
2451 * these checks all over your code, since there are doubtless many,
2452 * many things that the user could do. Instead, you can use the
2453 * following techniques:
2458 * Use gtk_widget_set_sensitive() or modal dialogs to prevent
2459 * the user from interacting with elements while the main
2460 * loop is recursing.
2465 * Avoid main loop recursion in situations where you can't handle
2466 * arbitrary callbacks. Instead, structure your code so that you
2467 * simply return to the main loop and then get called again when
2468 * there is more work to do.
2473 * Return value: The main loop recursion level in the current thread
2478 GMainDispatch *dispatch = get_dispatch ();
2479 return dispatch->depth;
2483 * g_main_current_source:
2485 * Returns the currently firing source for this thread.
2487 * Return value: (transfer none): The currently firing source or %NULL.
2492 g_main_current_source (void)
2494 GMainDispatch *dispatch = get_dispatch ();
2495 return dispatch->dispatching_sources ? dispatch->dispatching_sources->data : NULL;
2499 * g_source_is_destroyed:
2500 * @source: a #GSource
2502 * Returns whether @source has been destroyed.
2504 * This is important when you operate upon your objects
2505 * from within idle handlers, but may have freed the object
2506 * before the dispatch of your idle handler.
2510 * idle_callback (gpointer data)
2512 * SomeWidget *self = data;
2514 * GDK_THREADS_ENTER (<!-- -->);
2515 * /<!-- -->* do stuff with self *<!-- -->/
2516 * self->idle_id = 0;
2517 * GDK_THREADS_LEAVE (<!-- -->);
2519 * return G_SOURCE_REMOVE;
2523 * some_widget_do_stuff_later (SomeWidget *self)
2525 * self->idle_id = g_idle_add (idle_callback, self);
2529 * some_widget_finalize (GObject *object)
2531 * SomeWidget *self = SOME_WIDGET (object);
2533 * if (self->idle_id)
2534 * g_source_remove (self->idle_id);
2536 * G_OBJECT_CLASS (parent_class)->finalize (object);
2540 * This will fail in a multi-threaded application if the
2541 * widget is destroyed before the idle handler fires due
2542 * to the use after free in the callback. A solution, to
2543 * this particular problem, is to check to if the source
2544 * has already been destroy within the callback.
2548 * idle_callback (gpointer data)
2550 * SomeWidget *self = data;
2552 * GDK_THREADS_ENTER ();
2553 * if (!g_source_is_destroyed (g_main_current_source ()))
2555 * /<!-- -->* do stuff with self *<!-- -->/
2557 * GDK_THREADS_LEAVE ();
2563 * Return value: %TRUE if the source has been destroyed
2568 g_source_is_destroyed (GSource *source)
2570 return SOURCE_DESTROYED (source);
2573 /* Temporarily remove all this source's file descriptors from the
2574 * poll(), so that if data comes available for one of the file descriptors
2575 * we don't continually spin in the poll()
2577 /* HOLDS: source->context's lock */
2579 block_source (GSource *source)
2583 g_return_if_fail (!SOURCE_BLOCKED (source));
2585 source->flags |= G_SOURCE_BLOCKED;
2587 tmp_list = source->poll_fds;
2590 g_main_context_remove_poll_unlocked (source->context, tmp_list->data);
2591 tmp_list = tmp_list->next;
2594 if (source->priv && source->priv->child_sources)
2596 tmp_list = source->priv->child_sources;
2599 block_source (tmp_list->data);
2600 tmp_list = tmp_list->next;
2605 /* HOLDS: source->context's lock */
2607 unblock_source (GSource *source)
2611 g_return_if_fail (SOURCE_BLOCKED (source)); /* Source already unblocked */
2612 g_return_if_fail (!SOURCE_DESTROYED (source));
2614 source->flags &= ~G_SOURCE_BLOCKED;
2616 tmp_list = source->poll_fds;
2619 g_main_context_add_poll_unlocked (source->context, source->priority, tmp_list->data);
2620 tmp_list = tmp_list->next;
2623 if (source->priv && source->priv->child_sources)
2625 tmp_list = source->priv->child_sources;
2628 unblock_source (tmp_list->data);
2629 tmp_list = tmp_list->next;
2634 /* HOLDS: context's lock */
2636 g_main_dispatch (GMainContext *context)
2638 GMainDispatch *current = get_dispatch ();
2641 for (i = 0; i < context->pending_dispatches->len; i++)
2643 GSource *source = context->pending_dispatches->pdata[i];
2645 context->pending_dispatches->pdata[i] = NULL;
2648 source->flags &= ~G_SOURCE_READY;
2650 if (!SOURCE_DESTROYED (source))
2652 gboolean was_in_call;
2653 gpointer user_data = NULL;
2654 GSourceFunc callback = NULL;
2655 GSourceCallbackFuncs *cb_funcs;
2657 gboolean need_destroy;
2659 gboolean (*dispatch) (GSource *,
2662 GSList current_source_link;
2664 dispatch = source->source_funcs->dispatch;
2665 cb_funcs = source->callback_funcs;
2666 cb_data = source->callback_data;
2669 cb_funcs->ref (cb_data);
2671 if ((source->flags & G_SOURCE_CAN_RECURSE) == 0)
2672 block_source (source);
2674 was_in_call = source->flags & G_HOOK_FLAG_IN_CALL;
2675 source->flags |= G_HOOK_FLAG_IN_CALL;
2678 cb_funcs->get (cb_data, source, &callback, &user_data);
2680 UNLOCK_CONTEXT (context);
2683 /* The on-stack allocation of the GSList is unconventional, but
2684 * we know that the lifetime of the link is bounded to this
2685 * function as the link is kept in a thread specific list and
2686 * not manipulated outside of this function and its descendants.
2687 * Avoiding the overhead of a g_slist_alloc() is useful as many
2688 * applications do little more than dispatch events.
2690 * This is a performance hack - do not revert to g_slist_prepend()!
2692 current_source_link.data = source;
2693 current_source_link.next = current->dispatching_sources;
2694 current->dispatching_sources = ¤t_source_link;
2695 need_destroy = ! dispatch (source,
2698 g_assert (current->dispatching_sources == ¤t_source_link);
2699 current->dispatching_sources = current_source_link.next;
2703 cb_funcs->unref (cb_data);
2705 LOCK_CONTEXT (context);
2708 source->flags &= ~G_HOOK_FLAG_IN_CALL;
2710 if (SOURCE_BLOCKED (source) && !SOURCE_DESTROYED (source))
2711 unblock_source (source);
2713 /* Note: this depends on the fact that we can't switch
2714 * sources from one main context to another
2716 if (need_destroy && !SOURCE_DESTROYED (source))
2718 g_assert (source->context == context);
2719 g_source_destroy_internal (source, context, TRUE);
2723 SOURCE_UNREF (source, context);
2726 g_ptr_array_set_size (context->pending_dispatches, 0);
2730 * g_main_context_acquire:
2731 * @context: a #GMainContext
2733 * Tries to become the owner of the specified context.
2734 * If some other thread is the owner of the context,
2735 * returns %FALSE immediately. Ownership is properly
2736 * recursive: the owner can require ownership again
2737 * and will release ownership when g_main_context_release()
2738 * is called as many times as g_main_context_acquire().
2740 * You must be the owner of a context before you
2741 * can call g_main_context_prepare(), g_main_context_query(),
2742 * g_main_context_check(), g_main_context_dispatch().
2744 * Return value: %TRUE if the operation succeeded, and
2745 * this thread is now the owner of @context.
2748 g_main_context_acquire (GMainContext *context)
2750 gboolean result = FALSE;
2751 GThread *self = G_THREAD_SELF;
2753 if (context == NULL)
2754 context = g_main_context_default ();
2756 LOCK_CONTEXT (context);
2758 if (!context->owner)
2760 context->owner = self;
2761 g_assert (context->owner_count == 0);
2764 if (context->owner == self)
2766 context->owner_count++;
2770 UNLOCK_CONTEXT (context);
2776 * g_main_context_release:
2777 * @context: a #GMainContext
2779 * Releases ownership of a context previously acquired by this thread
2780 * with g_main_context_acquire(). If the context was acquired multiple
2781 * times, the ownership will be released only when g_main_context_release()
2782 * is called as many times as it was acquired.
2785 g_main_context_release (GMainContext *context)
2787 if (context == NULL)
2788 context = g_main_context_default ();
2790 LOCK_CONTEXT (context);
2792 context->owner_count--;
2793 if (context->owner_count == 0)
2795 context->owner = NULL;
2797 if (context->waiters)
2799 GMainWaiter *waiter = context->waiters->data;
2800 gboolean loop_internal_waiter = (waiter->mutex == &context->mutex);
2801 context->waiters = g_slist_delete_link (context->waiters,
2803 if (!loop_internal_waiter)
2804 g_mutex_lock (waiter->mutex);
2806 g_cond_signal (waiter->cond);
2808 if (!loop_internal_waiter)
2809 g_mutex_unlock (waiter->mutex);
2813 UNLOCK_CONTEXT (context);
2817 * g_main_context_wait:
2818 * @context: a #GMainContext
2819 * @cond: a condition variable
2820 * @mutex: a mutex, currently held
2822 * Tries to become the owner of the specified context,
2823 * as with g_main_context_acquire(). But if another thread
2824 * is the owner, atomically drop @mutex and wait on @cond until
2825 * that owner releases ownership or until @cond is signaled, then
2826 * try again (once) to become the owner.
2828 * Return value: %TRUE if the operation succeeded, and
2829 * this thread is now the owner of @context.
2832 g_main_context_wait (GMainContext *context,
2836 gboolean result = FALSE;
2837 GThread *self = G_THREAD_SELF;
2838 gboolean loop_internal_waiter;
2840 if (context == NULL)
2841 context = g_main_context_default ();
2843 loop_internal_waiter = (mutex == &context->mutex);
2845 if (!loop_internal_waiter)
2846 LOCK_CONTEXT (context);
2848 if (context->owner && context->owner != self)
2853 waiter.mutex = mutex;
2855 context->waiters = g_slist_append (context->waiters, &waiter);
2857 if (!loop_internal_waiter)
2858 UNLOCK_CONTEXT (context);
2859 g_cond_wait (cond, mutex);
2860 if (!loop_internal_waiter)
2861 LOCK_CONTEXT (context);
2863 context->waiters = g_slist_remove (context->waiters, &waiter);
2866 if (!context->owner)
2868 context->owner = self;
2869 g_assert (context->owner_count == 0);
2872 if (context->owner == self)
2874 context->owner_count++;
2878 if (!loop_internal_waiter)
2879 UNLOCK_CONTEXT (context);
2885 * g_main_context_prepare:
2886 * @context: a #GMainContext
2887 * @priority: location to store priority of highest priority
2888 * source already ready.
2890 * Prepares to poll sources within a main loop. The resulting information
2891 * for polling is determined by calling g_main_context_query ().
2893 * Return value: %TRUE if some source is ready to be dispatched
2897 g_main_context_prepare (GMainContext *context,
2902 gint current_priority = G_MAXINT;
2906 if (context == NULL)
2907 context = g_main_context_default ();
2909 LOCK_CONTEXT (context);
2911 context->time_is_fresh = FALSE;
2913 if (context->in_check_or_prepare)
2915 g_warning ("g_main_context_prepare() called recursively from within a source's check() or "
2916 "prepare() member.");
2917 UNLOCK_CONTEXT (context);
2922 /* If recursing, finish up current dispatch, before starting over */
2923 if (context->pending_dispatches)
2926 g_main_dispatch (context, ¤t_time);
2928 UNLOCK_CONTEXT (context);
2933 /* If recursing, clear list of pending dispatches */
2935 for (i = 0; i < context->pending_dispatches->len; i++)
2937 if (context->pending_dispatches->pdata[i])
2938 SOURCE_UNREF ((GSource *)context->pending_dispatches->pdata[i], context);
2940 g_ptr_array_set_size (context->pending_dispatches, 0);
2942 /* Prepare all sources */
2944 context->timeout = -1;
2946 g_source_iter_init (&iter, context, TRUE);
2947 while (g_source_iter_next (&iter, &source))
2949 gint source_timeout = -1;
2951 if (SOURCE_DESTROYED (source) || SOURCE_BLOCKED (source))
2953 if ((n_ready > 0) && (source->priority > current_priority))
2956 if (!(source->flags & G_SOURCE_READY))
2959 gboolean (*prepare) (GSource *source,
2962 prepare = source->source_funcs->prepare;
2963 context->in_check_or_prepare++;
2964 UNLOCK_CONTEXT (context);
2966 result = (*prepare) (source, &source_timeout);
2968 LOCK_CONTEXT (context);
2969 context->in_check_or_prepare--;
2973 GSource *ready_source = source;
2975 while (ready_source)
2977 ready_source->flags |= G_SOURCE_READY;
2978 ready_source = ready_source->priv->parent_source;
2983 if (source->flags & G_SOURCE_READY)
2986 current_priority = source->priority;
2987 context->timeout = 0;
2990 if (source_timeout >= 0)
2992 if (context->timeout < 0)
2993 context->timeout = source_timeout;
2995 context->timeout = MIN (context->timeout, source_timeout);
2998 g_source_iter_clear (&iter);
3000 UNLOCK_CONTEXT (context);
3003 *priority = current_priority;
3005 return (n_ready > 0);
3009 * g_main_context_query:
3010 * @context: a #GMainContext
3011 * @max_priority: maximum priority source to check
3012 * @timeout_: (out): location to store timeout to be used in polling
3013 * @fds: (out caller-allocates) (array length=n_fds): location to
3014 * store #GPollFD records that need to be polled.
3015 * @n_fds: length of @fds.
3017 * Determines information necessary to poll this main loop.
3019 * Return value: the number of records actually stored in @fds,
3020 * or, if more than @n_fds records need to be stored, the number
3021 * of records that need to be stored.
3024 g_main_context_query (GMainContext *context,
3033 LOCK_CONTEXT (context);
3035 pollrec = context->poll_records;
3037 while (pollrec && max_priority >= pollrec->priority)
3039 /* We need to include entries with fd->events == 0 in the array because
3040 * otherwise if the application changes fd->events behind our back and
3041 * makes it non-zero, we'll be out of sync when we check the fds[] array.
3042 * (Changing fd->events after adding an FD wasn't an anticipated use of
3043 * this API, but it occurs in practice.) */
3046 fds[n_poll].fd = pollrec->fd->fd;
3047 /* In direct contradiction to the Unix98 spec, IRIX runs into
3048 * difficulty if you pass in POLLERR, POLLHUP or POLLNVAL
3049 * flags in the events field of the pollfd while it should
3050 * just ignoring them. So we mask them out here.
3052 fds[n_poll].events = pollrec->fd->events & ~(G_IO_ERR|G_IO_HUP|G_IO_NVAL);
3053 fds[n_poll].revents = 0;
3056 pollrec = pollrec->next;
3060 context->poll_changed = FALSE;
3064 *timeout = context->timeout;
3066 context->time_is_fresh = FALSE;
3069 UNLOCK_CONTEXT (context);
3075 * g_main_context_check:
3076 * @context: a #GMainContext
3077 * @max_priority: the maximum numerical priority of sources to check
3078 * @fds: (array length=n_fds): array of #GPollFD's that was passed to
3079 * the last call to g_main_context_query()
3080 * @n_fds: return value of g_main_context_query()
3082 * Passes the results of polling back to the main loop.
3084 * Return value: %TRUE if some sources are ready to be dispatched.
3087 g_main_context_check (GMainContext *context,
3098 LOCK_CONTEXT (context);
3100 if (context->in_check_or_prepare)
3102 g_warning ("g_main_context_check() called recursively from within a source's check() or "
3103 "prepare() member.");
3104 UNLOCK_CONTEXT (context);
3108 if (context->wake_up_rec.revents)
3109 g_wakeup_acknowledge (context->wakeup);
3111 /* If the set of poll file descriptors changed, bail out
3112 * and let the main loop rerun
3114 if (context->poll_changed)
3116 UNLOCK_CONTEXT (context);
3120 pollrec = context->poll_records;
3124 if (pollrec->fd->events)
3125 pollrec->fd->revents = fds[i].revents;
3127 pollrec = pollrec->next;
3131 g_source_iter_init (&iter, context, TRUE);
3132 while (g_source_iter_next (&iter, &source))
3134 if (SOURCE_DESTROYED (source) || SOURCE_BLOCKED (source))
3136 if ((n_ready > 0) && (source->priority > max_priority))
3139 if (!(source->flags & G_SOURCE_READY))
3142 gboolean (*check) (GSource *source);
3144 check = source->source_funcs->check;
3146 context->in_check_or_prepare++;
3147 UNLOCK_CONTEXT (context);
3149 result = (*check) (source);
3151 LOCK_CONTEXT (context);
3152 context->in_check_or_prepare--;
3156 GSource *ready_source = source;
3158 while (ready_source)
3160 ready_source->flags |= G_SOURCE_READY;
3161 ready_source = ready_source->priv->parent_source;
3166 if (source->flags & G_SOURCE_READY)
3168 source->ref_count++;
3169 g_ptr_array_add (context->pending_dispatches, source);
3173 /* never dispatch sources with less priority than the first
3174 * one we choose to dispatch
3176 max_priority = source->priority;
3179 g_source_iter_clear (&iter);
3181 UNLOCK_CONTEXT (context);
3187 * g_main_context_dispatch:
3188 * @context: a #GMainContext
3190 * Dispatches all pending sources.
3193 g_main_context_dispatch (GMainContext *context)
3195 LOCK_CONTEXT (context);
3197 if (context->pending_dispatches->len > 0)
3199 g_main_dispatch (context);
3202 UNLOCK_CONTEXT (context);
3205 /* HOLDS context lock */
3207 g_main_context_iterate (GMainContext *context,
3214 gboolean some_ready;
3215 gint nfds, allocated_nfds;
3216 GPollFD *fds = NULL;
3218 UNLOCK_CONTEXT (context);
3220 if (!g_main_context_acquire (context))
3222 gboolean got_ownership;
3224 LOCK_CONTEXT (context);
3229 got_ownership = g_main_context_wait (context,
3237 LOCK_CONTEXT (context);
3239 if (!context->cached_poll_array)
3241 context->cached_poll_array_size = context->n_poll_records;
3242 context->cached_poll_array = g_new (GPollFD, context->n_poll_records);
3245 allocated_nfds = context->cached_poll_array_size;
3246 fds = context->cached_poll_array;
3248 UNLOCK_CONTEXT (context);
3250 g_main_context_prepare (context, &max_priority);
3252 while ((nfds = g_main_context_query (context, max_priority, &timeout, fds,
3253 allocated_nfds)) > allocated_nfds)
3255 LOCK_CONTEXT (context);
3257 context->cached_poll_array_size = allocated_nfds = nfds;
3258 context->cached_poll_array = fds = g_new (GPollFD, nfds);
3259 UNLOCK_CONTEXT (context);
3265 g_main_context_poll (context, timeout, max_priority, fds, nfds);
3267 some_ready = g_main_context_check (context, max_priority, fds, nfds);
3270 g_main_context_dispatch (context);
3272 g_main_context_release (context);
3274 LOCK_CONTEXT (context);
3280 * g_main_context_pending:
3281 * @context: (allow-none): a #GMainContext (if %NULL, the default context will be used)
3283 * Checks if any sources have pending events for the given context.
3285 * Return value: %TRUE if events are pending.
3288 g_main_context_pending (GMainContext *context)
3293 context = g_main_context_default();
3295 LOCK_CONTEXT (context);
3296 retval = g_main_context_iterate (context, FALSE, FALSE, G_THREAD_SELF);
3297 UNLOCK_CONTEXT (context);
3303 * g_main_context_iteration:
3304 * @context: (allow-none): a #GMainContext (if %NULL, the default context will be used)
3305 * @may_block: whether the call may block.
3307 * Runs a single iteration for the given main loop. This involves
3308 * checking to see if any event sources are ready to be processed,
3309 * then if no events sources are ready and @may_block is %TRUE, waiting
3310 * for a source to become ready, then dispatching the highest priority
3311 * events sources that are ready. Otherwise, if @may_block is %FALSE
3312 * sources are not waited to become ready, only those highest priority
3313 * events sources will be dispatched (if any), that are ready at this
3314 * given moment without further waiting.
3316 * Note that even when @may_block is %TRUE, it is still possible for
3317 * g_main_context_iteration() to return %FALSE, since the the wait may
3318 * be interrupted for other reasons than an event source becoming ready.
3320 * Return value: %TRUE if events were dispatched.
3323 g_main_context_iteration (GMainContext *context, gboolean may_block)
3328 context = g_main_context_default();
3330 LOCK_CONTEXT (context);
3331 retval = g_main_context_iterate (context, may_block, TRUE, G_THREAD_SELF);
3332 UNLOCK_CONTEXT (context);
3339 * @context: (allow-none): a #GMainContext (if %NULL, the default context will be used).
3340 * @is_running: set to %TRUE to indicate that the loop is running. This
3341 * is not very important since calling g_main_loop_run() will set this to
3344 * Creates a new #GMainLoop structure.
3346 * Return value: a new #GMainLoop.
3349 g_main_loop_new (GMainContext *context,
3350 gboolean is_running)
3355 context = g_main_context_default();
3357 g_main_context_ref (context);
3359 loop = g_new0 (GMainLoop, 1);
3360 loop->context = context;
3361 loop->is_running = is_running != FALSE;
3362 loop->ref_count = 1;
3369 * @loop: a #GMainLoop
3371 * Increases the reference count on a #GMainLoop object by one.
3373 * Return value: @loop
3376 g_main_loop_ref (GMainLoop *loop)
3378 g_return_val_if_fail (loop != NULL, NULL);
3379 g_return_val_if_fail (g_atomic_int_get (&loop->ref_count) > 0, NULL);
3381 g_atomic_int_inc (&loop->ref_count);
3387 * g_main_loop_unref:
3388 * @loop: a #GMainLoop
3390 * Decreases the reference count on a #GMainLoop object by one. If
3391 * the result is zero, free the loop and free all associated memory.
3394 g_main_loop_unref (GMainLoop *loop)
3396 g_return_if_fail (loop != NULL);
3397 g_return_if_fail (g_atomic_int_get (&loop->ref_count) > 0);
3399 if (!g_atomic_int_dec_and_test (&loop->ref_count))
3402 g_main_context_unref (loop->context);
3408 * @loop: a #GMainLoop
3410 * Runs a main loop until g_main_loop_quit() is called on the loop.
3411 * If this is called for the thread of the loop's #GMainContext,
3412 * it will process events from the loop, otherwise it will
3416 g_main_loop_run (GMainLoop *loop)
3418 GThread *self = G_THREAD_SELF;
3420 g_return_if_fail (loop != NULL);
3421 g_return_if_fail (g_atomic_int_get (&loop->ref_count) > 0);
3423 if (!g_main_context_acquire (loop->context))
3425 gboolean got_ownership = FALSE;
3427 /* Another thread owns this context */
3428 LOCK_CONTEXT (loop->context);
3430 g_atomic_int_inc (&loop->ref_count);
3432 if (!loop->is_running)
3433 loop->is_running = TRUE;
3435 while (loop->is_running && !got_ownership)
3436 got_ownership = g_main_context_wait (loop->context,
3437 &loop->context->cond,
3438 &loop->context->mutex);
3440 if (!loop->is_running)
3442 UNLOCK_CONTEXT (loop->context);
3444 g_main_context_release (loop->context);
3445 g_main_loop_unref (loop);
3449 g_assert (got_ownership);
3452 LOCK_CONTEXT (loop->context);
3454 if (loop->context->in_check_or_prepare)
3456 g_warning ("g_main_loop_run(): called recursively from within a source's "
3457 "check() or prepare() member, iteration not possible.");
3461 g_atomic_int_inc (&loop->ref_count);
3462 loop->is_running = TRUE;
3463 while (loop->is_running)
3464 g_main_context_iterate (loop->context, TRUE, TRUE, self);
3466 UNLOCK_CONTEXT (loop->context);
3468 g_main_context_release (loop->context);
3470 g_main_loop_unref (loop);
3475 * @loop: a #GMainLoop
3477 * Stops a #GMainLoop from running. Any calls to g_main_loop_run()
3478 * for the loop will return.
3480 * Note that sources that have already been dispatched when
3481 * g_main_loop_quit() is called will still be executed.
3484 g_main_loop_quit (GMainLoop *loop)
3486 g_return_if_fail (loop != NULL);
3487 g_return_if_fail (g_atomic_int_get (&loop->ref_count) > 0);
3489 LOCK_CONTEXT (loop->context);
3490 loop->is_running = FALSE;
3491 g_wakeup_signal (loop->context->wakeup);
3493 g_cond_broadcast (&loop->context->cond);
3495 UNLOCK_CONTEXT (loop->context);
3499 * g_main_loop_is_running:
3500 * @loop: a #GMainLoop.
3502 * Checks to see if the main loop is currently being run via g_main_loop_run().
3504 * Return value: %TRUE if the mainloop is currently being run.
3507 g_main_loop_is_running (GMainLoop *loop)
3509 g_return_val_if_fail (loop != NULL, FALSE);
3510 g_return_val_if_fail (g_atomic_int_get (&loop->ref_count) > 0, FALSE);
3512 return loop->is_running;
3516 * g_main_loop_get_context:
3517 * @loop: a #GMainLoop.
3519 * Returns the #GMainContext of @loop.
3521 * Return value: (transfer none): the #GMainContext of @loop
3524 g_main_loop_get_context (GMainLoop *loop)
3526 g_return_val_if_fail (loop != NULL, NULL);
3527 g_return_val_if_fail (g_atomic_int_get (&loop->ref_count) > 0, NULL);
3529 return loop->context;
3532 /* HOLDS: context's lock */
3534 g_main_context_poll (GMainContext *context,
3540 #ifdef G_MAIN_POLL_DEBUG
3546 GPollFunc poll_func;
3548 if (n_fds || timeout != 0)
3550 #ifdef G_MAIN_POLL_DEBUG
3551 if (_g_main_poll_debug)
3553 g_print ("polling context=%p n=%d timeout=%d\n",
3554 context, n_fds, timeout);
3555 poll_timer = g_timer_new ();
3559 LOCK_CONTEXT (context);
3561 poll_func = context->poll_func;
3563 UNLOCK_CONTEXT (context);
3564 if ((*poll_func) (fds, n_fds, timeout) < 0 && errno != EINTR)
3567 g_warning ("poll(2) failed due to: %s.",
3568 g_strerror (errno));
3570 /* If g_poll () returns -1, it has already called g_warning() */
3574 #ifdef G_MAIN_POLL_DEBUG
3575 if (_g_main_poll_debug)
3577 LOCK_CONTEXT (context);
3579 g_print ("g_main_poll(%d) timeout: %d - elapsed %12.10f seconds",
3582 g_timer_elapsed (poll_timer, NULL));
3583 g_timer_destroy (poll_timer);
3584 pollrec = context->poll_records;
3586 while (pollrec != NULL)
3591 if (fds[i].fd == pollrec->fd->fd &&
3592 pollrec->fd->events &&
3595 g_print (" [" G_POLLFD_FORMAT " :", fds[i].fd);
3596 if (fds[i].revents & G_IO_IN)
3598 if (fds[i].revents & G_IO_OUT)
3600 if (fds[i].revents & G_IO_PRI)
3602 if (fds[i].revents & G_IO_ERR)
3604 if (fds[i].revents & G_IO_HUP)
3606 if (fds[i].revents & G_IO_NVAL)
3612 pollrec = pollrec->next;
3616 UNLOCK_CONTEXT (context);
3619 } /* if (n_fds || timeout != 0) */
3623 * g_main_context_add_poll:
3624 * @context: (allow-none): a #GMainContext (or %NULL for the default context)
3625 * @fd: a #GPollFD structure holding information about a file
3626 * descriptor to watch.
3627 * @priority: the priority for this file descriptor which should be
3628 * the same as the priority used for g_source_attach() to ensure that the
3629 * file descriptor is polled whenever the results may be needed.
3631 * Adds a file descriptor to the set of file descriptors polled for
3632 * this context. This will very seldom be used directly. Instead
3633 * a typical event source will use g_source_add_poll() instead.
3636 g_main_context_add_poll (GMainContext *context,
3641 context = g_main_context_default ();
3643 g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
3644 g_return_if_fail (fd);
3646 LOCK_CONTEXT (context);
3647 g_main_context_add_poll_unlocked (context, priority, fd);
3648 UNLOCK_CONTEXT (context);
3651 /* HOLDS: main_loop_lock */
3653 g_main_context_add_poll_unlocked (GMainContext *context,
3657 GPollRec *prevrec, *nextrec;
3658 GPollRec *newrec = g_slice_new (GPollRec);
3660 /* This file descriptor may be checked before we ever poll */
3663 newrec->priority = priority;
3665 prevrec = context->poll_records_tail;
3667 while (prevrec && priority < prevrec->priority)
3670 prevrec = prevrec->prev;
3674 prevrec->next = newrec;
3676 context->poll_records = newrec;
3678 newrec->prev = prevrec;
3679 newrec->next = nextrec;
3682 nextrec->prev = newrec;
3684 context->poll_records_tail = newrec;
3686 context->n_poll_records++;
3688 context->poll_changed = TRUE;
3690 /* Now wake up the main loop if it is waiting in the poll() */
3691 g_wakeup_signal (context->wakeup);
3695 * g_main_context_remove_poll:
3696 * @context:a #GMainContext
3697 * @fd: a #GPollFD descriptor previously added with g_main_context_add_poll()
3699 * Removes file descriptor from the set of file descriptors to be
3700 * polled for a particular context.
3703 g_main_context_remove_poll (GMainContext *context,
3707 context = g_main_context_default ();
3709 g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
3710 g_return_if_fail (fd);
3712 LOCK_CONTEXT (context);
3713 g_main_context_remove_poll_unlocked (context, fd);
3714 UNLOCK_CONTEXT (context);
3718 g_main_context_remove_poll_unlocked (GMainContext *context,
3721 GPollRec *pollrec, *prevrec, *nextrec;
3724 pollrec = context->poll_records;
3728 nextrec = pollrec->next;
3729 if (pollrec->fd == fd)
3731 if (prevrec != NULL)
3732 prevrec->next = nextrec;
3734 context->poll_records = nextrec;
3736 if (nextrec != NULL)
3737 nextrec->prev = prevrec;
3739 context->poll_records_tail = prevrec;
3741 g_slice_free (GPollRec, pollrec);
3743 context->n_poll_records--;
3750 context->poll_changed = TRUE;
3752 /* Now wake up the main loop if it is waiting in the poll() */
3753 g_wakeup_signal (context->wakeup);
3757 * g_source_get_current_time:
3758 * @source: a #GSource
3759 * @timeval: #GTimeVal structure in which to store current time.
3761 * This function ignores @source and is otherwise the same as
3762 * g_get_current_time().
3764 * Deprecated: 2.28: use g_source_get_time() instead
3767 g_source_get_current_time (GSource *source,
3770 g_get_current_time (timeval);
3774 * g_source_get_time:
3775 * @source: a #GSource
3777 * Gets the time to be used when checking this source. The advantage of
3778 * calling this function over calling g_get_monotonic_time() directly is
3779 * that when checking multiple sources, GLib can cache a single value
3780 * instead of having to repeatedly get the system monotonic time.
3782 * The time here is the system monotonic time, if available, or some
3783 * other reasonable alternative otherwise. See g_get_monotonic_time().
3785 * Returns: the monotonic time in microseconds
3790 g_source_get_time (GSource *source)
3792 GMainContext *context;
3795 g_return_val_if_fail (source->context != NULL, 0);
3797 context = source->context;
3799 LOCK_CONTEXT (context);
3801 if (!context->time_is_fresh)
3803 context->time = g_get_monotonic_time ();
3804 context->time_is_fresh = TRUE;
3807 result = context->time;
3809 UNLOCK_CONTEXT (context);
3815 * g_main_context_set_poll_func:
3816 * @context: a #GMainContext
3817 * @func: the function to call to poll all file descriptors
3819 * Sets the function to use to handle polling of file descriptors. It
3820 * will be used instead of the poll() system call
3821 * (or GLib's replacement function, which is used where
3822 * poll() isn't available).
3824 * This function could possibly be used to integrate the GLib event
3825 * loop with an external event loop.
3828 g_main_context_set_poll_func (GMainContext *context,
3832 context = g_main_context_default ();
3834 g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
3836 LOCK_CONTEXT (context);
3839 context->poll_func = func;
3841 context->poll_func = g_poll;
3843 UNLOCK_CONTEXT (context);
3847 * g_main_context_get_poll_func:
3848 * @context: a #GMainContext
3850 * Gets the poll function set by g_main_context_set_poll_func().
3852 * Return value: the poll function
3855 g_main_context_get_poll_func (GMainContext *context)
3860 context = g_main_context_default ();
3862 g_return_val_if_fail (g_atomic_int_get (&context->ref_count) > 0, NULL);
3864 LOCK_CONTEXT (context);
3865 result = context->poll_func;
3866 UNLOCK_CONTEXT (context);
3872 * g_main_context_wakeup:
3873 * @context: a #GMainContext
3875 * If @context is currently waiting in a poll(), interrupt
3876 * the poll(), and continue the iteration process.
3879 g_main_context_wakeup (GMainContext *context)
3882 context = g_main_context_default ();
3884 g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
3886 g_wakeup_signal (context->wakeup);
3890 * g_main_context_is_owner:
3891 * @context: a #GMainContext
3893 * Determines whether this thread holds the (recursive)
3894 * ownership of this #GMainContext. This is useful to
3895 * know before waiting on another thread that may be
3896 * blocking to get ownership of @context.
3898 * Returns: %TRUE if current thread is owner of @context.
3903 g_main_context_is_owner (GMainContext *context)
3908 context = g_main_context_default ();
3910 LOCK_CONTEXT (context);
3911 is_owner = context->owner == G_THREAD_SELF;
3912 UNLOCK_CONTEXT (context);
3920 g_timeout_set_expiration (GTimeoutSource *timeout_source,
3921 gint64 current_time)
3923 timeout_source->expiration = current_time +
3924 (guint64) timeout_source->interval * 1000;
3926 if (timeout_source->seconds)
3929 static gint timer_perturb = -1;
3931 if (timer_perturb == -1)
3934 * we want a per machine/session unique 'random' value; try the dbus
3935 * address first, that has a UUID in it. If there is no dbus, use the
3936 * hostname for hashing.
3938 const char *session_bus_address = g_getenv ("DBUS_SESSION_BUS_ADDRESS");
3939 if (!session_bus_address)
3940 session_bus_address = g_getenv ("HOSTNAME");
3941 if (session_bus_address)
3942 timer_perturb = ABS ((gint) g_str_hash (session_bus_address)) % 1000000;
3947 /* We want the microseconds part of the timeout to land on the
3948 * 'timer_perturb' mark, but we need to make sure we don't try to
3949 * set the timeout in the past. We do this by ensuring that we
3950 * always only *increase* the expiration time by adding a full
3951 * second in the case that the microsecond portion decreases.
3953 timeout_source->expiration -= timer_perturb;
3955 remainder = timeout_source->expiration % 1000000;
3956 if (remainder >= 1000000/4)
3957 timeout_source->expiration += 1000000;
3959 timeout_source->expiration -= remainder;
3960 timeout_source->expiration += timer_perturb;
3965 g_timeout_prepare (GSource *source,
3968 GTimeoutSource *timeout_source = (GTimeoutSource *) source;
3969 gint64 now = g_source_get_time (source);
3971 if (now < timeout_source->expiration)
3973 /* Round up to ensure that we don't try again too early */
3974 *timeout = (timeout_source->expiration - now + 999) / 1000;
3983 g_timeout_check (GSource *source)
3985 GTimeoutSource *timeout_source = (GTimeoutSource *) source;
3986 gint64 now = g_source_get_time (source);
3988 return timeout_source->expiration <= now;
3992 g_timeout_dispatch (GSource *source,
3993 GSourceFunc callback,
3996 GTimeoutSource *timeout_source = (GTimeoutSource *)source;
4001 g_warning ("Timeout source dispatched without callback\n"
4002 "You must call g_source_set_callback().");
4006 again = callback (user_data);
4009 g_timeout_set_expiration (timeout_source, g_source_get_time (source));
4015 * g_timeout_source_new:
4016 * @interval: the timeout interval in milliseconds.
4018 * Creates a new timeout source.
4020 * The source will not initially be associated with any #GMainContext
4021 * and must be added to one with g_source_attach() before it will be
4024 * The interval given is in terms of monotonic time, not wall clock
4025 * time. See g_get_monotonic_time().
4027 * Return value: the newly-created timeout source
4030 g_timeout_source_new (guint interval)
4032 GSource *source = g_source_new (&g_timeout_funcs, sizeof (GTimeoutSource));
4033 GTimeoutSource *timeout_source = (GTimeoutSource *)source;
4035 timeout_source->interval = interval;
4036 g_timeout_set_expiration (timeout_source, g_get_monotonic_time ());
4042 * g_timeout_source_new_seconds:
4043 * @interval: the timeout interval in seconds
4045 * Creates a new timeout source.
4047 * The source will not initially be associated with any #GMainContext
4048 * and must be added to one with g_source_attach() before it will be
4051 * The scheduling granularity/accuracy of this timeout source will be
4054 * The interval given in terms of monotonic time, not wall clock time.
4055 * See g_get_monotonic_time().
4057 * Return value: the newly-created timeout source
4062 g_timeout_source_new_seconds (guint interval)
4064 GSource *source = g_source_new (&g_timeout_funcs, sizeof (GTimeoutSource));
4065 GTimeoutSource *timeout_source = (GTimeoutSource *)source;
4067 timeout_source->interval = 1000 * interval;
4068 timeout_source->seconds = TRUE;
4070 g_timeout_set_expiration (timeout_source, g_get_monotonic_time ());
4077 * g_timeout_add_full:
4078 * @priority: the priority of the timeout source. Typically this will be in
4079 * the range between #G_PRIORITY_DEFAULT and #G_PRIORITY_HIGH.
4080 * @interval: the time between calls to the function, in milliseconds
4081 * (1/1000ths of a second)
4082 * @function: function to call
4083 * @data: data to pass to @function
4084 * @notify: (allow-none): function to call when the timeout is removed, or %NULL
4086 * Sets a function to be called at regular intervals, with the given
4087 * priority. The function is called repeatedly until it returns
4088 * %FALSE, at which point the timeout is automatically destroyed and
4089 * the function will not be called again. The @notify function is
4090 * called when the timeout is destroyed. The first call to the
4091 * function will be at the end of the first @interval.
4093 * Note that timeout functions may be delayed, due to the processing of other
4094 * event sources. Thus they should not be relied on for precise timing.
4095 * After each call to the timeout function, the time of the next
4096 * timeout is recalculated based on the current time and the given interval
4097 * (it does not try to 'catch up' time lost in delays).
4099 * This internally creates a main loop source using g_timeout_source_new()
4100 * and attaches it to the main loop context using g_source_attach(). You can
4101 * do these steps manually if you need greater control.
4103 * The interval given in terms of monotonic time, not wall clock time.
4104 * See g_get_monotonic_time().
4106 * Return value: the ID (greater than 0) of the event source.
4107 * Rename to: g_timeout_add
4110 g_timeout_add_full (gint priority,
4112 GSourceFunc function,
4114 GDestroyNotify notify)
4119 g_return_val_if_fail (function != NULL, 0);
4121 source = g_timeout_source_new (interval);
4123 if (priority != G_PRIORITY_DEFAULT)
4124 g_source_set_priority (source, priority);
4126 g_source_set_callback (source, function, data, notify);
4127 id = g_source_attach (source, NULL);
4128 g_source_unref (source);
4135 * @interval: the time between calls to the function, in milliseconds
4136 * (1/1000ths of a second)
4137 * @function: function to call
4138 * @data: data to pass to @function
4140 * Sets a function to be called at regular intervals, with the default
4141 * priority, #G_PRIORITY_DEFAULT. The function is called repeatedly
4142 * until it returns %FALSE, at which point the timeout is automatically
4143 * destroyed and the function will not be called again. The first call
4144 * to the function will be at the end of the first @interval.
4146 * Note that timeout functions may be delayed, due to the processing of other
4147 * event sources. Thus they should not be relied on for precise timing.
4148 * After each call to the timeout function, the time of the next
4149 * timeout is recalculated based on the current time and the given interval
4150 * (it does not try to 'catch up' time lost in delays).
4152 * If you want to have a timer in the "seconds" range and do not care
4153 * about the exact time of the first call of the timer, use the
4154 * g_timeout_add_seconds() function; this function allows for more
4155 * optimizations and more efficient system power usage.
4157 * This internally creates a main loop source using g_timeout_source_new()
4158 * and attaches it to the main loop context using g_source_attach(). You can
4159 * do these steps manually if you need greater control.
4161 * The interval given is in terms of monotonic time, not wall clock
4162 * time. See g_get_monotonic_time().
4164 * Return value: the ID (greater than 0) of the event source.
4167 g_timeout_add (guint32 interval,
4168 GSourceFunc function,
4171 return g_timeout_add_full (G_PRIORITY_DEFAULT,
4172 interval, function, data, NULL);
4176 * g_timeout_add_seconds_full:
4177 * @priority: the priority of the timeout source. Typically this will be in
4178 * the range between #G_PRIORITY_DEFAULT and #G_PRIORITY_HIGH.
4179 * @interval: the time between calls to the function, in seconds
4180 * @function: function to call
4181 * @data: data to pass to @function
4182 * @notify: (allow-none): function to call when the timeout is removed, or %NULL
4184 * Sets a function to be called at regular intervals, with @priority.
4185 * The function is called repeatedly until it returns %FALSE, at which
4186 * point the timeout is automatically destroyed and the function will
4187 * not be called again.
4189 * Unlike g_timeout_add(), this function operates at whole second granularity.
4190 * The initial starting point of the timer is determined by the implementation
4191 * and the implementation is expected to group multiple timers together so that
4192 * they fire all at the same time.
4193 * To allow this grouping, the @interval to the first timer is rounded
4194 * and can deviate up to one second from the specified interval.
4195 * Subsequent timer iterations will generally run at the specified interval.
4197 * Note that timeout functions may be delayed, due to the processing of other
4198 * event sources. Thus they should not be relied on for precise timing.
4199 * After each call to the timeout function, the time of the next
4200 * timeout is recalculated based on the current time and the given @interval
4202 * If you want timing more precise than whole seconds, use g_timeout_add()
4205 * The grouping of timers to fire at the same time results in a more power
4206 * and CPU efficient behavior so if your timer is in multiples of seconds
4207 * and you don't require the first timer exactly one second from now, the
4208 * use of g_timeout_add_seconds() is preferred over g_timeout_add().
4210 * This internally creates a main loop source using
4211 * g_timeout_source_new_seconds() and attaches it to the main loop context
4212 * using g_source_attach(). You can do these steps manually if you need
4215 * The interval given is in terms of monotonic time, not wall clock
4216 * time. See g_get_monotonic_time().
4218 * Return value: the ID (greater than 0) of the event source.
4220 * Rename to: g_timeout_add_seconds
4224 g_timeout_add_seconds_full (gint priority,
4226 GSourceFunc function,
4228 GDestroyNotify notify)
4233 g_return_val_if_fail (function != NULL, 0);
4235 source = g_timeout_source_new_seconds (interval);
4237 if (priority != G_PRIORITY_DEFAULT)
4238 g_source_set_priority (source, priority);
4240 g_source_set_callback (source, function, data, notify);
4241 id = g_source_attach (source, NULL);
4242 g_source_unref (source);
4248 * g_timeout_add_seconds:
4249 * @interval: the time between calls to the function, in seconds
4250 * @function: function to call
4251 * @data: data to pass to @function
4253 * Sets a function to be called at regular intervals with the default
4254 * priority, #G_PRIORITY_DEFAULT. The function is called repeatedly until
4255 * it returns %FALSE, at which point the timeout is automatically destroyed
4256 * and the function will not be called again.
4258 * This internally creates a main loop source using
4259 * g_timeout_source_new_seconds() and attaches it to the main loop context
4260 * using g_source_attach(). You can do these steps manually if you need
4261 * greater control. Also see g_timeout_add_seconds_full().
4263 * Note that the first call of the timer may not be precise for timeouts
4264 * of one second. If you need finer precision and have such a timeout,
4265 * you may want to use g_timeout_add() instead.
4267 * The interval given is in terms of monotonic time, not wall clock
4268 * time. See g_get_monotonic_time().
4270 * Return value: the ID (greater than 0) of the event source.
4275 g_timeout_add_seconds (guint interval,
4276 GSourceFunc function,
4279 g_return_val_if_fail (function != NULL, 0);
4281 return g_timeout_add_seconds_full (G_PRIORITY_DEFAULT, interval, function, data, NULL);
4284 /* Child watch functions */
4289 g_child_watch_prepare (GSource *source,
4297 g_child_watch_check (GSource *source)
4299 GChildWatchSource *child_watch_source;
4300 gboolean child_exited;
4302 child_watch_source = (GChildWatchSource *) source;
4304 child_exited = child_watch_source->poll.revents & G_IO_IN;
4311 * Note: We do _not_ check for the special value of STILL_ACTIVE
4312 * since we know that the process has exited and doing so runs into
4313 * problems if the child process "happens to return STILL_ACTIVE(259)"
4314 * as Microsoft's Platform SDK puts it.
4316 if (!GetExitCodeProcess (child_watch_source->pid, &child_status))
4318 gchar *emsg = g_win32_error_message (GetLastError ());
4319 g_warning (G_STRLOC ": GetExitCodeProcess() failed: %s", emsg);
4322 child_watch_source->child_status = -1;
4325 child_watch_source->child_status = child_status;
4328 return child_exited;
4332 g_child_watch_finalize (GSource *source)
4336 #else /* G_OS_WIN32 */
4339 wake_source (GSource *source)
4341 GMainContext *context;
4343 /* This should be thread-safe:
4345 * - if the source is currently being added to a context, that
4346 * context will be woken up anyway
4348 * - if the source is currently being destroyed, we simply need not
4351 * - the memory for the source will remain valid until after the
4352 * source finalize function was called (which would remove the
4353 * source from the global list which we are currently holding the
4356 * - the GMainContext will either be NULL or point to a live
4359 * - the GMainContext will remain valid since we hold the
4360 * main_context_list lock
4362 * Since we are holding a lot of locks here, don't try to enter any
4363 * more GMainContext functions for fear of dealock -- just hit the
4364 * GWakeup and run. Even if that's safe now, it could easily become
4365 * unsafe with some very minor changes in the future, and signal
4366 * handling is not the most well-tested codepath.
4368 G_LOCK(main_context_list);
4369 context = source->context;
4371 g_wakeup_signal (context->wakeup);
4372 G_UNLOCK(main_context_list);
4376 dispatch_unix_signals (void)
4380 /* clear this first incase another one arrives while we're processing */
4381 any_unix_signal_pending = FALSE;
4383 G_LOCK(unix_signal_lock);
4385 /* handle GChildWatchSource instances */
4386 if (unix_signal_pending[SIGCHLD])
4388 unix_signal_pending[SIGCHLD] = FALSE;
4390 /* The only way we can do this is to scan all of the children.
4392 * The docs promise that we will not reap children that we are not
4393 * explicitly watching, so that ties our hands from calling
4394 * waitpid(-1). We also can't use siginfo's si_pid field since if
4395 * multiple SIGCHLD arrive at the same time, one of them can be
4396 * dropped (since a given UNIX signal can only be pending once).
4398 for (node = unix_child_watches; node; node = node->next)
4400 GChildWatchSource *source = node->data;
4402 if (!source->child_exited)
4404 if (waitpid (source->pid, &source->child_status, WNOHANG) > 0)
4406 source->child_exited = TRUE;
4408 wake_source ((GSource *) source);
4414 /* handle GUnixSignalWatchSource instances */
4415 for (node = unix_signal_watches; node; node = node->next)
4417 GUnixSignalWatchSource *source = node->data;
4419 if (!source->pending)
4421 if (unix_signal_pending[source->signum])
4423 unix_signal_pending[source->signum] = FALSE;
4424 source->pending = TRUE;
4426 wake_source ((GSource *) source);
4431 G_UNLOCK(unix_signal_lock);
4435 g_child_watch_prepare (GSource *source,
4438 GChildWatchSource *child_watch_source;
4440 child_watch_source = (GChildWatchSource *) source;
4442 return child_watch_source->child_exited;
4446 g_child_watch_check (GSource *source)
4448 GChildWatchSource *child_watch_source;
4450 child_watch_source = (GChildWatchSource *) source;
4452 return child_watch_source->child_exited;
4456 g_unix_signal_watch_prepare (GSource *source,
4459 GUnixSignalWatchSource *unix_signal_source;
4461 unix_signal_source = (GUnixSignalWatchSource *) source;
4463 return unix_signal_source->pending;
4467 g_unix_signal_watch_check (GSource *source)
4469 GUnixSignalWatchSource *unix_signal_source;
4471 unix_signal_source = (GUnixSignalWatchSource *) source;
4473 return unix_signal_source->pending;
4477 g_unix_signal_watch_dispatch (GSource *source,
4478 GSourceFunc callback,
4481 GUnixSignalWatchSource *unix_signal_source;
4483 unix_signal_source = (GUnixSignalWatchSource *) source;
4487 g_warning ("Unix signal source dispatched without callback\n"
4488 "You must call g_source_set_callback().");
4492 (callback) (user_data);
4494 unix_signal_source->pending = FALSE;
4500 ensure_unix_signal_handler_installed_unlocked (int signum)
4502 static sigset_t installed_signal_mask;
4503 static gboolean initialized;
4504 struct sigaction action;
4508 sigemptyset (&installed_signal_mask);
4509 g_get_worker_context ();
4513 if (sigismember (&installed_signal_mask, signum))
4516 sigaddset (&installed_signal_mask, signum);
4518 action.sa_handler = g_unix_signal_handler;
4519 sigemptyset (&action.sa_mask);
4520 action.sa_flags = SA_RESTART | SA_NOCLDSTOP;
4521 sigaction (signum, &action, NULL);
4525 _g_main_create_unix_signal_watch (int signum)
4528 GUnixSignalWatchSource *unix_signal_source;
4530 source = g_source_new (&g_unix_signal_funcs, sizeof (GUnixSignalWatchSource));
4531 unix_signal_source = (GUnixSignalWatchSource *) source;
4533 unix_signal_source->signum = signum;
4534 unix_signal_source->pending = FALSE;
4536 G_LOCK (unix_signal_lock);
4537 ensure_unix_signal_handler_installed_unlocked (signum);
4538 unix_signal_watches = g_slist_prepend (unix_signal_watches, unix_signal_source);
4539 if (unix_signal_pending[signum])
4540 unix_signal_source->pending = TRUE;
4541 unix_signal_pending[signum] = FALSE;
4542 G_UNLOCK (unix_signal_lock);
4548 g_unix_signal_watch_finalize (GSource *source)
4550 G_LOCK (unix_signal_lock);
4551 unix_signal_watches = g_slist_remove (unix_signal_watches, source);
4552 G_UNLOCK (unix_signal_lock);
4556 g_child_watch_finalize (GSource *source)
4558 G_LOCK (unix_signal_lock);
4559 unix_child_watches = g_slist_remove (unix_child_watches, source);
4560 G_UNLOCK (unix_signal_lock);
4563 #endif /* G_OS_WIN32 */
4566 g_child_watch_dispatch (GSource *source,
4567 GSourceFunc callback,
4570 GChildWatchSource *child_watch_source;
4571 GChildWatchFunc child_watch_callback = (GChildWatchFunc) callback;
4573 child_watch_source = (GChildWatchSource *) source;
4577 g_warning ("Child watch source dispatched without callback\n"
4578 "You must call g_source_set_callback().");
4582 (child_watch_callback) (child_watch_source->pid, child_watch_source->child_status, user_data);
4584 /* We never keep a child watch source around as the child is gone */
4591 g_unix_signal_handler (int signum)
4593 unix_signal_pending[signum] = TRUE;
4594 any_unix_signal_pending = TRUE;
4596 g_wakeup_signal (glib_worker_context->wakeup);
4599 #endif /* !G_OS_WIN32 */
4602 * g_child_watch_source_new:
4603 * @pid: process to watch. On POSIX the pid of a child process. On
4604 * Windows a handle for a process (which doesn't have to be a child).
4606 * Creates a new child_watch source.
4608 * The source will not initially be associated with any #GMainContext
4609 * and must be added to one with g_source_attach() before it will be
4612 * Note that child watch sources can only be used in conjunction with
4613 * <literal>g_spawn...</literal> when the %G_SPAWN_DO_NOT_REAP_CHILD
4616 * Note that on platforms where #GPid must be explicitly closed
4617 * (see g_spawn_close_pid()) @pid must not be closed while the
4618 * source is still active. Typically, you will want to call
4619 * g_spawn_close_pid() in the callback function for the source.
4621 * Note further that using g_child_watch_source_new() is not
4622 * compatible with calling <literal>waitpid(-1)</literal> in
4623 * the application. Calling waitpid() for individual pids will
4626 * Return value: the newly-created child watch source
4631 g_child_watch_source_new (GPid pid)
4633 GSource *source = g_source_new (&g_child_watch_funcs, sizeof (GChildWatchSource));
4634 GChildWatchSource *child_watch_source = (GChildWatchSource *)source;
4636 child_watch_source->pid = pid;
4639 child_watch_source->poll.fd = (gintptr) pid;
4640 child_watch_source->poll.events = G_IO_IN;
4642 g_source_add_poll (source, &child_watch_source->poll);
4643 #else /* G_OS_WIN32 */
4644 G_LOCK (unix_signal_lock);
4645 ensure_unix_signal_handler_installed_unlocked (SIGCHLD);
4646 unix_child_watches = g_slist_prepend (unix_child_watches, child_watch_source);
4647 if (waitpid (pid, &child_watch_source->child_status, WNOHANG) > 0)
4648 child_watch_source->child_exited = TRUE;
4649 G_UNLOCK (unix_signal_lock);
4650 #endif /* G_OS_WIN32 */
4656 * g_child_watch_add_full:
4657 * @priority: the priority of the idle source. Typically this will be in the
4658 * range between #G_PRIORITY_DEFAULT_IDLE and #G_PRIORITY_HIGH_IDLE.
4659 * @pid: process to watch. On POSIX the pid of a child process. On
4660 * Windows a handle for a process (which doesn't have to be a child).
4661 * @function: function to call
4662 * @data: data to pass to @function
4663 * @notify: (allow-none): function to call when the idle is removed, or %NULL
4665 * Sets a function to be called when the child indicated by @pid
4666 * exits, at the priority @priority.
4668 * If you obtain @pid from g_spawn_async() or g_spawn_async_with_pipes()
4669 * you will need to pass #G_SPAWN_DO_NOT_REAP_CHILD as flag to
4670 * the spawn function for the child watching to work.
4672 * In many programs, you will want to call g_spawn_check_exit_status()
4673 * in the callback to determine whether or not the child exited
4676 * Also, note that on platforms where #GPid must be explicitly closed
4677 * (see g_spawn_close_pid()) @pid must not be closed while the source
4678 * is still active. Typically, you should invoke g_spawn_close_pid()
4679 * in the callback function for the source.
4681 * GLib supports only a single callback per process id.
4683 * This internally creates a main loop source using
4684 * g_child_watch_source_new() and attaches it to the main loop context
4685 * using g_source_attach(). You can do these steps manually if you
4686 * need greater control.
4688 * Return value: the ID (greater than 0) of the event source.
4690 * Rename to: g_child_watch_add
4694 g_child_watch_add_full (gint priority,
4696 GChildWatchFunc function,
4698 GDestroyNotify notify)
4703 g_return_val_if_fail (function != NULL, 0);
4705 source = g_child_watch_source_new (pid);
4707 if (priority != G_PRIORITY_DEFAULT)
4708 g_source_set_priority (source, priority);
4710 g_source_set_callback (source, (GSourceFunc) function, data, notify);
4711 id = g_source_attach (source, NULL);
4712 g_source_unref (source);
4718 * g_child_watch_add:
4719 * @pid: process id to watch. On POSIX the pid of a child process. On
4720 * Windows a handle for a process (which doesn't have to be a child).
4721 * @function: function to call
4722 * @data: data to pass to @function
4724 * Sets a function to be called when the child indicated by @pid
4725 * exits, at a default priority, #G_PRIORITY_DEFAULT.
4727 * If you obtain @pid from g_spawn_async() or g_spawn_async_with_pipes()
4728 * you will need to pass #G_SPAWN_DO_NOT_REAP_CHILD as flag to
4729 * the spawn function for the child watching to work.
4731 * Note that on platforms where #GPid must be explicitly closed
4732 * (see g_spawn_close_pid()) @pid must not be closed while the
4733 * source is still active. Typically, you will want to call
4734 * g_spawn_close_pid() in the callback function for the source.
4736 * GLib supports only a single callback per process id.
4738 * This internally creates a main loop source using
4739 * g_child_watch_source_new() and attaches it to the main loop context
4740 * using g_source_attach(). You can do these steps manually if you
4741 * need greater control.
4743 * Return value: the ID (greater than 0) of the event source.
4748 g_child_watch_add (GPid pid,
4749 GChildWatchFunc function,
4752 return g_child_watch_add_full (G_PRIORITY_DEFAULT, pid, function, data, NULL);
4756 /* Idle functions */
4759 g_idle_prepare (GSource *source,
4768 g_idle_check (GSource *source)
4774 g_idle_dispatch (GSource *source,
4775 GSourceFunc callback,
4780 g_warning ("Idle source dispatched without callback\n"
4781 "You must call g_source_set_callback().");
4785 return callback (user_data);
4789 * g_idle_source_new:
4791 * Creates a new idle source.
4793 * The source will not initially be associated with any #GMainContext
4794 * and must be added to one with g_source_attach() before it will be
4795 * executed. Note that the default priority for idle sources is
4796 * %G_PRIORITY_DEFAULT_IDLE, as compared to other sources which
4797 * have a default priority of %G_PRIORITY_DEFAULT.
4799 * Return value: the newly-created idle source
4802 g_idle_source_new (void)
4806 source = g_source_new (&g_idle_funcs, sizeof (GSource));
4807 g_source_set_priority (source, G_PRIORITY_DEFAULT_IDLE);
4814 * @priority: the priority of the idle source. Typically this will be in the
4815 * range between #G_PRIORITY_DEFAULT_IDLE and #G_PRIORITY_HIGH_IDLE.
4816 * @function: function to call
4817 * @data: data to pass to @function
4818 * @notify: (allow-none): function to call when the idle is removed, or %NULL
4820 * Adds a function to be called whenever there are no higher priority
4821 * events pending. If the function returns %FALSE it is automatically
4822 * removed from the list of event sources and will not be called again.
4824 * This internally creates a main loop source using g_idle_source_new()
4825 * and attaches it to the main loop context using g_source_attach().
4826 * You can do these steps manually if you need greater control.
4828 * Return value: the ID (greater than 0) of the event source.
4829 * Rename to: g_idle_add
4832 g_idle_add_full (gint priority,
4833 GSourceFunc function,
4835 GDestroyNotify notify)
4840 g_return_val_if_fail (function != NULL, 0);
4842 source = g_idle_source_new ();
4844 if (priority != G_PRIORITY_DEFAULT_IDLE)
4845 g_source_set_priority (source, priority);
4847 g_source_set_callback (source, function, data, notify);
4848 id = g_source_attach (source, NULL);
4849 g_source_unref (source);
4856 * @function: function to call
4857 * @data: data to pass to @function.
4859 * Adds a function to be called whenever there are no higher priority
4860 * events pending to the default main loop. The function is given the
4861 * default idle priority, #G_PRIORITY_DEFAULT_IDLE. If the function
4862 * returns %FALSE it is automatically removed from the list of event
4863 * sources and will not be called again.
4865 * This internally creates a main loop source using g_idle_source_new()
4866 * and attaches it to the main loop context using g_source_attach().
4867 * You can do these steps manually if you need greater control.
4869 * Return value: the ID (greater than 0) of the event source.
4872 g_idle_add (GSourceFunc function,
4875 return g_idle_add_full (G_PRIORITY_DEFAULT_IDLE, function, data, NULL);
4879 * g_idle_remove_by_data:
4880 * @data: the data for the idle source's callback.
4882 * Removes the idle function with the given data.
4884 * Return value: %TRUE if an idle source was found and removed.
4887 g_idle_remove_by_data (gpointer data)
4889 return g_source_remove_by_funcs_user_data (&g_idle_funcs, data);
4893 * g_main_context_invoke:
4894 * @context: (allow-none): a #GMainContext, or %NULL
4895 * @function: function to call
4896 * @data: data to pass to @function
4898 * Invokes a function in such a way that @context is owned during the
4899 * invocation of @function.
4901 * If @context is %NULL then the global default main context — as
4902 * returned by g_main_context_default() — is used.
4904 * If @context is owned by the current thread, @function is called
4905 * directly. Otherwise, if @context is the thread-default main context
4906 * of the current thread and g_main_context_acquire() succeeds, then
4907 * @function is called and g_main_context_release() is called
4910 * In any other case, an idle source is created to call @function and
4911 * that source is attached to @context (presumably to be run in another
4912 * thread). The idle source is attached with #G_PRIORITY_DEFAULT
4913 * priority. If you want a different priority, use
4914 * g_main_context_invoke_full().
4916 * Note that, as with normal idle functions, @function should probably
4917 * return %FALSE. If it returns %TRUE, it will be continuously run in a
4918 * loop (and may prevent this call from returning).
4923 g_main_context_invoke (GMainContext *context,
4924 GSourceFunc function,
4927 g_main_context_invoke_full (context,
4929 function, data, NULL);
4933 * g_main_context_invoke_full:
4934 * @context: (allow-none): a #GMainContext, or %NULL
4935 * @priority: the priority at which to run @function
4936 * @function: function to call
4937 * @data: data to pass to @function
4938 * @notify: (allow-none): a function to call when @data is no longer in use, or %NULL.
4940 * Invokes a function in such a way that @context is owned during the
4941 * invocation of @function.
4943 * This function is the same as g_main_context_invoke() except that it
4944 * lets you specify the priority incase @function ends up being
4945 * scheduled as an idle and also lets you give a #GDestroyNotify for @data.
4947 * @notify should not assume that it is called from any particular
4948 * thread or with any particular context acquired.
4953 g_main_context_invoke_full (GMainContext *context,
4955 GSourceFunc function,
4957 GDestroyNotify notify)
4959 g_return_if_fail (function != NULL);
4962 context = g_main_context_default ();
4964 if (g_main_context_is_owner (context))
4966 while (function (data));
4973 GMainContext *thread_default;
4975 thread_default = g_main_context_get_thread_default ();
4977 if (!thread_default)
4978 thread_default = g_main_context_default ();
4980 if (thread_default == context && g_main_context_acquire (context))
4982 while (function (data));
4984 g_main_context_release (context);
4993 source = g_idle_source_new ();
4994 g_source_set_priority (source, priority);
4995 g_source_set_callback (source, function, data, notify);
4996 g_source_attach (source, context);
4997 g_source_unref (source);
5003 glib_worker_main (gpointer data)
5007 g_main_context_iteration (glib_worker_context, TRUE);
5010 if (any_unix_signal_pending)
5011 dispatch_unix_signals ();
5015 return NULL; /* worst GCC warning message ever... */
5019 g_get_worker_context (void)
5021 static gsize initialised;
5023 if (g_once_init_enter (&initialised))
5025 /* mask all signals in the worker thread */
5031 pthread_sigmask (SIG_SETMASK, &all, &prev_mask);
5033 glib_worker_context = g_main_context_new ();
5034 g_thread_new ("gmain", glib_worker_main, NULL);
5036 pthread_sigmask (SIG_SETMASK, &prev_mask, NULL);
5038 g_once_init_leave (&initialised, TRUE);
5041 return glib_worker_context;