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 GMainContext *glib_worker_context;
405 G_LOCK_DEFINE_STATIC (main_loop);
406 static GMainContext *default_main_context;
411 /* UNIX signals work by marking one of these variables then waking the
412 * worker context to check on them and dispatch accordingly.
414 #ifdef HAVE_SIG_ATOMIC_T
415 static volatile sig_atomic_t unix_signal_pending[NSIG];
416 static volatile sig_atomic_t any_unix_signal_pending;
418 static volatile int unix_signal_pending[NSIG];
419 static volatile int any_unix_signal_pending;
422 /* Guards all the data below */
423 G_LOCK_DEFINE_STATIC (unix_signal_lock);
424 static GSList *unix_signal_watches;
425 static GSList *unix_child_watches;
427 static GSourceFuncs g_unix_signal_funcs =
429 g_unix_signal_watch_prepare,
430 g_unix_signal_watch_check,
431 g_unix_signal_watch_dispatch,
432 g_unix_signal_watch_finalize
434 #endif /* !G_OS_WIN32 */
435 G_LOCK_DEFINE_STATIC (main_context_list);
436 static GSList *main_context_list = NULL;
438 GSourceFuncs g_timeout_funcs =
446 GSourceFuncs g_child_watch_funcs =
448 g_child_watch_prepare,
450 g_child_watch_dispatch,
451 g_child_watch_finalize
454 GSourceFuncs g_idle_funcs =
463 * g_main_context_ref:
464 * @context: a #GMainContext
466 * Increases the reference count on a #GMainContext object by one.
468 * Returns: the @context that was passed in (since 2.6)
471 g_main_context_ref (GMainContext *context)
473 g_return_val_if_fail (context != NULL, NULL);
474 g_return_val_if_fail (g_atomic_int_get (&context->ref_count) > 0, NULL);
476 g_atomic_int_inc (&context->ref_count);
482 poll_rec_list_free (GMainContext *context,
485 g_slice_free_chain (GPollRec, list, next);
489 * g_main_context_unref:
490 * @context: a #GMainContext
492 * Decreases the reference count on a #GMainContext object by one. If
493 * the result is zero, free the context and free all associated memory.
496 g_main_context_unref (GMainContext *context)
501 g_return_if_fail (context != NULL);
502 g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
504 if (!g_atomic_int_dec_and_test (&context->ref_count))
507 G_LOCK (main_context_list);
508 main_context_list = g_slist_remove (main_context_list, context);
509 G_UNLOCK (main_context_list);
511 g_source_iter_init (&iter, context, TRUE);
512 while (g_source_iter_next (&iter, &source))
513 g_source_destroy_internal (source, context, FALSE);
515 g_mutex_clear (&context->mutex);
517 g_ptr_array_free (context->pending_dispatches, TRUE);
518 g_free (context->cached_poll_array);
520 poll_rec_list_free (context, context->poll_records);
522 g_wakeup_free (context->wakeup);
523 g_cond_clear (&context->cond);
529 * g_main_context_new:
531 * Creates a new #GMainContext structure.
533 * Return value: the new #GMainContext
536 g_main_context_new (void)
538 static gsize initialised;
539 GMainContext *context;
541 if (g_once_init_enter (&initialised))
543 #ifdef G_MAIN_POLL_DEBUG
544 if (getenv ("G_MAIN_POLL_DEBUG") != NULL)
545 _g_main_poll_debug = TRUE;
548 g_once_init_leave (&initialised, TRUE);
551 context = g_new0 (GMainContext, 1);
553 g_mutex_init (&context->mutex);
554 g_cond_init (&context->cond);
556 context->owner = NULL;
557 context->waiters = NULL;
559 context->ref_count = 1;
561 context->next_id = 1;
563 context->source_lists = NULL;
565 context->poll_func = g_poll;
567 context->cached_poll_array = NULL;
568 context->cached_poll_array_size = 0;
570 context->pending_dispatches = g_ptr_array_new ();
572 context->time_is_fresh = FALSE;
574 context->wakeup = g_wakeup_new ();
575 g_wakeup_get_pollfd (context->wakeup, &context->wake_up_rec);
576 g_main_context_add_poll_unlocked (context, 0, &context->wake_up_rec);
578 G_LOCK (main_context_list);
579 main_context_list = g_slist_append (main_context_list, context);
581 #ifdef G_MAIN_POLL_DEBUG
582 if (_g_main_poll_debug)
583 g_print ("created context=%p\n", context);
586 G_UNLOCK (main_context_list);
592 * g_main_context_default:
594 * Returns the global default main context. This is the main context
595 * used for main loop functions when a main loop is not explicitly
596 * specified, and corresponds to the "main" main loop. See also
597 * g_main_context_get_thread_default().
599 * Return value: (transfer none): the global default main context.
602 g_main_context_default (void)
608 if (!default_main_context)
610 default_main_context = g_main_context_new ();
611 #ifdef G_MAIN_POLL_DEBUG
612 if (_g_main_poll_debug)
613 g_print ("default context=%p\n", default_main_context);
617 G_UNLOCK (main_loop);
619 return default_main_context;
623 free_context (gpointer data)
625 GMainContext *context = data;
627 g_main_context_release (context);
629 g_main_context_unref (context);
633 free_context_stack (gpointer data)
635 g_queue_free_full((GQueue *) data, (GDestroyNotify) free_context);
638 static GPrivate thread_context_stack = G_PRIVATE_INIT (free_context_stack);
641 * g_main_context_push_thread_default:
642 * @context: (allow-none): a #GMainContext, or %NULL for the global default context
644 * Acquires @context and sets it as the thread-default context for the
645 * current thread. This will cause certain asynchronous operations
646 * (such as most <link linkend="gio">gio</link>-based I/O) which are
647 * started in this thread to run under @context and deliver their
648 * results to its main loop, rather than running under the global
649 * default context in the main thread. Note that calling this function
650 * changes the context returned by
651 * g_main_context_get_thread_default(), <emphasis>not</emphasis> the
652 * one returned by g_main_context_default(), so it does not affect the
653 * context used by functions like g_idle_add().
655 * Normally you would call this function shortly after creating a new
656 * thread, passing it a #GMainContext which will be run by a
657 * #GMainLoop in that thread, to set a new default context for all
658 * async operations in that thread. (In this case, you don't need to
659 * ever call g_main_context_pop_thread_default().) In some cases
660 * however, you may want to schedule a single operation in a
661 * non-default context, or temporarily use a non-default context in
662 * the main thread. In that case, you can wrap the call to the
663 * asynchronous operation inside a
664 * g_main_context_push_thread_default() /
665 * g_main_context_pop_thread_default() pair, but it is up to you to
666 * ensure that no other asynchronous operations accidentally get
667 * started while the non-default context is active.
669 * Beware that libraries that predate this function may not correctly
670 * handle being used from a thread with a thread-default context. Eg,
671 * see g_file_supports_thread_contexts().
676 g_main_context_push_thread_default (GMainContext *context)
679 gboolean acquired_context;
681 acquired_context = g_main_context_acquire (context);
682 g_return_if_fail (acquired_context);
684 if (context == g_main_context_default ())
687 g_main_context_ref (context);
689 stack = g_private_get (&thread_context_stack);
692 stack = g_queue_new ();
693 g_private_set (&thread_context_stack, stack);
696 g_queue_push_head (stack, context);
700 * g_main_context_pop_thread_default:
701 * @context: (allow-none): a #GMainContext object, or %NULL
703 * Pops @context off the thread-default context stack (verifying that
704 * it was on the top of the stack).
709 g_main_context_pop_thread_default (GMainContext *context)
713 if (context == g_main_context_default ())
716 stack = g_private_get (&thread_context_stack);
718 g_return_if_fail (stack != NULL);
719 g_return_if_fail (g_queue_peek_head (stack) == context);
721 g_queue_pop_head (stack);
723 g_main_context_release (context);
725 g_main_context_unref (context);
729 * g_main_context_get_thread_default:
731 * Gets the thread-default #GMainContext for this thread. Asynchronous
732 * operations that want to be able to be run in contexts other than
733 * the default one should call this method or
734 * g_main_context_ref_thread_default() to get a #GMainContext to add
735 * their #GSource<!-- -->s to. (Note that even in single-threaded
736 * programs applications may sometimes want to temporarily push a
737 * non-default context, so it is not safe to assume that this will
738 * always return %NULL if you are running in the default thread.)
740 * If you need to hold a reference on the context, use
741 * g_main_context_ref_thread_default() instead.
743 * Returns: (transfer none): the thread-default #GMainContext, or
744 * %NULL if the thread-default context is the global default context.
749 g_main_context_get_thread_default (void)
753 stack = g_private_get (&thread_context_stack);
755 return g_queue_peek_head (stack);
761 * g_main_context_ref_thread_default:
763 * Gets the thread-default #GMainContext for this thread, as with
764 * g_main_context_get_thread_default(), but also adds a reference to
765 * it with g_main_context_ref(). In addition, unlike
766 * g_main_context_get_thread_default(), if the thread-default context
767 * is the global default context, this will return that #GMainContext
768 * (with a ref added to it) rather than returning %NULL.
770 * Returns: (transfer full): the thread-default #GMainContext. Unref
771 * with g_main_context_unref() when you are done with it.
776 g_main_context_ref_thread_default (void)
778 GMainContext *context;
780 context = g_main_context_get_thread_default ();
782 context = g_main_context_default ();
783 return g_main_context_ref (context);
786 /* Hooks for adding to the main loop */
790 * @source_funcs: structure containing functions that implement
791 * the sources behavior.
792 * @struct_size: size of the #GSource structure to create.
794 * Creates a new #GSource structure. The size is specified to
795 * allow creating structures derived from #GSource that contain
796 * additional data. The size passed in must be at least
797 * <literal>sizeof (GSource)</literal>.
799 * The source will not initially be associated with any #GMainContext
800 * and must be added to one with g_source_attach() before it will be
803 * Return value: the newly-created #GSource.
806 g_source_new (GSourceFuncs *source_funcs,
811 g_return_val_if_fail (source_funcs != NULL, NULL);
812 g_return_val_if_fail (struct_size >= sizeof (GSource), NULL);
814 source = (GSource*) g_malloc0 (struct_size);
815 source->priv = g_slice_new0 (GSourcePrivate);
816 source->source_funcs = source_funcs;
817 source->ref_count = 1;
819 source->priority = G_PRIORITY_DEFAULT;
821 source->flags = G_HOOK_FLAG_ACTIVE;
823 /* NULL/0 initialization for all other fields */
828 /* Holds context's lock */
830 g_source_iter_init (GSourceIter *iter,
831 GMainContext *context,
834 iter->context = context;
835 iter->current_list = NULL;
837 iter->may_modify = may_modify;
840 /* Holds context's lock */
842 g_source_iter_next (GSourceIter *iter, GSource **source)
844 GSource *next_source;
847 next_source = iter->source->next;
853 if (iter->current_list)
854 iter->current_list = iter->current_list->next;
856 iter->current_list = iter->context->source_lists;
858 if (iter->current_list)
860 GSourceList *source_list = iter->current_list->data;
862 next_source = source_list->head;
866 /* Note: unreffing iter->source could potentially cause its
867 * GSourceList to be removed from source_lists (if iter->source is
868 * the only source in its list, and it is destroyed), so we have to
869 * keep it reffed until after we advance iter->current_list, above.
872 if (iter->source && iter->may_modify)
873 SOURCE_UNREF (iter->source, iter->context);
874 iter->source = next_source;
875 if (iter->source && iter->may_modify)
876 iter->source->ref_count++;
878 *source = iter->source;
879 return *source != NULL;
882 /* Holds context's lock. Only necessary to call if you broke out of
883 * the g_source_iter_next() loop early.
886 g_source_iter_clear (GSourceIter *iter)
888 if (iter->source && iter->may_modify)
890 SOURCE_UNREF (iter->source, iter->context);
895 /* Holds context's lock
898 find_source_list_for_priority (GMainContext *context,
903 GSourceList *source_list;
906 for (iter = context->source_lists; iter != NULL; last = iter, iter = iter->next)
908 source_list = iter->data;
910 if (source_list->priority == priority)
913 if (source_list->priority > priority)
918 source_list = g_slice_new0 (GSourceList);
919 source_list->priority = priority;
920 context->source_lists = g_list_insert_before (context->source_lists,
930 source_list = g_slice_new0 (GSourceList);
931 source_list->priority = priority;
934 context->source_lists = g_list_append (NULL, source_list);
937 /* This just appends source_list to the end of
938 * context->source_lists without having to walk the list again.
940 last = g_list_append (last, source_list);
945 /* Holds context's lock
948 source_add_to_context (GSource *source,
949 GMainContext *context)
951 GSourceList *source_list;
952 GSource *prev, *next;
954 source_list = find_source_list_for_priority (context, source->priority, TRUE);
956 if (source->priv->parent_source)
958 g_assert (source_list->head != NULL);
960 /* Put the source immediately before its parent */
961 prev = source->priv->parent_source->prev;
962 next = source->priv->parent_source;
966 prev = source_list->tail;
974 source_list->tail = source;
980 source_list->head = source;
983 /* Holds context's lock
986 source_remove_from_context (GSource *source,
987 GMainContext *context)
989 GSourceList *source_list;
991 source_list = find_source_list_for_priority (context, source->priority, FALSE);
992 g_return_if_fail (source_list != NULL);
995 source->prev->next = source->next;
997 source_list->head = source->next;
1000 source->next->prev = source->prev;
1002 source_list->tail = source->prev;
1004 source->prev = NULL;
1005 source->next = NULL;
1007 if (source_list->head == NULL)
1009 context->source_lists = g_list_remove (context->source_lists, source_list);
1010 g_slice_free (GSourceList, source_list);
1015 g_source_attach_unlocked (GSource *source,
1016 GMainContext *context)
1021 source->context = context;
1022 result = source->source_id = context->next_id++;
1024 source->ref_count++;
1025 source_add_to_context (source, context);
1027 tmp_list = source->poll_fds;
1030 g_main_context_add_poll_unlocked (context, source->priority, tmp_list->data);
1031 tmp_list = tmp_list->next;
1034 tmp_list = source->priv->child_sources;
1037 g_source_attach_unlocked (tmp_list->data, context);
1038 tmp_list = tmp_list->next;
1046 * @source: a #GSource
1047 * @context: (allow-none): a #GMainContext (if %NULL, the default context will be used)
1049 * Adds a #GSource to a @context so that it will be executed within
1050 * that context. Remove it by calling g_source_destroy().
1052 * Return value: the ID (greater than 0) for the source within the
1056 g_source_attach (GSource *source,
1057 GMainContext *context)
1061 g_return_val_if_fail (source->context == NULL, 0);
1062 g_return_val_if_fail (!SOURCE_DESTROYED (source), 0);
1065 context = g_main_context_default ();
1067 LOCK_CONTEXT (context);
1069 result = g_source_attach_unlocked (source, context);
1071 /* If another thread has acquired the context, wake it up since it
1072 * might be in poll() right now.
1074 if (context->owner && context->owner != G_THREAD_SELF)
1075 g_wakeup_signal (context->wakeup);
1077 UNLOCK_CONTEXT (context);
1083 g_source_destroy_internal (GSource *source,
1084 GMainContext *context,
1088 LOCK_CONTEXT (context);
1090 if (!SOURCE_DESTROYED (source))
1093 gpointer old_cb_data;
1094 GSourceCallbackFuncs *old_cb_funcs;
1096 source->flags &= ~G_HOOK_FLAG_ACTIVE;
1098 old_cb_data = source->callback_data;
1099 old_cb_funcs = source->callback_funcs;
1101 source->callback_data = NULL;
1102 source->callback_funcs = NULL;
1106 UNLOCK_CONTEXT (context);
1107 old_cb_funcs->unref (old_cb_data);
1108 LOCK_CONTEXT (context);
1111 if (!SOURCE_BLOCKED (source))
1113 tmp_list = source->poll_fds;
1116 g_main_context_remove_poll_unlocked (context, tmp_list->data);
1117 tmp_list = tmp_list->next;
1121 if (source->priv->child_sources)
1123 /* This is safe because even if a child_source finalizer or
1124 * closure notify tried to modify source->priv->child_sources
1125 * from outside the lock, it would fail since
1126 * SOURCE_DESTROYED(source) is now TRUE.
1128 tmp_list = source->priv->child_sources;
1131 g_source_destroy_internal (tmp_list->data, context, TRUE);
1132 g_source_unref_internal (tmp_list->data, context, TRUE);
1133 tmp_list = tmp_list->next;
1135 g_slist_free (source->priv->child_sources);
1136 source->priv->child_sources = NULL;
1139 g_source_unref_internal (source, context, TRUE);
1143 UNLOCK_CONTEXT (context);
1148 * @source: a #GSource
1150 * Removes a source from its #GMainContext, if any, and mark it as
1151 * destroyed. The source cannot be subsequently added to another
1155 g_source_destroy (GSource *source)
1157 GMainContext *context;
1159 g_return_if_fail (source != NULL);
1161 context = source->context;
1164 g_source_destroy_internal (source, context, FALSE);
1166 source->flags &= ~G_HOOK_FLAG_ACTIVE;
1171 * @source: a #GSource
1173 * Returns the numeric ID for a particular source. The ID of a source
1174 * is a positive integer which is unique within a particular main loop
1175 * context. The reverse
1176 * mapping from ID to source is done by g_main_context_find_source_by_id().
1178 * Return value: the ID (greater than 0) for the source
1181 g_source_get_id (GSource *source)
1185 g_return_val_if_fail (source != NULL, 0);
1186 g_return_val_if_fail (source->context != NULL, 0);
1188 LOCK_CONTEXT (source->context);
1189 result = source->source_id;
1190 UNLOCK_CONTEXT (source->context);
1196 * g_source_get_context:
1197 * @source: a #GSource
1199 * Gets the #GMainContext with which the source is associated.
1200 * Calling this function on a destroyed source is an error.
1202 * Return value: (transfer none) (allow-none): the #GMainContext with which the
1203 * source is associated, or %NULL if the context has not
1204 * yet been added to a source.
1207 g_source_get_context (GSource *source)
1209 g_return_val_if_fail (!SOURCE_DESTROYED (source), NULL);
1211 return source->context;
1215 * g_source_add_poll:
1216 * @source:a #GSource
1217 * @fd: a #GPollFD structure holding information about a file
1218 * descriptor to watch.
1220 * Adds a file descriptor to the set of file descriptors polled for
1221 * this source. This is usually combined with g_source_new() to add an
1222 * event source. The event source's check function will typically test
1223 * the @revents field in the #GPollFD struct and return %TRUE if events need
1227 g_source_add_poll (GSource *source,
1230 GMainContext *context;
1232 g_return_if_fail (source != NULL);
1233 g_return_if_fail (fd != NULL);
1234 g_return_if_fail (!SOURCE_DESTROYED (source));
1236 context = source->context;
1239 LOCK_CONTEXT (context);
1241 source->poll_fds = g_slist_prepend (source->poll_fds, fd);
1245 if (!SOURCE_BLOCKED (source))
1246 g_main_context_add_poll_unlocked (context, source->priority, fd);
1247 UNLOCK_CONTEXT (context);
1252 * g_source_remove_poll:
1253 * @source:a #GSource
1254 * @fd: a #GPollFD structure previously passed to g_source_add_poll().
1256 * Removes a file descriptor from the set of file descriptors polled for
1260 g_source_remove_poll (GSource *source,
1263 GMainContext *context;
1265 g_return_if_fail (source != NULL);
1266 g_return_if_fail (fd != NULL);
1267 g_return_if_fail (!SOURCE_DESTROYED (source));
1269 context = source->context;
1272 LOCK_CONTEXT (context);
1274 source->poll_fds = g_slist_remove (source->poll_fds, fd);
1278 if (!SOURCE_BLOCKED (source))
1279 g_main_context_remove_poll_unlocked (context, fd);
1280 UNLOCK_CONTEXT (context);
1285 * g_source_add_child_source:
1286 * @source:a #GSource
1287 * @child_source: a second #GSource that @source should "poll"
1289 * Adds @child_source to @source as a "polled" source; when @source is
1290 * added to a #GMainContext, @child_source will be automatically added
1291 * with the same priority, when @child_source is triggered, it will
1292 * cause @source to dispatch (in addition to calling its own
1293 * callback), and when @source is destroyed, it will destroy
1294 * @child_source as well. (@source will also still be dispatched if
1295 * its own prepare/check functions indicate that it is ready.)
1297 * If you don't need @child_source to do anything on its own when it
1298 * triggers, you can call g_source_set_dummy_callback() on it to set a
1299 * callback that does nothing (except return %TRUE if appropriate).
1301 * @source will hold a reference on @child_source while @child_source
1302 * is attached to it.
1307 g_source_add_child_source (GSource *source,
1308 GSource *child_source)
1310 GMainContext *context;
1312 g_return_if_fail (source != NULL);
1313 g_return_if_fail (child_source != NULL);
1314 g_return_if_fail (!SOURCE_DESTROYED (source));
1315 g_return_if_fail (!SOURCE_DESTROYED (child_source));
1316 g_return_if_fail (child_source->context == NULL);
1317 g_return_if_fail (child_source->priv->parent_source == NULL);
1319 context = source->context;
1322 LOCK_CONTEXT (context);
1324 source->priv->child_sources = g_slist_prepend (source->priv->child_sources,
1325 g_source_ref (child_source));
1326 child_source->priv->parent_source = source;
1327 g_source_set_priority_unlocked (child_source, NULL, source->priority);
1331 UNLOCK_CONTEXT (context);
1332 g_source_attach (child_source, context);
1337 * g_source_remove_child_source:
1338 * @source:a #GSource
1339 * @child_source: a #GSource previously passed to
1340 * g_source_add_child_source().
1342 * Detaches @child_source from @source and destroys it.
1347 g_source_remove_child_source (GSource *source,
1348 GSource *child_source)
1350 GMainContext *context;
1352 g_return_if_fail (source != NULL);
1353 g_return_if_fail (child_source != NULL);
1354 g_return_if_fail (child_source->priv->parent_source == source);
1355 g_return_if_fail (!SOURCE_DESTROYED (source));
1356 g_return_if_fail (!SOURCE_DESTROYED (child_source));
1358 context = source->context;
1361 LOCK_CONTEXT (context);
1363 source->priv->child_sources = g_slist_remove (source->priv->child_sources, child_source);
1364 g_source_destroy_internal (child_source, context, TRUE);
1365 g_source_unref_internal (child_source, context, TRUE);
1368 UNLOCK_CONTEXT (context);
1372 * g_source_set_callback_indirect:
1373 * @source: the source
1374 * @callback_data: pointer to callback data "object"
1375 * @callback_funcs: functions for reference counting @callback_data
1376 * and getting the callback and data
1378 * Sets the callback function storing the data as a refcounted callback
1379 * "object". This is used internally. Note that calling
1380 * g_source_set_callback_indirect() assumes
1381 * an initial reference count on @callback_data, and thus
1382 * @callback_funcs->unref will eventually be called once more
1383 * than @callback_funcs->ref.
1386 g_source_set_callback_indirect (GSource *source,
1387 gpointer callback_data,
1388 GSourceCallbackFuncs *callback_funcs)
1390 GMainContext *context;
1391 gpointer old_cb_data;
1392 GSourceCallbackFuncs *old_cb_funcs;
1394 g_return_if_fail (source != NULL);
1395 g_return_if_fail (callback_funcs != NULL || callback_data == NULL);
1397 context = source->context;
1400 LOCK_CONTEXT (context);
1402 old_cb_data = source->callback_data;
1403 old_cb_funcs = source->callback_funcs;
1405 source->callback_data = callback_data;
1406 source->callback_funcs = callback_funcs;
1409 UNLOCK_CONTEXT (context);
1412 old_cb_funcs->unref (old_cb_data);
1416 g_source_callback_ref (gpointer cb_data)
1418 GSourceCallback *callback = cb_data;
1420 callback->ref_count++;
1425 g_source_callback_unref (gpointer cb_data)
1427 GSourceCallback *callback = cb_data;
1429 callback->ref_count--;
1430 if (callback->ref_count == 0)
1432 if (callback->notify)
1433 callback->notify (callback->data);
1439 g_source_callback_get (gpointer cb_data,
1444 GSourceCallback *callback = cb_data;
1446 *func = callback->func;
1447 *data = callback->data;
1450 static GSourceCallbackFuncs g_source_callback_funcs = {
1451 g_source_callback_ref,
1452 g_source_callback_unref,
1453 g_source_callback_get,
1457 * g_source_set_callback:
1458 * @source: the source
1459 * @func: a callback function
1460 * @data: the data to pass to callback function
1461 * @notify: (allow-none): a function to call when @data is no longer in use, or %NULL.
1463 * Sets the callback function for a source. The callback for a source is
1464 * called from the source's dispatch function.
1466 * The exact type of @func depends on the type of source; ie. you
1467 * should not count on @func being called with @data as its first
1470 * Typically, you won't use this function. Instead use functions specific
1471 * to the type of source you are using.
1474 g_source_set_callback (GSource *source,
1477 GDestroyNotify notify)
1479 GSourceCallback *new_callback;
1481 g_return_if_fail (source != NULL);
1483 new_callback = g_new (GSourceCallback, 1);
1485 new_callback->ref_count = 1;
1486 new_callback->func = func;
1487 new_callback->data = data;
1488 new_callback->notify = notify;
1490 g_source_set_callback_indirect (source, new_callback, &g_source_callback_funcs);
1495 * g_source_set_funcs:
1496 * @source: a #GSource
1497 * @funcs: the new #GSourceFuncs
1499 * Sets the source functions (can be used to override
1500 * default implementations) of an unattached source.
1505 g_source_set_funcs (GSource *source,
1506 GSourceFuncs *funcs)
1508 g_return_if_fail (source != NULL);
1509 g_return_if_fail (source->context == NULL);
1510 g_return_if_fail (source->ref_count > 0);
1511 g_return_if_fail (funcs != NULL);
1513 source->source_funcs = funcs;
1517 g_source_set_priority_unlocked (GSource *source,
1518 GMainContext *context,
1523 g_return_if_fail (source->priv->parent_source == NULL ||
1524 source->priv->parent_source->priority == priority);
1528 /* Remove the source from the context's source and then
1529 * add it back after so it is sorted in the correct place
1531 source_remove_from_context (source, source->context);
1534 source->priority = priority;
1538 source_add_to_context (source, source->context);
1540 if (!SOURCE_BLOCKED (source))
1542 tmp_list = source->poll_fds;
1545 g_main_context_remove_poll_unlocked (context, tmp_list->data);
1546 g_main_context_add_poll_unlocked (context, priority, tmp_list->data);
1548 tmp_list = tmp_list->next;
1553 if (source->priv->child_sources)
1555 tmp_list = source->priv->child_sources;
1558 g_source_set_priority_unlocked (tmp_list->data, context, priority);
1559 tmp_list = tmp_list->next;
1565 * g_source_set_priority:
1566 * @source: a #GSource
1567 * @priority: the new priority.
1569 * Sets the priority of a source. While the main loop is being run, a
1570 * source will be dispatched if it is ready to be dispatched and no
1571 * sources at a higher (numerically smaller) priority are ready to be
1575 g_source_set_priority (GSource *source,
1578 GMainContext *context;
1580 g_return_if_fail (source != NULL);
1582 context = source->context;
1585 LOCK_CONTEXT (context);
1586 g_source_set_priority_unlocked (source, context, priority);
1588 UNLOCK_CONTEXT (source->context);
1592 * g_source_get_priority:
1593 * @source: a #GSource
1595 * Gets the priority of a source.
1597 * Return value: the priority of the source
1600 g_source_get_priority (GSource *source)
1602 g_return_val_if_fail (source != NULL, 0);
1604 return source->priority;
1608 * g_source_set_can_recurse:
1609 * @source: a #GSource
1610 * @can_recurse: whether recursion is allowed for this source
1612 * Sets whether a source can be called recursively. If @can_recurse is
1613 * %TRUE, then while the source is being dispatched then this source
1614 * will be processed normally. Otherwise, all processing of this
1615 * source is blocked until the dispatch function returns.
1618 g_source_set_can_recurse (GSource *source,
1619 gboolean can_recurse)
1621 GMainContext *context;
1623 g_return_if_fail (source != NULL);
1625 context = source->context;
1628 LOCK_CONTEXT (context);
1631 source->flags |= G_SOURCE_CAN_RECURSE;
1633 source->flags &= ~G_SOURCE_CAN_RECURSE;
1636 UNLOCK_CONTEXT (context);
1640 * g_source_get_can_recurse:
1641 * @source: a #GSource
1643 * Checks whether a source is allowed to be called recursively.
1644 * see g_source_set_can_recurse().
1646 * Return value: whether recursion is allowed.
1649 g_source_get_can_recurse (GSource *source)
1651 g_return_val_if_fail (source != NULL, FALSE);
1653 return (source->flags & G_SOURCE_CAN_RECURSE) != 0;
1658 * g_source_set_name:
1659 * @source: a #GSource
1660 * @name: debug name for the source
1662 * Sets a name for the source, used in debugging and profiling.
1663 * The name defaults to #NULL.
1665 * The source name should describe in a human-readable way
1666 * what the source does. For example, "X11 event queue"
1667 * or "GTK+ repaint idle handler" or whatever it is.
1669 * It is permitted to call this function multiple times, but is not
1670 * recommended due to the potential performance impact. For example,
1671 * one could change the name in the "check" function of a #GSourceFuncs
1672 * to include details like the event type in the source name.
1677 g_source_set_name (GSource *source,
1680 g_return_if_fail (source != NULL);
1682 /* setting back to NULL is allowed, just because it's
1683 * weird if get_name can return NULL but you can't
1687 g_free (source->name);
1688 source->name = g_strdup (name);
1692 * g_source_get_name:
1693 * @source: a #GSource
1695 * Gets a name for the source, used in debugging and profiling.
1696 * The name may be #NULL if it has never been set with
1697 * g_source_set_name().
1699 * Return value: the name of the source
1703 g_source_get_name (GSource *source)
1705 g_return_val_if_fail (source != NULL, NULL);
1707 return source->name;
1711 * g_source_set_name_by_id:
1712 * @tag: a #GSource ID
1713 * @name: debug name for the source
1715 * Sets the name of a source using its ID.
1717 * This is a convenience utility to set source names from the return
1718 * value of g_idle_add(), g_timeout_add(), etc.
1723 g_source_set_name_by_id (guint tag,
1728 g_return_if_fail (tag > 0);
1730 source = g_main_context_find_source_by_id (NULL, tag);
1734 g_source_set_name (source, name);
1740 * @source: a #GSource
1742 * Increases the reference count on a source by one.
1744 * Return value: @source
1747 g_source_ref (GSource *source)
1749 GMainContext *context;
1751 g_return_val_if_fail (source != NULL, NULL);
1753 context = source->context;
1756 LOCK_CONTEXT (context);
1758 source->ref_count++;
1761 UNLOCK_CONTEXT (context);
1766 /* g_source_unref() but possible to call within context lock
1769 g_source_unref_internal (GSource *source,
1770 GMainContext *context,
1773 gpointer old_cb_data = NULL;
1774 GSourceCallbackFuncs *old_cb_funcs = NULL;
1776 g_return_if_fail (source != NULL);
1778 if (!have_lock && context)
1779 LOCK_CONTEXT (context);
1781 source->ref_count--;
1782 if (source->ref_count == 0)
1784 old_cb_data = source->callback_data;
1785 old_cb_funcs = source->callback_funcs;
1787 source->callback_data = NULL;
1788 source->callback_funcs = NULL;
1792 if (!SOURCE_DESTROYED (source))
1793 g_warning (G_STRLOC ": ref_count == 0, but source was still attached to a context!");
1794 source_remove_from_context (source, context);
1797 if (source->source_funcs->finalize)
1800 UNLOCK_CONTEXT (context);
1801 source->source_funcs->finalize (source);
1803 LOCK_CONTEXT (context);
1806 g_free (source->name);
1807 source->name = NULL;
1809 g_slist_free (source->poll_fds);
1810 source->poll_fds = NULL;
1812 g_slice_free (GSourcePrivate, source->priv);
1813 source->priv = NULL;
1818 if (!have_lock && context)
1819 UNLOCK_CONTEXT (context);
1824 UNLOCK_CONTEXT (context);
1826 old_cb_funcs->unref (old_cb_data);
1829 LOCK_CONTEXT (context);
1835 * @source: a #GSource
1837 * Decreases the reference count of a source by one. If the
1838 * resulting reference count is zero the source and associated
1839 * memory will be destroyed.
1842 g_source_unref (GSource *source)
1844 g_return_if_fail (source != NULL);
1846 g_source_unref_internal (source, source->context, FALSE);
1850 * g_main_context_find_source_by_id:
1851 * @context: (allow-none): a #GMainContext (if %NULL, the default context will be used)
1852 * @source_id: the source ID, as returned by g_source_get_id().
1854 * Finds a #GSource given a pair of context and ID.
1856 * Return value: (transfer none): the #GSource if found, otherwise, %NULL
1859 g_main_context_find_source_by_id (GMainContext *context,
1865 g_return_val_if_fail (source_id > 0, NULL);
1867 if (context == NULL)
1868 context = g_main_context_default ();
1870 LOCK_CONTEXT (context);
1872 g_source_iter_init (&iter, context, FALSE);
1873 while (g_source_iter_next (&iter, &source))
1875 if (!SOURCE_DESTROYED (source) &&
1876 source->source_id == source_id)
1879 g_source_iter_clear (&iter);
1881 UNLOCK_CONTEXT (context);
1887 * g_main_context_find_source_by_funcs_user_data:
1888 * @context: (allow-none): a #GMainContext (if %NULL, the default context will be used).
1889 * @funcs: the @source_funcs passed to g_source_new().
1890 * @user_data: the user data from the callback.
1892 * Finds a source with the given source functions and user data. If
1893 * multiple sources exist with the same source function and user data,
1894 * the first one found will be returned.
1896 * Return value: (transfer none): the source, if one was found, otherwise %NULL
1899 g_main_context_find_source_by_funcs_user_data (GMainContext *context,
1900 GSourceFuncs *funcs,
1906 g_return_val_if_fail (funcs != NULL, NULL);
1908 if (context == NULL)
1909 context = g_main_context_default ();
1911 LOCK_CONTEXT (context);
1913 g_source_iter_init (&iter, context, FALSE);
1914 while (g_source_iter_next (&iter, &source))
1916 if (!SOURCE_DESTROYED (source) &&
1917 source->source_funcs == funcs &&
1918 source->callback_funcs)
1920 GSourceFunc callback;
1921 gpointer callback_data;
1923 source->callback_funcs->get (source->callback_data, source, &callback, &callback_data);
1925 if (callback_data == user_data)
1929 g_source_iter_clear (&iter);
1931 UNLOCK_CONTEXT (context);
1937 * g_main_context_find_source_by_user_data:
1938 * @context: a #GMainContext
1939 * @user_data: the user_data for the callback.
1941 * Finds a source with the given user data for the callback. If
1942 * multiple sources exist with the same user data, the first
1943 * one found will be returned.
1945 * Return value: (transfer none): the source, if one was found, otherwise %NULL
1948 g_main_context_find_source_by_user_data (GMainContext *context,
1954 if (context == NULL)
1955 context = g_main_context_default ();
1957 LOCK_CONTEXT (context);
1959 g_source_iter_init (&iter, context, FALSE);
1960 while (g_source_iter_next (&iter, &source))
1962 if (!SOURCE_DESTROYED (source) &&
1963 source->callback_funcs)
1965 GSourceFunc callback;
1966 gpointer callback_data = NULL;
1968 source->callback_funcs->get (source->callback_data, source, &callback, &callback_data);
1970 if (callback_data == user_data)
1974 g_source_iter_clear (&iter);
1976 UNLOCK_CONTEXT (context);
1983 * @tag: the ID of the source to remove.
1985 * Removes the source with the given id from the default main context.
1987 * a #GSource is given by g_source_get_id(), or will be returned by the
1988 * functions g_source_attach(), g_idle_add(), g_idle_add_full(),
1989 * g_timeout_add(), g_timeout_add_full(), g_child_watch_add(),
1990 * g_child_watch_add_full(), g_io_add_watch(), and g_io_add_watch_full().
1992 * See also g_source_destroy(). You must use g_source_destroy() for sources
1993 * added to a non-default main context.
1995 * Return value: %TRUE if the source was found and removed.
1998 g_source_remove (guint tag)
2002 g_return_val_if_fail (tag > 0, FALSE);
2004 source = g_main_context_find_source_by_id (NULL, tag);
2006 g_source_destroy (source);
2008 return source != NULL;
2012 * g_source_remove_by_user_data:
2013 * @user_data: the user_data for the callback.
2015 * Removes a source from the default main loop context given the user
2016 * data for the callback. If multiple sources exist with the same user
2017 * data, only one will be destroyed.
2019 * Return value: %TRUE if a source was found and removed.
2022 g_source_remove_by_user_data (gpointer user_data)
2026 source = g_main_context_find_source_by_user_data (NULL, user_data);
2029 g_source_destroy (source);
2037 * g_source_remove_by_funcs_user_data:
2038 * @funcs: The @source_funcs passed to g_source_new()
2039 * @user_data: the user data for the callback
2041 * Removes a source from the default main loop context given the
2042 * source functions and user data. If multiple sources exist with the
2043 * same source functions and user data, only one will be destroyed.
2045 * Return value: %TRUE if a source was found and removed.
2048 g_source_remove_by_funcs_user_data (GSourceFuncs *funcs,
2053 g_return_val_if_fail (funcs != NULL, FALSE);
2055 source = g_main_context_find_source_by_funcs_user_data (NULL, funcs, user_data);
2058 g_source_destroy (source);
2066 * g_get_current_time:
2067 * @result: #GTimeVal structure in which to store current time.
2069 * Equivalent to the UNIX gettimeofday() function, but portable.
2071 * You may find g_get_real_time() to be more convenient.
2074 g_get_current_time (GTimeVal *result)
2079 g_return_if_fail (result != NULL);
2081 /*this is required on alpha, there the timeval structs are int's
2082 not longs and a cast only would fail horribly*/
2083 gettimeofday (&r, NULL);
2084 result->tv_sec = r.tv_sec;
2085 result->tv_usec = r.tv_usec;
2090 g_return_if_fail (result != NULL);
2092 GetSystemTimeAsFileTime (&ft);
2093 memmove (&time64, &ft, sizeof (FILETIME));
2095 /* Convert from 100s of nanoseconds since 1601-01-01
2096 * to Unix epoch. Yes, this is Y2038 unsafe.
2098 time64 -= G_GINT64_CONSTANT (116444736000000000);
2101 result->tv_sec = time64 / 1000000;
2102 result->tv_usec = time64 % 1000000;
2109 * Queries the system wall-clock time.
2111 * This call is functionally equivalent to g_get_current_time() except
2112 * that the return value is often more convenient than dealing with a
2115 * You should only use this call if you are actually interested in the real
2116 * wall-clock time. g_get_monotonic_time() is probably more useful for
2117 * measuring intervals.
2119 * Returns: the number of microseconds since January 1, 1970 UTC.
2124 g_get_real_time (void)
2128 g_get_current_time (&tv);
2130 return (((gint64) tv.tv_sec) * 1000000) + tv.tv_usec;
2134 static ULONGLONG (*g_GetTickCount64) (void) = NULL;
2135 static guint32 g_win32_tick_epoch = 0;
2137 G_GNUC_INTERNAL void
2138 g_clock_win32_init (void)
2142 g_GetTickCount64 = NULL;
2143 kernel32 = GetModuleHandle ("KERNEL32.DLL");
2144 if (kernel32 != NULL)
2145 g_GetTickCount64 = (void *) GetProcAddress (kernel32, "GetTickCount64");
2146 g_win32_tick_epoch = ((guint32)GetTickCount()) >> 31;
2151 * g_get_monotonic_time:
2153 * Queries the system monotonic time, if available.
2155 * On POSIX systems with clock_gettime() and <literal>CLOCK_MONOTONIC</literal> this call
2156 * is a very shallow wrapper for that. Otherwise, we make a best effort
2157 * that probably involves returning the wall clock time (with at least
2158 * microsecond accuracy, subject to the limitations of the OS kernel).
2160 * It's important to note that POSIX <literal>CLOCK_MONOTONIC</literal> does
2161 * not count time spent while the machine is suspended.
2163 * On Windows, "limitations of the OS kernel" is a rather substantial
2164 * statement. Depending on the configuration of the system, the wall
2165 * clock time is updated as infrequently as 64 times a second (which
2166 * is approximately every 16ms). Also, on XP (but not on Vista or later)
2167 * the monotonic clock is locally monotonic, but may differ in exact
2168 * value between processes due to timer wrap handling.
2170 * Returns: the monotonic time, in microseconds
2175 g_get_monotonic_time (void)
2177 #ifdef HAVE_CLOCK_GETTIME
2178 /* librt clock_gettime() is our first choice */
2181 #ifdef CLOCK_MONOTONIC
2182 clock_gettime (CLOCK_MONOTONIC, &ts);
2184 clock_gettime (CLOCK_REALTIME, &ts);
2187 /* In theory monotonic time can have any epoch.
2189 * glib presently assumes the following:
2191 * 1) The epoch comes some time after the birth of Jesus of Nazareth, but
2192 * not more than 10000 years later.
2194 * 2) The current time also falls sometime within this range.
2196 * These two reasonable assumptions leave us with a maximum deviation from
2197 * the epoch of 10000 years, or 315569520000000000 seconds.
2199 * If we restrict ourselves to this range then the number of microseconds
2200 * will always fit well inside the constraints of a int64 (by a factor of
2203 * If you actually hit the following assertion, probably you should file a
2204 * bug against your operating system for being excessively silly.
2206 g_assert (G_GINT64_CONSTANT (-315569520000000000) < ts.tv_sec &&
2207 ts.tv_sec < G_GINT64_CONSTANT (315569520000000000));
2209 return (((gint64) ts.tv_sec) * 1000000) + (ts.tv_nsec / 1000);
2211 #elif defined (G_OS_WIN32)
2215 /* There are four sources for the monotonic time on Windows:
2217 * Three are based on a (1 msec accuracy, but only read periodically) clock chip:
2218 * - GetTickCount (GTC)
2219 * 32bit msec counter, updated each ~15msec, wraps in ~50 days
2220 * - GetTickCount64 (GTC64)
2221 * Same as GetTickCount, but extended to 64bit, so no wrap
2222 * Only available in Vista or later
2223 * - timeGetTime (TGT)
2224 * similar to GetTickCount by default: 15msec, 50 day wrap.
2225 * available in winmm.dll (thus known as the multimedia timers)
2226 * However apps can raise the system timer clock frequency using timeBeginPeriod()
2227 * increasing the accuracy up to 1 msec, at a cost in general system performance
2230 * One is based on high precision clocks:
2231 * - QueryPrecisionCounter (QPC)
2232 * This has much higher accuracy, but is not guaranteed monotonic, and
2233 * has lots of complications like clock jumps and different times on different
2234 * CPUs. It also has lower long term accuracy (i.e. it will drift compared to
2235 * the low precision clocks.
2237 * Additionally, the precision available in the timer-based wakeup such as
2238 * MsgWaitForMultipleObjectsEx (which is what the mainloop is based on) is based
2239 * on the TGT resolution, so by default it is ~15msec, but can be increased by apps.
2241 * The QPC timer has too many issues to be used as is. The only way it could be used
2242 * is to use it to interpolate the lower precision clocks. Firefox does something like
2244 * https://bugzilla.mozilla.org/show_bug.cgi?id=363258
2246 * However this seems quite complicated, so we're not doing this right now.
2248 * The approach we take instead is to use the TGT timer, extending it to 64bit
2249 * either by using the GTC64 value, or if that is not available, a process local
2250 * time epoch that we increment when we detect a timer wrap (assumes that we read
2251 * the time at least once every 50 days).
2254 * - We have a globally consistent monotonic clock on Vista and later
2255 * - We have a locally monotonic clock on XP
2256 * - Apps that need higher precision in timeouts and clock reads can call
2257 * timeBeginPeriod() to increase it as much as they want
2260 if (g_GetTickCount64 != NULL)
2262 guint32 ticks_as_32bit;
2264 ticks = g_GetTickCount64 ();
2265 ticks32 = timeGetTime();
2267 /* GTC64 and TGT are sampled at different times, however they
2268 * have the same base and source (msecs since system boot).
2269 * They can differ by as much as -16 to +16 msecs.
2270 * We can't just inject the low bits into the 64bit counter
2271 * as one of the counters can have wrapped in 32bit space and
2272 * the other not. Instead we calculate the signed difference
2273 * in 32bit space and apply that difference to the 64bit counter.
2275 ticks_as_32bit = (guint32)ticks;
2277 /* We could do some 2's complement hack, but we play it safe */
2278 if (ticks32 - ticks_as_32bit <= G_MAXINT32)
2279 ticks += ticks32 - ticks_as_32bit;
2281 ticks -= ticks_as_32bit - ticks32;
2287 epoch = g_atomic_int_get (&g_win32_tick_epoch);
2289 /* Must read ticks after the epoch. Then we're guaranteed
2290 * that the ticks value we read is higher or equal to any
2291 * previous ones that lead to the writing of the epoch.
2293 ticks32 = timeGetTime();
2295 /* We store the MSB of the current time as the LSB
2296 * of the epoch. Comparing these bits lets us detect when
2297 * the 32bit counter has wrapped so we can increase the
2300 * This will work as long as this function is called at
2301 * least once every ~24 days, which is half the wrap time
2302 * of a 32bit msec counter. I think this is pretty likely.
2304 * Note that g_win32_tick_epoch is a process local state,
2305 * so the monotonic clock will not be the same between
2308 if ((ticks32 >> 31) != (epoch & 1))
2311 g_atomic_int_set (&g_win32_tick_epoch, epoch);
2315 ticks = (guint64)ticks32 | ((guint64)epoch) << 31;
2318 return ticks * 1000;
2320 #else /* !HAVE_CLOCK_GETTIME && ! G_OS_WIN32*/
2324 g_get_current_time (&tv);
2326 return (((gint64) tv.tv_sec) * 1000000) + tv.tv_usec;
2331 g_main_dispatch_free (gpointer dispatch)
2333 g_slice_free (GMainDispatch, dispatch);
2336 /* Running the main loop */
2338 static GMainDispatch *
2341 static GPrivate depth_private = G_PRIVATE_INIT (g_main_dispatch_free);
2342 GMainDispatch *dispatch;
2344 dispatch = g_private_get (&depth_private);
2348 dispatch = g_slice_new0 (GMainDispatch);
2349 g_private_set (&depth_private, dispatch);
2358 * Returns the depth of the stack of calls to
2359 * g_main_context_dispatch() on any #GMainContext in the current thread.
2360 * That is, when called from the toplevel, it gives 0. When
2361 * called from within a callback from g_main_context_iteration()
2362 * (or g_main_loop_run(), etc.) it returns 1. When called from within
2363 * a callback to a recursive call to g_main_context_iteration(),
2364 * it returns 2. And so forth.
2366 * This function is useful in a situation like the following:
2367 * Imagine an extremely simple "garbage collected" system.
2370 * static GList *free_list;
2373 * allocate_memory (gsize size)
2375 * gpointer result = g_malloc (size);
2376 * free_list = g_list_prepend (free_list, result);
2381 * free_allocated_memory (void)
2384 * for (l = free_list; l; l = l->next);
2386 * g_list_free (free_list);
2394 * g_main_context_iteration (NULL, TRUE);
2395 * free_allocated_memory();
2399 * This works from an application, however, if you want to do the same
2400 * thing from a library, it gets more difficult, since you no longer
2401 * control the main loop. You might think you can simply use an idle
2402 * function to make the call to free_allocated_memory(), but that
2403 * doesn't work, since the idle function could be called from a
2404 * recursive callback. This can be fixed by using g_main_depth()
2408 * allocate_memory (gsize size)
2410 * FreeListBlock *block = g_new (FreeListBlock, 1);
2411 * block->mem = g_malloc (size);
2412 * block->depth = g_main_depth ();
2413 * free_list = g_list_prepend (free_list, block);
2414 * return block->mem;
2418 * free_allocated_memory (void)
2422 * int depth = g_main_depth ();
2423 * for (l = free_list; l; );
2425 * GList *next = l->next;
2426 * FreeListBlock *block = l->data;
2427 * if (block->depth > depth)
2429 * g_free (block->mem);
2431 * free_list = g_list_delete_link (free_list, l);
2439 * There is a temptation to use g_main_depth() to solve
2440 * problems with reentrancy. For instance, while waiting for data
2441 * to be received from the network in response to a menu item,
2442 * the menu item might be selected again. It might seem that
2443 * one could make the menu item's callback return immediately
2444 * and do nothing if g_main_depth() returns a value greater than 1.
2445 * However, this should be avoided since the user then sees selecting
2446 * the menu item do nothing. Furthermore, you'll find yourself adding
2447 * these checks all over your code, since there are doubtless many,
2448 * many things that the user could do. Instead, you can use the
2449 * following techniques:
2454 * Use gtk_widget_set_sensitive() or modal dialogs to prevent
2455 * the user from interacting with elements while the main
2456 * loop is recursing.
2461 * Avoid main loop recursion in situations where you can't handle
2462 * arbitrary callbacks. Instead, structure your code so that you
2463 * simply return to the main loop and then get called again when
2464 * there is more work to do.
2469 * Return value: The main loop recursion level in the current thread
2474 GMainDispatch *dispatch = get_dispatch ();
2475 return dispatch->depth;
2479 * g_main_current_source:
2481 * Returns the currently firing source for this thread.
2483 * Return value: (transfer none): The currently firing source or %NULL.
2488 g_main_current_source (void)
2490 GMainDispatch *dispatch = get_dispatch ();
2491 return dispatch->dispatching_sources ? dispatch->dispatching_sources->data : NULL;
2495 * g_source_is_destroyed:
2496 * @source: a #GSource
2498 * Returns whether @source has been destroyed.
2500 * This is important when you operate upon your objects
2501 * from within idle handlers, but may have freed the object
2502 * before the dispatch of your idle handler.
2506 * idle_callback (gpointer data)
2508 * SomeWidget *self = data;
2510 * GDK_THREADS_ENTER (<!-- -->);
2511 * /<!-- -->* do stuff with self *<!-- -->/
2512 * self->idle_id = 0;
2513 * GDK_THREADS_LEAVE (<!-- -->);
2515 * return G_SOURCE_REMOVE;
2519 * some_widget_do_stuff_later (SomeWidget *self)
2521 * self->idle_id = g_idle_add (idle_callback, self);
2525 * some_widget_finalize (GObject *object)
2527 * SomeWidget *self = SOME_WIDGET (object);
2529 * if (self->idle_id)
2530 * g_source_remove (self->idle_id);
2532 * G_OBJECT_CLASS (parent_class)->finalize (object);
2536 * This will fail in a multi-threaded application if the
2537 * widget is destroyed before the idle handler fires due
2538 * to the use after free in the callback. A solution, to
2539 * this particular problem, is to check to if the source
2540 * has already been destroy within the callback.
2544 * idle_callback (gpointer data)
2546 * SomeWidget *self = data;
2548 * GDK_THREADS_ENTER ();
2549 * if (!g_source_is_destroyed (g_main_current_source ()))
2551 * /<!-- -->* do stuff with self *<!-- -->/
2553 * GDK_THREADS_LEAVE ();
2559 * Return value: %TRUE if the source has been destroyed
2564 g_source_is_destroyed (GSource *source)
2566 return SOURCE_DESTROYED (source);
2569 /* Temporarily remove all this source's file descriptors from the
2570 * poll(), so that if data comes available for one of the file descriptors
2571 * we don't continually spin in the poll()
2573 /* HOLDS: source->context's lock */
2575 block_source (GSource *source)
2579 g_return_if_fail (!SOURCE_BLOCKED (source));
2581 source->flags |= G_SOURCE_BLOCKED;
2583 tmp_list = source->poll_fds;
2586 g_main_context_remove_poll_unlocked (source->context, tmp_list->data);
2587 tmp_list = tmp_list->next;
2590 if (source->priv && source->priv->child_sources)
2592 tmp_list = source->priv->child_sources;
2595 block_source (tmp_list->data);
2596 tmp_list = tmp_list->next;
2601 /* HOLDS: source->context's lock */
2603 unblock_source (GSource *source)
2607 g_return_if_fail (SOURCE_BLOCKED (source)); /* Source already unblocked */
2608 g_return_if_fail (!SOURCE_DESTROYED (source));
2610 source->flags &= ~G_SOURCE_BLOCKED;
2612 tmp_list = source->poll_fds;
2615 g_main_context_add_poll_unlocked (source->context, source->priority, tmp_list->data);
2616 tmp_list = tmp_list->next;
2619 if (source->priv && source->priv->child_sources)
2621 tmp_list = source->priv->child_sources;
2624 unblock_source (tmp_list->data);
2625 tmp_list = tmp_list->next;
2630 /* HOLDS: context's lock */
2632 g_main_dispatch (GMainContext *context)
2634 GMainDispatch *current = get_dispatch ();
2637 for (i = 0; i < context->pending_dispatches->len; i++)
2639 GSource *source = context->pending_dispatches->pdata[i];
2641 context->pending_dispatches->pdata[i] = NULL;
2644 source->flags &= ~G_SOURCE_READY;
2646 if (!SOURCE_DESTROYED (source))
2648 gboolean was_in_call;
2649 gpointer user_data = NULL;
2650 GSourceFunc callback = NULL;
2651 GSourceCallbackFuncs *cb_funcs;
2653 gboolean need_destroy;
2655 gboolean (*dispatch) (GSource *,
2658 GSList current_source_link;
2660 dispatch = source->source_funcs->dispatch;
2661 cb_funcs = source->callback_funcs;
2662 cb_data = source->callback_data;
2665 cb_funcs->ref (cb_data);
2667 if ((source->flags & G_SOURCE_CAN_RECURSE) == 0)
2668 block_source (source);
2670 was_in_call = source->flags & G_HOOK_FLAG_IN_CALL;
2671 source->flags |= G_HOOK_FLAG_IN_CALL;
2674 cb_funcs->get (cb_data, source, &callback, &user_data);
2676 UNLOCK_CONTEXT (context);
2679 /* The on-stack allocation of the GSList is unconventional, but
2680 * we know that the lifetime of the link is bounded to this
2681 * function as the link is kept in a thread specific list and
2682 * not manipulated outside of this function and its descendants.
2683 * Avoiding the overhead of a g_slist_alloc() is useful as many
2684 * applications do little more than dispatch events.
2686 * This is a performance hack - do not revert to g_slist_prepend()!
2688 current_source_link.data = source;
2689 current_source_link.next = current->dispatching_sources;
2690 current->dispatching_sources = ¤t_source_link;
2691 need_destroy = ! dispatch (source,
2694 g_assert (current->dispatching_sources == ¤t_source_link);
2695 current->dispatching_sources = current_source_link.next;
2699 cb_funcs->unref (cb_data);
2701 LOCK_CONTEXT (context);
2704 source->flags &= ~G_HOOK_FLAG_IN_CALL;
2706 if (SOURCE_BLOCKED (source) && !SOURCE_DESTROYED (source))
2707 unblock_source (source);
2709 /* Note: this depends on the fact that we can't switch
2710 * sources from one main context to another
2712 if (need_destroy && !SOURCE_DESTROYED (source))
2714 g_assert (source->context == context);
2715 g_source_destroy_internal (source, context, TRUE);
2719 SOURCE_UNREF (source, context);
2722 g_ptr_array_set_size (context->pending_dispatches, 0);
2726 * g_main_context_acquire:
2727 * @context: a #GMainContext
2729 * Tries to become the owner of the specified context.
2730 * If some other thread is the owner of the context,
2731 * returns %FALSE immediately. Ownership is properly
2732 * recursive: the owner can require ownership again
2733 * and will release ownership when g_main_context_release()
2734 * is called as many times as g_main_context_acquire().
2736 * You must be the owner of a context before you
2737 * can call g_main_context_prepare(), g_main_context_query(),
2738 * g_main_context_check(), g_main_context_dispatch().
2740 * Return value: %TRUE if the operation succeeded, and
2741 * this thread is now the owner of @context.
2744 g_main_context_acquire (GMainContext *context)
2746 gboolean result = FALSE;
2747 GThread *self = G_THREAD_SELF;
2749 if (context == NULL)
2750 context = g_main_context_default ();
2752 LOCK_CONTEXT (context);
2754 if (!context->owner)
2756 context->owner = self;
2757 g_assert (context->owner_count == 0);
2760 if (context->owner == self)
2762 context->owner_count++;
2766 UNLOCK_CONTEXT (context);
2772 * g_main_context_release:
2773 * @context: a #GMainContext
2775 * Releases ownership of a context previously acquired by this thread
2776 * with g_main_context_acquire(). If the context was acquired multiple
2777 * times, the ownership will be released only when g_main_context_release()
2778 * is called as many times as it was acquired.
2781 g_main_context_release (GMainContext *context)
2783 if (context == NULL)
2784 context = g_main_context_default ();
2786 LOCK_CONTEXT (context);
2788 context->owner_count--;
2789 if (context->owner_count == 0)
2791 context->owner = NULL;
2793 if (context->waiters)
2795 GMainWaiter *waiter = context->waiters->data;
2796 gboolean loop_internal_waiter = (waiter->mutex == &context->mutex);
2797 context->waiters = g_slist_delete_link (context->waiters,
2799 if (!loop_internal_waiter)
2800 g_mutex_lock (waiter->mutex);
2802 g_cond_signal (waiter->cond);
2804 if (!loop_internal_waiter)
2805 g_mutex_unlock (waiter->mutex);
2809 UNLOCK_CONTEXT (context);
2813 * g_main_context_wait:
2814 * @context: a #GMainContext
2815 * @cond: a condition variable
2816 * @mutex: a mutex, currently held
2818 * Tries to become the owner of the specified context,
2819 * as with g_main_context_acquire(). But if another thread
2820 * is the owner, atomically drop @mutex and wait on @cond until
2821 * that owner releases ownership or until @cond is signaled, then
2822 * try again (once) to become the owner.
2824 * Return value: %TRUE if the operation succeeded, and
2825 * this thread is now the owner of @context.
2828 g_main_context_wait (GMainContext *context,
2832 gboolean result = FALSE;
2833 GThread *self = G_THREAD_SELF;
2834 gboolean loop_internal_waiter;
2836 if (context == NULL)
2837 context = g_main_context_default ();
2839 loop_internal_waiter = (mutex == &context->mutex);
2841 if (!loop_internal_waiter)
2842 LOCK_CONTEXT (context);
2844 if (context->owner && context->owner != self)
2849 waiter.mutex = mutex;
2851 context->waiters = g_slist_append (context->waiters, &waiter);
2853 if (!loop_internal_waiter)
2854 UNLOCK_CONTEXT (context);
2855 g_cond_wait (cond, mutex);
2856 if (!loop_internal_waiter)
2857 LOCK_CONTEXT (context);
2859 context->waiters = g_slist_remove (context->waiters, &waiter);
2862 if (!context->owner)
2864 context->owner = self;
2865 g_assert (context->owner_count == 0);
2868 if (context->owner == self)
2870 context->owner_count++;
2874 if (!loop_internal_waiter)
2875 UNLOCK_CONTEXT (context);
2881 * g_main_context_prepare:
2882 * @context: a #GMainContext
2883 * @priority: location to store priority of highest priority
2884 * source already ready.
2886 * Prepares to poll sources within a main loop. The resulting information
2887 * for polling is determined by calling g_main_context_query ().
2889 * Return value: %TRUE if some source is ready to be dispatched
2893 g_main_context_prepare (GMainContext *context,
2898 gint current_priority = G_MAXINT;
2902 if (context == NULL)
2903 context = g_main_context_default ();
2905 LOCK_CONTEXT (context);
2907 context->time_is_fresh = FALSE;
2909 if (context->in_check_or_prepare)
2911 g_warning ("g_main_context_prepare() called recursively from within a source's check() or "
2912 "prepare() member.");
2913 UNLOCK_CONTEXT (context);
2918 /* If recursing, finish up current dispatch, before starting over */
2919 if (context->pending_dispatches)
2922 g_main_dispatch (context, ¤t_time);
2924 UNLOCK_CONTEXT (context);
2929 /* If recursing, clear list of pending dispatches */
2931 for (i = 0; i < context->pending_dispatches->len; i++)
2933 if (context->pending_dispatches->pdata[i])
2934 SOURCE_UNREF ((GSource *)context->pending_dispatches->pdata[i], context);
2936 g_ptr_array_set_size (context->pending_dispatches, 0);
2938 /* Prepare all sources */
2940 context->timeout = -1;
2942 g_source_iter_init (&iter, context, TRUE);
2943 while (g_source_iter_next (&iter, &source))
2945 gint source_timeout = -1;
2947 if (SOURCE_DESTROYED (source) || SOURCE_BLOCKED (source))
2949 if ((n_ready > 0) && (source->priority > current_priority))
2952 if (!(source->flags & G_SOURCE_READY))
2955 gboolean (*prepare) (GSource *source,
2958 prepare = source->source_funcs->prepare;
2959 context->in_check_or_prepare++;
2960 UNLOCK_CONTEXT (context);
2962 result = (*prepare) (source, &source_timeout);
2964 LOCK_CONTEXT (context);
2965 context->in_check_or_prepare--;
2969 GSource *ready_source = source;
2971 while (ready_source)
2973 ready_source->flags |= G_SOURCE_READY;
2974 ready_source = ready_source->priv->parent_source;
2979 if (source->flags & G_SOURCE_READY)
2982 current_priority = source->priority;
2983 context->timeout = 0;
2986 if (source_timeout >= 0)
2988 if (context->timeout < 0)
2989 context->timeout = source_timeout;
2991 context->timeout = MIN (context->timeout, source_timeout);
2994 g_source_iter_clear (&iter);
2996 UNLOCK_CONTEXT (context);
2999 *priority = current_priority;
3001 return (n_ready > 0);
3005 * g_main_context_query:
3006 * @context: a #GMainContext
3007 * @max_priority: maximum priority source to check
3008 * @timeout_: (out): location to store timeout to be used in polling
3009 * @fds: (out caller-allocates) (array length=n_fds): location to
3010 * store #GPollFD records that need to be polled.
3011 * @n_fds: length of @fds.
3013 * Determines information necessary to poll this main loop.
3015 * Return value: the number of records actually stored in @fds,
3016 * or, if more than @n_fds records need to be stored, the number
3017 * of records that need to be stored.
3020 g_main_context_query (GMainContext *context,
3029 LOCK_CONTEXT (context);
3031 pollrec = context->poll_records;
3033 while (pollrec && max_priority >= pollrec->priority)
3035 /* We need to include entries with fd->events == 0 in the array because
3036 * otherwise if the application changes fd->events behind our back and
3037 * makes it non-zero, we'll be out of sync when we check the fds[] array.
3038 * (Changing fd->events after adding an FD wasn't an anticipated use of
3039 * this API, but it occurs in practice.) */
3042 fds[n_poll].fd = pollrec->fd->fd;
3043 /* In direct contradiction to the Unix98 spec, IRIX runs into
3044 * difficulty if you pass in POLLERR, POLLHUP or POLLNVAL
3045 * flags in the events field of the pollfd while it should
3046 * just ignoring them. So we mask them out here.
3048 fds[n_poll].events = pollrec->fd->events & ~(G_IO_ERR|G_IO_HUP|G_IO_NVAL);
3049 fds[n_poll].revents = 0;
3052 pollrec = pollrec->next;
3056 context->poll_changed = FALSE;
3060 *timeout = context->timeout;
3062 context->time_is_fresh = FALSE;
3065 UNLOCK_CONTEXT (context);
3071 * g_main_context_check:
3072 * @context: a #GMainContext
3073 * @max_priority: the maximum numerical priority of sources to check
3074 * @fds: (array length=n_fds): array of #GPollFD's that was passed to
3075 * the last call to g_main_context_query()
3076 * @n_fds: return value of g_main_context_query()
3078 * Passes the results of polling back to the main loop.
3080 * Return value: %TRUE if some sources are ready to be dispatched.
3083 g_main_context_check (GMainContext *context,
3094 LOCK_CONTEXT (context);
3096 if (context->in_check_or_prepare)
3098 g_warning ("g_main_context_check() called recursively from within a source's check() or "
3099 "prepare() member.");
3100 UNLOCK_CONTEXT (context);
3104 if (context->wake_up_rec.revents)
3105 g_wakeup_acknowledge (context->wakeup);
3107 /* If the set of poll file descriptors changed, bail out
3108 * and let the main loop rerun
3110 if (context->poll_changed)
3112 UNLOCK_CONTEXT (context);
3116 pollrec = context->poll_records;
3120 if (pollrec->fd->events)
3121 pollrec->fd->revents = fds[i].revents;
3123 pollrec = pollrec->next;
3127 g_source_iter_init (&iter, context, TRUE);
3128 while (g_source_iter_next (&iter, &source))
3130 if (SOURCE_DESTROYED (source) || SOURCE_BLOCKED (source))
3132 if ((n_ready > 0) && (source->priority > max_priority))
3135 if (!(source->flags & G_SOURCE_READY))
3138 gboolean (*check) (GSource *source);
3140 check = source->source_funcs->check;
3142 context->in_check_or_prepare++;
3143 UNLOCK_CONTEXT (context);
3145 result = (*check) (source);
3147 LOCK_CONTEXT (context);
3148 context->in_check_or_prepare--;
3152 GSource *ready_source = source;
3154 while (ready_source)
3156 ready_source->flags |= G_SOURCE_READY;
3157 ready_source = ready_source->priv->parent_source;
3162 if (source->flags & G_SOURCE_READY)
3164 source->ref_count++;
3165 g_ptr_array_add (context->pending_dispatches, source);
3169 /* never dispatch sources with less priority than the first
3170 * one we choose to dispatch
3172 max_priority = source->priority;
3175 g_source_iter_clear (&iter);
3177 UNLOCK_CONTEXT (context);
3183 * g_main_context_dispatch:
3184 * @context: a #GMainContext
3186 * Dispatches all pending sources.
3189 g_main_context_dispatch (GMainContext *context)
3191 LOCK_CONTEXT (context);
3193 if (context->pending_dispatches->len > 0)
3195 g_main_dispatch (context);
3198 UNLOCK_CONTEXT (context);
3201 /* HOLDS context lock */
3203 g_main_context_iterate (GMainContext *context,
3210 gboolean some_ready;
3211 gint nfds, allocated_nfds;
3212 GPollFD *fds = NULL;
3214 UNLOCK_CONTEXT (context);
3216 if (!g_main_context_acquire (context))
3218 gboolean got_ownership;
3220 LOCK_CONTEXT (context);
3225 got_ownership = g_main_context_wait (context,
3233 LOCK_CONTEXT (context);
3235 if (!context->cached_poll_array)
3237 context->cached_poll_array_size = context->n_poll_records;
3238 context->cached_poll_array = g_new (GPollFD, context->n_poll_records);
3241 allocated_nfds = context->cached_poll_array_size;
3242 fds = context->cached_poll_array;
3244 UNLOCK_CONTEXT (context);
3246 g_main_context_prepare (context, &max_priority);
3248 while ((nfds = g_main_context_query (context, max_priority, &timeout, fds,
3249 allocated_nfds)) > allocated_nfds)
3251 LOCK_CONTEXT (context);
3253 context->cached_poll_array_size = allocated_nfds = nfds;
3254 context->cached_poll_array = fds = g_new (GPollFD, nfds);
3255 UNLOCK_CONTEXT (context);
3261 g_main_context_poll (context, timeout, max_priority, fds, nfds);
3263 some_ready = g_main_context_check (context, max_priority, fds, nfds);
3266 g_main_context_dispatch (context);
3268 g_main_context_release (context);
3270 LOCK_CONTEXT (context);
3276 * g_main_context_pending:
3277 * @context: (allow-none): a #GMainContext (if %NULL, the default context will be used)
3279 * Checks if any sources have pending events for the given context.
3281 * Return value: %TRUE if events are pending.
3284 g_main_context_pending (GMainContext *context)
3289 context = g_main_context_default();
3291 LOCK_CONTEXT (context);
3292 retval = g_main_context_iterate (context, FALSE, FALSE, G_THREAD_SELF);
3293 UNLOCK_CONTEXT (context);
3299 * g_main_context_iteration:
3300 * @context: (allow-none): a #GMainContext (if %NULL, the default context will be used)
3301 * @may_block: whether the call may block.
3303 * Runs a single iteration for the given main loop. This involves
3304 * checking to see if any event sources are ready to be processed,
3305 * then if no events sources are ready and @may_block is %TRUE, waiting
3306 * for a source to become ready, then dispatching the highest priority
3307 * events sources that are ready. Otherwise, if @may_block is %FALSE
3308 * sources are not waited to become ready, only those highest priority
3309 * events sources will be dispatched (if any), that are ready at this
3310 * given moment without further waiting.
3312 * Note that even when @may_block is %TRUE, it is still possible for
3313 * g_main_context_iteration() to return %FALSE, since the the wait may
3314 * be interrupted for other reasons than an event source becoming ready.
3316 * Return value: %TRUE if events were dispatched.
3319 g_main_context_iteration (GMainContext *context, gboolean may_block)
3324 context = g_main_context_default();
3326 LOCK_CONTEXT (context);
3327 retval = g_main_context_iterate (context, may_block, TRUE, G_THREAD_SELF);
3328 UNLOCK_CONTEXT (context);
3335 * @context: (allow-none): a #GMainContext (if %NULL, the default context will be used).
3336 * @is_running: set to %TRUE to indicate that the loop is running. This
3337 * is not very important since calling g_main_loop_run() will set this to
3340 * Creates a new #GMainLoop structure.
3342 * Return value: a new #GMainLoop.
3345 g_main_loop_new (GMainContext *context,
3346 gboolean is_running)
3351 context = g_main_context_default();
3353 g_main_context_ref (context);
3355 loop = g_new0 (GMainLoop, 1);
3356 loop->context = context;
3357 loop->is_running = is_running != FALSE;
3358 loop->ref_count = 1;
3365 * @loop: a #GMainLoop
3367 * Increases the reference count on a #GMainLoop object by one.
3369 * Return value: @loop
3372 g_main_loop_ref (GMainLoop *loop)
3374 g_return_val_if_fail (loop != NULL, NULL);
3375 g_return_val_if_fail (g_atomic_int_get (&loop->ref_count) > 0, NULL);
3377 g_atomic_int_inc (&loop->ref_count);
3383 * g_main_loop_unref:
3384 * @loop: a #GMainLoop
3386 * Decreases the reference count on a #GMainLoop object by one. If
3387 * the result is zero, free the loop and free all associated memory.
3390 g_main_loop_unref (GMainLoop *loop)
3392 g_return_if_fail (loop != NULL);
3393 g_return_if_fail (g_atomic_int_get (&loop->ref_count) > 0);
3395 if (!g_atomic_int_dec_and_test (&loop->ref_count))
3398 g_main_context_unref (loop->context);
3404 * @loop: a #GMainLoop
3406 * Runs a main loop until g_main_loop_quit() is called on the loop.
3407 * If this is called for the thread of the loop's #GMainContext,
3408 * it will process events from the loop, otherwise it will
3412 g_main_loop_run (GMainLoop *loop)
3414 GThread *self = G_THREAD_SELF;
3416 g_return_if_fail (loop != NULL);
3417 g_return_if_fail (g_atomic_int_get (&loop->ref_count) > 0);
3419 if (!g_main_context_acquire (loop->context))
3421 gboolean got_ownership = FALSE;
3423 /* Another thread owns this context */
3424 LOCK_CONTEXT (loop->context);
3426 g_atomic_int_inc (&loop->ref_count);
3428 if (!loop->is_running)
3429 loop->is_running = TRUE;
3431 while (loop->is_running && !got_ownership)
3432 got_ownership = g_main_context_wait (loop->context,
3433 &loop->context->cond,
3434 &loop->context->mutex);
3436 if (!loop->is_running)
3438 UNLOCK_CONTEXT (loop->context);
3440 g_main_context_release (loop->context);
3441 g_main_loop_unref (loop);
3445 g_assert (got_ownership);
3448 LOCK_CONTEXT (loop->context);
3450 if (loop->context->in_check_or_prepare)
3452 g_warning ("g_main_loop_run(): called recursively from within a source's "
3453 "check() or prepare() member, iteration not possible.");
3457 g_atomic_int_inc (&loop->ref_count);
3458 loop->is_running = TRUE;
3459 while (loop->is_running)
3460 g_main_context_iterate (loop->context, TRUE, TRUE, self);
3462 UNLOCK_CONTEXT (loop->context);
3464 g_main_context_release (loop->context);
3466 g_main_loop_unref (loop);
3471 * @loop: a #GMainLoop
3473 * Stops a #GMainLoop from running. Any calls to g_main_loop_run()
3474 * for the loop will return.
3476 * Note that sources that have already been dispatched when
3477 * g_main_loop_quit() is called will still be executed.
3480 g_main_loop_quit (GMainLoop *loop)
3482 g_return_if_fail (loop != NULL);
3483 g_return_if_fail (g_atomic_int_get (&loop->ref_count) > 0);
3485 LOCK_CONTEXT (loop->context);
3486 loop->is_running = FALSE;
3487 g_wakeup_signal (loop->context->wakeup);
3489 g_cond_broadcast (&loop->context->cond);
3491 UNLOCK_CONTEXT (loop->context);
3495 * g_main_loop_is_running:
3496 * @loop: a #GMainLoop.
3498 * Checks to see if the main loop is currently being run via g_main_loop_run().
3500 * Return value: %TRUE if the mainloop is currently being run.
3503 g_main_loop_is_running (GMainLoop *loop)
3505 g_return_val_if_fail (loop != NULL, FALSE);
3506 g_return_val_if_fail (g_atomic_int_get (&loop->ref_count) > 0, FALSE);
3508 return loop->is_running;
3512 * g_main_loop_get_context:
3513 * @loop: a #GMainLoop.
3515 * Returns the #GMainContext of @loop.
3517 * Return value: (transfer none): the #GMainContext of @loop
3520 g_main_loop_get_context (GMainLoop *loop)
3522 g_return_val_if_fail (loop != NULL, NULL);
3523 g_return_val_if_fail (g_atomic_int_get (&loop->ref_count) > 0, NULL);
3525 return loop->context;
3528 /* HOLDS: context's lock */
3530 g_main_context_poll (GMainContext *context,
3536 #ifdef G_MAIN_POLL_DEBUG
3542 GPollFunc poll_func;
3544 if (n_fds || timeout != 0)
3546 #ifdef G_MAIN_POLL_DEBUG
3547 if (_g_main_poll_debug)
3549 g_print ("polling context=%p n=%d timeout=%d\n",
3550 context, n_fds, timeout);
3551 poll_timer = g_timer_new ();
3555 LOCK_CONTEXT (context);
3557 poll_func = context->poll_func;
3559 UNLOCK_CONTEXT (context);
3560 if ((*poll_func) (fds, n_fds, timeout) < 0 && errno != EINTR)
3563 g_warning ("poll(2) failed due to: %s.",
3564 g_strerror (errno));
3566 /* If g_poll () returns -1, it has already called g_warning() */
3570 #ifdef G_MAIN_POLL_DEBUG
3571 if (_g_main_poll_debug)
3573 LOCK_CONTEXT (context);
3575 g_print ("g_main_poll(%d) timeout: %d - elapsed %12.10f seconds",
3578 g_timer_elapsed (poll_timer, NULL));
3579 g_timer_destroy (poll_timer);
3580 pollrec = context->poll_records;
3582 while (pollrec != NULL)
3587 if (fds[i].fd == pollrec->fd->fd &&
3588 pollrec->fd->events &&
3591 g_print (" [" G_POLLFD_FORMAT " :", fds[i].fd);
3592 if (fds[i].revents & G_IO_IN)
3594 if (fds[i].revents & G_IO_OUT)
3596 if (fds[i].revents & G_IO_PRI)
3598 if (fds[i].revents & G_IO_ERR)
3600 if (fds[i].revents & G_IO_HUP)
3602 if (fds[i].revents & G_IO_NVAL)
3608 pollrec = pollrec->next;
3612 UNLOCK_CONTEXT (context);
3615 } /* if (n_fds || timeout != 0) */
3619 * g_main_context_add_poll:
3620 * @context: (allow-none): a #GMainContext (or %NULL for the default context)
3621 * @fd: a #GPollFD structure holding information about a file
3622 * descriptor to watch.
3623 * @priority: the priority for this file descriptor which should be
3624 * the same as the priority used for g_source_attach() to ensure that the
3625 * file descriptor is polled whenever the results may be needed.
3627 * Adds a file descriptor to the set of file descriptors polled for
3628 * this context. This will very seldom be used directly. Instead
3629 * a typical event source will use g_source_add_poll() instead.
3632 g_main_context_add_poll (GMainContext *context,
3637 context = g_main_context_default ();
3639 g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
3640 g_return_if_fail (fd);
3642 LOCK_CONTEXT (context);
3643 g_main_context_add_poll_unlocked (context, priority, fd);
3644 UNLOCK_CONTEXT (context);
3647 /* HOLDS: main_loop_lock */
3649 g_main_context_add_poll_unlocked (GMainContext *context,
3653 GPollRec *prevrec, *nextrec;
3654 GPollRec *newrec = g_slice_new (GPollRec);
3656 /* This file descriptor may be checked before we ever poll */
3659 newrec->priority = priority;
3661 prevrec = context->poll_records_tail;
3663 while (prevrec && priority < prevrec->priority)
3666 prevrec = prevrec->prev;
3670 prevrec->next = newrec;
3672 context->poll_records = newrec;
3674 newrec->prev = prevrec;
3675 newrec->next = nextrec;
3678 nextrec->prev = newrec;
3680 context->poll_records_tail = newrec;
3682 context->n_poll_records++;
3684 context->poll_changed = TRUE;
3686 /* Now wake up the main loop if it is waiting in the poll() */
3687 g_wakeup_signal (context->wakeup);
3691 * g_main_context_remove_poll:
3692 * @context:a #GMainContext
3693 * @fd: a #GPollFD descriptor previously added with g_main_context_add_poll()
3695 * Removes file descriptor from the set of file descriptors to be
3696 * polled for a particular context.
3699 g_main_context_remove_poll (GMainContext *context,
3703 context = g_main_context_default ();
3705 g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
3706 g_return_if_fail (fd);
3708 LOCK_CONTEXT (context);
3709 g_main_context_remove_poll_unlocked (context, fd);
3710 UNLOCK_CONTEXT (context);
3714 g_main_context_remove_poll_unlocked (GMainContext *context,
3717 GPollRec *pollrec, *prevrec, *nextrec;
3720 pollrec = context->poll_records;
3724 nextrec = pollrec->next;
3725 if (pollrec->fd == fd)
3727 if (prevrec != NULL)
3728 prevrec->next = nextrec;
3730 context->poll_records = nextrec;
3732 if (nextrec != NULL)
3733 nextrec->prev = prevrec;
3735 context->poll_records_tail = prevrec;
3737 g_slice_free (GPollRec, pollrec);
3739 context->n_poll_records--;
3746 context->poll_changed = TRUE;
3748 /* Now wake up the main loop if it is waiting in the poll() */
3749 g_wakeup_signal (context->wakeup);
3753 * g_source_get_current_time:
3754 * @source: a #GSource
3755 * @timeval: #GTimeVal structure in which to store current time.
3757 * This function ignores @source and is otherwise the same as
3758 * g_get_current_time().
3760 * Deprecated: 2.28: use g_source_get_time() instead
3763 g_source_get_current_time (GSource *source,
3766 g_get_current_time (timeval);
3770 * g_source_get_time:
3771 * @source: a #GSource
3773 * Gets the time to be used when checking this source. The advantage of
3774 * calling this function over calling g_get_monotonic_time() directly is
3775 * that when checking multiple sources, GLib can cache a single value
3776 * instead of having to repeatedly get the system monotonic time.
3778 * The time here is the system monotonic time, if available, or some
3779 * other reasonable alternative otherwise. See g_get_monotonic_time().
3781 * Returns: the monotonic time in microseconds
3786 g_source_get_time (GSource *source)
3788 GMainContext *context;
3791 g_return_val_if_fail (source->context != NULL, 0);
3793 context = source->context;
3795 LOCK_CONTEXT (context);
3797 if (!context->time_is_fresh)
3799 context->time = g_get_monotonic_time ();
3800 context->time_is_fresh = TRUE;
3803 result = context->time;
3805 UNLOCK_CONTEXT (context);
3811 * g_main_context_set_poll_func:
3812 * @context: a #GMainContext
3813 * @func: the function to call to poll all file descriptors
3815 * Sets the function to use to handle polling of file descriptors. It
3816 * will be used instead of the poll() system call
3817 * (or GLib's replacement function, which is used where
3818 * poll() isn't available).
3820 * This function could possibly be used to integrate the GLib event
3821 * loop with an external event loop.
3824 g_main_context_set_poll_func (GMainContext *context,
3828 context = g_main_context_default ();
3830 g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
3832 LOCK_CONTEXT (context);
3835 context->poll_func = func;
3837 context->poll_func = g_poll;
3839 UNLOCK_CONTEXT (context);
3843 * g_main_context_get_poll_func:
3844 * @context: a #GMainContext
3846 * Gets the poll function set by g_main_context_set_poll_func().
3848 * Return value: the poll function
3851 g_main_context_get_poll_func (GMainContext *context)
3856 context = g_main_context_default ();
3858 g_return_val_if_fail (g_atomic_int_get (&context->ref_count) > 0, NULL);
3860 LOCK_CONTEXT (context);
3861 result = context->poll_func;
3862 UNLOCK_CONTEXT (context);
3868 * g_main_context_wakeup:
3869 * @context: a #GMainContext
3871 * If @context is currently waiting in a poll(), interrupt
3872 * the poll(), and continue the iteration process.
3875 g_main_context_wakeup (GMainContext *context)
3878 context = g_main_context_default ();
3880 g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
3882 g_wakeup_signal (context->wakeup);
3886 * g_main_context_is_owner:
3887 * @context: a #GMainContext
3889 * Determines whether this thread holds the (recursive)
3890 * ownership of this #GMainContext. This is useful to
3891 * know before waiting on another thread that may be
3892 * blocking to get ownership of @context.
3894 * Returns: %TRUE if current thread is owner of @context.
3899 g_main_context_is_owner (GMainContext *context)
3904 context = g_main_context_default ();
3906 LOCK_CONTEXT (context);
3907 is_owner = context->owner == G_THREAD_SELF;
3908 UNLOCK_CONTEXT (context);
3916 g_timeout_set_expiration (GTimeoutSource *timeout_source,
3917 gint64 current_time)
3919 timeout_source->expiration = current_time +
3920 (guint64) timeout_source->interval * 1000;
3922 if (timeout_source->seconds)
3925 static gint timer_perturb = -1;
3927 if (timer_perturb == -1)
3930 * we want a per machine/session unique 'random' value; try the dbus
3931 * address first, that has a UUID in it. If there is no dbus, use the
3932 * hostname for hashing.
3934 const char *session_bus_address = g_getenv ("DBUS_SESSION_BUS_ADDRESS");
3935 if (!session_bus_address)
3936 session_bus_address = g_getenv ("HOSTNAME");
3937 if (session_bus_address)
3938 timer_perturb = ABS ((gint) g_str_hash (session_bus_address)) % 1000000;
3943 /* We want the microseconds part of the timeout to land on the
3944 * 'timer_perturb' mark, but we need to make sure we don't try to
3945 * set the timeout in the past. We do this by ensuring that we
3946 * always only *increase* the expiration time by adding a full
3947 * second in the case that the microsecond portion decreases.
3949 timeout_source->expiration -= timer_perturb;
3951 remainder = timeout_source->expiration % 1000000;
3952 if (remainder >= 1000000/4)
3953 timeout_source->expiration += 1000000;
3955 timeout_source->expiration -= remainder;
3956 timeout_source->expiration += timer_perturb;
3961 g_timeout_prepare (GSource *source,
3964 GTimeoutSource *timeout_source = (GTimeoutSource *) source;
3965 gint64 now = g_source_get_time (source);
3967 if (now < timeout_source->expiration)
3969 /* Round up to ensure that we don't try again too early */
3970 *timeout = (timeout_source->expiration - now + 999) / 1000;
3979 g_timeout_check (GSource *source)
3981 GTimeoutSource *timeout_source = (GTimeoutSource *) source;
3982 gint64 now = g_source_get_time (source);
3984 return timeout_source->expiration <= now;
3988 g_timeout_dispatch (GSource *source,
3989 GSourceFunc callback,
3992 GTimeoutSource *timeout_source = (GTimeoutSource *)source;
3997 g_warning ("Timeout source dispatched without callback\n"
3998 "You must call g_source_set_callback().");
4002 again = callback (user_data);
4005 g_timeout_set_expiration (timeout_source, g_source_get_time (source));
4011 * g_timeout_source_new:
4012 * @interval: the timeout interval in milliseconds.
4014 * Creates a new timeout source.
4016 * The source will not initially be associated with any #GMainContext
4017 * and must be added to one with g_source_attach() before it will be
4020 * The interval given is in terms of monotonic time, not wall clock
4021 * time. See g_get_monotonic_time().
4023 * Return value: the newly-created timeout source
4026 g_timeout_source_new (guint interval)
4028 GSource *source = g_source_new (&g_timeout_funcs, sizeof (GTimeoutSource));
4029 GTimeoutSource *timeout_source = (GTimeoutSource *)source;
4031 timeout_source->interval = interval;
4032 g_timeout_set_expiration (timeout_source, g_get_monotonic_time ());
4038 * g_timeout_source_new_seconds:
4039 * @interval: the timeout interval in seconds
4041 * Creates a new timeout source.
4043 * The source will not initially be associated with any #GMainContext
4044 * and must be added to one with g_source_attach() before it will be
4047 * The scheduling granularity/accuracy of this timeout source will be
4050 * The interval given in terms of monotonic time, not wall clock time.
4051 * See g_get_monotonic_time().
4053 * Return value: the newly-created timeout source
4058 g_timeout_source_new_seconds (guint interval)
4060 GSource *source = g_source_new (&g_timeout_funcs, sizeof (GTimeoutSource));
4061 GTimeoutSource *timeout_source = (GTimeoutSource *)source;
4063 timeout_source->interval = 1000 * interval;
4064 timeout_source->seconds = TRUE;
4066 g_timeout_set_expiration (timeout_source, g_get_monotonic_time ());
4073 * g_timeout_add_full:
4074 * @priority: the priority of the timeout source. Typically this will be in
4075 * the range between #G_PRIORITY_DEFAULT and #G_PRIORITY_HIGH.
4076 * @interval: the time between calls to the function, in milliseconds
4077 * (1/1000ths of a second)
4078 * @function: function to call
4079 * @data: data to pass to @function
4080 * @notify: (allow-none): function to call when the timeout is removed, or %NULL
4082 * Sets a function to be called at regular intervals, with the given
4083 * priority. The function is called repeatedly until it returns
4084 * %FALSE, at which point the timeout is automatically destroyed and
4085 * the function will not be called again. The @notify function is
4086 * called when the timeout is destroyed. The first call to the
4087 * function will be at the end of the first @interval.
4089 * Note that timeout functions may be delayed, due to the processing of other
4090 * event sources. Thus they should not be relied on for precise timing.
4091 * After each call to the timeout function, the time of the next
4092 * timeout is recalculated based on the current time and the given interval
4093 * (it does not try to 'catch up' time lost in delays).
4095 * This internally creates a main loop source using g_timeout_source_new()
4096 * and attaches it to the main loop context using g_source_attach(). You can
4097 * do these steps manually if you need greater control.
4099 * The interval given in terms of monotonic time, not wall clock time.
4100 * See g_get_monotonic_time().
4102 * Return value: the ID (greater than 0) of the event source.
4103 * Rename to: g_timeout_add
4106 g_timeout_add_full (gint priority,
4108 GSourceFunc function,
4110 GDestroyNotify notify)
4115 g_return_val_if_fail (function != NULL, 0);
4117 source = g_timeout_source_new (interval);
4119 if (priority != G_PRIORITY_DEFAULT)
4120 g_source_set_priority (source, priority);
4122 g_source_set_callback (source, function, data, notify);
4123 id = g_source_attach (source, NULL);
4124 g_source_unref (source);
4131 * @interval: the time between calls to the function, in milliseconds
4132 * (1/1000ths of a second)
4133 * @function: function to call
4134 * @data: data to pass to @function
4136 * Sets a function to be called at regular intervals, with the default
4137 * priority, #G_PRIORITY_DEFAULT. The function is called repeatedly
4138 * until it returns %FALSE, at which point the timeout is automatically
4139 * destroyed and the function will not be called again. The first call
4140 * to the function will be at the end of the first @interval.
4142 * Note that timeout functions may be delayed, due to the processing of other
4143 * event sources. Thus they should not be relied on for precise timing.
4144 * After each call to the timeout function, the time of the next
4145 * timeout is recalculated based on the current time and the given interval
4146 * (it does not try to 'catch up' time lost in delays).
4148 * If you want to have a timer in the "seconds" range and do not care
4149 * about the exact time of the first call of the timer, use the
4150 * g_timeout_add_seconds() function; this function allows for more
4151 * optimizations and more efficient system power usage.
4153 * This internally creates a main loop source using g_timeout_source_new()
4154 * and attaches it to the main loop context using g_source_attach(). You can
4155 * do these steps manually if you need greater control.
4157 * The interval given is in terms of monotonic time, not wall clock
4158 * time. See g_get_monotonic_time().
4160 * Return value: the ID (greater than 0) of the event source.
4163 g_timeout_add (guint32 interval,
4164 GSourceFunc function,
4167 return g_timeout_add_full (G_PRIORITY_DEFAULT,
4168 interval, function, data, NULL);
4172 * g_timeout_add_seconds_full:
4173 * @priority: the priority of the timeout source. Typically this will be in
4174 * the range between #G_PRIORITY_DEFAULT and #G_PRIORITY_HIGH.
4175 * @interval: the time between calls to the function, in seconds
4176 * @function: function to call
4177 * @data: data to pass to @function
4178 * @notify: (allow-none): function to call when the timeout is removed, or %NULL
4180 * Sets a function to be called at regular intervals, with @priority.
4181 * The function is called repeatedly until it returns %FALSE, at which
4182 * point the timeout is automatically destroyed and the function will
4183 * not be called again.
4185 * Unlike g_timeout_add(), this function operates at whole second granularity.
4186 * The initial starting point of the timer is determined by the implementation
4187 * and the implementation is expected to group multiple timers together so that
4188 * they fire all at the same time.
4189 * To allow this grouping, the @interval to the first timer is rounded
4190 * and can deviate up to one second from the specified interval.
4191 * Subsequent timer iterations will generally run at the specified interval.
4193 * Note that timeout functions may be delayed, due to the processing of other
4194 * event sources. Thus they should not be relied on for precise timing.
4195 * After each call to the timeout function, the time of the next
4196 * timeout is recalculated based on the current time and the given @interval
4198 * If you want timing more precise than whole seconds, use g_timeout_add()
4201 * The grouping of timers to fire at the same time results in a more power
4202 * and CPU efficient behavior so if your timer is in multiples of seconds
4203 * and you don't require the first timer exactly one second from now, the
4204 * use of g_timeout_add_seconds() is preferred over g_timeout_add().
4206 * This internally creates a main loop source using
4207 * g_timeout_source_new_seconds() and attaches it to the main loop context
4208 * using g_source_attach(). You can do these steps manually if you need
4211 * The interval given is in terms of monotonic time, not wall clock
4212 * time. See g_get_monotonic_time().
4214 * Return value: the ID (greater than 0) of the event source.
4216 * Rename to: g_timeout_add_seconds
4220 g_timeout_add_seconds_full (gint priority,
4222 GSourceFunc function,
4224 GDestroyNotify notify)
4229 g_return_val_if_fail (function != NULL, 0);
4231 source = g_timeout_source_new_seconds (interval);
4233 if (priority != G_PRIORITY_DEFAULT)
4234 g_source_set_priority (source, priority);
4236 g_source_set_callback (source, function, data, notify);
4237 id = g_source_attach (source, NULL);
4238 g_source_unref (source);
4244 * g_timeout_add_seconds:
4245 * @interval: the time between calls to the function, in seconds
4246 * @function: function to call
4247 * @data: data to pass to @function
4249 * Sets a function to be called at regular intervals with the default
4250 * priority, #G_PRIORITY_DEFAULT. The function is called repeatedly until
4251 * it returns %FALSE, at which point the timeout is automatically destroyed
4252 * and the function will not be called again.
4254 * This internally creates a main loop source using
4255 * g_timeout_source_new_seconds() and attaches it to the main loop context
4256 * using g_source_attach(). You can do these steps manually if you need
4257 * greater control. Also see g_timeout_add_seconds_full().
4259 * Note that the first call of the timer may not be precise for timeouts
4260 * of one second. If you need finer precision and have such a timeout,
4261 * you may want to use g_timeout_add() instead.
4263 * The interval given is in terms of monotonic time, not wall clock
4264 * time. See g_get_monotonic_time().
4266 * Return value: the ID (greater than 0) of the event source.
4271 g_timeout_add_seconds (guint interval,
4272 GSourceFunc function,
4275 g_return_val_if_fail (function != NULL, 0);
4277 return g_timeout_add_seconds_full (G_PRIORITY_DEFAULT, interval, function, data, NULL);
4280 /* Child watch functions */
4285 g_child_watch_prepare (GSource *source,
4293 g_child_watch_check (GSource *source)
4295 GChildWatchSource *child_watch_source;
4296 gboolean child_exited;
4298 child_watch_source = (GChildWatchSource *) source;
4300 child_exited = child_watch_source->poll.revents & G_IO_IN;
4307 * Note: We do _not_ check for the special value of STILL_ACTIVE
4308 * since we know that the process has exited and doing so runs into
4309 * problems if the child process "happens to return STILL_ACTIVE(259)"
4310 * as Microsoft's Platform SDK puts it.
4312 if (!GetExitCodeProcess (child_watch_source->pid, &child_status))
4314 gchar *emsg = g_win32_error_message (GetLastError ());
4315 g_warning (G_STRLOC ": GetExitCodeProcess() failed: %s", emsg);
4318 child_watch_source->child_status = -1;
4321 child_watch_source->child_status = child_status;
4324 return child_exited;
4328 g_child_watch_finalize (GSource *source)
4332 #else /* G_OS_WIN32 */
4335 wake_source (GSource *source)
4337 GMainContext *context;
4339 /* This should be thread-safe:
4341 * - if the source is currently being added to a context, that
4342 * context will be woken up anyway
4344 * - if the source is currently being destroyed, we simply need not
4347 * - the memory for the source will remain valid until after the
4348 * source finalize function was called (which would remove the
4349 * source from the global list which we are currently holding the
4352 * - the GMainContext will either be NULL or point to a live
4355 * - the GMainContext will remain valid since we hold the
4356 * main_context_list lock
4358 * Since we are holding a lot of locks here, don't try to enter any
4359 * more GMainContext functions for fear of dealock -- just hit the
4360 * GWakeup and run. Even if that's safe now, it could easily become
4361 * unsafe with some very minor changes in the future, and signal
4362 * handling is not the most well-tested codepath.
4364 G_LOCK(main_context_list);
4365 context = source->context;
4367 g_wakeup_signal (context->wakeup);
4368 G_UNLOCK(main_context_list);
4372 dispatch_unix_signals (void)
4376 /* clear this first incase another one arrives while we're processing */
4377 any_unix_signal_pending = FALSE;
4379 G_LOCK(unix_signal_lock);
4381 /* handle GChildWatchSource instances */
4382 if (unix_signal_pending[SIGCHLD])
4384 unix_signal_pending[SIGCHLD] = FALSE;
4386 /* The only way we can do this is to scan all of the children.
4388 * The docs promise that we will not reap children that we are not
4389 * explicitly watching, so that ties our hands from calling
4390 * waitpid(-1). We also can't use siginfo's si_pid field since if
4391 * multiple SIGCHLD arrive at the same time, one of them can be
4392 * dropped (since a given UNIX signal can only be pending once).
4394 for (node = unix_child_watches; node; node = node->next)
4396 GChildWatchSource *source = node->data;
4398 if (!source->child_exited)
4400 if (waitpid (source->pid, &source->child_status, WNOHANG) > 0)
4402 source->child_exited = TRUE;
4404 wake_source ((GSource *) source);
4410 /* handle GUnixSignalWatchSource instances */
4411 for (node = unix_signal_watches; node; node = node->next)
4413 GUnixSignalWatchSource *source = node->data;
4415 if (!source->pending)
4417 if (unix_signal_pending[source->signum])
4419 unix_signal_pending[source->signum] = FALSE;
4420 source->pending = TRUE;
4422 wake_source ((GSource *) source);
4427 G_UNLOCK(unix_signal_lock);
4431 g_child_watch_prepare (GSource *source,
4434 GChildWatchSource *child_watch_source;
4436 child_watch_source = (GChildWatchSource *) source;
4438 return child_watch_source->child_exited;
4442 g_child_watch_check (GSource *source)
4444 GChildWatchSource *child_watch_source;
4446 child_watch_source = (GChildWatchSource *) source;
4448 return child_watch_source->child_exited;
4452 g_unix_signal_watch_prepare (GSource *source,
4455 GUnixSignalWatchSource *unix_signal_source;
4457 unix_signal_source = (GUnixSignalWatchSource *) source;
4459 return unix_signal_source->pending;
4463 g_unix_signal_watch_check (GSource *source)
4465 GUnixSignalWatchSource *unix_signal_source;
4467 unix_signal_source = (GUnixSignalWatchSource *) source;
4469 return unix_signal_source->pending;
4473 g_unix_signal_watch_dispatch (GSource *source,
4474 GSourceFunc callback,
4477 GUnixSignalWatchSource *unix_signal_source;
4479 unix_signal_source = (GUnixSignalWatchSource *) source;
4483 g_warning ("Unix signal source dispatched without callback\n"
4484 "You must call g_source_set_callback().");
4488 (callback) (user_data);
4490 unix_signal_source->pending = FALSE;
4496 ensure_unix_signal_handler_installed_unlocked (int signum)
4498 static sigset_t installed_signal_mask;
4499 static gboolean initialized;
4500 struct sigaction action;
4504 sigemptyset (&installed_signal_mask);
4505 g_get_worker_context ();
4509 if (sigismember (&installed_signal_mask, signum))
4512 sigaddset (&installed_signal_mask, signum);
4514 action.sa_handler = g_unix_signal_handler;
4515 sigemptyset (&action.sa_mask);
4516 action.sa_flags = SA_RESTART | SA_NOCLDSTOP;
4517 sigaction (signum, &action, NULL);
4521 _g_main_create_unix_signal_watch (int signum)
4524 GUnixSignalWatchSource *unix_signal_source;
4526 source = g_source_new (&g_unix_signal_funcs, sizeof (GUnixSignalWatchSource));
4527 unix_signal_source = (GUnixSignalWatchSource *) source;
4529 unix_signal_source->signum = signum;
4530 unix_signal_source->pending = FALSE;
4532 G_LOCK (unix_signal_lock);
4533 ensure_unix_signal_handler_installed_unlocked (signum);
4534 unix_signal_watches = g_slist_prepend (unix_signal_watches, unix_signal_source);
4535 if (unix_signal_pending[signum])
4536 unix_signal_source->pending = TRUE;
4537 unix_signal_pending[signum] = FALSE;
4538 G_UNLOCK (unix_signal_lock);
4544 g_unix_signal_watch_finalize (GSource *source)
4546 G_LOCK (unix_signal_lock);
4547 unix_signal_watches = g_slist_remove (unix_signal_watches, source);
4548 G_UNLOCK (unix_signal_lock);
4552 g_child_watch_finalize (GSource *source)
4554 G_LOCK (unix_signal_lock);
4555 unix_child_watches = g_slist_remove (unix_child_watches, source);
4556 G_UNLOCK (unix_signal_lock);
4559 #endif /* G_OS_WIN32 */
4562 g_child_watch_dispatch (GSource *source,
4563 GSourceFunc callback,
4566 GChildWatchSource *child_watch_source;
4567 GChildWatchFunc child_watch_callback = (GChildWatchFunc) callback;
4569 child_watch_source = (GChildWatchSource *) source;
4573 g_warning ("Child watch source dispatched without callback\n"
4574 "You must call g_source_set_callback().");
4578 (child_watch_callback) (child_watch_source->pid, child_watch_source->child_status, user_data);
4580 /* We never keep a child watch source around as the child is gone */
4587 g_unix_signal_handler (int signum)
4589 unix_signal_pending[signum] = TRUE;
4590 any_unix_signal_pending = TRUE;
4592 g_wakeup_signal (glib_worker_context->wakeup);
4595 #endif /* !G_OS_WIN32 */
4598 * g_child_watch_source_new:
4599 * @pid: process to watch. On POSIX the pid of a child process. On
4600 * Windows a handle for a process (which doesn't have to be a child).
4602 * Creates a new child_watch source.
4604 * The source will not initially be associated with any #GMainContext
4605 * and must be added to one with g_source_attach() before it will be
4608 * Note that child watch sources can only be used in conjunction with
4609 * <literal>g_spawn...</literal> when the %G_SPAWN_DO_NOT_REAP_CHILD
4612 * Note that on platforms where #GPid must be explicitly closed
4613 * (see g_spawn_close_pid()) @pid must not be closed while the
4614 * source is still active. Typically, you will want to call
4615 * g_spawn_close_pid() in the callback function for the source.
4617 * Note further that using g_child_watch_source_new() is not
4618 * compatible with calling <literal>waitpid(-1)</literal> in
4619 * the application. Calling waitpid() for individual pids will
4622 * Return value: the newly-created child watch source
4627 g_child_watch_source_new (GPid pid)
4629 GSource *source = g_source_new (&g_child_watch_funcs, sizeof (GChildWatchSource));
4630 GChildWatchSource *child_watch_source = (GChildWatchSource *)source;
4632 child_watch_source->pid = pid;
4635 child_watch_source->poll.fd = (gintptr) pid;
4636 child_watch_source->poll.events = G_IO_IN;
4638 g_source_add_poll (source, &child_watch_source->poll);
4639 #else /* G_OS_WIN32 */
4640 G_LOCK (unix_signal_lock);
4641 ensure_unix_signal_handler_installed_unlocked (SIGCHLD);
4642 unix_child_watches = g_slist_prepend (unix_child_watches, child_watch_source);
4643 if (waitpid (pid, &child_watch_source->child_status, WNOHANG) > 0)
4644 child_watch_source->child_exited = TRUE;
4645 G_UNLOCK (unix_signal_lock);
4646 #endif /* G_OS_WIN32 */
4652 * g_child_watch_add_full:
4653 * @priority: the priority of the idle source. Typically this will be in the
4654 * range between #G_PRIORITY_DEFAULT_IDLE and #G_PRIORITY_HIGH_IDLE.
4655 * @pid: process to watch. On POSIX the pid of a child process. On
4656 * Windows a handle for a process (which doesn't have to be a child).
4657 * @function: function to call
4658 * @data: data to pass to @function
4659 * @notify: (allow-none): function to call when the idle is removed, or %NULL
4661 * Sets a function to be called when the child indicated by @pid
4662 * exits, at the priority @priority.
4664 * If you obtain @pid from g_spawn_async() or g_spawn_async_with_pipes()
4665 * you will need to pass #G_SPAWN_DO_NOT_REAP_CHILD as flag to
4666 * the spawn function for the child watching to work.
4668 * Note that on platforms where #GPid must be explicitly closed
4669 * (see g_spawn_close_pid()) @pid must not be closed while the
4670 * source is still active. Typically, you will want to call
4671 * g_spawn_close_pid() in the callback function for the source.
4673 * GLib supports only a single callback per process id.
4675 * This internally creates a main loop source using
4676 * g_child_watch_source_new() and attaches it to the main loop context
4677 * using g_source_attach(). You can do these steps manually if you
4678 * need greater control.
4680 * Return value: the ID (greater than 0) of the event source.
4682 * Rename to: g_child_watch_add
4686 g_child_watch_add_full (gint priority,
4688 GChildWatchFunc function,
4690 GDestroyNotify notify)
4695 g_return_val_if_fail (function != NULL, 0);
4697 source = g_child_watch_source_new (pid);
4699 if (priority != G_PRIORITY_DEFAULT)
4700 g_source_set_priority (source, priority);
4702 g_source_set_callback (source, (GSourceFunc) function, data, notify);
4703 id = g_source_attach (source, NULL);
4704 g_source_unref (source);
4710 * g_child_watch_add:
4711 * @pid: process id to watch. On POSIX the pid of a child process. On
4712 * Windows a handle for a process (which doesn't have to be a child).
4713 * @function: function to call
4714 * @data: data to pass to @function
4716 * Sets a function to be called when the child indicated by @pid
4717 * exits, at a default priority, #G_PRIORITY_DEFAULT.
4719 * If you obtain @pid from g_spawn_async() or g_spawn_async_with_pipes()
4720 * you will need to pass #G_SPAWN_DO_NOT_REAP_CHILD as flag to
4721 * the spawn function for the child watching to work.
4723 * Note that on platforms where #GPid must be explicitly closed
4724 * (see g_spawn_close_pid()) @pid must not be closed while the
4725 * source is still active. Typically, you will want to call
4726 * g_spawn_close_pid() in the callback function for the source.
4728 * GLib supports only a single callback per process id.
4730 * This internally creates a main loop source using
4731 * g_child_watch_source_new() and attaches it to the main loop context
4732 * using g_source_attach(). You can do these steps manually if you
4733 * need greater control.
4735 * Return value: the ID (greater than 0) of the event source.
4740 g_child_watch_add (GPid pid,
4741 GChildWatchFunc function,
4744 return g_child_watch_add_full (G_PRIORITY_DEFAULT, pid, function, data, NULL);
4748 /* Idle functions */
4751 g_idle_prepare (GSource *source,
4760 g_idle_check (GSource *source)
4766 g_idle_dispatch (GSource *source,
4767 GSourceFunc callback,
4772 g_warning ("Idle source dispatched without callback\n"
4773 "You must call g_source_set_callback().");
4777 return callback (user_data);
4781 * g_idle_source_new:
4783 * Creates a new idle source.
4785 * The source will not initially be associated with any #GMainContext
4786 * and must be added to one with g_source_attach() before it will be
4787 * executed. Note that the default priority for idle sources is
4788 * %G_PRIORITY_DEFAULT_IDLE, as compared to other sources which
4789 * have a default priority of %G_PRIORITY_DEFAULT.
4791 * Return value: the newly-created idle source
4794 g_idle_source_new (void)
4798 source = g_source_new (&g_idle_funcs, sizeof (GSource));
4799 g_source_set_priority (source, G_PRIORITY_DEFAULT_IDLE);
4806 * @priority: the priority of the idle source. Typically this will be in the
4807 * range between #G_PRIORITY_DEFAULT_IDLE and #G_PRIORITY_HIGH_IDLE.
4808 * @function: function to call
4809 * @data: data to pass to @function
4810 * @notify: (allow-none): function to call when the idle is removed, or %NULL
4812 * Adds a function to be called whenever there are no higher priority
4813 * events pending. If the function returns %FALSE it is automatically
4814 * removed from the list of event sources and will not be called again.
4816 * This internally creates a main loop source using g_idle_source_new()
4817 * and attaches it to the main loop context using g_source_attach().
4818 * You can do these steps manually if you need greater control.
4820 * Return value: the ID (greater than 0) of the event source.
4821 * Rename to: g_idle_add
4824 g_idle_add_full (gint priority,
4825 GSourceFunc function,
4827 GDestroyNotify notify)
4832 g_return_val_if_fail (function != NULL, 0);
4834 source = g_idle_source_new ();
4836 if (priority != G_PRIORITY_DEFAULT_IDLE)
4837 g_source_set_priority (source, priority);
4839 g_source_set_callback (source, function, data, notify);
4840 id = g_source_attach (source, NULL);
4841 g_source_unref (source);
4848 * @function: function to call
4849 * @data: data to pass to @function.
4851 * Adds a function to be called whenever there are no higher priority
4852 * events pending to the default main loop. The function is given the
4853 * default idle priority, #G_PRIORITY_DEFAULT_IDLE. If the function
4854 * returns %FALSE it is automatically removed from the list of event
4855 * sources and will not be called again.
4857 * This internally creates a main loop source using g_idle_source_new()
4858 * and attaches it to the main loop context using g_source_attach().
4859 * You can do these steps manually if you need greater control.
4861 * Return value: the ID (greater than 0) of the event source.
4864 g_idle_add (GSourceFunc function,
4867 return g_idle_add_full (G_PRIORITY_DEFAULT_IDLE, function, data, NULL);
4871 * g_idle_remove_by_data:
4872 * @data: the data for the idle source's callback.
4874 * Removes the idle function with the given data.
4876 * Return value: %TRUE if an idle source was found and removed.
4879 g_idle_remove_by_data (gpointer data)
4881 return g_source_remove_by_funcs_user_data (&g_idle_funcs, data);
4885 * g_main_context_invoke:
4886 * @context: (allow-none): a #GMainContext, or %NULL
4887 * @function: function to call
4888 * @data: data to pass to @function
4890 * Invokes a function in such a way that @context is owned during the
4891 * invocation of @function.
4893 * If @context is %NULL then the global default main context — as
4894 * returned by g_main_context_default() — is used.
4896 * If @context is owned by the current thread, @function is called
4897 * directly. Otherwise, if @context is the thread-default main context
4898 * of the current thread and g_main_context_acquire() succeeds, then
4899 * @function is called and g_main_context_release() is called
4902 * In any other case, an idle source is created to call @function and
4903 * that source is attached to @context (presumably to be run in another
4904 * thread). The idle source is attached with #G_PRIORITY_DEFAULT
4905 * priority. If you want a different priority, use
4906 * g_main_context_invoke_full().
4908 * Note that, as with normal idle functions, @function should probably
4909 * return %FALSE. If it returns %TRUE, it will be continuously run in a
4910 * loop (and may prevent this call from returning).
4915 g_main_context_invoke (GMainContext *context,
4916 GSourceFunc function,
4919 g_main_context_invoke_full (context,
4921 function, data, NULL);
4925 * g_main_context_invoke_full:
4926 * @context: (allow-none): a #GMainContext, or %NULL
4927 * @priority: the priority at which to run @function
4928 * @function: function to call
4929 * @data: data to pass to @function
4930 * @notify: (allow-none): a function to call when @data is no longer in use, or %NULL.
4932 * Invokes a function in such a way that @context is owned during the
4933 * invocation of @function.
4935 * This function is the same as g_main_context_invoke() except that it
4936 * lets you specify the priority incase @function ends up being
4937 * scheduled as an idle and also lets you give a #GDestroyNotify for @data.
4939 * @notify should not assume that it is called from any particular
4940 * thread or with any particular context acquired.
4945 g_main_context_invoke_full (GMainContext *context,
4947 GSourceFunc function,
4949 GDestroyNotify notify)
4951 g_return_if_fail (function != NULL);
4954 context = g_main_context_default ();
4956 if (g_main_context_is_owner (context))
4958 while (function (data));
4965 GMainContext *thread_default;
4967 thread_default = g_main_context_get_thread_default ();
4969 if (!thread_default)
4970 thread_default = g_main_context_default ();
4972 if (thread_default == context && g_main_context_acquire (context))
4974 while (function (data));
4976 g_main_context_release (context);
4985 source = g_idle_source_new ();
4986 g_source_set_priority (source, priority);
4987 g_source_set_callback (source, function, data, notify);
4988 g_source_attach (source, context);
4989 g_source_unref (source);
4995 glib_worker_main (gpointer data)
4999 g_main_context_iteration (glib_worker_context, TRUE);
5002 if (any_unix_signal_pending)
5003 dispatch_unix_signals ();
5007 return NULL; /* worst GCC warning message ever... */
5011 g_get_worker_context (void)
5013 static gsize initialised;
5015 if (g_once_init_enter (&initialised))
5017 /* mask all signals in the worker thread */
5023 pthread_sigmask (SIG_SETMASK, &all, &prev_mask);
5025 glib_worker_context = g_main_context_new ();
5026 g_thread_new ("gmain", glib_worker_main, NULL);
5028 pthread_sigmask (SIG_SETMASK, &prev_mask, NULL);
5030 g_once_init_leave (&initialised, TRUE);
5033 return glib_worker_context;