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))
1094 GSList *sources, *tmp_list;
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 sources = tmp_list = source->priv->child_sources;
1126 source->priv->child_sources = NULL;
1129 g_source_destroy_internal (tmp_list->data, context, TRUE);
1130 g_source_unref_internal (tmp_list->data, context, TRUE);
1131 tmp_list = tmp_list->next;
1133 g_slist_free (sources);
1136 if (source->priv->parent_source)
1138 GSource *parent = source->priv->parent_source;
1140 parent->priv->child_sources =
1141 g_slist_remove (parent->priv->child_sources, source);
1142 source->priv->parent_source = NULL;
1145 g_source_unref_internal (source, context, TRUE);
1149 UNLOCK_CONTEXT (context);
1154 * @source: a #GSource
1156 * Removes a source from its #GMainContext, if any, and mark it as
1157 * destroyed. The source cannot be subsequently added to another
1161 g_source_destroy (GSource *source)
1163 GMainContext *context;
1165 g_return_if_fail (source != NULL);
1167 context = source->context;
1170 g_source_destroy_internal (source, context, FALSE);
1172 source->flags &= ~G_HOOK_FLAG_ACTIVE;
1177 * @source: a #GSource
1179 * Returns the numeric ID for a particular source. The ID of a source
1180 * is a positive integer which is unique within a particular main loop
1181 * context. The reverse
1182 * mapping from ID to source is done by g_main_context_find_source_by_id().
1184 * Return value: the ID (greater than 0) for the source
1187 g_source_get_id (GSource *source)
1191 g_return_val_if_fail (source != NULL, 0);
1192 g_return_val_if_fail (source->context != NULL, 0);
1194 LOCK_CONTEXT (source->context);
1195 result = source->source_id;
1196 UNLOCK_CONTEXT (source->context);
1202 * g_source_get_context:
1203 * @source: a #GSource
1205 * Gets the #GMainContext with which the source is associated.
1206 * Calling this function on a destroyed source is an error.
1208 * Return value: (transfer none) (allow-none): the #GMainContext with which the
1209 * source is associated, or %NULL if the context has not
1210 * yet been added to a source.
1213 g_source_get_context (GSource *source)
1215 g_return_val_if_fail (!SOURCE_DESTROYED (source), NULL);
1217 return source->context;
1221 * g_source_add_poll:
1222 * @source:a #GSource
1223 * @fd: a #GPollFD structure holding information about a file
1224 * descriptor to watch.
1226 * Adds a file descriptor to the set of file descriptors polled for
1227 * this source. This is usually combined with g_source_new() to add an
1228 * event source. The event source's check function will typically test
1229 * the @revents field in the #GPollFD struct and return %TRUE if events need
1233 g_source_add_poll (GSource *source,
1236 GMainContext *context;
1238 g_return_if_fail (source != NULL);
1239 g_return_if_fail (fd != NULL);
1240 g_return_if_fail (!SOURCE_DESTROYED (source));
1242 context = source->context;
1245 LOCK_CONTEXT (context);
1247 source->poll_fds = g_slist_prepend (source->poll_fds, fd);
1251 if (!SOURCE_BLOCKED (source))
1252 g_main_context_add_poll_unlocked (context, source->priority, fd);
1253 UNLOCK_CONTEXT (context);
1258 * g_source_remove_poll:
1259 * @source:a #GSource
1260 * @fd: a #GPollFD structure previously passed to g_source_add_poll().
1262 * Removes a file descriptor from the set of file descriptors polled for
1266 g_source_remove_poll (GSource *source,
1269 GMainContext *context;
1271 g_return_if_fail (source != NULL);
1272 g_return_if_fail (fd != NULL);
1273 g_return_if_fail (!SOURCE_DESTROYED (source));
1275 context = source->context;
1278 LOCK_CONTEXT (context);
1280 source->poll_fds = g_slist_remove (source->poll_fds, fd);
1284 if (!SOURCE_BLOCKED (source))
1285 g_main_context_remove_poll_unlocked (context, fd);
1286 UNLOCK_CONTEXT (context);
1291 * g_source_add_child_source:
1292 * @source:a #GSource
1293 * @child_source: a second #GSource that @source should "poll"
1295 * Adds @child_source to @source as a "polled" source; when @source is
1296 * added to a #GMainContext, @child_source will be automatically added
1297 * with the same priority, when @child_source is triggered, it will
1298 * cause @source to dispatch (in addition to calling its own
1299 * callback), and when @source is destroyed, it will destroy
1300 * @child_source as well. (@source will also still be dispatched if
1301 * its own prepare/check functions indicate that it is ready.)
1303 * If you don't need @child_source to do anything on its own when it
1304 * triggers, you can call g_source_set_dummy_callback() on it to set a
1305 * callback that does nothing (except return %TRUE if appropriate).
1307 * @source will hold a reference on @child_source while @child_source
1308 * is attached to it.
1313 g_source_add_child_source (GSource *source,
1314 GSource *child_source)
1316 GMainContext *context;
1318 g_return_if_fail (source != NULL);
1319 g_return_if_fail (child_source != NULL);
1320 g_return_if_fail (!SOURCE_DESTROYED (source));
1321 g_return_if_fail (!SOURCE_DESTROYED (child_source));
1322 g_return_if_fail (child_source->context == NULL);
1323 g_return_if_fail (child_source->priv->parent_source == NULL);
1325 context = source->context;
1328 LOCK_CONTEXT (context);
1330 source->priv->child_sources = g_slist_prepend (source->priv->child_sources,
1331 g_source_ref (child_source));
1332 child_source->priv->parent_source = source;
1333 g_source_set_priority_unlocked (child_source, NULL, source->priority);
1334 if (SOURCE_BLOCKED (source))
1335 block_source (child_source);
1339 UNLOCK_CONTEXT (context);
1340 g_source_attach (child_source, context);
1345 * g_source_remove_child_source:
1346 * @source:a #GSource
1347 * @child_source: a #GSource previously passed to
1348 * g_source_add_child_source().
1350 * Detaches @child_source from @source and destroys it.
1355 g_source_remove_child_source (GSource *source,
1356 GSource *child_source)
1358 GMainContext *context;
1360 g_return_if_fail (source != NULL);
1361 g_return_if_fail (child_source != NULL);
1362 g_return_if_fail (child_source->priv->parent_source == source);
1363 g_return_if_fail (!SOURCE_DESTROYED (source));
1364 g_return_if_fail (!SOURCE_DESTROYED (child_source));
1366 context = source->context;
1369 LOCK_CONTEXT (context);
1371 g_source_destroy_internal (child_source, context, TRUE);
1372 g_source_unref_internal (child_source, context, TRUE);
1375 UNLOCK_CONTEXT (context);
1379 * g_source_set_callback_indirect:
1380 * @source: the source
1381 * @callback_data: pointer to callback data "object"
1382 * @callback_funcs: functions for reference counting @callback_data
1383 * and getting the callback and data
1385 * Sets the callback function storing the data as a refcounted callback
1386 * "object". This is used internally. Note that calling
1387 * g_source_set_callback_indirect() assumes
1388 * an initial reference count on @callback_data, and thus
1389 * @callback_funcs->unref will eventually be called once more
1390 * than @callback_funcs->ref.
1393 g_source_set_callback_indirect (GSource *source,
1394 gpointer callback_data,
1395 GSourceCallbackFuncs *callback_funcs)
1397 GMainContext *context;
1398 gpointer old_cb_data;
1399 GSourceCallbackFuncs *old_cb_funcs;
1401 g_return_if_fail (source != NULL);
1402 g_return_if_fail (callback_funcs != NULL || callback_data == NULL);
1404 context = source->context;
1407 LOCK_CONTEXT (context);
1409 old_cb_data = source->callback_data;
1410 old_cb_funcs = source->callback_funcs;
1412 source->callback_data = callback_data;
1413 source->callback_funcs = callback_funcs;
1416 UNLOCK_CONTEXT (context);
1419 old_cb_funcs->unref (old_cb_data);
1423 g_source_callback_ref (gpointer cb_data)
1425 GSourceCallback *callback = cb_data;
1427 callback->ref_count++;
1432 g_source_callback_unref (gpointer cb_data)
1434 GSourceCallback *callback = cb_data;
1436 callback->ref_count--;
1437 if (callback->ref_count == 0)
1439 if (callback->notify)
1440 callback->notify (callback->data);
1446 g_source_callback_get (gpointer cb_data,
1451 GSourceCallback *callback = cb_data;
1453 *func = callback->func;
1454 *data = callback->data;
1457 static GSourceCallbackFuncs g_source_callback_funcs = {
1458 g_source_callback_ref,
1459 g_source_callback_unref,
1460 g_source_callback_get,
1464 * g_source_set_callback:
1465 * @source: the source
1466 * @func: a callback function
1467 * @data: the data to pass to callback function
1468 * @notify: (allow-none): a function to call when @data is no longer in use, or %NULL.
1470 * Sets the callback function for a source. The callback for a source is
1471 * called from the source's dispatch function.
1473 * The exact type of @func depends on the type of source; ie. you
1474 * should not count on @func being called with @data as its first
1477 * Typically, you won't use this function. Instead use functions specific
1478 * to the type of source you are using.
1481 g_source_set_callback (GSource *source,
1484 GDestroyNotify notify)
1486 GSourceCallback *new_callback;
1488 g_return_if_fail (source != NULL);
1490 new_callback = g_new (GSourceCallback, 1);
1492 new_callback->ref_count = 1;
1493 new_callback->func = func;
1494 new_callback->data = data;
1495 new_callback->notify = notify;
1497 g_source_set_callback_indirect (source, new_callback, &g_source_callback_funcs);
1502 * g_source_set_funcs:
1503 * @source: a #GSource
1504 * @funcs: the new #GSourceFuncs
1506 * Sets the source functions (can be used to override
1507 * default implementations) of an unattached source.
1512 g_source_set_funcs (GSource *source,
1513 GSourceFuncs *funcs)
1515 g_return_if_fail (source != NULL);
1516 g_return_if_fail (source->context == NULL);
1517 g_return_if_fail (source->ref_count > 0);
1518 g_return_if_fail (funcs != NULL);
1520 source->source_funcs = funcs;
1524 g_source_set_priority_unlocked (GSource *source,
1525 GMainContext *context,
1530 g_return_if_fail (source->priv->parent_source == NULL ||
1531 source->priv->parent_source->priority == priority);
1535 /* Remove the source from the context's source and then
1536 * add it back after so it is sorted in the correct place
1538 source_remove_from_context (source, source->context);
1541 source->priority = priority;
1545 source_add_to_context (source, source->context);
1547 if (!SOURCE_BLOCKED (source))
1549 tmp_list = source->poll_fds;
1552 g_main_context_remove_poll_unlocked (context, tmp_list->data);
1553 g_main_context_add_poll_unlocked (context, priority, tmp_list->data);
1555 tmp_list = tmp_list->next;
1560 if (source->priv->child_sources)
1562 tmp_list = source->priv->child_sources;
1565 g_source_set_priority_unlocked (tmp_list->data, context, priority);
1566 tmp_list = tmp_list->next;
1572 * g_source_set_priority:
1573 * @source: a #GSource
1574 * @priority: the new priority.
1576 * Sets the priority of a source. While the main loop is being run, a
1577 * source will be dispatched if it is ready to be dispatched and no
1578 * sources at a higher (numerically smaller) priority are ready to be
1582 g_source_set_priority (GSource *source,
1585 GMainContext *context;
1587 g_return_if_fail (source != NULL);
1589 context = source->context;
1592 LOCK_CONTEXT (context);
1593 g_source_set_priority_unlocked (source, context, priority);
1595 UNLOCK_CONTEXT (source->context);
1599 * g_source_get_priority:
1600 * @source: a #GSource
1602 * Gets the priority of a source.
1604 * Return value: the priority of the source
1607 g_source_get_priority (GSource *source)
1609 g_return_val_if_fail (source != NULL, 0);
1611 return source->priority;
1615 * g_source_set_can_recurse:
1616 * @source: a #GSource
1617 * @can_recurse: whether recursion is allowed for this source
1619 * Sets whether a source can be called recursively. If @can_recurse is
1620 * %TRUE, then while the source is being dispatched then this source
1621 * will be processed normally. Otherwise, all processing of this
1622 * source is blocked until the dispatch function returns.
1625 g_source_set_can_recurse (GSource *source,
1626 gboolean can_recurse)
1628 GMainContext *context;
1630 g_return_if_fail (source != NULL);
1632 context = source->context;
1635 LOCK_CONTEXT (context);
1638 source->flags |= G_SOURCE_CAN_RECURSE;
1640 source->flags &= ~G_SOURCE_CAN_RECURSE;
1643 UNLOCK_CONTEXT (context);
1647 * g_source_get_can_recurse:
1648 * @source: a #GSource
1650 * Checks whether a source is allowed to be called recursively.
1651 * see g_source_set_can_recurse().
1653 * Return value: whether recursion is allowed.
1656 g_source_get_can_recurse (GSource *source)
1658 g_return_val_if_fail (source != NULL, FALSE);
1660 return (source->flags & G_SOURCE_CAN_RECURSE) != 0;
1665 * g_source_set_name:
1666 * @source: a #GSource
1667 * @name: debug name for the source
1669 * Sets a name for the source, used in debugging and profiling.
1670 * The name defaults to #NULL.
1672 * The source name should describe in a human-readable way
1673 * what the source does. For example, "X11 event queue"
1674 * or "GTK+ repaint idle handler" or whatever it is.
1676 * It is permitted to call this function multiple times, but is not
1677 * recommended due to the potential performance impact. For example,
1678 * one could change the name in the "check" function of a #GSourceFuncs
1679 * to include details like the event type in the source name.
1684 g_source_set_name (GSource *source,
1687 g_return_if_fail (source != NULL);
1689 /* setting back to NULL is allowed, just because it's
1690 * weird if get_name can return NULL but you can't
1694 g_free (source->name);
1695 source->name = g_strdup (name);
1699 * g_source_get_name:
1700 * @source: a #GSource
1702 * Gets a name for the source, used in debugging and profiling.
1703 * The name may be #NULL if it has never been set with
1704 * g_source_set_name().
1706 * Return value: the name of the source
1710 g_source_get_name (GSource *source)
1712 g_return_val_if_fail (source != NULL, NULL);
1714 return source->name;
1718 * g_source_set_name_by_id:
1719 * @tag: a #GSource ID
1720 * @name: debug name for the source
1722 * Sets the name of a source using its ID.
1724 * This is a convenience utility to set source names from the return
1725 * value of g_idle_add(), g_timeout_add(), etc.
1730 g_source_set_name_by_id (guint tag,
1735 g_return_if_fail (tag > 0);
1737 source = g_main_context_find_source_by_id (NULL, tag);
1741 g_source_set_name (source, name);
1747 * @source: a #GSource
1749 * Increases the reference count on a source by one.
1751 * Return value: @source
1754 g_source_ref (GSource *source)
1756 GMainContext *context;
1758 g_return_val_if_fail (source != NULL, NULL);
1760 context = source->context;
1763 LOCK_CONTEXT (context);
1765 source->ref_count++;
1768 UNLOCK_CONTEXT (context);
1773 /* g_source_unref() but possible to call within context lock
1776 g_source_unref_internal (GSource *source,
1777 GMainContext *context,
1780 gpointer old_cb_data = NULL;
1781 GSourceCallbackFuncs *old_cb_funcs = NULL;
1783 g_return_if_fail (source != NULL);
1785 if (!have_lock && context)
1786 LOCK_CONTEXT (context);
1788 source->ref_count--;
1789 if (source->ref_count == 0)
1791 old_cb_data = source->callback_data;
1792 old_cb_funcs = source->callback_funcs;
1794 source->callback_data = NULL;
1795 source->callback_funcs = NULL;
1799 if (!SOURCE_DESTROYED (source))
1800 g_warning (G_STRLOC ": ref_count == 0, but source was still attached to a context!");
1801 source_remove_from_context (source, context);
1804 if (source->source_funcs->finalize)
1807 UNLOCK_CONTEXT (context);
1808 source->source_funcs->finalize (source);
1810 LOCK_CONTEXT (context);
1813 g_free (source->name);
1814 source->name = NULL;
1816 g_slist_free (source->poll_fds);
1817 source->poll_fds = NULL;
1819 g_slice_free (GSourcePrivate, source->priv);
1820 source->priv = NULL;
1825 if (!have_lock && context)
1826 UNLOCK_CONTEXT (context);
1831 UNLOCK_CONTEXT (context);
1833 old_cb_funcs->unref (old_cb_data);
1836 LOCK_CONTEXT (context);
1842 * @source: a #GSource
1844 * Decreases the reference count of a source by one. If the
1845 * resulting reference count is zero the source and associated
1846 * memory will be destroyed.
1849 g_source_unref (GSource *source)
1851 g_return_if_fail (source != NULL);
1853 g_source_unref_internal (source, source->context, FALSE);
1857 * g_main_context_find_source_by_id:
1858 * @context: (allow-none): a #GMainContext (if %NULL, the default context will be used)
1859 * @source_id: the source ID, as returned by g_source_get_id().
1861 * Finds a #GSource given a pair of context and ID.
1863 * Return value: (transfer none): the #GSource if found, otherwise, %NULL
1866 g_main_context_find_source_by_id (GMainContext *context,
1872 g_return_val_if_fail (source_id > 0, NULL);
1874 if (context == NULL)
1875 context = g_main_context_default ();
1877 LOCK_CONTEXT (context);
1879 g_source_iter_init (&iter, context, FALSE);
1880 while (g_source_iter_next (&iter, &source))
1882 if (!SOURCE_DESTROYED (source) &&
1883 source->source_id == source_id)
1886 g_source_iter_clear (&iter);
1888 UNLOCK_CONTEXT (context);
1894 * g_main_context_find_source_by_funcs_user_data:
1895 * @context: (allow-none): a #GMainContext (if %NULL, the default context will be used).
1896 * @funcs: the @source_funcs passed to g_source_new().
1897 * @user_data: the user data from the callback.
1899 * Finds a source with the given source functions and user data. If
1900 * multiple sources exist with the same source function and user data,
1901 * the first one found will be returned.
1903 * Return value: (transfer none): the source, if one was found, otherwise %NULL
1906 g_main_context_find_source_by_funcs_user_data (GMainContext *context,
1907 GSourceFuncs *funcs,
1913 g_return_val_if_fail (funcs != NULL, NULL);
1915 if (context == NULL)
1916 context = g_main_context_default ();
1918 LOCK_CONTEXT (context);
1920 g_source_iter_init (&iter, context, FALSE);
1921 while (g_source_iter_next (&iter, &source))
1923 if (!SOURCE_DESTROYED (source) &&
1924 source->source_funcs == funcs &&
1925 source->callback_funcs)
1927 GSourceFunc callback;
1928 gpointer callback_data;
1930 source->callback_funcs->get (source->callback_data, source, &callback, &callback_data);
1932 if (callback_data == user_data)
1936 g_source_iter_clear (&iter);
1938 UNLOCK_CONTEXT (context);
1944 * g_main_context_find_source_by_user_data:
1945 * @context: a #GMainContext
1946 * @user_data: the user_data for the callback.
1948 * Finds a source with the given user data for the callback. If
1949 * multiple sources exist with the same user data, the first
1950 * one found will be returned.
1952 * Return value: (transfer none): the source, if one was found, otherwise %NULL
1955 g_main_context_find_source_by_user_data (GMainContext *context,
1961 if (context == NULL)
1962 context = g_main_context_default ();
1964 LOCK_CONTEXT (context);
1966 g_source_iter_init (&iter, context, FALSE);
1967 while (g_source_iter_next (&iter, &source))
1969 if (!SOURCE_DESTROYED (source) &&
1970 source->callback_funcs)
1972 GSourceFunc callback;
1973 gpointer callback_data = NULL;
1975 source->callback_funcs->get (source->callback_data, source, &callback, &callback_data);
1977 if (callback_data == user_data)
1981 g_source_iter_clear (&iter);
1983 UNLOCK_CONTEXT (context);
1990 * @tag: the ID of the source to remove.
1992 * Removes the source with the given id from the default main context.
1994 * a #GSource is given by g_source_get_id(), or will be returned by the
1995 * functions g_source_attach(), g_idle_add(), g_idle_add_full(),
1996 * g_timeout_add(), g_timeout_add_full(), g_child_watch_add(),
1997 * g_child_watch_add_full(), g_io_add_watch(), and g_io_add_watch_full().
1999 * See also g_source_destroy(). You must use g_source_destroy() for sources
2000 * added to a non-default main context.
2002 * Return value: %TRUE if the source was found and removed.
2005 g_source_remove (guint tag)
2009 g_return_val_if_fail (tag > 0, FALSE);
2011 source = g_main_context_find_source_by_id (NULL, tag);
2013 g_source_destroy (source);
2015 return source != NULL;
2019 * g_source_remove_by_user_data:
2020 * @user_data: the user_data for the callback.
2022 * Removes a source from the default main loop context given the user
2023 * data for the callback. If multiple sources exist with the same user
2024 * data, only one will be destroyed.
2026 * Return value: %TRUE if a source was found and removed.
2029 g_source_remove_by_user_data (gpointer user_data)
2033 source = g_main_context_find_source_by_user_data (NULL, user_data);
2036 g_source_destroy (source);
2044 * g_source_remove_by_funcs_user_data:
2045 * @funcs: The @source_funcs passed to g_source_new()
2046 * @user_data: the user data for the callback
2048 * Removes a source from the default main loop context given the
2049 * source functions and user data. If multiple sources exist with the
2050 * same source functions and user data, only one will be destroyed.
2052 * Return value: %TRUE if a source was found and removed.
2055 g_source_remove_by_funcs_user_data (GSourceFuncs *funcs,
2060 g_return_val_if_fail (funcs != NULL, FALSE);
2062 source = g_main_context_find_source_by_funcs_user_data (NULL, funcs, user_data);
2065 g_source_destroy (source);
2073 * g_get_current_time:
2074 * @result: #GTimeVal structure in which to store current time.
2076 * Equivalent to the UNIX gettimeofday() function, but portable.
2078 * You may find g_get_real_time() to be more convenient.
2081 g_get_current_time (GTimeVal *result)
2086 g_return_if_fail (result != NULL);
2088 /*this is required on alpha, there the timeval structs are int's
2089 not longs and a cast only would fail horribly*/
2090 gettimeofday (&r, NULL);
2091 result->tv_sec = r.tv_sec;
2092 result->tv_usec = r.tv_usec;
2097 g_return_if_fail (result != NULL);
2099 GetSystemTimeAsFileTime (&ft);
2100 memmove (&time64, &ft, sizeof (FILETIME));
2102 /* Convert from 100s of nanoseconds since 1601-01-01
2103 * to Unix epoch. Yes, this is Y2038 unsafe.
2105 time64 -= G_GINT64_CONSTANT (116444736000000000);
2108 result->tv_sec = time64 / 1000000;
2109 result->tv_usec = time64 % 1000000;
2116 * Queries the system wall-clock time.
2118 * This call is functionally equivalent to g_get_current_time() except
2119 * that the return value is often more convenient than dealing with a
2122 * You should only use this call if you are actually interested in the real
2123 * wall-clock time. g_get_monotonic_time() is probably more useful for
2124 * measuring intervals.
2126 * Returns: the number of microseconds since January 1, 1970 UTC.
2131 g_get_real_time (void)
2135 g_get_current_time (&tv);
2137 return (((gint64) tv.tv_sec) * 1000000) + tv.tv_usec;
2141 static ULONGLONG (*g_GetTickCount64) (void) = NULL;
2142 static guint32 g_win32_tick_epoch = 0;
2144 G_GNUC_INTERNAL void
2145 g_clock_win32_init (void)
2149 g_GetTickCount64 = NULL;
2150 kernel32 = GetModuleHandle ("KERNEL32.DLL");
2151 if (kernel32 != NULL)
2152 g_GetTickCount64 = (void *) GetProcAddress (kernel32, "GetTickCount64");
2153 g_win32_tick_epoch = ((guint32)GetTickCount()) >> 31;
2158 * g_get_monotonic_time:
2160 * Queries the system monotonic time, if available.
2162 * On POSIX systems with clock_gettime() and <literal>CLOCK_MONOTONIC</literal> this call
2163 * is a very shallow wrapper for that. Otherwise, we make a best effort
2164 * that probably involves returning the wall clock time (with at least
2165 * microsecond accuracy, subject to the limitations of the OS kernel).
2167 * It's important to note that POSIX <literal>CLOCK_MONOTONIC</literal> does
2168 * not count time spent while the machine is suspended.
2170 * On Windows, "limitations of the OS kernel" is a rather substantial
2171 * statement. Depending on the configuration of the system, the wall
2172 * clock time is updated as infrequently as 64 times a second (which
2173 * is approximately every 16ms). Also, on XP (but not on Vista or later)
2174 * the monotonic clock is locally monotonic, but may differ in exact
2175 * value between processes due to timer wrap handling.
2177 * Returns: the monotonic time, in microseconds
2182 g_get_monotonic_time (void)
2184 #ifdef HAVE_CLOCK_GETTIME
2185 /* librt clock_gettime() is our first choice */
2188 #ifdef CLOCK_MONOTONIC
2189 clock_gettime (CLOCK_MONOTONIC, &ts);
2191 clock_gettime (CLOCK_REALTIME, &ts);
2194 /* In theory monotonic time can have any epoch.
2196 * glib presently assumes the following:
2198 * 1) The epoch comes some time after the birth of Jesus of Nazareth, but
2199 * not more than 10000 years later.
2201 * 2) The current time also falls sometime within this range.
2203 * These two reasonable assumptions leave us with a maximum deviation from
2204 * the epoch of 10000 years, or 315569520000000000 seconds.
2206 * If we restrict ourselves to this range then the number of microseconds
2207 * will always fit well inside the constraints of a int64 (by a factor of
2210 * If you actually hit the following assertion, probably you should file a
2211 * bug against your operating system for being excessively silly.
2213 g_assert (G_GINT64_CONSTANT (-315569520000000000) < ts.tv_sec &&
2214 ts.tv_sec < G_GINT64_CONSTANT (315569520000000000));
2216 return (((gint64) ts.tv_sec) * 1000000) + (ts.tv_nsec / 1000);
2218 #elif defined (G_OS_WIN32)
2222 /* There are four sources for the monotonic time on Windows:
2224 * Three are based on a (1 msec accuracy, but only read periodically) clock chip:
2225 * - GetTickCount (GTC)
2226 * 32bit msec counter, updated each ~15msec, wraps in ~50 days
2227 * - GetTickCount64 (GTC64)
2228 * Same as GetTickCount, but extended to 64bit, so no wrap
2229 * Only available in Vista or later
2230 * - timeGetTime (TGT)
2231 * similar to GetTickCount by default: 15msec, 50 day wrap.
2232 * available in winmm.dll (thus known as the multimedia timers)
2233 * However apps can raise the system timer clock frequency using timeBeginPeriod()
2234 * increasing the accuracy up to 1 msec, at a cost in general system performance
2237 * One is based on high precision clocks:
2238 * - QueryPrecisionCounter (QPC)
2239 * This has much higher accuracy, but is not guaranteed monotonic, and
2240 * has lots of complications like clock jumps and different times on different
2241 * CPUs. It also has lower long term accuracy (i.e. it will drift compared to
2242 * the low precision clocks.
2244 * Additionally, the precision available in the timer-based wakeup such as
2245 * MsgWaitForMultipleObjectsEx (which is what the mainloop is based on) is based
2246 * on the TGT resolution, so by default it is ~15msec, but can be increased by apps.
2248 * The QPC timer has too many issues to be used as is. The only way it could be used
2249 * is to use it to interpolate the lower precision clocks. Firefox does something like
2251 * https://bugzilla.mozilla.org/show_bug.cgi?id=363258
2253 * However this seems quite complicated, so we're not doing this right now.
2255 * The approach we take instead is to use the TGT timer, extending it to 64bit
2256 * either by using the GTC64 value, or if that is not available, a process local
2257 * time epoch that we increment when we detect a timer wrap (assumes that we read
2258 * the time at least once every 50 days).
2261 * - We have a globally consistent monotonic clock on Vista and later
2262 * - We have a locally monotonic clock on XP
2263 * - Apps that need higher precision in timeouts and clock reads can call
2264 * timeBeginPeriod() to increase it as much as they want
2267 if (g_GetTickCount64 != NULL)
2269 guint32 ticks_as_32bit;
2271 ticks = g_GetTickCount64 ();
2272 ticks32 = timeGetTime();
2274 /* GTC64 and TGT are sampled at different times, however they
2275 * have the same base and source (msecs since system boot).
2276 * They can differ by as much as -16 to +16 msecs.
2277 * We can't just inject the low bits into the 64bit counter
2278 * as one of the counters can have wrapped in 32bit space and
2279 * the other not. Instead we calculate the signed difference
2280 * in 32bit space and apply that difference to the 64bit counter.
2282 ticks_as_32bit = (guint32)ticks;
2284 /* We could do some 2's complement hack, but we play it safe */
2285 if (ticks32 - ticks_as_32bit <= G_MAXINT32)
2286 ticks += ticks32 - ticks_as_32bit;
2288 ticks -= ticks_as_32bit - ticks32;
2294 epoch = g_atomic_int_get (&g_win32_tick_epoch);
2296 /* Must read ticks after the epoch. Then we're guaranteed
2297 * that the ticks value we read is higher or equal to any
2298 * previous ones that lead to the writing of the epoch.
2300 ticks32 = timeGetTime();
2302 /* We store the MSB of the current time as the LSB
2303 * of the epoch. Comparing these bits lets us detect when
2304 * the 32bit counter has wrapped so we can increase the
2307 * This will work as long as this function is called at
2308 * least once every ~24 days, which is half the wrap time
2309 * of a 32bit msec counter. I think this is pretty likely.
2311 * Note that g_win32_tick_epoch is a process local state,
2312 * so the monotonic clock will not be the same between
2315 if ((ticks32 >> 31) != (epoch & 1))
2318 g_atomic_int_set (&g_win32_tick_epoch, epoch);
2322 ticks = (guint64)ticks32 | ((guint64)epoch) << 31;
2325 return ticks * 1000;
2327 #else /* !HAVE_CLOCK_GETTIME && ! G_OS_WIN32*/
2331 g_get_current_time (&tv);
2333 return (((gint64) tv.tv_sec) * 1000000) + tv.tv_usec;
2338 g_main_dispatch_free (gpointer dispatch)
2340 g_slice_free (GMainDispatch, dispatch);
2343 /* Running the main loop */
2345 static GMainDispatch *
2348 static GPrivate depth_private = G_PRIVATE_INIT (g_main_dispatch_free);
2349 GMainDispatch *dispatch;
2351 dispatch = g_private_get (&depth_private);
2355 dispatch = g_slice_new0 (GMainDispatch);
2356 g_private_set (&depth_private, dispatch);
2365 * Returns the depth of the stack of calls to
2366 * g_main_context_dispatch() on any #GMainContext in the current thread.
2367 * That is, when called from the toplevel, it gives 0. When
2368 * called from within a callback from g_main_context_iteration()
2369 * (or g_main_loop_run(), etc.) it returns 1. When called from within
2370 * a callback to a recursive call to g_main_context_iteration(),
2371 * it returns 2. And so forth.
2373 * This function is useful in a situation like the following:
2374 * Imagine an extremely simple "garbage collected" system.
2377 * static GList *free_list;
2380 * allocate_memory (gsize size)
2382 * gpointer result = g_malloc (size);
2383 * free_list = g_list_prepend (free_list, result);
2388 * free_allocated_memory (void)
2391 * for (l = free_list; l; l = l->next);
2393 * g_list_free (free_list);
2401 * g_main_context_iteration (NULL, TRUE);
2402 * free_allocated_memory();
2406 * This works from an application, however, if you want to do the same
2407 * thing from a library, it gets more difficult, since you no longer
2408 * control the main loop. You might think you can simply use an idle
2409 * function to make the call to free_allocated_memory(), but that
2410 * doesn't work, since the idle function could be called from a
2411 * recursive callback. This can be fixed by using g_main_depth()
2415 * allocate_memory (gsize size)
2417 * FreeListBlock *block = g_new (FreeListBlock, 1);
2418 * block->mem = g_malloc (size);
2419 * block->depth = g_main_depth ();
2420 * free_list = g_list_prepend (free_list, block);
2421 * return block->mem;
2425 * free_allocated_memory (void)
2429 * int depth = g_main_depth ();
2430 * for (l = free_list; l; );
2432 * GList *next = l->next;
2433 * FreeListBlock *block = l->data;
2434 * if (block->depth > depth)
2436 * g_free (block->mem);
2438 * free_list = g_list_delete_link (free_list, l);
2446 * There is a temptation to use g_main_depth() to solve
2447 * problems with reentrancy. For instance, while waiting for data
2448 * to be received from the network in response to a menu item,
2449 * the menu item might be selected again. It might seem that
2450 * one could make the menu item's callback return immediately
2451 * and do nothing if g_main_depth() returns a value greater than 1.
2452 * However, this should be avoided since the user then sees selecting
2453 * the menu item do nothing. Furthermore, you'll find yourself adding
2454 * these checks all over your code, since there are doubtless many,
2455 * many things that the user could do. Instead, you can use the
2456 * following techniques:
2461 * Use gtk_widget_set_sensitive() or modal dialogs to prevent
2462 * the user from interacting with elements while the main
2463 * loop is recursing.
2468 * Avoid main loop recursion in situations where you can't handle
2469 * arbitrary callbacks. Instead, structure your code so that you
2470 * simply return to the main loop and then get called again when
2471 * there is more work to do.
2476 * Return value: The main loop recursion level in the current thread
2481 GMainDispatch *dispatch = get_dispatch ();
2482 return dispatch->depth;
2486 * g_main_current_source:
2488 * Returns the currently firing source for this thread.
2490 * Return value: (transfer none): The currently firing source or %NULL.
2495 g_main_current_source (void)
2497 GMainDispatch *dispatch = get_dispatch ();
2498 return dispatch->dispatching_sources ? dispatch->dispatching_sources->data : NULL;
2502 * g_source_is_destroyed:
2503 * @source: a #GSource
2505 * Returns whether @source has been destroyed.
2507 * This is important when you operate upon your objects
2508 * from within idle handlers, but may have freed the object
2509 * before the dispatch of your idle handler.
2513 * idle_callback (gpointer data)
2515 * SomeWidget *self = data;
2517 * GDK_THREADS_ENTER (<!-- -->);
2518 * /<!-- -->* do stuff with self *<!-- -->/
2519 * self->idle_id = 0;
2520 * GDK_THREADS_LEAVE (<!-- -->);
2522 * return G_SOURCE_REMOVE;
2526 * some_widget_do_stuff_later (SomeWidget *self)
2528 * self->idle_id = g_idle_add (idle_callback, self);
2532 * some_widget_finalize (GObject *object)
2534 * SomeWidget *self = SOME_WIDGET (object);
2536 * if (self->idle_id)
2537 * g_source_remove (self->idle_id);
2539 * G_OBJECT_CLASS (parent_class)->finalize (object);
2543 * This will fail in a multi-threaded application if the
2544 * widget is destroyed before the idle handler fires due
2545 * to the use after free in the callback. A solution, to
2546 * this particular problem, is to check to if the source
2547 * has already been destroy within the callback.
2551 * idle_callback (gpointer data)
2553 * SomeWidget *self = data;
2555 * GDK_THREADS_ENTER ();
2556 * if (!g_source_is_destroyed (g_main_current_source ()))
2558 * /<!-- -->* do stuff with self *<!-- -->/
2560 * GDK_THREADS_LEAVE ();
2566 * Return value: %TRUE if the source has been destroyed
2571 g_source_is_destroyed (GSource *source)
2573 return SOURCE_DESTROYED (source);
2576 /* Temporarily remove all this source's file descriptors from the
2577 * poll(), so that if data comes available for one of the file descriptors
2578 * we don't continually spin in the poll()
2580 /* HOLDS: source->context's lock */
2582 block_source (GSource *source)
2586 g_return_if_fail (!SOURCE_BLOCKED (source));
2588 source->flags |= G_SOURCE_BLOCKED;
2590 tmp_list = source->poll_fds;
2593 g_main_context_remove_poll_unlocked (source->context, tmp_list->data);
2594 tmp_list = tmp_list->next;
2597 if (source->priv && source->priv->child_sources)
2599 tmp_list = source->priv->child_sources;
2602 block_source (tmp_list->data);
2603 tmp_list = tmp_list->next;
2608 /* HOLDS: source->context's lock */
2610 unblock_source (GSource *source)
2614 g_return_if_fail (SOURCE_BLOCKED (source)); /* Source already unblocked */
2615 g_return_if_fail (!SOURCE_DESTROYED (source));
2617 source->flags &= ~G_SOURCE_BLOCKED;
2619 tmp_list = source->poll_fds;
2622 g_main_context_add_poll_unlocked (source->context, source->priority, tmp_list->data);
2623 tmp_list = tmp_list->next;
2626 if (source->priv && source->priv->child_sources)
2628 tmp_list = source->priv->child_sources;
2631 unblock_source (tmp_list->data);
2632 tmp_list = tmp_list->next;
2637 /* HOLDS: context's lock */
2639 g_main_dispatch (GMainContext *context)
2641 GMainDispatch *current = get_dispatch ();
2644 for (i = 0; i < context->pending_dispatches->len; i++)
2646 GSource *source = context->pending_dispatches->pdata[i];
2648 context->pending_dispatches->pdata[i] = NULL;
2651 source->flags &= ~G_SOURCE_READY;
2653 if (!SOURCE_DESTROYED (source))
2655 gboolean was_in_call;
2656 gpointer user_data = NULL;
2657 GSourceFunc callback = NULL;
2658 GSourceCallbackFuncs *cb_funcs;
2660 gboolean need_destroy;
2662 gboolean (*dispatch) (GSource *,
2665 GSList current_source_link;
2667 dispatch = source->source_funcs->dispatch;
2668 cb_funcs = source->callback_funcs;
2669 cb_data = source->callback_data;
2672 cb_funcs->ref (cb_data);
2674 if ((source->flags & G_SOURCE_CAN_RECURSE) == 0)
2675 block_source (source);
2677 was_in_call = source->flags & G_HOOK_FLAG_IN_CALL;
2678 source->flags |= G_HOOK_FLAG_IN_CALL;
2681 cb_funcs->get (cb_data, source, &callback, &user_data);
2683 UNLOCK_CONTEXT (context);
2686 /* The on-stack allocation of the GSList is unconventional, but
2687 * we know that the lifetime of the link is bounded to this
2688 * function as the link is kept in a thread specific list and
2689 * not manipulated outside of this function and its descendants.
2690 * Avoiding the overhead of a g_slist_alloc() is useful as many
2691 * applications do little more than dispatch events.
2693 * This is a performance hack - do not revert to g_slist_prepend()!
2695 current_source_link.data = source;
2696 current_source_link.next = current->dispatching_sources;
2697 current->dispatching_sources = ¤t_source_link;
2698 need_destroy = ! dispatch (source,
2701 g_assert (current->dispatching_sources == ¤t_source_link);
2702 current->dispatching_sources = current_source_link.next;
2706 cb_funcs->unref (cb_data);
2708 LOCK_CONTEXT (context);
2711 source->flags &= ~G_HOOK_FLAG_IN_CALL;
2713 if (SOURCE_BLOCKED (source) && !SOURCE_DESTROYED (source))
2714 unblock_source (source);
2716 /* Note: this depends on the fact that we can't switch
2717 * sources from one main context to another
2719 if (need_destroy && !SOURCE_DESTROYED (source))
2721 g_assert (source->context == context);
2722 g_source_destroy_internal (source, context, TRUE);
2726 SOURCE_UNREF (source, context);
2729 g_ptr_array_set_size (context->pending_dispatches, 0);
2733 * g_main_context_acquire:
2734 * @context: a #GMainContext
2736 * Tries to become the owner of the specified context.
2737 * If some other thread is the owner of the context,
2738 * returns %FALSE immediately. Ownership is properly
2739 * recursive: the owner can require ownership again
2740 * and will release ownership when g_main_context_release()
2741 * is called as many times as g_main_context_acquire().
2743 * You must be the owner of a context before you
2744 * can call g_main_context_prepare(), g_main_context_query(),
2745 * g_main_context_check(), g_main_context_dispatch().
2747 * Return value: %TRUE if the operation succeeded, and
2748 * this thread is now the owner of @context.
2751 g_main_context_acquire (GMainContext *context)
2753 gboolean result = FALSE;
2754 GThread *self = G_THREAD_SELF;
2756 if (context == NULL)
2757 context = g_main_context_default ();
2759 LOCK_CONTEXT (context);
2761 if (!context->owner)
2763 context->owner = self;
2764 g_assert (context->owner_count == 0);
2767 if (context->owner == self)
2769 context->owner_count++;
2773 UNLOCK_CONTEXT (context);
2779 * g_main_context_release:
2780 * @context: a #GMainContext
2782 * Releases ownership of a context previously acquired by this thread
2783 * with g_main_context_acquire(). If the context was acquired multiple
2784 * times, the ownership will be released only when g_main_context_release()
2785 * is called as many times as it was acquired.
2788 g_main_context_release (GMainContext *context)
2790 if (context == NULL)
2791 context = g_main_context_default ();
2793 LOCK_CONTEXT (context);
2795 context->owner_count--;
2796 if (context->owner_count == 0)
2798 context->owner = NULL;
2800 if (context->waiters)
2802 GMainWaiter *waiter = context->waiters->data;
2803 gboolean loop_internal_waiter = (waiter->mutex == &context->mutex);
2804 context->waiters = g_slist_delete_link (context->waiters,
2806 if (!loop_internal_waiter)
2807 g_mutex_lock (waiter->mutex);
2809 g_cond_signal (waiter->cond);
2811 if (!loop_internal_waiter)
2812 g_mutex_unlock (waiter->mutex);
2816 UNLOCK_CONTEXT (context);
2820 * g_main_context_wait:
2821 * @context: a #GMainContext
2822 * @cond: a condition variable
2823 * @mutex: a mutex, currently held
2825 * Tries to become the owner of the specified context,
2826 * as with g_main_context_acquire(). But if another thread
2827 * is the owner, atomically drop @mutex and wait on @cond until
2828 * that owner releases ownership or until @cond is signaled, then
2829 * try again (once) to become the owner.
2831 * Return value: %TRUE if the operation succeeded, and
2832 * this thread is now the owner of @context.
2835 g_main_context_wait (GMainContext *context,
2839 gboolean result = FALSE;
2840 GThread *self = G_THREAD_SELF;
2841 gboolean loop_internal_waiter;
2843 if (context == NULL)
2844 context = g_main_context_default ();
2846 loop_internal_waiter = (mutex == &context->mutex);
2848 if (!loop_internal_waiter)
2849 LOCK_CONTEXT (context);
2851 if (context->owner && context->owner != self)
2856 waiter.mutex = mutex;
2858 context->waiters = g_slist_append (context->waiters, &waiter);
2860 if (!loop_internal_waiter)
2861 UNLOCK_CONTEXT (context);
2862 g_cond_wait (cond, mutex);
2863 if (!loop_internal_waiter)
2864 LOCK_CONTEXT (context);
2866 context->waiters = g_slist_remove (context->waiters, &waiter);
2869 if (!context->owner)
2871 context->owner = self;
2872 g_assert (context->owner_count == 0);
2875 if (context->owner == self)
2877 context->owner_count++;
2881 if (!loop_internal_waiter)
2882 UNLOCK_CONTEXT (context);
2888 * g_main_context_prepare:
2889 * @context: a #GMainContext
2890 * @priority: location to store priority of highest priority
2891 * source already ready.
2893 * Prepares to poll sources within a main loop. The resulting information
2894 * for polling is determined by calling g_main_context_query ().
2896 * Return value: %TRUE if some source is ready to be dispatched
2900 g_main_context_prepare (GMainContext *context,
2905 gint current_priority = G_MAXINT;
2909 if (context == NULL)
2910 context = g_main_context_default ();
2912 LOCK_CONTEXT (context);
2914 context->time_is_fresh = FALSE;
2916 if (context->in_check_or_prepare)
2918 g_warning ("g_main_context_prepare() called recursively from within a source's check() or "
2919 "prepare() member.");
2920 UNLOCK_CONTEXT (context);
2925 /* If recursing, finish up current dispatch, before starting over */
2926 if (context->pending_dispatches)
2929 g_main_dispatch (context, ¤t_time);
2931 UNLOCK_CONTEXT (context);
2936 /* If recursing, clear list of pending dispatches */
2938 for (i = 0; i < context->pending_dispatches->len; i++)
2940 if (context->pending_dispatches->pdata[i])
2941 SOURCE_UNREF ((GSource *)context->pending_dispatches->pdata[i], context);
2943 g_ptr_array_set_size (context->pending_dispatches, 0);
2945 /* Prepare all sources */
2947 context->timeout = -1;
2949 g_source_iter_init (&iter, context, TRUE);
2950 while (g_source_iter_next (&iter, &source))
2952 gint source_timeout = -1;
2954 if (SOURCE_DESTROYED (source) || SOURCE_BLOCKED (source))
2956 if ((n_ready > 0) && (source->priority > current_priority))
2959 if (!(source->flags & G_SOURCE_READY))
2962 gboolean (*prepare) (GSource *source,
2965 prepare = source->source_funcs->prepare;
2966 context->in_check_or_prepare++;
2967 UNLOCK_CONTEXT (context);
2969 result = (*prepare) (source, &source_timeout);
2971 LOCK_CONTEXT (context);
2972 context->in_check_or_prepare--;
2976 GSource *ready_source = source;
2978 while (ready_source)
2980 ready_source->flags |= G_SOURCE_READY;
2981 ready_source = ready_source->priv->parent_source;
2986 if (source->flags & G_SOURCE_READY)
2989 current_priority = source->priority;
2990 context->timeout = 0;
2993 if (source_timeout >= 0)
2995 if (context->timeout < 0)
2996 context->timeout = source_timeout;
2998 context->timeout = MIN (context->timeout, source_timeout);
3001 g_source_iter_clear (&iter);
3003 UNLOCK_CONTEXT (context);
3006 *priority = current_priority;
3008 return (n_ready > 0);
3012 * g_main_context_query:
3013 * @context: a #GMainContext
3014 * @max_priority: maximum priority source to check
3015 * @timeout_: (out): location to store timeout to be used in polling
3016 * @fds: (out caller-allocates) (array length=n_fds): location to
3017 * store #GPollFD records that need to be polled.
3018 * @n_fds: length of @fds.
3020 * Determines information necessary to poll this main loop.
3022 * Return value: the number of records actually stored in @fds,
3023 * or, if more than @n_fds records need to be stored, the number
3024 * of records that need to be stored.
3027 g_main_context_query (GMainContext *context,
3036 LOCK_CONTEXT (context);
3038 pollrec = context->poll_records;
3040 while (pollrec && max_priority >= pollrec->priority)
3042 /* We need to include entries with fd->events == 0 in the array because
3043 * otherwise if the application changes fd->events behind our back and
3044 * makes it non-zero, we'll be out of sync when we check the fds[] array.
3045 * (Changing fd->events after adding an FD wasn't an anticipated use of
3046 * this API, but it occurs in practice.) */
3049 fds[n_poll].fd = pollrec->fd->fd;
3050 /* In direct contradiction to the Unix98 spec, IRIX runs into
3051 * difficulty if you pass in POLLERR, POLLHUP or POLLNVAL
3052 * flags in the events field of the pollfd while it should
3053 * just ignoring them. So we mask them out here.
3055 fds[n_poll].events = pollrec->fd->events & ~(G_IO_ERR|G_IO_HUP|G_IO_NVAL);
3056 fds[n_poll].revents = 0;
3059 pollrec = pollrec->next;
3063 context->poll_changed = FALSE;
3067 *timeout = context->timeout;
3069 context->time_is_fresh = FALSE;
3072 UNLOCK_CONTEXT (context);
3078 * g_main_context_check:
3079 * @context: a #GMainContext
3080 * @max_priority: the maximum numerical priority of sources to check
3081 * @fds: (array length=n_fds): array of #GPollFD's that was passed to
3082 * the last call to g_main_context_query()
3083 * @n_fds: return value of g_main_context_query()
3085 * Passes the results of polling back to the main loop.
3087 * Return value: %TRUE if some sources are ready to be dispatched.
3090 g_main_context_check (GMainContext *context,
3101 LOCK_CONTEXT (context);
3103 if (context->in_check_or_prepare)
3105 g_warning ("g_main_context_check() called recursively from within a source's check() or "
3106 "prepare() member.");
3107 UNLOCK_CONTEXT (context);
3111 if (context->wake_up_rec.revents)
3112 g_wakeup_acknowledge (context->wakeup);
3114 /* If the set of poll file descriptors changed, bail out
3115 * and let the main loop rerun
3117 if (context->poll_changed)
3119 UNLOCK_CONTEXT (context);
3123 pollrec = context->poll_records;
3127 if (pollrec->fd->events)
3128 pollrec->fd->revents = fds[i].revents;
3130 pollrec = pollrec->next;
3134 g_source_iter_init (&iter, context, TRUE);
3135 while (g_source_iter_next (&iter, &source))
3137 if (SOURCE_DESTROYED (source) || SOURCE_BLOCKED (source))
3139 if ((n_ready > 0) && (source->priority > max_priority))
3142 if (!(source->flags & G_SOURCE_READY))
3145 gboolean (*check) (GSource *source);
3147 check = source->source_funcs->check;
3149 context->in_check_or_prepare++;
3150 UNLOCK_CONTEXT (context);
3152 result = (*check) (source);
3154 LOCK_CONTEXT (context);
3155 context->in_check_or_prepare--;
3159 GSource *ready_source = source;
3161 while (ready_source)
3163 ready_source->flags |= G_SOURCE_READY;
3164 ready_source = ready_source->priv->parent_source;
3169 if (source->flags & G_SOURCE_READY)
3171 source->ref_count++;
3172 g_ptr_array_add (context->pending_dispatches, source);
3176 /* never dispatch sources with less priority than the first
3177 * one we choose to dispatch
3179 max_priority = source->priority;
3182 g_source_iter_clear (&iter);
3184 UNLOCK_CONTEXT (context);
3190 * g_main_context_dispatch:
3191 * @context: a #GMainContext
3193 * Dispatches all pending sources.
3196 g_main_context_dispatch (GMainContext *context)
3198 LOCK_CONTEXT (context);
3200 if (context->pending_dispatches->len > 0)
3202 g_main_dispatch (context);
3205 UNLOCK_CONTEXT (context);
3208 /* HOLDS context lock */
3210 g_main_context_iterate (GMainContext *context,
3217 gboolean some_ready;
3218 gint nfds, allocated_nfds;
3219 GPollFD *fds = NULL;
3221 UNLOCK_CONTEXT (context);
3223 if (!g_main_context_acquire (context))
3225 gboolean got_ownership;
3227 LOCK_CONTEXT (context);
3232 got_ownership = g_main_context_wait (context,
3240 LOCK_CONTEXT (context);
3242 if (!context->cached_poll_array)
3244 context->cached_poll_array_size = context->n_poll_records;
3245 context->cached_poll_array = g_new (GPollFD, context->n_poll_records);
3248 allocated_nfds = context->cached_poll_array_size;
3249 fds = context->cached_poll_array;
3251 UNLOCK_CONTEXT (context);
3253 g_main_context_prepare (context, &max_priority);
3255 while ((nfds = g_main_context_query (context, max_priority, &timeout, fds,
3256 allocated_nfds)) > allocated_nfds)
3258 LOCK_CONTEXT (context);
3260 context->cached_poll_array_size = allocated_nfds = nfds;
3261 context->cached_poll_array = fds = g_new (GPollFD, nfds);
3262 UNLOCK_CONTEXT (context);
3268 g_main_context_poll (context, timeout, max_priority, fds, nfds);
3270 some_ready = g_main_context_check (context, max_priority, fds, nfds);
3273 g_main_context_dispatch (context);
3275 g_main_context_release (context);
3277 LOCK_CONTEXT (context);
3283 * g_main_context_pending:
3284 * @context: (allow-none): a #GMainContext (if %NULL, the default context will be used)
3286 * Checks if any sources have pending events for the given context.
3288 * Return value: %TRUE if events are pending.
3291 g_main_context_pending (GMainContext *context)
3296 context = g_main_context_default();
3298 LOCK_CONTEXT (context);
3299 retval = g_main_context_iterate (context, FALSE, FALSE, G_THREAD_SELF);
3300 UNLOCK_CONTEXT (context);
3306 * g_main_context_iteration:
3307 * @context: (allow-none): a #GMainContext (if %NULL, the default context will be used)
3308 * @may_block: whether the call may block.
3310 * Runs a single iteration for the given main loop. This involves
3311 * checking to see if any event sources are ready to be processed,
3312 * then if no events sources are ready and @may_block is %TRUE, waiting
3313 * for a source to become ready, then dispatching the highest priority
3314 * events sources that are ready. Otherwise, if @may_block is %FALSE
3315 * sources are not waited to become ready, only those highest priority
3316 * events sources will be dispatched (if any), that are ready at this
3317 * given moment without further waiting.
3319 * Note that even when @may_block is %TRUE, it is still possible for
3320 * g_main_context_iteration() to return %FALSE, since the the wait may
3321 * be interrupted for other reasons than an event source becoming ready.
3323 * Return value: %TRUE if events were dispatched.
3326 g_main_context_iteration (GMainContext *context, gboolean may_block)
3331 context = g_main_context_default();
3333 LOCK_CONTEXT (context);
3334 retval = g_main_context_iterate (context, may_block, TRUE, G_THREAD_SELF);
3335 UNLOCK_CONTEXT (context);
3342 * @context: (allow-none): a #GMainContext (if %NULL, the default context will be used).
3343 * @is_running: set to %TRUE to indicate that the loop is running. This
3344 * is not very important since calling g_main_loop_run() will set this to
3347 * Creates a new #GMainLoop structure.
3349 * Return value: a new #GMainLoop.
3352 g_main_loop_new (GMainContext *context,
3353 gboolean is_running)
3358 context = g_main_context_default();
3360 g_main_context_ref (context);
3362 loop = g_new0 (GMainLoop, 1);
3363 loop->context = context;
3364 loop->is_running = is_running != FALSE;
3365 loop->ref_count = 1;
3372 * @loop: a #GMainLoop
3374 * Increases the reference count on a #GMainLoop object by one.
3376 * Return value: @loop
3379 g_main_loop_ref (GMainLoop *loop)
3381 g_return_val_if_fail (loop != NULL, NULL);
3382 g_return_val_if_fail (g_atomic_int_get (&loop->ref_count) > 0, NULL);
3384 g_atomic_int_inc (&loop->ref_count);
3390 * g_main_loop_unref:
3391 * @loop: a #GMainLoop
3393 * Decreases the reference count on a #GMainLoop object by one. If
3394 * the result is zero, free the loop and free all associated memory.
3397 g_main_loop_unref (GMainLoop *loop)
3399 g_return_if_fail (loop != NULL);
3400 g_return_if_fail (g_atomic_int_get (&loop->ref_count) > 0);
3402 if (!g_atomic_int_dec_and_test (&loop->ref_count))
3405 g_main_context_unref (loop->context);
3411 * @loop: a #GMainLoop
3413 * Runs a main loop until g_main_loop_quit() is called on the loop.
3414 * If this is called for the thread of the loop's #GMainContext,
3415 * it will process events from the loop, otherwise it will
3419 g_main_loop_run (GMainLoop *loop)
3421 GThread *self = G_THREAD_SELF;
3423 g_return_if_fail (loop != NULL);
3424 g_return_if_fail (g_atomic_int_get (&loop->ref_count) > 0);
3426 if (!g_main_context_acquire (loop->context))
3428 gboolean got_ownership = FALSE;
3430 /* Another thread owns this context */
3431 LOCK_CONTEXT (loop->context);
3433 g_atomic_int_inc (&loop->ref_count);
3435 if (!loop->is_running)
3436 loop->is_running = TRUE;
3438 while (loop->is_running && !got_ownership)
3439 got_ownership = g_main_context_wait (loop->context,
3440 &loop->context->cond,
3441 &loop->context->mutex);
3443 if (!loop->is_running)
3445 UNLOCK_CONTEXT (loop->context);
3447 g_main_context_release (loop->context);
3448 g_main_loop_unref (loop);
3452 g_assert (got_ownership);
3455 LOCK_CONTEXT (loop->context);
3457 if (loop->context->in_check_or_prepare)
3459 g_warning ("g_main_loop_run(): called recursively from within a source's "
3460 "check() or prepare() member, iteration not possible.");
3464 g_atomic_int_inc (&loop->ref_count);
3465 loop->is_running = TRUE;
3466 while (loop->is_running)
3467 g_main_context_iterate (loop->context, TRUE, TRUE, self);
3469 UNLOCK_CONTEXT (loop->context);
3471 g_main_context_release (loop->context);
3473 g_main_loop_unref (loop);
3478 * @loop: a #GMainLoop
3480 * Stops a #GMainLoop from running. Any calls to g_main_loop_run()
3481 * for the loop will return.
3483 * Note that sources that have already been dispatched when
3484 * g_main_loop_quit() is called will still be executed.
3487 g_main_loop_quit (GMainLoop *loop)
3489 g_return_if_fail (loop != NULL);
3490 g_return_if_fail (g_atomic_int_get (&loop->ref_count) > 0);
3492 LOCK_CONTEXT (loop->context);
3493 loop->is_running = FALSE;
3494 g_wakeup_signal (loop->context->wakeup);
3496 g_cond_broadcast (&loop->context->cond);
3498 UNLOCK_CONTEXT (loop->context);
3502 * g_main_loop_is_running:
3503 * @loop: a #GMainLoop.
3505 * Checks to see if the main loop is currently being run via g_main_loop_run().
3507 * Return value: %TRUE if the mainloop is currently being run.
3510 g_main_loop_is_running (GMainLoop *loop)
3512 g_return_val_if_fail (loop != NULL, FALSE);
3513 g_return_val_if_fail (g_atomic_int_get (&loop->ref_count) > 0, FALSE);
3515 return loop->is_running;
3519 * g_main_loop_get_context:
3520 * @loop: a #GMainLoop.
3522 * Returns the #GMainContext of @loop.
3524 * Return value: (transfer none): the #GMainContext of @loop
3527 g_main_loop_get_context (GMainLoop *loop)
3529 g_return_val_if_fail (loop != NULL, NULL);
3530 g_return_val_if_fail (g_atomic_int_get (&loop->ref_count) > 0, NULL);
3532 return loop->context;
3535 /* HOLDS: context's lock */
3537 g_main_context_poll (GMainContext *context,
3543 #ifdef G_MAIN_POLL_DEBUG
3549 GPollFunc poll_func;
3551 if (n_fds || timeout != 0)
3553 #ifdef G_MAIN_POLL_DEBUG
3554 if (_g_main_poll_debug)
3556 g_print ("polling context=%p n=%d timeout=%d\n",
3557 context, n_fds, timeout);
3558 poll_timer = g_timer_new ();
3562 LOCK_CONTEXT (context);
3564 poll_func = context->poll_func;
3566 UNLOCK_CONTEXT (context);
3567 if ((*poll_func) (fds, n_fds, timeout) < 0 && errno != EINTR)
3570 g_warning ("poll(2) failed due to: %s.",
3571 g_strerror (errno));
3573 /* If g_poll () returns -1, it has already called g_warning() */
3577 #ifdef G_MAIN_POLL_DEBUG
3578 if (_g_main_poll_debug)
3580 LOCK_CONTEXT (context);
3582 g_print ("g_main_poll(%d) timeout: %d - elapsed %12.10f seconds",
3585 g_timer_elapsed (poll_timer, NULL));
3586 g_timer_destroy (poll_timer);
3587 pollrec = context->poll_records;
3589 while (pollrec != NULL)
3594 if (fds[i].fd == pollrec->fd->fd &&
3595 pollrec->fd->events &&
3598 g_print (" [" G_POLLFD_FORMAT " :", fds[i].fd);
3599 if (fds[i].revents & G_IO_IN)
3601 if (fds[i].revents & G_IO_OUT)
3603 if (fds[i].revents & G_IO_PRI)
3605 if (fds[i].revents & G_IO_ERR)
3607 if (fds[i].revents & G_IO_HUP)
3609 if (fds[i].revents & G_IO_NVAL)
3615 pollrec = pollrec->next;
3619 UNLOCK_CONTEXT (context);
3622 } /* if (n_fds || timeout != 0) */
3626 * g_main_context_add_poll:
3627 * @context: (allow-none): a #GMainContext (or %NULL for the default context)
3628 * @fd: a #GPollFD structure holding information about a file
3629 * descriptor to watch.
3630 * @priority: the priority for this file descriptor which should be
3631 * the same as the priority used for g_source_attach() to ensure that the
3632 * file descriptor is polled whenever the results may be needed.
3634 * Adds a file descriptor to the set of file descriptors polled for
3635 * this context. This will very seldom be used directly. Instead
3636 * a typical event source will use g_source_add_poll() instead.
3639 g_main_context_add_poll (GMainContext *context,
3644 context = g_main_context_default ();
3646 g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
3647 g_return_if_fail (fd);
3649 LOCK_CONTEXT (context);
3650 g_main_context_add_poll_unlocked (context, priority, fd);
3651 UNLOCK_CONTEXT (context);
3654 /* HOLDS: main_loop_lock */
3656 g_main_context_add_poll_unlocked (GMainContext *context,
3660 GPollRec *prevrec, *nextrec;
3661 GPollRec *newrec = g_slice_new (GPollRec);
3663 /* This file descriptor may be checked before we ever poll */
3666 newrec->priority = priority;
3668 prevrec = context->poll_records_tail;
3670 while (prevrec && priority < prevrec->priority)
3673 prevrec = prevrec->prev;
3677 prevrec->next = newrec;
3679 context->poll_records = newrec;
3681 newrec->prev = prevrec;
3682 newrec->next = nextrec;
3685 nextrec->prev = newrec;
3687 context->poll_records_tail = newrec;
3689 context->n_poll_records++;
3691 context->poll_changed = TRUE;
3693 /* Now wake up the main loop if it is waiting in the poll() */
3694 g_wakeup_signal (context->wakeup);
3698 * g_main_context_remove_poll:
3699 * @context:a #GMainContext
3700 * @fd: a #GPollFD descriptor previously added with g_main_context_add_poll()
3702 * Removes file descriptor from the set of file descriptors to be
3703 * polled for a particular context.
3706 g_main_context_remove_poll (GMainContext *context,
3710 context = g_main_context_default ();
3712 g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
3713 g_return_if_fail (fd);
3715 LOCK_CONTEXT (context);
3716 g_main_context_remove_poll_unlocked (context, fd);
3717 UNLOCK_CONTEXT (context);
3721 g_main_context_remove_poll_unlocked (GMainContext *context,
3724 GPollRec *pollrec, *prevrec, *nextrec;
3727 pollrec = context->poll_records;
3731 nextrec = pollrec->next;
3732 if (pollrec->fd == fd)
3734 if (prevrec != NULL)
3735 prevrec->next = nextrec;
3737 context->poll_records = nextrec;
3739 if (nextrec != NULL)
3740 nextrec->prev = prevrec;
3742 context->poll_records_tail = prevrec;
3744 g_slice_free (GPollRec, pollrec);
3746 context->n_poll_records--;
3753 context->poll_changed = TRUE;
3755 /* Now wake up the main loop if it is waiting in the poll() */
3756 g_wakeup_signal (context->wakeup);
3760 * g_source_get_current_time:
3761 * @source: a #GSource
3762 * @timeval: #GTimeVal structure in which to store current time.
3764 * This function ignores @source and is otherwise the same as
3765 * g_get_current_time().
3767 * Deprecated: 2.28: use g_source_get_time() instead
3770 g_source_get_current_time (GSource *source,
3773 g_get_current_time (timeval);
3777 * g_source_get_time:
3778 * @source: a #GSource
3780 * Gets the time to be used when checking this source. The advantage of
3781 * calling this function over calling g_get_monotonic_time() directly is
3782 * that when checking multiple sources, GLib can cache a single value
3783 * instead of having to repeatedly get the system monotonic time.
3785 * The time here is the system monotonic time, if available, or some
3786 * other reasonable alternative otherwise. See g_get_monotonic_time().
3788 * Returns: the monotonic time in microseconds
3793 g_source_get_time (GSource *source)
3795 GMainContext *context;
3798 g_return_val_if_fail (source->context != NULL, 0);
3800 context = source->context;
3802 LOCK_CONTEXT (context);
3804 if (!context->time_is_fresh)
3806 context->time = g_get_monotonic_time ();
3807 context->time_is_fresh = TRUE;
3810 result = context->time;
3812 UNLOCK_CONTEXT (context);
3818 * g_main_context_set_poll_func:
3819 * @context: a #GMainContext
3820 * @func: the function to call to poll all file descriptors
3822 * Sets the function to use to handle polling of file descriptors. It
3823 * will be used instead of the poll() system call
3824 * (or GLib's replacement function, which is used where
3825 * poll() isn't available).
3827 * This function could possibly be used to integrate the GLib event
3828 * loop with an external event loop.
3831 g_main_context_set_poll_func (GMainContext *context,
3835 context = g_main_context_default ();
3837 g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
3839 LOCK_CONTEXT (context);
3842 context->poll_func = func;
3844 context->poll_func = g_poll;
3846 UNLOCK_CONTEXT (context);
3850 * g_main_context_get_poll_func:
3851 * @context: a #GMainContext
3853 * Gets the poll function set by g_main_context_set_poll_func().
3855 * Return value: the poll function
3858 g_main_context_get_poll_func (GMainContext *context)
3863 context = g_main_context_default ();
3865 g_return_val_if_fail (g_atomic_int_get (&context->ref_count) > 0, NULL);
3867 LOCK_CONTEXT (context);
3868 result = context->poll_func;
3869 UNLOCK_CONTEXT (context);
3875 * g_main_context_wakeup:
3876 * @context: a #GMainContext
3878 * If @context is currently waiting in a poll(), interrupt
3879 * the poll(), and continue the iteration process.
3882 g_main_context_wakeup (GMainContext *context)
3885 context = g_main_context_default ();
3887 g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
3889 g_wakeup_signal (context->wakeup);
3893 * g_main_context_is_owner:
3894 * @context: a #GMainContext
3896 * Determines whether this thread holds the (recursive)
3897 * ownership of this #GMainContext. This is useful to
3898 * know before waiting on another thread that may be
3899 * blocking to get ownership of @context.
3901 * Returns: %TRUE if current thread is owner of @context.
3906 g_main_context_is_owner (GMainContext *context)
3911 context = g_main_context_default ();
3913 LOCK_CONTEXT (context);
3914 is_owner = context->owner == G_THREAD_SELF;
3915 UNLOCK_CONTEXT (context);
3923 g_timeout_set_expiration (GTimeoutSource *timeout_source,
3924 gint64 current_time)
3926 timeout_source->expiration = current_time +
3927 (guint64) timeout_source->interval * 1000;
3929 if (timeout_source->seconds)
3932 static gint timer_perturb = -1;
3934 if (timer_perturb == -1)
3937 * we want a per machine/session unique 'random' value; try the dbus
3938 * address first, that has a UUID in it. If there is no dbus, use the
3939 * hostname for hashing.
3941 const char *session_bus_address = g_getenv ("DBUS_SESSION_BUS_ADDRESS");
3942 if (!session_bus_address)
3943 session_bus_address = g_getenv ("HOSTNAME");
3944 if (session_bus_address)
3945 timer_perturb = ABS ((gint) g_str_hash (session_bus_address)) % 1000000;
3950 /* We want the microseconds part of the timeout to land on the
3951 * 'timer_perturb' mark, but we need to make sure we don't try to
3952 * set the timeout in the past. We do this by ensuring that we
3953 * always only *increase* the expiration time by adding a full
3954 * second in the case that the microsecond portion decreases.
3956 timeout_source->expiration -= timer_perturb;
3958 remainder = timeout_source->expiration % 1000000;
3959 if (remainder >= 1000000/4)
3960 timeout_source->expiration += 1000000;
3962 timeout_source->expiration -= remainder;
3963 timeout_source->expiration += timer_perturb;
3968 g_timeout_prepare (GSource *source,
3971 GTimeoutSource *timeout_source = (GTimeoutSource *) source;
3972 gint64 now = g_source_get_time (source);
3974 if (now < timeout_source->expiration)
3976 /* Round up to ensure that we don't try again too early */
3977 *timeout = (timeout_source->expiration - now + 999) / 1000;
3986 g_timeout_check (GSource *source)
3988 GTimeoutSource *timeout_source = (GTimeoutSource *) source;
3989 gint64 now = g_source_get_time (source);
3991 return timeout_source->expiration <= now;
3995 g_timeout_dispatch (GSource *source,
3996 GSourceFunc callback,
3999 GTimeoutSource *timeout_source = (GTimeoutSource *)source;
4004 g_warning ("Timeout source dispatched without callback\n"
4005 "You must call g_source_set_callback().");
4009 again = callback (user_data);
4012 g_timeout_set_expiration (timeout_source, g_source_get_time (source));
4018 * g_timeout_source_new:
4019 * @interval: the timeout interval in milliseconds.
4021 * Creates a new timeout source.
4023 * The source will not initially be associated with any #GMainContext
4024 * and must be added to one with g_source_attach() before it will be
4027 * The interval given is in terms of monotonic time, not wall clock
4028 * time. See g_get_monotonic_time().
4030 * Return value: the newly-created timeout source
4033 g_timeout_source_new (guint interval)
4035 GSource *source = g_source_new (&g_timeout_funcs, sizeof (GTimeoutSource));
4036 GTimeoutSource *timeout_source = (GTimeoutSource *)source;
4038 timeout_source->interval = interval;
4039 g_timeout_set_expiration (timeout_source, g_get_monotonic_time ());
4045 * g_timeout_source_new_seconds:
4046 * @interval: the timeout interval in seconds
4048 * Creates a new timeout source.
4050 * The source will not initially be associated with any #GMainContext
4051 * and must be added to one with g_source_attach() before it will be
4054 * The scheduling granularity/accuracy of this timeout source will be
4057 * The interval given in terms of monotonic time, not wall clock time.
4058 * See g_get_monotonic_time().
4060 * Return value: the newly-created timeout source
4065 g_timeout_source_new_seconds (guint interval)
4067 GSource *source = g_source_new (&g_timeout_funcs, sizeof (GTimeoutSource));
4068 GTimeoutSource *timeout_source = (GTimeoutSource *)source;
4070 timeout_source->interval = 1000 * interval;
4071 timeout_source->seconds = TRUE;
4073 g_timeout_set_expiration (timeout_source, g_get_monotonic_time ());
4080 * g_timeout_add_full:
4081 * @priority: the priority of the timeout source. Typically this will be in
4082 * the range between #G_PRIORITY_DEFAULT and #G_PRIORITY_HIGH.
4083 * @interval: the time between calls to the function, in milliseconds
4084 * (1/1000ths of a second)
4085 * @function: function to call
4086 * @data: data to pass to @function
4087 * @notify: (allow-none): function to call when the timeout is removed, or %NULL
4089 * Sets a function to be called at regular intervals, with the given
4090 * priority. The function is called repeatedly until it returns
4091 * %FALSE, at which point the timeout is automatically destroyed and
4092 * the function will not be called again. The @notify function is
4093 * called when the timeout is destroyed. The first call to the
4094 * function will be at the end of the first @interval.
4096 * Note that timeout functions may be delayed, due to the processing of other
4097 * event sources. Thus they should not be relied on for precise timing.
4098 * After each call to the timeout function, the time of the next
4099 * timeout is recalculated based on the current time and the given interval
4100 * (it does not try to 'catch up' time lost in delays).
4102 * This internally creates a main loop source using g_timeout_source_new()
4103 * and attaches it to the main loop context using g_source_attach(). You can
4104 * do these steps manually if you need greater control.
4106 * The interval given in terms of monotonic time, not wall clock time.
4107 * See g_get_monotonic_time().
4109 * Return value: the ID (greater than 0) of the event source.
4110 * Rename to: g_timeout_add
4113 g_timeout_add_full (gint priority,
4115 GSourceFunc function,
4117 GDestroyNotify notify)
4122 g_return_val_if_fail (function != NULL, 0);
4124 source = g_timeout_source_new (interval);
4126 if (priority != G_PRIORITY_DEFAULT)
4127 g_source_set_priority (source, priority);
4129 g_source_set_callback (source, function, data, notify);
4130 id = g_source_attach (source, NULL);
4131 g_source_unref (source);
4138 * @interval: the time between calls to the function, in milliseconds
4139 * (1/1000ths of a second)
4140 * @function: function to call
4141 * @data: data to pass to @function
4143 * Sets a function to be called at regular intervals, with the default
4144 * priority, #G_PRIORITY_DEFAULT. The function is called repeatedly
4145 * until it returns %FALSE, at which point the timeout is automatically
4146 * destroyed and the function will not be called again. The first call
4147 * to the function will be at the end of the first @interval.
4149 * Note that timeout functions may be delayed, due to the processing of other
4150 * event sources. Thus they should not be relied on for precise timing.
4151 * After each call to the timeout function, the time of the next
4152 * timeout is recalculated based on the current time and the given interval
4153 * (it does not try to 'catch up' time lost in delays).
4155 * If you want to have a timer in the "seconds" range and do not care
4156 * about the exact time of the first call of the timer, use the
4157 * g_timeout_add_seconds() function; this function allows for more
4158 * optimizations and more efficient system power usage.
4160 * This internally creates a main loop source using g_timeout_source_new()
4161 * and attaches it to the main loop context using g_source_attach(). You can
4162 * do these steps manually if you need greater control.
4164 * The interval given is in terms of monotonic time, not wall clock
4165 * time. See g_get_monotonic_time().
4167 * Return value: the ID (greater than 0) of the event source.
4170 g_timeout_add (guint32 interval,
4171 GSourceFunc function,
4174 return g_timeout_add_full (G_PRIORITY_DEFAULT,
4175 interval, function, data, NULL);
4179 * g_timeout_add_seconds_full:
4180 * @priority: the priority of the timeout source. Typically this will be in
4181 * the range between #G_PRIORITY_DEFAULT and #G_PRIORITY_HIGH.
4182 * @interval: the time between calls to the function, in seconds
4183 * @function: function to call
4184 * @data: data to pass to @function
4185 * @notify: (allow-none): function to call when the timeout is removed, or %NULL
4187 * Sets a function to be called at regular intervals, with @priority.
4188 * The function is called repeatedly until it returns %FALSE, at which
4189 * point the timeout is automatically destroyed and the function will
4190 * not be called again.
4192 * Unlike g_timeout_add(), this function operates at whole second granularity.
4193 * The initial starting point of the timer is determined by the implementation
4194 * and the implementation is expected to group multiple timers together so that
4195 * they fire all at the same time.
4196 * To allow this grouping, the @interval to the first timer is rounded
4197 * and can deviate up to one second from the specified interval.
4198 * Subsequent timer iterations will generally run at the specified interval.
4200 * Note that timeout functions may be delayed, due to the processing of other
4201 * event sources. Thus they should not be relied on for precise timing.
4202 * After each call to the timeout function, the time of the next
4203 * timeout is recalculated based on the current time and the given @interval
4205 * If you want timing more precise than whole seconds, use g_timeout_add()
4208 * The grouping of timers to fire at the same time results in a more power
4209 * and CPU efficient behavior so if your timer is in multiples of seconds
4210 * and you don't require the first timer exactly one second from now, the
4211 * use of g_timeout_add_seconds() is preferred over g_timeout_add().
4213 * This internally creates a main loop source using
4214 * g_timeout_source_new_seconds() and attaches it to the main loop context
4215 * using g_source_attach(). You can do these steps manually if you need
4218 * The interval given is in terms of monotonic time, not wall clock
4219 * time. See g_get_monotonic_time().
4221 * Return value: the ID (greater than 0) of the event source.
4223 * Rename to: g_timeout_add_seconds
4227 g_timeout_add_seconds_full (gint priority,
4229 GSourceFunc function,
4231 GDestroyNotify notify)
4236 g_return_val_if_fail (function != NULL, 0);
4238 source = g_timeout_source_new_seconds (interval);
4240 if (priority != G_PRIORITY_DEFAULT)
4241 g_source_set_priority (source, priority);
4243 g_source_set_callback (source, function, data, notify);
4244 id = g_source_attach (source, NULL);
4245 g_source_unref (source);
4251 * g_timeout_add_seconds:
4252 * @interval: the time between calls to the function, in seconds
4253 * @function: function to call
4254 * @data: data to pass to @function
4256 * Sets a function to be called at regular intervals with the default
4257 * priority, #G_PRIORITY_DEFAULT. The function is called repeatedly until
4258 * it returns %FALSE, at which point the timeout is automatically destroyed
4259 * and the function will not be called again.
4261 * This internally creates a main loop source using
4262 * g_timeout_source_new_seconds() and attaches it to the main loop context
4263 * using g_source_attach(). You can do these steps manually if you need
4264 * greater control. Also see g_timeout_add_seconds_full().
4266 * Note that the first call of the timer may not be precise for timeouts
4267 * of one second. If you need finer precision and have such a timeout,
4268 * you may want to use g_timeout_add() instead.
4270 * The interval given is in terms of monotonic time, not wall clock
4271 * time. See g_get_monotonic_time().
4273 * Return value: the ID (greater than 0) of the event source.
4278 g_timeout_add_seconds (guint interval,
4279 GSourceFunc function,
4282 g_return_val_if_fail (function != NULL, 0);
4284 return g_timeout_add_seconds_full (G_PRIORITY_DEFAULT, interval, function, data, NULL);
4287 /* Child watch functions */
4292 g_child_watch_prepare (GSource *source,
4300 g_child_watch_check (GSource *source)
4302 GChildWatchSource *child_watch_source;
4303 gboolean child_exited;
4305 child_watch_source = (GChildWatchSource *) source;
4307 child_exited = child_watch_source->poll.revents & G_IO_IN;
4314 * Note: We do _not_ check for the special value of STILL_ACTIVE
4315 * since we know that the process has exited and doing so runs into
4316 * problems if the child process "happens to return STILL_ACTIVE(259)"
4317 * as Microsoft's Platform SDK puts it.
4319 if (!GetExitCodeProcess (child_watch_source->pid, &child_status))
4321 gchar *emsg = g_win32_error_message (GetLastError ());
4322 g_warning (G_STRLOC ": GetExitCodeProcess() failed: %s", emsg);
4325 child_watch_source->child_status = -1;
4328 child_watch_source->child_status = child_status;
4331 return child_exited;
4335 g_child_watch_finalize (GSource *source)
4339 #else /* G_OS_WIN32 */
4342 wake_source (GSource *source)
4344 GMainContext *context;
4346 /* This should be thread-safe:
4348 * - if the source is currently being added to a context, that
4349 * context will be woken up anyway
4351 * - if the source is currently being destroyed, we simply need not
4354 * - the memory for the source will remain valid until after the
4355 * source finalize function was called (which would remove the
4356 * source from the global list which we are currently holding the
4359 * - the GMainContext will either be NULL or point to a live
4362 * - the GMainContext will remain valid since we hold the
4363 * main_context_list lock
4365 * Since we are holding a lot of locks here, don't try to enter any
4366 * more GMainContext functions for fear of dealock -- just hit the
4367 * GWakeup and run. Even if that's safe now, it could easily become
4368 * unsafe with some very minor changes in the future, and signal
4369 * handling is not the most well-tested codepath.
4371 G_LOCK(main_context_list);
4372 context = source->context;
4374 g_wakeup_signal (context->wakeup);
4375 G_UNLOCK(main_context_list);
4379 dispatch_unix_signals (void)
4383 /* clear this first incase another one arrives while we're processing */
4384 any_unix_signal_pending = FALSE;
4386 G_LOCK(unix_signal_lock);
4388 /* handle GChildWatchSource instances */
4389 if (unix_signal_pending[SIGCHLD])
4391 unix_signal_pending[SIGCHLD] = FALSE;
4393 /* The only way we can do this is to scan all of the children.
4395 * The docs promise that we will not reap children that we are not
4396 * explicitly watching, so that ties our hands from calling
4397 * waitpid(-1). We also can't use siginfo's si_pid field since if
4398 * multiple SIGCHLD arrive at the same time, one of them can be
4399 * dropped (since a given UNIX signal can only be pending once).
4401 for (node = unix_child_watches; node; node = node->next)
4403 GChildWatchSource *source = node->data;
4405 if (!source->child_exited)
4407 if (waitpid (source->pid, &source->child_status, WNOHANG) > 0)
4409 source->child_exited = TRUE;
4411 wake_source ((GSource *) source);
4417 /* handle GUnixSignalWatchSource instances */
4418 for (node = unix_signal_watches; node; node = node->next)
4420 GUnixSignalWatchSource *source = node->data;
4422 if (!source->pending)
4424 if (unix_signal_pending[source->signum])
4426 unix_signal_pending[source->signum] = FALSE;
4427 source->pending = TRUE;
4429 wake_source ((GSource *) source);
4434 G_UNLOCK(unix_signal_lock);
4438 g_child_watch_prepare (GSource *source,
4441 GChildWatchSource *child_watch_source;
4443 child_watch_source = (GChildWatchSource *) source;
4445 return child_watch_source->child_exited;
4449 g_child_watch_check (GSource *source)
4451 GChildWatchSource *child_watch_source;
4453 child_watch_source = (GChildWatchSource *) source;
4455 return child_watch_source->child_exited;
4459 g_unix_signal_watch_prepare (GSource *source,
4462 GUnixSignalWatchSource *unix_signal_source;
4464 unix_signal_source = (GUnixSignalWatchSource *) source;
4466 return unix_signal_source->pending;
4470 g_unix_signal_watch_check (GSource *source)
4472 GUnixSignalWatchSource *unix_signal_source;
4474 unix_signal_source = (GUnixSignalWatchSource *) source;
4476 return unix_signal_source->pending;
4480 g_unix_signal_watch_dispatch (GSource *source,
4481 GSourceFunc callback,
4484 GUnixSignalWatchSource *unix_signal_source;
4486 unix_signal_source = (GUnixSignalWatchSource *) source;
4490 g_warning ("Unix signal source dispatched without callback\n"
4491 "You must call g_source_set_callback().");
4495 (callback) (user_data);
4497 unix_signal_source->pending = FALSE;
4503 ensure_unix_signal_handler_installed_unlocked (int signum)
4505 static sigset_t installed_signal_mask;
4506 static gboolean initialized;
4507 struct sigaction action;
4511 sigemptyset (&installed_signal_mask);
4512 g_get_worker_context ();
4516 if (sigismember (&installed_signal_mask, signum))
4519 sigaddset (&installed_signal_mask, signum);
4521 action.sa_handler = g_unix_signal_handler;
4522 sigemptyset (&action.sa_mask);
4523 action.sa_flags = SA_RESTART | SA_NOCLDSTOP;
4524 sigaction (signum, &action, NULL);
4528 _g_main_create_unix_signal_watch (int signum)
4531 GUnixSignalWatchSource *unix_signal_source;
4533 source = g_source_new (&g_unix_signal_funcs, sizeof (GUnixSignalWatchSource));
4534 unix_signal_source = (GUnixSignalWatchSource *) source;
4536 unix_signal_source->signum = signum;
4537 unix_signal_source->pending = FALSE;
4539 G_LOCK (unix_signal_lock);
4540 ensure_unix_signal_handler_installed_unlocked (signum);
4541 unix_signal_watches = g_slist_prepend (unix_signal_watches, unix_signal_source);
4542 if (unix_signal_pending[signum])
4543 unix_signal_source->pending = TRUE;
4544 unix_signal_pending[signum] = FALSE;
4545 G_UNLOCK (unix_signal_lock);
4551 g_unix_signal_watch_finalize (GSource *source)
4553 G_LOCK (unix_signal_lock);
4554 unix_signal_watches = g_slist_remove (unix_signal_watches, source);
4555 G_UNLOCK (unix_signal_lock);
4559 g_child_watch_finalize (GSource *source)
4561 G_LOCK (unix_signal_lock);
4562 unix_child_watches = g_slist_remove (unix_child_watches, source);
4563 G_UNLOCK (unix_signal_lock);
4566 #endif /* G_OS_WIN32 */
4569 g_child_watch_dispatch (GSource *source,
4570 GSourceFunc callback,
4573 GChildWatchSource *child_watch_source;
4574 GChildWatchFunc child_watch_callback = (GChildWatchFunc) callback;
4576 child_watch_source = (GChildWatchSource *) source;
4580 g_warning ("Child watch source dispatched without callback\n"
4581 "You must call g_source_set_callback().");
4585 (child_watch_callback) (child_watch_source->pid, child_watch_source->child_status, user_data);
4587 /* We never keep a child watch source around as the child is gone */
4594 g_unix_signal_handler (int signum)
4596 unix_signal_pending[signum] = TRUE;
4597 any_unix_signal_pending = TRUE;
4599 g_wakeup_signal (glib_worker_context->wakeup);
4602 #endif /* !G_OS_WIN32 */
4605 * g_child_watch_source_new:
4606 * @pid: process to watch. On POSIX the pid of a child process. On
4607 * Windows a handle for a process (which doesn't have to be a child).
4609 * Creates a new child_watch source.
4611 * The source will not initially be associated with any #GMainContext
4612 * and must be added to one with g_source_attach() before it will be
4615 * Note that child watch sources can only be used in conjunction with
4616 * <literal>g_spawn...</literal> when the %G_SPAWN_DO_NOT_REAP_CHILD
4619 * Note that on platforms where #GPid must be explicitly closed
4620 * (see g_spawn_close_pid()) @pid must not be closed while the
4621 * source is still active. Typically, you will want to call
4622 * g_spawn_close_pid() in the callback function for the source.
4624 * Note further that using g_child_watch_source_new() is not
4625 * compatible with calling <literal>waitpid(-1)</literal> in
4626 * the application. Calling waitpid() for individual pids will
4629 * Return value: the newly-created child watch source
4634 g_child_watch_source_new (GPid pid)
4636 GSource *source = g_source_new (&g_child_watch_funcs, sizeof (GChildWatchSource));
4637 GChildWatchSource *child_watch_source = (GChildWatchSource *)source;
4639 child_watch_source->pid = pid;
4642 child_watch_source->poll.fd = (gintptr) pid;
4643 child_watch_source->poll.events = G_IO_IN;
4645 g_source_add_poll (source, &child_watch_source->poll);
4646 #else /* G_OS_WIN32 */
4647 G_LOCK (unix_signal_lock);
4648 ensure_unix_signal_handler_installed_unlocked (SIGCHLD);
4649 unix_child_watches = g_slist_prepend (unix_child_watches, child_watch_source);
4650 if (waitpid (pid, &child_watch_source->child_status, WNOHANG) > 0)
4651 child_watch_source->child_exited = TRUE;
4652 G_UNLOCK (unix_signal_lock);
4653 #endif /* G_OS_WIN32 */
4659 * g_child_watch_add_full:
4660 * @priority: the priority of the idle source. Typically this will be in the
4661 * range between #G_PRIORITY_DEFAULT_IDLE and #G_PRIORITY_HIGH_IDLE.
4662 * @pid: process to watch. On POSIX the pid of a child process. On
4663 * Windows a handle for a process (which doesn't have to be a child).
4664 * @function: function to call
4665 * @data: data to pass to @function
4666 * @notify: (allow-none): function to call when the idle is removed, or %NULL
4668 * Sets a function to be called when the child indicated by @pid
4669 * exits, at the priority @priority.
4671 * If you obtain @pid from g_spawn_async() or g_spawn_async_with_pipes()
4672 * you will need to pass #G_SPAWN_DO_NOT_REAP_CHILD as flag to
4673 * the spawn function for the child watching to work.
4675 * In many programs, you will want to call g_spawn_check_exit_status()
4676 * in the callback to determine whether or not the child exited
4679 * Also, note that on platforms where #GPid must be explicitly closed
4680 * (see g_spawn_close_pid()) @pid must not be closed while the source
4681 * is still active. Typically, you should invoke g_spawn_close_pid()
4682 * in the callback function for the source.
4684 * GLib supports only a single callback per process id.
4686 * This internally creates a main loop source using
4687 * g_child_watch_source_new() and attaches it to the main loop context
4688 * using g_source_attach(). You can do these steps manually if you
4689 * need greater control.
4691 * Return value: the ID (greater than 0) of the event source.
4693 * Rename to: g_child_watch_add
4697 g_child_watch_add_full (gint priority,
4699 GChildWatchFunc function,
4701 GDestroyNotify notify)
4706 g_return_val_if_fail (function != NULL, 0);
4708 source = g_child_watch_source_new (pid);
4710 if (priority != G_PRIORITY_DEFAULT)
4711 g_source_set_priority (source, priority);
4713 g_source_set_callback (source, (GSourceFunc) function, data, notify);
4714 id = g_source_attach (source, NULL);
4715 g_source_unref (source);
4721 * g_child_watch_add:
4722 * @pid: process id to watch. On POSIX the pid of a child process. On
4723 * Windows a handle for a process (which doesn't have to be a child).
4724 * @function: function to call
4725 * @data: data to pass to @function
4727 * Sets a function to be called when the child indicated by @pid
4728 * exits, at a default priority, #G_PRIORITY_DEFAULT.
4730 * If you obtain @pid from g_spawn_async() or g_spawn_async_with_pipes()
4731 * you will need to pass #G_SPAWN_DO_NOT_REAP_CHILD as flag to
4732 * the spawn function for the child watching to work.
4734 * Note that on platforms where #GPid must be explicitly closed
4735 * (see g_spawn_close_pid()) @pid must not be closed while the
4736 * source is still active. Typically, you will want to call
4737 * g_spawn_close_pid() in the callback function for the source.
4739 * GLib supports only a single callback per process id.
4741 * This internally creates a main loop source using
4742 * g_child_watch_source_new() and attaches it to the main loop context
4743 * using g_source_attach(). You can do these steps manually if you
4744 * need greater control.
4746 * Return value: the ID (greater than 0) of the event source.
4751 g_child_watch_add (GPid pid,
4752 GChildWatchFunc function,
4755 return g_child_watch_add_full (G_PRIORITY_DEFAULT, pid, function, data, NULL);
4759 /* Idle functions */
4762 g_idle_prepare (GSource *source,
4771 g_idle_check (GSource *source)
4777 g_idle_dispatch (GSource *source,
4778 GSourceFunc callback,
4783 g_warning ("Idle source dispatched without callback\n"
4784 "You must call g_source_set_callback().");
4788 return callback (user_data);
4792 * g_idle_source_new:
4794 * Creates a new idle source.
4796 * The source will not initially be associated with any #GMainContext
4797 * and must be added to one with g_source_attach() before it will be
4798 * executed. Note that the default priority for idle sources is
4799 * %G_PRIORITY_DEFAULT_IDLE, as compared to other sources which
4800 * have a default priority of %G_PRIORITY_DEFAULT.
4802 * Return value: the newly-created idle source
4805 g_idle_source_new (void)
4809 source = g_source_new (&g_idle_funcs, sizeof (GSource));
4810 g_source_set_priority (source, G_PRIORITY_DEFAULT_IDLE);
4817 * @priority: the priority of the idle source. Typically this will be in the
4818 * range between #G_PRIORITY_DEFAULT_IDLE and #G_PRIORITY_HIGH_IDLE.
4819 * @function: function to call
4820 * @data: data to pass to @function
4821 * @notify: (allow-none): function to call when the idle is removed, or %NULL
4823 * Adds a function to be called whenever there are no higher priority
4824 * events pending. If the function returns %FALSE it is automatically
4825 * removed from the list of event sources and will not be called again.
4827 * This internally creates a main loop source using g_idle_source_new()
4828 * and attaches it to the main loop context using g_source_attach().
4829 * You can do these steps manually if you need greater control.
4831 * Return value: the ID (greater than 0) of the event source.
4832 * Rename to: g_idle_add
4835 g_idle_add_full (gint priority,
4836 GSourceFunc function,
4838 GDestroyNotify notify)
4843 g_return_val_if_fail (function != NULL, 0);
4845 source = g_idle_source_new ();
4847 if (priority != G_PRIORITY_DEFAULT_IDLE)
4848 g_source_set_priority (source, priority);
4850 g_source_set_callback (source, function, data, notify);
4851 id = g_source_attach (source, NULL);
4852 g_source_unref (source);
4859 * @function: function to call
4860 * @data: data to pass to @function.
4862 * Adds a function to be called whenever there are no higher priority
4863 * events pending to the default main loop. The function is given the
4864 * default idle priority, #G_PRIORITY_DEFAULT_IDLE. If the function
4865 * returns %FALSE it is automatically removed from the list of event
4866 * sources and will not be called again.
4868 * This internally creates a main loop source using g_idle_source_new()
4869 * and attaches it to the main loop context using g_source_attach().
4870 * You can do these steps manually if you need greater control.
4872 * Return value: the ID (greater than 0) of the event source.
4875 g_idle_add (GSourceFunc function,
4878 return g_idle_add_full (G_PRIORITY_DEFAULT_IDLE, function, data, NULL);
4882 * g_idle_remove_by_data:
4883 * @data: the data for the idle source's callback.
4885 * Removes the idle function with the given data.
4887 * Return value: %TRUE if an idle source was found and removed.
4890 g_idle_remove_by_data (gpointer data)
4892 return g_source_remove_by_funcs_user_data (&g_idle_funcs, data);
4896 * g_main_context_invoke:
4897 * @context: (allow-none): a #GMainContext, or %NULL
4898 * @function: function to call
4899 * @data: data to pass to @function
4901 * Invokes a function in such a way that @context is owned during the
4902 * invocation of @function.
4904 * If @context is %NULL then the global default main context — as
4905 * returned by g_main_context_default() — is used.
4907 * If @context is owned by the current thread, @function is called
4908 * directly. Otherwise, if @context is the thread-default main context
4909 * of the current thread and g_main_context_acquire() succeeds, then
4910 * @function is called and g_main_context_release() is called
4913 * In any other case, an idle source is created to call @function and
4914 * that source is attached to @context (presumably to be run in another
4915 * thread). The idle source is attached with #G_PRIORITY_DEFAULT
4916 * priority. If you want a different priority, use
4917 * g_main_context_invoke_full().
4919 * Note that, as with normal idle functions, @function should probably
4920 * return %FALSE. If it returns %TRUE, it will be continuously run in a
4921 * loop (and may prevent this call from returning).
4926 g_main_context_invoke (GMainContext *context,
4927 GSourceFunc function,
4930 g_main_context_invoke_full (context,
4932 function, data, NULL);
4936 * g_main_context_invoke_full:
4937 * @context: (allow-none): a #GMainContext, or %NULL
4938 * @priority: the priority at which to run @function
4939 * @function: function to call
4940 * @data: data to pass to @function
4941 * @notify: (allow-none): a function to call when @data is no longer in use, or %NULL.
4943 * Invokes a function in such a way that @context is owned during the
4944 * invocation of @function.
4946 * This function is the same as g_main_context_invoke() except that it
4947 * lets you specify the priority incase @function ends up being
4948 * scheduled as an idle and also lets you give a #GDestroyNotify for @data.
4950 * @notify should not assume that it is called from any particular
4951 * thread or with any particular context acquired.
4956 g_main_context_invoke_full (GMainContext *context,
4958 GSourceFunc function,
4960 GDestroyNotify notify)
4962 g_return_if_fail (function != NULL);
4965 context = g_main_context_default ();
4967 if (g_main_context_is_owner (context))
4969 while (function (data));
4976 GMainContext *thread_default;
4978 thread_default = g_main_context_get_thread_default ();
4980 if (!thread_default)
4981 thread_default = g_main_context_default ();
4983 if (thread_default == context && g_main_context_acquire (context))
4985 while (function (data));
4987 g_main_context_release (context);
4996 source = g_idle_source_new ();
4997 g_source_set_priority (source, priority);
4998 g_source_set_callback (source, function, data, notify);
4999 g_source_attach (source, context);
5000 g_source_unref (source);
5006 glib_worker_main (gpointer data)
5010 g_main_context_iteration (glib_worker_context, TRUE);
5013 if (any_unix_signal_pending)
5014 dispatch_unix_signals ();
5018 return NULL; /* worst GCC warning message ever... */
5022 g_get_worker_context (void)
5024 static gsize initialised;
5026 if (g_once_init_enter (&initialised))
5028 /* mask all signals in the worker thread */
5034 pthread_sigmask (SIG_SETMASK, &all, &prev_mask);
5036 glib_worker_context = g_main_context_new ();
5037 g_thread_new ("gmain", glib_worker_main, NULL);
5039 pthread_sigmask (SIG_SETMASK, &prev_mask, NULL);
5041 g_once_init_leave (&initialised, TRUE);
5044 return glib_worker_context;