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 */
243 GHashTable *overflow_used_source_ids; /* set<guint> */
245 gint in_check_or_prepare;
247 GPollRec *poll_records, *poll_records_tail;
248 guint n_poll_records;
249 GPollFD *cached_poll_array;
250 guint cached_poll_array_size;
256 /* Flag indicating whether the set of fd's changed during a poll */
257 gboolean poll_changed;
262 gboolean time_is_fresh;
265 struct _GSourceCallback
270 GDestroyNotify notify;
275 GMainContext *context;
280 struct _GTimeoutSource
288 struct _GChildWatchSource
295 #else /* G_OS_WIN32 */
296 guint child_exited : 1;
299 #endif /* G_OS_WIN32 */
302 struct _GUnixSignalWatchSource
317 struct _GSourcePrivate
319 GSList *child_sources;
320 GSource *parent_source;
323 typedef struct _GSourceIter
325 GMainContext *context;
331 #define LOCK_CONTEXT(context) g_mutex_lock (&context->mutex)
332 #define UNLOCK_CONTEXT(context) g_mutex_unlock (&context->mutex)
333 #define G_THREAD_SELF g_thread_self ()
335 #define SOURCE_DESTROYED(source) (((source)->flags & G_HOOK_FLAG_ACTIVE) == 0)
336 #define SOURCE_BLOCKED(source) (((source)->flags & G_SOURCE_BLOCKED) != 0)
338 #define SOURCE_UNREF(source, context) \
340 if ((source)->ref_count > 1) \
341 (source)->ref_count--; \
343 g_source_unref_internal ((source), (context), TRUE); \
347 /* Forward declarations */
349 static void g_source_unref_internal (GSource *source,
350 GMainContext *context,
352 static void g_source_destroy_internal (GSource *source,
353 GMainContext *context,
355 static void g_source_set_priority_unlocked (GSource *source,
356 GMainContext *context,
358 static void g_child_source_remove_internal (GSource *child_source,
359 GMainContext *context);
361 static void g_main_context_poll (GMainContext *context,
366 static void g_main_context_add_poll_unlocked (GMainContext *context,
369 static void g_main_context_remove_poll_unlocked (GMainContext *context,
372 static void g_source_iter_init (GSourceIter *iter,
373 GMainContext *context,
374 gboolean may_modify);
375 static gboolean g_source_iter_next (GSourceIter *iter,
377 static void g_source_iter_clear (GSourceIter *iter);
379 static gboolean g_timeout_prepare (GSource *source,
381 static gboolean g_timeout_check (GSource *source);
382 static gboolean g_timeout_dispatch (GSource *source,
383 GSourceFunc callback,
385 static gboolean g_child_watch_prepare (GSource *source,
387 static gboolean g_child_watch_check (GSource *source);
388 static gboolean g_child_watch_dispatch (GSource *source,
389 GSourceFunc callback,
391 static void g_child_watch_finalize (GSource *source);
393 static void g_unix_signal_handler (int signum);
394 static gboolean g_unix_signal_watch_prepare (GSource *source,
396 static gboolean g_unix_signal_watch_check (GSource *source);
397 static gboolean g_unix_signal_watch_dispatch (GSource *source,
398 GSourceFunc callback,
400 static void g_unix_signal_watch_finalize (GSource *source);
402 static gboolean g_idle_prepare (GSource *source,
404 static gboolean g_idle_check (GSource *source);
405 static gboolean g_idle_dispatch (GSource *source,
406 GSourceFunc callback,
409 static void block_source (GSource *source);
411 static GMainContext *glib_worker_context;
413 G_LOCK_DEFINE_STATIC (main_loop);
414 static GMainContext *default_main_context;
419 /* UNIX signals work by marking one of these variables then waking the
420 * worker context to check on them and dispatch accordingly.
422 #ifdef HAVE_SIG_ATOMIC_T
423 static volatile sig_atomic_t unix_signal_pending[NSIG];
424 static volatile sig_atomic_t any_unix_signal_pending;
426 static volatile int unix_signal_pending[NSIG];
427 static volatile int any_unix_signal_pending;
430 /* Guards all the data below */
431 G_LOCK_DEFINE_STATIC (unix_signal_lock);
432 static GSList *unix_signal_watches;
433 static GSList *unix_child_watches;
435 static GSourceFuncs g_unix_signal_funcs =
437 g_unix_signal_watch_prepare,
438 g_unix_signal_watch_check,
439 g_unix_signal_watch_dispatch,
440 g_unix_signal_watch_finalize
442 #endif /* !G_OS_WIN32 */
443 G_LOCK_DEFINE_STATIC (main_context_list);
444 static GSList *main_context_list = NULL;
446 GSourceFuncs g_timeout_funcs =
454 GSourceFuncs g_child_watch_funcs =
456 g_child_watch_prepare,
458 g_child_watch_dispatch,
459 g_child_watch_finalize
462 GSourceFuncs g_idle_funcs =
471 * g_main_context_ref:
472 * @context: a #GMainContext
474 * Increases the reference count on a #GMainContext object by one.
476 * Returns: the @context that was passed in (since 2.6)
479 g_main_context_ref (GMainContext *context)
481 g_return_val_if_fail (context != NULL, NULL);
482 g_return_val_if_fail (g_atomic_int_get (&context->ref_count) > 0, NULL);
484 g_atomic_int_inc (&context->ref_count);
490 poll_rec_list_free (GMainContext *context,
493 g_slice_free_chain (GPollRec, list, next);
497 * g_main_context_unref:
498 * @context: a #GMainContext
500 * Decreases the reference count on a #GMainContext object by one. If
501 * the result is zero, free the context and free all associated memory.
504 g_main_context_unref (GMainContext *context)
511 g_return_if_fail (context != NULL);
512 g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
514 if (!g_atomic_int_dec_and_test (&context->ref_count))
517 G_LOCK (main_context_list);
518 main_context_list = g_slist_remove (main_context_list, context);
519 G_UNLOCK (main_context_list);
521 g_source_iter_init (&iter, context, TRUE);
522 while (g_source_iter_next (&iter, &source))
524 source->context = NULL;
525 g_source_destroy_internal (source, context, FALSE);
527 for (sl_iter = context->source_lists; sl_iter; sl_iter = sl_iter->next)
529 list = sl_iter->data;
530 g_slice_free (GSourceList, list);
532 g_list_free (context->source_lists);
534 if (context->overflow_used_source_ids)
535 g_hash_table_destroy (context->overflow_used_source_ids);
537 g_mutex_clear (&context->mutex);
539 g_ptr_array_free (context->pending_dispatches, TRUE);
540 g_free (context->cached_poll_array);
542 poll_rec_list_free (context, context->poll_records);
544 g_wakeup_free (context->wakeup);
545 g_cond_clear (&context->cond);
550 /* Helper function used by mainloop/overflow test.
553 g_main_context_new_with_next_id (guint next_id)
555 GMainContext *ret = g_main_context_new ();
557 ret->next_id = next_id;
563 * g_main_context_new:
565 * Creates a new #GMainContext structure.
567 * Return value: the new #GMainContext
570 g_main_context_new (void)
572 static gsize initialised;
573 GMainContext *context;
575 if (g_once_init_enter (&initialised))
577 #ifdef G_MAIN_POLL_DEBUG
578 if (getenv ("G_MAIN_POLL_DEBUG") != NULL)
579 _g_main_poll_debug = TRUE;
582 g_once_init_leave (&initialised, TRUE);
585 context = g_new0 (GMainContext, 1);
587 g_mutex_init (&context->mutex);
588 g_cond_init (&context->cond);
590 context->owner = NULL;
591 context->waiters = NULL;
593 context->ref_count = 1;
595 context->next_id = 1;
597 context->source_lists = NULL;
599 context->poll_func = g_poll;
601 context->cached_poll_array = NULL;
602 context->cached_poll_array_size = 0;
604 context->pending_dispatches = g_ptr_array_new ();
606 context->time_is_fresh = FALSE;
608 context->wakeup = g_wakeup_new ();
609 g_wakeup_get_pollfd (context->wakeup, &context->wake_up_rec);
610 g_main_context_add_poll_unlocked (context, 0, &context->wake_up_rec);
612 G_LOCK (main_context_list);
613 main_context_list = g_slist_append (main_context_list, context);
615 #ifdef G_MAIN_POLL_DEBUG
616 if (_g_main_poll_debug)
617 g_print ("created context=%p\n", context);
620 G_UNLOCK (main_context_list);
626 * g_main_context_default:
628 * Returns the global default main context. This is the main context
629 * used for main loop functions when a main loop is not explicitly
630 * specified, and corresponds to the "main" main loop. See also
631 * g_main_context_get_thread_default().
633 * Return value: (transfer none): the global default main context.
636 g_main_context_default (void)
642 if (!default_main_context)
644 default_main_context = g_main_context_new ();
645 #ifdef G_MAIN_POLL_DEBUG
646 if (_g_main_poll_debug)
647 g_print ("default context=%p\n", default_main_context);
651 G_UNLOCK (main_loop);
653 return default_main_context;
657 free_context (gpointer data)
659 GMainContext *context = data;
661 g_main_context_release (context);
663 g_main_context_unref (context);
667 free_context_stack (gpointer data)
669 g_queue_free_full((GQueue *) data, (GDestroyNotify) free_context);
672 static GPrivate thread_context_stack = G_PRIVATE_INIT (free_context_stack);
675 * g_main_context_push_thread_default:
676 * @context: (allow-none): a #GMainContext, or %NULL for the global default context
678 * Acquires @context and sets it as the thread-default context for the
679 * current thread. This will cause certain asynchronous operations
680 * (such as most <link linkend="gio">gio</link>-based I/O) which are
681 * started in this thread to run under @context and deliver their
682 * results to its main loop, rather than running under the global
683 * default context in the main thread. Note that calling this function
684 * changes the context returned by
685 * g_main_context_get_thread_default(), <emphasis>not</emphasis> the
686 * one returned by g_main_context_default(), so it does not affect the
687 * context used by functions like g_idle_add().
689 * Normally you would call this function shortly after creating a new
690 * thread, passing it a #GMainContext which will be run by a
691 * #GMainLoop in that thread, to set a new default context for all
692 * async operations in that thread. (In this case, you don't need to
693 * ever call g_main_context_pop_thread_default().) In some cases
694 * however, you may want to schedule a single operation in a
695 * non-default context, or temporarily use a non-default context in
696 * the main thread. In that case, you can wrap the call to the
697 * asynchronous operation inside a
698 * g_main_context_push_thread_default() /
699 * g_main_context_pop_thread_default() pair, but it is up to you to
700 * ensure that no other asynchronous operations accidentally get
701 * started while the non-default context is active.
703 * Beware that libraries that predate this function may not correctly
704 * handle being used from a thread with a thread-default context. Eg,
705 * see g_file_supports_thread_contexts().
710 g_main_context_push_thread_default (GMainContext *context)
713 gboolean acquired_context;
715 acquired_context = g_main_context_acquire (context);
716 g_return_if_fail (acquired_context);
718 if (context == g_main_context_default ())
721 g_main_context_ref (context);
723 stack = g_private_get (&thread_context_stack);
726 stack = g_queue_new ();
727 g_private_set (&thread_context_stack, stack);
730 g_queue_push_head (stack, context);
734 * g_main_context_pop_thread_default:
735 * @context: (allow-none): a #GMainContext object, or %NULL
737 * Pops @context off the thread-default context stack (verifying that
738 * it was on the top of the stack).
743 g_main_context_pop_thread_default (GMainContext *context)
747 if (context == g_main_context_default ())
750 stack = g_private_get (&thread_context_stack);
752 g_return_if_fail (stack != NULL);
753 g_return_if_fail (g_queue_peek_head (stack) == context);
755 g_queue_pop_head (stack);
757 g_main_context_release (context);
759 g_main_context_unref (context);
763 * g_main_context_get_thread_default:
765 * Gets the thread-default #GMainContext for this thread. Asynchronous
766 * operations that want to be able to be run in contexts other than
767 * the default one should call this method or
768 * g_main_context_ref_thread_default() to get a #GMainContext to add
769 * their #GSource<!-- -->s to. (Note that even in single-threaded
770 * programs applications may sometimes want to temporarily push a
771 * non-default context, so it is not safe to assume that this will
772 * always return %NULL if you are running in the default thread.)
774 * If you need to hold a reference on the context, use
775 * g_main_context_ref_thread_default() instead.
777 * Returns: (transfer none): the thread-default #GMainContext, or
778 * %NULL if the thread-default context is the global default context.
783 g_main_context_get_thread_default (void)
787 stack = g_private_get (&thread_context_stack);
789 return g_queue_peek_head (stack);
795 * g_main_context_ref_thread_default:
797 * Gets the thread-default #GMainContext for this thread, as with
798 * g_main_context_get_thread_default(), but also adds a reference to
799 * it with g_main_context_ref(). In addition, unlike
800 * g_main_context_get_thread_default(), if the thread-default context
801 * is the global default context, this will return that #GMainContext
802 * (with a ref added to it) rather than returning %NULL.
804 * Returns: (transfer full): the thread-default #GMainContext. Unref
805 * with g_main_context_unref() when you are done with it.
810 g_main_context_ref_thread_default (void)
812 GMainContext *context;
814 context = g_main_context_get_thread_default ();
816 context = g_main_context_default ();
817 return g_main_context_ref (context);
820 /* Hooks for adding to the main loop */
824 * @source_funcs: structure containing functions that implement
825 * the sources behavior.
826 * @struct_size: size of the #GSource structure to create.
828 * Creates a new #GSource structure. The size is specified to
829 * allow creating structures derived from #GSource that contain
830 * additional data. The size passed in must be at least
831 * <literal>sizeof (GSource)</literal>.
833 * The source will not initially be associated with any #GMainContext
834 * and must be added to one with g_source_attach() before it will be
837 * Return value: the newly-created #GSource.
840 g_source_new (GSourceFuncs *source_funcs,
845 g_return_val_if_fail (source_funcs != NULL, NULL);
846 g_return_val_if_fail (struct_size >= sizeof (GSource), NULL);
848 source = (GSource*) g_malloc0 (struct_size);
849 source->priv = g_slice_new0 (GSourcePrivate);
850 source->source_funcs = source_funcs;
851 source->ref_count = 1;
853 source->priority = G_PRIORITY_DEFAULT;
855 source->flags = G_HOOK_FLAG_ACTIVE;
857 /* NULL/0 initialization for all other fields */
862 /* Holds context's lock */
864 g_source_iter_init (GSourceIter *iter,
865 GMainContext *context,
868 iter->context = context;
869 iter->current_list = NULL;
871 iter->may_modify = may_modify;
874 /* Holds context's lock */
876 g_source_iter_next (GSourceIter *iter, GSource **source)
878 GSource *next_source;
881 next_source = iter->source->next;
887 if (iter->current_list)
888 iter->current_list = iter->current_list->next;
890 iter->current_list = iter->context->source_lists;
892 if (iter->current_list)
894 GSourceList *source_list = iter->current_list->data;
896 next_source = source_list->head;
900 /* Note: unreffing iter->source could potentially cause its
901 * GSourceList to be removed from source_lists (if iter->source is
902 * the only source in its list, and it is destroyed), so we have to
903 * keep it reffed until after we advance iter->current_list, above.
906 if (iter->source && iter->may_modify)
907 SOURCE_UNREF (iter->source, iter->context);
908 iter->source = next_source;
909 if (iter->source && iter->may_modify)
910 iter->source->ref_count++;
912 *source = iter->source;
913 return *source != NULL;
916 /* Holds context's lock. Only necessary to call if you broke out of
917 * the g_source_iter_next() loop early.
920 g_source_iter_clear (GSourceIter *iter)
922 if (iter->source && iter->may_modify)
924 SOURCE_UNREF (iter->source, iter->context);
929 /* Holds context's lock
932 find_source_list_for_priority (GMainContext *context,
937 GSourceList *source_list;
940 for (iter = context->source_lists; iter != NULL; last = iter, iter = iter->next)
942 source_list = iter->data;
944 if (source_list->priority == priority)
947 if (source_list->priority > priority)
952 source_list = g_slice_new0 (GSourceList);
953 source_list->priority = priority;
954 context->source_lists = g_list_insert_before (context->source_lists,
964 source_list = g_slice_new0 (GSourceList);
965 source_list->priority = priority;
968 context->source_lists = g_list_append (NULL, source_list);
971 /* This just appends source_list to the end of
972 * context->source_lists without having to walk the list again.
974 last = g_list_append (last, source_list);
979 /* Holds context's lock
982 source_add_to_context (GSource *source,
983 GMainContext *context)
985 GSourceList *source_list;
986 GSource *prev, *next;
988 source_list = find_source_list_for_priority (context, source->priority, TRUE);
990 if (source->priv->parent_source)
992 g_assert (source_list->head != NULL);
994 /* Put the source immediately before its parent */
995 prev = source->priv->parent_source->prev;
996 next = source->priv->parent_source;
1000 prev = source_list->tail;
1004 source->next = next;
1006 next->prev = source;
1008 source_list->tail = source;
1010 source->prev = prev;
1012 prev->next = source;
1014 source_list->head = source;
1017 /* Holds context's lock
1020 source_remove_from_context (GSource *source,
1021 GMainContext *context)
1023 GSourceList *source_list;
1025 source_list = find_source_list_for_priority (context, source->priority, FALSE);
1026 g_return_if_fail (source_list != NULL);
1029 source->prev->next = source->next;
1031 source_list->head = source->next;
1034 source->next->prev = source->prev;
1036 source_list->tail = source->prev;
1038 source->prev = NULL;
1039 source->next = NULL;
1041 if (source_list->head == NULL)
1043 context->source_lists = g_list_remove (context->source_lists, source_list);
1044 g_slice_free (GSourceList, source_list);
1047 if (context->overflow_used_source_ids)
1048 g_hash_table_remove (context->overflow_used_source_ids,
1049 GUINT_TO_POINTER (source->source_id));
1054 assign_source_id_unlocked (GMainContext *context,
1059 /* Are we about to overflow back to 0?
1060 * See https://bugzilla.gnome.org/show_bug.cgi?id=687098
1062 if (G_UNLIKELY (context->next_id == G_MAXUINT &&
1063 context->overflow_used_source_ids == NULL))
1068 context->overflow_used_source_ids = g_hash_table_new (NULL, NULL);
1070 g_source_iter_init (&iter, context, FALSE);
1071 while (g_source_iter_next (&iter, &source))
1073 g_hash_table_add (context->overflow_used_source_ids,
1074 GUINT_TO_POINTER (source->source_id));
1078 else if (context->overflow_used_source_ids == NULL)
1080 id = context->next_id++;
1085 * If we overran G_MAXUINT, we fall back to randomly probing the
1086 * source ids for the current context. This will be slower the more
1087 * sources there are, but we're mainly concerned right now about
1088 * correctness and code size. There's time for a more clever solution
1092 id = g_random_int ();
1094 g_hash_table_contains (context->overflow_used_source_ids,
1095 GUINT_TO_POINTER (id)));
1096 g_hash_table_add (context->overflow_used_source_ids, GUINT_TO_POINTER (id));
1099 source->source_id = id;
1103 g_source_attach_unlocked (GSource *source,
1104 GMainContext *context)
1108 source->context = context;
1109 assign_source_id_unlocked (context, source);
1110 source->ref_count++;
1111 source_add_to_context (source, context);
1113 tmp_list = source->poll_fds;
1116 g_main_context_add_poll_unlocked (context, source->priority, tmp_list->data);
1117 tmp_list = tmp_list->next;
1120 tmp_list = source->priv->child_sources;
1123 g_source_attach_unlocked (tmp_list->data, context);
1124 tmp_list = tmp_list->next;
1127 return source->source_id;
1132 * @source: a #GSource
1133 * @context: (allow-none): a #GMainContext (if %NULL, the default context will be used)
1135 * Adds a #GSource to a @context so that it will be executed within
1136 * that context. Remove it by calling g_source_destroy().
1138 * Return value: the ID (greater than 0) for the source within the
1142 g_source_attach (GSource *source,
1143 GMainContext *context)
1147 g_return_val_if_fail (source->context == NULL, 0);
1148 g_return_val_if_fail (!SOURCE_DESTROYED (source), 0);
1151 context = g_main_context_default ();
1153 LOCK_CONTEXT (context);
1155 result = g_source_attach_unlocked (source, context);
1157 /* If another thread has acquired the context, wake it up since it
1158 * might be in poll() right now.
1160 if (context->owner && context->owner != G_THREAD_SELF)
1161 g_wakeup_signal (context->wakeup);
1163 UNLOCK_CONTEXT (context);
1169 g_source_destroy_internal (GSource *source,
1170 GMainContext *context,
1174 LOCK_CONTEXT (context);
1176 if (!SOURCE_DESTROYED (source))
1179 gpointer old_cb_data;
1180 GSourceCallbackFuncs *old_cb_funcs;
1182 source->flags &= ~G_HOOK_FLAG_ACTIVE;
1184 old_cb_data = source->callback_data;
1185 old_cb_funcs = source->callback_funcs;
1187 source->callback_data = NULL;
1188 source->callback_funcs = NULL;
1192 UNLOCK_CONTEXT (context);
1193 old_cb_funcs->unref (old_cb_data);
1194 LOCK_CONTEXT (context);
1197 if (!SOURCE_BLOCKED (source))
1199 tmp_list = source->poll_fds;
1202 g_main_context_remove_poll_unlocked (context, tmp_list->data);
1203 tmp_list = tmp_list->next;
1207 while (source->priv->child_sources)
1208 g_child_source_remove_internal (source->priv->child_sources->data, context);
1210 if (source->priv->parent_source)
1211 g_child_source_remove_internal (source, context);
1213 g_source_unref_internal (source, context, TRUE);
1217 UNLOCK_CONTEXT (context);
1222 * @source: a #GSource
1224 * Removes a source from its #GMainContext, if any, and mark it as
1225 * destroyed. The source cannot be subsequently added to another
1229 g_source_destroy (GSource *source)
1231 GMainContext *context;
1233 g_return_if_fail (source != NULL);
1235 context = source->context;
1238 g_source_destroy_internal (source, context, FALSE);
1240 source->flags &= ~G_HOOK_FLAG_ACTIVE;
1245 * @source: a #GSource
1247 * Returns the numeric ID for a particular source. The ID of a source
1248 * is a positive integer which is unique within a particular main loop
1249 * context. The reverse
1250 * mapping from ID to source is done by g_main_context_find_source_by_id().
1252 * Return value: the ID (greater than 0) for the source
1255 g_source_get_id (GSource *source)
1259 g_return_val_if_fail (source != NULL, 0);
1260 g_return_val_if_fail (source->context != NULL, 0);
1262 LOCK_CONTEXT (source->context);
1263 result = source->source_id;
1264 UNLOCK_CONTEXT (source->context);
1270 * g_source_get_context:
1271 * @source: a #GSource
1273 * Gets the #GMainContext with which the source is associated.
1275 * You can call this on a source that has been destroyed, provided
1276 * that the #GMainContext it was attached to still exists (in which
1277 * case it will return that #GMainContext). In particular, you can
1278 * always call this function on the source returned from
1279 * g_main_current_source(). But calling this function on a source
1280 * whose #GMainContext has been destroyed is an error.
1282 * Return value: (transfer none) (allow-none): the #GMainContext with which the
1283 * source is associated, or %NULL if the context has not
1284 * yet been added to a source.
1287 g_source_get_context (GSource *source)
1289 g_return_val_if_fail (source->context != NULL || !SOURCE_DESTROYED (source), NULL);
1291 return source->context;
1295 * g_source_add_poll:
1296 * @source:a #GSource
1297 * @fd: a #GPollFD structure holding information about a file
1298 * descriptor to watch.
1300 * Adds a file descriptor to the set of file descriptors polled for
1301 * this source. This is usually combined with g_source_new() to add an
1302 * event source. The event source's check function will typically test
1303 * the @revents field in the #GPollFD struct and return %TRUE if events need
1307 g_source_add_poll (GSource *source,
1310 GMainContext *context;
1312 g_return_if_fail (source != NULL);
1313 g_return_if_fail (fd != NULL);
1314 g_return_if_fail (!SOURCE_DESTROYED (source));
1316 context = source->context;
1319 LOCK_CONTEXT (context);
1321 source->poll_fds = g_slist_prepend (source->poll_fds, fd);
1325 if (!SOURCE_BLOCKED (source))
1326 g_main_context_add_poll_unlocked (context, source->priority, fd);
1327 UNLOCK_CONTEXT (context);
1332 * g_source_remove_poll:
1333 * @source:a #GSource
1334 * @fd: a #GPollFD structure previously passed to g_source_add_poll().
1336 * Removes a file descriptor from the set of file descriptors polled for
1340 g_source_remove_poll (GSource *source,
1343 GMainContext *context;
1345 g_return_if_fail (source != NULL);
1346 g_return_if_fail (fd != NULL);
1347 g_return_if_fail (!SOURCE_DESTROYED (source));
1349 context = source->context;
1352 LOCK_CONTEXT (context);
1354 source->poll_fds = g_slist_remove (source->poll_fds, fd);
1358 if (!SOURCE_BLOCKED (source))
1359 g_main_context_remove_poll_unlocked (context, fd);
1360 UNLOCK_CONTEXT (context);
1365 * g_source_add_child_source:
1366 * @source:a #GSource
1367 * @child_source: a second #GSource that @source should "poll"
1369 * Adds @child_source to @source as a "polled" source; when @source is
1370 * added to a #GMainContext, @child_source will be automatically added
1371 * with the same priority, when @child_source is triggered, it will
1372 * cause @source to dispatch (in addition to calling its own
1373 * callback), and when @source is destroyed, it will destroy
1374 * @child_source as well. (@source will also still be dispatched if
1375 * its own prepare/check functions indicate that it is ready.)
1377 * If you don't need @child_source to do anything on its own when it
1378 * triggers, you can call g_source_set_dummy_callback() on it to set a
1379 * callback that does nothing (except return %TRUE if appropriate).
1381 * @source will hold a reference on @child_source while @child_source
1382 * is attached to it.
1387 g_source_add_child_source (GSource *source,
1388 GSource *child_source)
1390 GMainContext *context;
1392 g_return_if_fail (source != NULL);
1393 g_return_if_fail (child_source != NULL);
1394 g_return_if_fail (!SOURCE_DESTROYED (source));
1395 g_return_if_fail (!SOURCE_DESTROYED (child_source));
1396 g_return_if_fail (child_source->context == NULL);
1397 g_return_if_fail (child_source->priv->parent_source == NULL);
1399 context = source->context;
1402 LOCK_CONTEXT (context);
1404 source->priv->child_sources = g_slist_prepend (source->priv->child_sources,
1405 g_source_ref (child_source));
1406 child_source->priv->parent_source = source;
1407 g_source_set_priority_unlocked (child_source, NULL, source->priority);
1408 if (SOURCE_BLOCKED (source))
1409 block_source (child_source);
1413 UNLOCK_CONTEXT (context);
1414 g_source_attach (child_source, context);
1419 g_child_source_remove_internal (GSource *child_source,
1420 GMainContext *context)
1422 GSource *parent_source = child_source->priv->parent_source;
1424 parent_source->priv->child_sources =
1425 g_slist_remove (parent_source->priv->child_sources, child_source);
1426 child_source->priv->parent_source = NULL;
1428 g_source_destroy_internal (child_source, context, TRUE);
1429 g_source_unref_internal (child_source, context, TRUE);
1433 * g_source_remove_child_source:
1434 * @source:a #GSource
1435 * @child_source: a #GSource previously passed to
1436 * g_source_add_child_source().
1438 * Detaches @child_source from @source and destroys it.
1443 g_source_remove_child_source (GSource *source,
1444 GSource *child_source)
1446 GMainContext *context;
1448 g_return_if_fail (source != NULL);
1449 g_return_if_fail (child_source != NULL);
1450 g_return_if_fail (child_source->priv->parent_source == source);
1451 g_return_if_fail (!SOURCE_DESTROYED (source));
1452 g_return_if_fail (!SOURCE_DESTROYED (child_source));
1454 context = source->context;
1457 LOCK_CONTEXT (context);
1459 g_child_source_remove_internal (child_source, context);
1462 UNLOCK_CONTEXT (context);
1466 * g_source_set_callback_indirect:
1467 * @source: the source
1468 * @callback_data: pointer to callback data "object"
1469 * @callback_funcs: functions for reference counting @callback_data
1470 * and getting the callback and data
1472 * Sets the callback function storing the data as a refcounted callback
1473 * "object". This is used internally. Note that calling
1474 * g_source_set_callback_indirect() assumes
1475 * an initial reference count on @callback_data, and thus
1476 * @callback_funcs->unref will eventually be called once more
1477 * than @callback_funcs->ref.
1480 g_source_set_callback_indirect (GSource *source,
1481 gpointer callback_data,
1482 GSourceCallbackFuncs *callback_funcs)
1484 GMainContext *context;
1485 gpointer old_cb_data;
1486 GSourceCallbackFuncs *old_cb_funcs;
1488 g_return_if_fail (source != NULL);
1489 g_return_if_fail (callback_funcs != NULL || callback_data == NULL);
1491 context = source->context;
1494 LOCK_CONTEXT (context);
1496 old_cb_data = source->callback_data;
1497 old_cb_funcs = source->callback_funcs;
1499 source->callback_data = callback_data;
1500 source->callback_funcs = callback_funcs;
1503 UNLOCK_CONTEXT (context);
1506 old_cb_funcs->unref (old_cb_data);
1510 g_source_callback_ref (gpointer cb_data)
1512 GSourceCallback *callback = cb_data;
1514 callback->ref_count++;
1519 g_source_callback_unref (gpointer cb_data)
1521 GSourceCallback *callback = cb_data;
1523 callback->ref_count--;
1524 if (callback->ref_count == 0)
1526 if (callback->notify)
1527 callback->notify (callback->data);
1533 g_source_callback_get (gpointer cb_data,
1538 GSourceCallback *callback = cb_data;
1540 *func = callback->func;
1541 *data = callback->data;
1544 static GSourceCallbackFuncs g_source_callback_funcs = {
1545 g_source_callback_ref,
1546 g_source_callback_unref,
1547 g_source_callback_get,
1551 * g_source_set_callback:
1552 * @source: the source
1553 * @func: a callback function
1554 * @data: the data to pass to callback function
1555 * @notify: (allow-none): a function to call when @data is no longer in use, or %NULL.
1557 * Sets the callback function for a source. The callback for a source is
1558 * called from the source's dispatch function.
1560 * The exact type of @func depends on the type of source; ie. you
1561 * should not count on @func being called with @data as its first
1564 * Typically, you won't use this function. Instead use functions specific
1565 * to the type of source you are using.
1568 g_source_set_callback (GSource *source,
1571 GDestroyNotify notify)
1573 GSourceCallback *new_callback;
1575 g_return_if_fail (source != NULL);
1577 new_callback = g_new (GSourceCallback, 1);
1579 new_callback->ref_count = 1;
1580 new_callback->func = func;
1581 new_callback->data = data;
1582 new_callback->notify = notify;
1584 g_source_set_callback_indirect (source, new_callback, &g_source_callback_funcs);
1589 * g_source_set_funcs:
1590 * @source: a #GSource
1591 * @funcs: the new #GSourceFuncs
1593 * Sets the source functions (can be used to override
1594 * default implementations) of an unattached source.
1599 g_source_set_funcs (GSource *source,
1600 GSourceFuncs *funcs)
1602 g_return_if_fail (source != NULL);
1603 g_return_if_fail (source->context == NULL);
1604 g_return_if_fail (source->ref_count > 0);
1605 g_return_if_fail (funcs != NULL);
1607 source->source_funcs = funcs;
1611 g_source_set_priority_unlocked (GSource *source,
1612 GMainContext *context,
1617 g_return_if_fail (source->priv->parent_source == NULL ||
1618 source->priv->parent_source->priority == priority);
1622 /* Remove the source from the context's source and then
1623 * add it back after so it is sorted in the correct place
1625 source_remove_from_context (source, source->context);
1628 source->priority = priority;
1632 source_add_to_context (source, source->context);
1634 if (!SOURCE_BLOCKED (source))
1636 tmp_list = source->poll_fds;
1639 g_main_context_remove_poll_unlocked (context, tmp_list->data);
1640 g_main_context_add_poll_unlocked (context, priority, tmp_list->data);
1642 tmp_list = tmp_list->next;
1647 if (source->priv->child_sources)
1649 tmp_list = source->priv->child_sources;
1652 g_source_set_priority_unlocked (tmp_list->data, context, priority);
1653 tmp_list = tmp_list->next;
1659 * g_source_set_priority:
1660 * @source: a #GSource
1661 * @priority: the new priority.
1663 * Sets the priority of a source. While the main loop is being run, a
1664 * source will be dispatched if it is ready to be dispatched and no
1665 * sources at a higher (numerically smaller) priority are ready to be
1669 g_source_set_priority (GSource *source,
1672 GMainContext *context;
1674 g_return_if_fail (source != NULL);
1676 context = source->context;
1679 LOCK_CONTEXT (context);
1680 g_source_set_priority_unlocked (source, context, priority);
1682 UNLOCK_CONTEXT (source->context);
1686 * g_source_get_priority:
1687 * @source: a #GSource
1689 * Gets the priority of a source.
1691 * Return value: the priority of the source
1694 g_source_get_priority (GSource *source)
1696 g_return_val_if_fail (source != NULL, 0);
1698 return source->priority;
1702 * g_source_set_can_recurse:
1703 * @source: a #GSource
1704 * @can_recurse: whether recursion is allowed for this source
1706 * Sets whether a source can be called recursively. If @can_recurse is
1707 * %TRUE, then while the source is being dispatched then this source
1708 * will be processed normally. Otherwise, all processing of this
1709 * source is blocked until the dispatch function returns.
1712 g_source_set_can_recurse (GSource *source,
1713 gboolean can_recurse)
1715 GMainContext *context;
1717 g_return_if_fail (source != NULL);
1719 context = source->context;
1722 LOCK_CONTEXT (context);
1725 source->flags |= G_SOURCE_CAN_RECURSE;
1727 source->flags &= ~G_SOURCE_CAN_RECURSE;
1730 UNLOCK_CONTEXT (context);
1734 * g_source_get_can_recurse:
1735 * @source: a #GSource
1737 * Checks whether a source is allowed to be called recursively.
1738 * see g_source_set_can_recurse().
1740 * Return value: whether recursion is allowed.
1743 g_source_get_can_recurse (GSource *source)
1745 g_return_val_if_fail (source != NULL, FALSE);
1747 return (source->flags & G_SOURCE_CAN_RECURSE) != 0;
1752 * g_source_set_name:
1753 * @source: a #GSource
1754 * @name: debug name for the source
1756 * Sets a name for the source, used in debugging and profiling.
1757 * The name defaults to #NULL.
1759 * The source name should describe in a human-readable way
1760 * what the source does. For example, "X11 event queue"
1761 * or "GTK+ repaint idle handler" or whatever it is.
1763 * It is permitted to call this function multiple times, but is not
1764 * recommended due to the potential performance impact. For example,
1765 * one could change the name in the "check" function of a #GSourceFuncs
1766 * to include details like the event type in the source name.
1771 g_source_set_name (GSource *source,
1774 g_return_if_fail (source != NULL);
1776 /* setting back to NULL is allowed, just because it's
1777 * weird if get_name can return NULL but you can't
1781 g_free (source->name);
1782 source->name = g_strdup (name);
1786 * g_source_get_name:
1787 * @source: a #GSource
1789 * Gets a name for the source, used in debugging and profiling.
1790 * The name may be #NULL if it has never been set with
1791 * g_source_set_name().
1793 * Return value: the name of the source
1797 g_source_get_name (GSource *source)
1799 g_return_val_if_fail (source != NULL, NULL);
1801 return source->name;
1805 * g_source_set_name_by_id:
1806 * @tag: a #GSource ID
1807 * @name: debug name for the source
1809 * Sets the name of a source using its ID.
1811 * This is a convenience utility to set source names from the return
1812 * value of g_idle_add(), g_timeout_add(), etc.
1817 g_source_set_name_by_id (guint tag,
1822 g_return_if_fail (tag > 0);
1824 source = g_main_context_find_source_by_id (NULL, tag);
1828 g_source_set_name (source, name);
1834 * @source: a #GSource
1836 * Increases the reference count on a source by one.
1838 * Return value: @source
1841 g_source_ref (GSource *source)
1843 GMainContext *context;
1845 g_return_val_if_fail (source != NULL, NULL);
1847 context = source->context;
1850 LOCK_CONTEXT (context);
1852 source->ref_count++;
1855 UNLOCK_CONTEXT (context);
1860 /* g_source_unref() but possible to call within context lock
1863 g_source_unref_internal (GSource *source,
1864 GMainContext *context,
1867 gpointer old_cb_data = NULL;
1868 GSourceCallbackFuncs *old_cb_funcs = NULL;
1870 g_return_if_fail (source != NULL);
1872 if (!have_lock && context)
1873 LOCK_CONTEXT (context);
1875 source->ref_count--;
1876 if (source->ref_count == 0)
1878 old_cb_data = source->callback_data;
1879 old_cb_funcs = source->callback_funcs;
1881 source->callback_data = NULL;
1882 source->callback_funcs = NULL;
1886 if (!SOURCE_DESTROYED (source))
1887 g_warning (G_STRLOC ": ref_count == 0, but source was still attached to a context!");
1888 source_remove_from_context (source, context);
1891 if (source->source_funcs->finalize)
1894 UNLOCK_CONTEXT (context);
1895 source->source_funcs->finalize (source);
1897 LOCK_CONTEXT (context);
1900 g_free (source->name);
1901 source->name = NULL;
1903 g_slist_free (source->poll_fds);
1904 source->poll_fds = NULL;
1906 g_slice_free (GSourcePrivate, source->priv);
1907 source->priv = NULL;
1912 if (!have_lock && context)
1913 UNLOCK_CONTEXT (context);
1918 UNLOCK_CONTEXT (context);
1920 old_cb_funcs->unref (old_cb_data);
1923 LOCK_CONTEXT (context);
1929 * @source: a #GSource
1931 * Decreases the reference count of a source by one. If the
1932 * resulting reference count is zero the source and associated
1933 * memory will be destroyed.
1936 g_source_unref (GSource *source)
1938 g_return_if_fail (source != NULL);
1940 g_source_unref_internal (source, source->context, FALSE);
1944 * g_main_context_find_source_by_id:
1945 * @context: (allow-none): a #GMainContext (if %NULL, the default context will be used)
1946 * @source_id: the source ID, as returned by g_source_get_id().
1948 * Finds a #GSource given a pair of context and ID.
1950 * Return value: (transfer none): the #GSource if found, otherwise, %NULL
1953 g_main_context_find_source_by_id (GMainContext *context,
1959 g_return_val_if_fail (source_id > 0, NULL);
1961 if (context == NULL)
1962 context = g_main_context_default ();
1964 LOCK_CONTEXT (context);
1966 g_source_iter_init (&iter, context, FALSE);
1967 while (g_source_iter_next (&iter, &source))
1969 if (!SOURCE_DESTROYED (source) &&
1970 source->source_id == source_id)
1973 g_source_iter_clear (&iter);
1975 UNLOCK_CONTEXT (context);
1981 * g_main_context_find_source_by_funcs_user_data:
1982 * @context: (allow-none): a #GMainContext (if %NULL, the default context will be used).
1983 * @funcs: the @source_funcs passed to g_source_new().
1984 * @user_data: the user data from the callback.
1986 * Finds a source with the given source functions and user data. If
1987 * multiple sources exist with the same source function and user data,
1988 * the first one found will be returned.
1990 * Return value: (transfer none): the source, if one was found, otherwise %NULL
1993 g_main_context_find_source_by_funcs_user_data (GMainContext *context,
1994 GSourceFuncs *funcs,
2000 g_return_val_if_fail (funcs != NULL, NULL);
2002 if (context == NULL)
2003 context = g_main_context_default ();
2005 LOCK_CONTEXT (context);
2007 g_source_iter_init (&iter, context, FALSE);
2008 while (g_source_iter_next (&iter, &source))
2010 if (!SOURCE_DESTROYED (source) &&
2011 source->source_funcs == funcs &&
2012 source->callback_funcs)
2014 GSourceFunc callback;
2015 gpointer callback_data;
2017 source->callback_funcs->get (source->callback_data, source, &callback, &callback_data);
2019 if (callback_data == user_data)
2023 g_source_iter_clear (&iter);
2025 UNLOCK_CONTEXT (context);
2031 * g_main_context_find_source_by_user_data:
2032 * @context: a #GMainContext
2033 * @user_data: the user_data for the callback.
2035 * Finds a source with the given user data for the callback. If
2036 * multiple sources exist with the same user data, the first
2037 * one found will be returned.
2039 * Return value: (transfer none): the source, if one was found, otherwise %NULL
2042 g_main_context_find_source_by_user_data (GMainContext *context,
2048 if (context == NULL)
2049 context = g_main_context_default ();
2051 LOCK_CONTEXT (context);
2053 g_source_iter_init (&iter, context, FALSE);
2054 while (g_source_iter_next (&iter, &source))
2056 if (!SOURCE_DESTROYED (source) &&
2057 source->callback_funcs)
2059 GSourceFunc callback;
2060 gpointer callback_data = NULL;
2062 source->callback_funcs->get (source->callback_data, source, &callback, &callback_data);
2064 if (callback_data == user_data)
2068 g_source_iter_clear (&iter);
2070 UNLOCK_CONTEXT (context);
2077 * @tag: the ID of the source to remove.
2079 * Removes the source with the given id from the default main context.
2081 * a #GSource is given by g_source_get_id(), or will be returned by the
2082 * functions g_source_attach(), g_idle_add(), g_idle_add_full(),
2083 * g_timeout_add(), g_timeout_add_full(), g_child_watch_add(),
2084 * g_child_watch_add_full(), g_io_add_watch(), and g_io_add_watch_full().
2086 * See also g_source_destroy(). You must use g_source_destroy() for sources
2087 * added to a non-default main context.
2089 * Return value: %TRUE if the source was found and removed.
2092 g_source_remove (guint tag)
2096 g_return_val_if_fail (tag > 0, FALSE);
2098 source = g_main_context_find_source_by_id (NULL, tag);
2100 g_source_destroy (source);
2102 return source != NULL;
2106 * g_source_remove_by_user_data:
2107 * @user_data: the user_data for the callback.
2109 * Removes a source from the default main loop context given the user
2110 * data for the callback. If multiple sources exist with the same user
2111 * data, only one will be destroyed.
2113 * Return value: %TRUE if a source was found and removed.
2116 g_source_remove_by_user_data (gpointer user_data)
2120 source = g_main_context_find_source_by_user_data (NULL, user_data);
2123 g_source_destroy (source);
2131 * g_source_remove_by_funcs_user_data:
2132 * @funcs: The @source_funcs passed to g_source_new()
2133 * @user_data: the user data for the callback
2135 * Removes a source from the default main loop context given the
2136 * source functions and user data. If multiple sources exist with the
2137 * same source functions and user data, only one will be destroyed.
2139 * Return value: %TRUE if a source was found and removed.
2142 g_source_remove_by_funcs_user_data (GSourceFuncs *funcs,
2147 g_return_val_if_fail (funcs != NULL, FALSE);
2149 source = g_main_context_find_source_by_funcs_user_data (NULL, funcs, user_data);
2152 g_source_destroy (source);
2160 * g_get_current_time:
2161 * @result: #GTimeVal structure in which to store current time.
2163 * Equivalent to the UNIX gettimeofday() function, but portable.
2165 * You may find g_get_real_time() to be more convenient.
2168 g_get_current_time (GTimeVal *result)
2173 g_return_if_fail (result != NULL);
2175 /*this is required on alpha, there the timeval structs are int's
2176 not longs and a cast only would fail horribly*/
2177 gettimeofday (&r, NULL);
2178 result->tv_sec = r.tv_sec;
2179 result->tv_usec = r.tv_usec;
2184 g_return_if_fail (result != NULL);
2186 GetSystemTimeAsFileTime (&ft);
2187 memmove (&time64, &ft, sizeof (FILETIME));
2189 /* Convert from 100s of nanoseconds since 1601-01-01
2190 * to Unix epoch. Yes, this is Y2038 unsafe.
2192 time64 -= G_GINT64_CONSTANT (116444736000000000);
2195 result->tv_sec = time64 / 1000000;
2196 result->tv_usec = time64 % 1000000;
2203 * Queries the system wall-clock time.
2205 * This call is functionally equivalent to g_get_current_time() except
2206 * that the return value is often more convenient than dealing with a
2209 * You should only use this call if you are actually interested in the real
2210 * wall-clock time. g_get_monotonic_time() is probably more useful for
2211 * measuring intervals.
2213 * Returns: the number of microseconds since January 1, 1970 UTC.
2218 g_get_real_time (void)
2222 g_get_current_time (&tv);
2224 return (((gint64) tv.tv_sec) * 1000000) + tv.tv_usec;
2228 static ULONGLONG (*g_GetTickCount64) (void) = NULL;
2229 static guint32 g_win32_tick_epoch = 0;
2231 G_GNUC_INTERNAL void
2232 g_clock_win32_init (void)
2236 g_GetTickCount64 = NULL;
2237 kernel32 = GetModuleHandle ("KERNEL32.DLL");
2238 if (kernel32 != NULL)
2239 g_GetTickCount64 = (void *) GetProcAddress (kernel32, "GetTickCount64");
2240 g_win32_tick_epoch = ((guint32)GetTickCount()) >> 31;
2245 * g_get_monotonic_time:
2247 * Queries the system monotonic time, if available.
2249 * On POSIX systems with clock_gettime() and <literal>CLOCK_MONOTONIC</literal> this call
2250 * is a very shallow wrapper for that. Otherwise, we make a best effort
2251 * that probably involves returning the wall clock time (with at least
2252 * microsecond accuracy, subject to the limitations of the OS kernel).
2254 * It's important to note that POSIX <literal>CLOCK_MONOTONIC</literal> does
2255 * not count time spent while the machine is suspended.
2257 * On Windows, "limitations of the OS kernel" is a rather substantial
2258 * statement. Depending on the configuration of the system, the wall
2259 * clock time is updated as infrequently as 64 times a second (which
2260 * is approximately every 16ms). Also, on XP (but not on Vista or later)
2261 * the monotonic clock is locally monotonic, but may differ in exact
2262 * value between processes due to timer wrap handling.
2264 * Returns: the monotonic time, in microseconds
2269 g_get_monotonic_time (void)
2271 #ifdef HAVE_CLOCK_GETTIME
2272 /* librt clock_gettime() is our first choice */
2275 #ifdef CLOCK_MONOTONIC
2276 clock_gettime (CLOCK_MONOTONIC, &ts);
2278 clock_gettime (CLOCK_REALTIME, &ts);
2281 /* In theory monotonic time can have any epoch.
2283 * glib presently assumes the following:
2285 * 1) The epoch comes some time after the birth of Jesus of Nazareth, but
2286 * not more than 10000 years later.
2288 * 2) The current time also falls sometime within this range.
2290 * These two reasonable assumptions leave us with a maximum deviation from
2291 * the epoch of 10000 years, or 315569520000000000 seconds.
2293 * If we restrict ourselves to this range then the number of microseconds
2294 * will always fit well inside the constraints of a int64 (by a factor of
2297 * If you actually hit the following assertion, probably you should file a
2298 * bug against your operating system for being excessively silly.
2300 g_assert (G_GINT64_CONSTANT (-315569520000000000) < ts.tv_sec &&
2301 ts.tv_sec < G_GINT64_CONSTANT (315569520000000000));
2303 return (((gint64) ts.tv_sec) * 1000000) + (ts.tv_nsec / 1000);
2305 #elif defined (G_OS_WIN32)
2309 /* There are four sources for the monotonic time on Windows:
2311 * Three are based on a (1 msec accuracy, but only read periodically) clock chip:
2312 * - GetTickCount (GTC)
2313 * 32bit msec counter, updated each ~15msec, wraps in ~50 days
2314 * - GetTickCount64 (GTC64)
2315 * Same as GetTickCount, but extended to 64bit, so no wrap
2316 * Only available in Vista or later
2317 * - timeGetTime (TGT)
2318 * similar to GetTickCount by default: 15msec, 50 day wrap.
2319 * available in winmm.dll (thus known as the multimedia timers)
2320 * However apps can raise the system timer clock frequency using timeBeginPeriod()
2321 * increasing the accuracy up to 1 msec, at a cost in general system performance
2324 * One is based on high precision clocks:
2325 * - QueryPrecisionCounter (QPC)
2326 * This has much higher accuracy, but is not guaranteed monotonic, and
2327 * has lots of complications like clock jumps and different times on different
2328 * CPUs. It also has lower long term accuracy (i.e. it will drift compared to
2329 * the low precision clocks.
2331 * Additionally, the precision available in the timer-based wakeup such as
2332 * MsgWaitForMultipleObjectsEx (which is what the mainloop is based on) is based
2333 * on the TGT resolution, so by default it is ~15msec, but can be increased by apps.
2335 * The QPC timer has too many issues to be used as is. The only way it could be used
2336 * is to use it to interpolate the lower precision clocks. Firefox does something like
2338 * https://bugzilla.mozilla.org/show_bug.cgi?id=363258
2340 * However this seems quite complicated, so we're not doing this right now.
2342 * The approach we take instead is to use the TGT timer, extending it to 64bit
2343 * either by using the GTC64 value, or if that is not available, a process local
2344 * time epoch that we increment when we detect a timer wrap (assumes that we read
2345 * the time at least once every 50 days).
2348 * - We have a globally consistent monotonic clock on Vista and later
2349 * - We have a locally monotonic clock on XP
2350 * - Apps that need higher precision in timeouts and clock reads can call
2351 * timeBeginPeriod() to increase it as much as they want
2354 if (g_GetTickCount64 != NULL)
2356 guint32 ticks_as_32bit;
2358 ticks = g_GetTickCount64 ();
2359 ticks32 = timeGetTime();
2361 /* GTC64 and TGT are sampled at different times, however they
2362 * have the same base and source (msecs since system boot).
2363 * They can differ by as much as -16 to +16 msecs.
2364 * We can't just inject the low bits into the 64bit counter
2365 * as one of the counters can have wrapped in 32bit space and
2366 * the other not. Instead we calculate the signed difference
2367 * in 32bit space and apply that difference to the 64bit counter.
2369 ticks_as_32bit = (guint32)ticks;
2371 /* We could do some 2's complement hack, but we play it safe */
2372 if (ticks32 - ticks_as_32bit <= G_MAXINT32)
2373 ticks += ticks32 - ticks_as_32bit;
2375 ticks -= ticks_as_32bit - ticks32;
2381 epoch = g_atomic_int_get (&g_win32_tick_epoch);
2383 /* Must read ticks after the epoch. Then we're guaranteed
2384 * that the ticks value we read is higher or equal to any
2385 * previous ones that lead to the writing of the epoch.
2387 ticks32 = timeGetTime();
2389 /* We store the MSB of the current time as the LSB
2390 * of the epoch. Comparing these bits lets us detect when
2391 * the 32bit counter has wrapped so we can increase the
2394 * This will work as long as this function is called at
2395 * least once every ~24 days, which is half the wrap time
2396 * of a 32bit msec counter. I think this is pretty likely.
2398 * Note that g_win32_tick_epoch is a process local state,
2399 * so the monotonic clock will not be the same between
2402 if ((ticks32 >> 31) != (epoch & 1))
2405 g_atomic_int_set (&g_win32_tick_epoch, epoch);
2409 ticks = (guint64)ticks32 | ((guint64)epoch) << 31;
2412 return ticks * 1000;
2414 #else /* !HAVE_CLOCK_GETTIME && ! G_OS_WIN32*/
2418 g_get_current_time (&tv);
2420 return (((gint64) tv.tv_sec) * 1000000) + tv.tv_usec;
2425 g_main_dispatch_free (gpointer dispatch)
2427 g_slice_free (GMainDispatch, dispatch);
2430 /* Running the main loop */
2432 static GMainDispatch *
2435 static GPrivate depth_private = G_PRIVATE_INIT (g_main_dispatch_free);
2436 GMainDispatch *dispatch;
2438 dispatch = g_private_get (&depth_private);
2442 dispatch = g_slice_new0 (GMainDispatch);
2443 g_private_set (&depth_private, dispatch);
2452 * Returns the depth of the stack of calls to
2453 * g_main_context_dispatch() on any #GMainContext in the current thread.
2454 * That is, when called from the toplevel, it gives 0. When
2455 * called from within a callback from g_main_context_iteration()
2456 * (or g_main_loop_run(), etc.) it returns 1. When called from within
2457 * a callback to a recursive call to g_main_context_iteration(),
2458 * it returns 2. And so forth.
2460 * This function is useful in a situation like the following:
2461 * Imagine an extremely simple "garbage collected" system.
2464 * static GList *free_list;
2467 * allocate_memory (gsize size)
2469 * gpointer result = g_malloc (size);
2470 * free_list = g_list_prepend (free_list, result);
2475 * free_allocated_memory (void)
2478 * for (l = free_list; l; l = l->next);
2480 * g_list_free (free_list);
2488 * g_main_context_iteration (NULL, TRUE);
2489 * free_allocated_memory();
2493 * This works from an application, however, if you want to do the same
2494 * thing from a library, it gets more difficult, since you no longer
2495 * control the main loop. You might think you can simply use an idle
2496 * function to make the call to free_allocated_memory(), but that
2497 * doesn't work, since the idle function could be called from a
2498 * recursive callback. This can be fixed by using g_main_depth()
2502 * allocate_memory (gsize size)
2504 * FreeListBlock *block = g_new (FreeListBlock, 1);
2505 * block->mem = g_malloc (size);
2506 * block->depth = g_main_depth ();
2507 * free_list = g_list_prepend (free_list, block);
2508 * return block->mem;
2512 * free_allocated_memory (void)
2516 * int depth = g_main_depth ();
2517 * for (l = free_list; l; );
2519 * GList *next = l->next;
2520 * FreeListBlock *block = l->data;
2521 * if (block->depth > depth)
2523 * g_free (block->mem);
2525 * free_list = g_list_delete_link (free_list, l);
2533 * There is a temptation to use g_main_depth() to solve
2534 * problems with reentrancy. For instance, while waiting for data
2535 * to be received from the network in response to a menu item,
2536 * the menu item might be selected again. It might seem that
2537 * one could make the menu item's callback return immediately
2538 * and do nothing if g_main_depth() returns a value greater than 1.
2539 * However, this should be avoided since the user then sees selecting
2540 * the menu item do nothing. Furthermore, you'll find yourself adding
2541 * these checks all over your code, since there are doubtless many,
2542 * many things that the user could do. Instead, you can use the
2543 * following techniques:
2548 * Use gtk_widget_set_sensitive() or modal dialogs to prevent
2549 * the user from interacting with elements while the main
2550 * loop is recursing.
2555 * Avoid main loop recursion in situations where you can't handle
2556 * arbitrary callbacks. Instead, structure your code so that you
2557 * simply return to the main loop and then get called again when
2558 * there is more work to do.
2563 * Return value: The main loop recursion level in the current thread
2568 GMainDispatch *dispatch = get_dispatch ();
2569 return dispatch->depth;
2573 * g_main_current_source:
2575 * Returns the currently firing source for this thread.
2577 * Return value: (transfer none): The currently firing source or %NULL.
2582 g_main_current_source (void)
2584 GMainDispatch *dispatch = get_dispatch ();
2585 return dispatch->dispatching_sources ? dispatch->dispatching_sources->data : NULL;
2589 * g_source_is_destroyed:
2590 * @source: a #GSource
2592 * Returns whether @source has been destroyed.
2594 * This is important when you operate upon your objects
2595 * from within idle handlers, but may have freed the object
2596 * before the dispatch of your idle handler.
2600 * idle_callback (gpointer data)
2602 * SomeWidget *self = data;
2604 * GDK_THREADS_ENTER (<!-- -->);
2605 * /<!-- -->* do stuff with self *<!-- -->/
2606 * self->idle_id = 0;
2607 * GDK_THREADS_LEAVE (<!-- -->);
2609 * return G_SOURCE_REMOVE;
2613 * some_widget_do_stuff_later (SomeWidget *self)
2615 * self->idle_id = g_idle_add (idle_callback, self);
2619 * some_widget_finalize (GObject *object)
2621 * SomeWidget *self = SOME_WIDGET (object);
2623 * if (self->idle_id)
2624 * g_source_remove (self->idle_id);
2626 * G_OBJECT_CLASS (parent_class)->finalize (object);
2630 * This will fail in a multi-threaded application if the
2631 * widget is destroyed before the idle handler fires due
2632 * to the use after free in the callback. A solution, to
2633 * this particular problem, is to check to if the source
2634 * has already been destroy within the callback.
2638 * idle_callback (gpointer data)
2640 * SomeWidget *self = data;
2642 * GDK_THREADS_ENTER ();
2643 * if (!g_source_is_destroyed (g_main_current_source ()))
2645 * /<!-- -->* do stuff with self *<!-- -->/
2647 * GDK_THREADS_LEAVE ();
2653 * Return value: %TRUE if the source has been destroyed
2658 g_source_is_destroyed (GSource *source)
2660 return SOURCE_DESTROYED (source);
2663 /* Temporarily remove all this source's file descriptors from the
2664 * poll(), so that if data comes available for one of the file descriptors
2665 * we don't continually spin in the poll()
2667 /* HOLDS: source->context's lock */
2669 block_source (GSource *source)
2673 g_return_if_fail (!SOURCE_BLOCKED (source));
2675 source->flags |= G_SOURCE_BLOCKED;
2677 tmp_list = source->poll_fds;
2680 g_main_context_remove_poll_unlocked (source->context, tmp_list->data);
2681 tmp_list = tmp_list->next;
2684 if (source->priv && source->priv->child_sources)
2686 tmp_list = source->priv->child_sources;
2689 block_source (tmp_list->data);
2690 tmp_list = tmp_list->next;
2695 /* HOLDS: source->context's lock */
2697 unblock_source (GSource *source)
2701 g_return_if_fail (SOURCE_BLOCKED (source)); /* Source already unblocked */
2702 g_return_if_fail (!SOURCE_DESTROYED (source));
2704 source->flags &= ~G_SOURCE_BLOCKED;
2706 tmp_list = source->poll_fds;
2709 g_main_context_add_poll_unlocked (source->context, source->priority, tmp_list->data);
2710 tmp_list = tmp_list->next;
2713 if (source->priv && source->priv->child_sources)
2715 tmp_list = source->priv->child_sources;
2718 unblock_source (tmp_list->data);
2719 tmp_list = tmp_list->next;
2724 /* HOLDS: context's lock */
2726 g_main_dispatch (GMainContext *context)
2728 GMainDispatch *current = get_dispatch ();
2731 for (i = 0; i < context->pending_dispatches->len; i++)
2733 GSource *source = context->pending_dispatches->pdata[i];
2735 context->pending_dispatches->pdata[i] = NULL;
2738 source->flags &= ~G_SOURCE_READY;
2740 if (!SOURCE_DESTROYED (source))
2742 gboolean was_in_call;
2743 gpointer user_data = NULL;
2744 GSourceFunc callback = NULL;
2745 GSourceCallbackFuncs *cb_funcs;
2747 gboolean need_destroy;
2749 gboolean (*dispatch) (GSource *,
2752 GSList current_source_link;
2754 dispatch = source->source_funcs->dispatch;
2755 cb_funcs = source->callback_funcs;
2756 cb_data = source->callback_data;
2759 cb_funcs->ref (cb_data);
2761 if ((source->flags & G_SOURCE_CAN_RECURSE) == 0)
2762 block_source (source);
2764 was_in_call = source->flags & G_HOOK_FLAG_IN_CALL;
2765 source->flags |= G_HOOK_FLAG_IN_CALL;
2768 cb_funcs->get (cb_data, source, &callback, &user_data);
2770 UNLOCK_CONTEXT (context);
2773 /* The on-stack allocation of the GSList is unconventional, but
2774 * we know that the lifetime of the link is bounded to this
2775 * function as the link is kept in a thread specific list and
2776 * not manipulated outside of this function and its descendants.
2777 * Avoiding the overhead of a g_slist_alloc() is useful as many
2778 * applications do little more than dispatch events.
2780 * This is a performance hack - do not revert to g_slist_prepend()!
2782 current_source_link.data = source;
2783 current_source_link.next = current->dispatching_sources;
2784 current->dispatching_sources = ¤t_source_link;
2785 need_destroy = ! dispatch (source,
2788 g_assert (current->dispatching_sources == ¤t_source_link);
2789 current->dispatching_sources = current_source_link.next;
2793 cb_funcs->unref (cb_data);
2795 LOCK_CONTEXT (context);
2798 source->flags &= ~G_HOOK_FLAG_IN_CALL;
2800 if (SOURCE_BLOCKED (source) && !SOURCE_DESTROYED (source))
2801 unblock_source (source);
2803 /* Note: this depends on the fact that we can't switch
2804 * sources from one main context to another
2806 if (need_destroy && !SOURCE_DESTROYED (source))
2808 g_assert (source->context == context);
2809 g_source_destroy_internal (source, context, TRUE);
2813 SOURCE_UNREF (source, context);
2816 g_ptr_array_set_size (context->pending_dispatches, 0);
2820 * g_main_context_acquire:
2821 * @context: a #GMainContext
2823 * Tries to become the owner of the specified context.
2824 * If some other thread is the owner of the context,
2825 * returns %FALSE immediately. Ownership is properly
2826 * recursive: the owner can require ownership again
2827 * and will release ownership when g_main_context_release()
2828 * is called as many times as g_main_context_acquire().
2830 * You must be the owner of a context before you
2831 * can call g_main_context_prepare(), g_main_context_query(),
2832 * g_main_context_check(), g_main_context_dispatch().
2834 * Return value: %TRUE if the operation succeeded, and
2835 * this thread is now the owner of @context.
2838 g_main_context_acquire (GMainContext *context)
2840 gboolean result = FALSE;
2841 GThread *self = G_THREAD_SELF;
2843 if (context == NULL)
2844 context = g_main_context_default ();
2846 LOCK_CONTEXT (context);
2848 if (!context->owner)
2850 context->owner = self;
2851 g_assert (context->owner_count == 0);
2854 if (context->owner == self)
2856 context->owner_count++;
2860 UNLOCK_CONTEXT (context);
2866 * g_main_context_release:
2867 * @context: a #GMainContext
2869 * Releases ownership of a context previously acquired by this thread
2870 * with g_main_context_acquire(). If the context was acquired multiple
2871 * times, the ownership will be released only when g_main_context_release()
2872 * is called as many times as it was acquired.
2875 g_main_context_release (GMainContext *context)
2877 if (context == NULL)
2878 context = g_main_context_default ();
2880 LOCK_CONTEXT (context);
2882 context->owner_count--;
2883 if (context->owner_count == 0)
2885 context->owner = NULL;
2887 if (context->waiters)
2889 GMainWaiter *waiter = context->waiters->data;
2890 gboolean loop_internal_waiter = (waiter->mutex == &context->mutex);
2891 context->waiters = g_slist_delete_link (context->waiters,
2893 if (!loop_internal_waiter)
2894 g_mutex_lock (waiter->mutex);
2896 g_cond_signal (waiter->cond);
2898 if (!loop_internal_waiter)
2899 g_mutex_unlock (waiter->mutex);
2903 UNLOCK_CONTEXT (context);
2907 * g_main_context_wait:
2908 * @context: a #GMainContext
2909 * @cond: a condition variable
2910 * @mutex: a mutex, currently held
2912 * Tries to become the owner of the specified context,
2913 * as with g_main_context_acquire(). But if another thread
2914 * is the owner, atomically drop @mutex and wait on @cond until
2915 * that owner releases ownership or until @cond is signaled, then
2916 * try again (once) to become the owner.
2918 * Return value: %TRUE if the operation succeeded, and
2919 * this thread is now the owner of @context.
2922 g_main_context_wait (GMainContext *context,
2926 gboolean result = FALSE;
2927 GThread *self = G_THREAD_SELF;
2928 gboolean loop_internal_waiter;
2930 if (context == NULL)
2931 context = g_main_context_default ();
2933 loop_internal_waiter = (mutex == &context->mutex);
2935 if (!loop_internal_waiter)
2936 LOCK_CONTEXT (context);
2938 if (context->owner && context->owner != self)
2943 waiter.mutex = mutex;
2945 context->waiters = g_slist_append (context->waiters, &waiter);
2947 if (!loop_internal_waiter)
2948 UNLOCK_CONTEXT (context);
2949 g_cond_wait (cond, mutex);
2950 if (!loop_internal_waiter)
2951 LOCK_CONTEXT (context);
2953 context->waiters = g_slist_remove (context->waiters, &waiter);
2956 if (!context->owner)
2958 context->owner = self;
2959 g_assert (context->owner_count == 0);
2962 if (context->owner == self)
2964 context->owner_count++;
2968 if (!loop_internal_waiter)
2969 UNLOCK_CONTEXT (context);
2975 * g_main_context_prepare:
2976 * @context: a #GMainContext
2977 * @priority: location to store priority of highest priority
2978 * source already ready.
2980 * Prepares to poll sources within a main loop. The resulting information
2981 * for polling is determined by calling g_main_context_query ().
2983 * Return value: %TRUE if some source is ready to be dispatched
2987 g_main_context_prepare (GMainContext *context,
2992 gint current_priority = G_MAXINT;
2996 if (context == NULL)
2997 context = g_main_context_default ();
2999 LOCK_CONTEXT (context);
3001 context->time_is_fresh = FALSE;
3003 if (context->in_check_or_prepare)
3005 g_warning ("g_main_context_prepare() called recursively from within a source's check() or "
3006 "prepare() member.");
3007 UNLOCK_CONTEXT (context);
3012 /* If recursing, finish up current dispatch, before starting over */
3013 if (context->pending_dispatches)
3016 g_main_dispatch (context, ¤t_time);
3018 UNLOCK_CONTEXT (context);
3023 /* If recursing, clear list of pending dispatches */
3025 for (i = 0; i < context->pending_dispatches->len; i++)
3027 if (context->pending_dispatches->pdata[i])
3028 SOURCE_UNREF ((GSource *)context->pending_dispatches->pdata[i], context);
3030 g_ptr_array_set_size (context->pending_dispatches, 0);
3032 /* Prepare all sources */
3034 context->timeout = -1;
3036 g_source_iter_init (&iter, context, TRUE);
3037 while (g_source_iter_next (&iter, &source))
3039 gint source_timeout = -1;
3041 if (SOURCE_DESTROYED (source) || SOURCE_BLOCKED (source))
3043 if ((n_ready > 0) && (source->priority > current_priority))
3046 if (!(source->flags & G_SOURCE_READY))
3049 gboolean (*prepare) (GSource *source,
3052 prepare = source->source_funcs->prepare;
3053 context->in_check_or_prepare++;
3054 UNLOCK_CONTEXT (context);
3056 result = (*prepare) (source, &source_timeout);
3058 LOCK_CONTEXT (context);
3059 context->in_check_or_prepare--;
3063 GSource *ready_source = source;
3065 while (ready_source)
3067 ready_source->flags |= G_SOURCE_READY;
3068 ready_source = ready_source->priv->parent_source;
3073 if (source->flags & G_SOURCE_READY)
3076 current_priority = source->priority;
3077 context->timeout = 0;
3080 if (source_timeout >= 0)
3082 if (context->timeout < 0)
3083 context->timeout = source_timeout;
3085 context->timeout = MIN (context->timeout, source_timeout);
3088 g_source_iter_clear (&iter);
3090 UNLOCK_CONTEXT (context);
3093 *priority = current_priority;
3095 return (n_ready > 0);
3099 * g_main_context_query:
3100 * @context: a #GMainContext
3101 * @max_priority: maximum priority source to check
3102 * @timeout_: (out): location to store timeout to be used in polling
3103 * @fds: (out caller-allocates) (array length=n_fds): location to
3104 * store #GPollFD records that need to be polled.
3105 * @n_fds: length of @fds.
3107 * Determines information necessary to poll this main loop.
3109 * Return value: the number of records actually stored in @fds,
3110 * or, if more than @n_fds records need to be stored, the number
3111 * of records that need to be stored.
3114 g_main_context_query (GMainContext *context,
3123 LOCK_CONTEXT (context);
3125 pollrec = context->poll_records;
3127 while (pollrec && max_priority >= pollrec->priority)
3129 /* We need to include entries with fd->events == 0 in the array because
3130 * otherwise if the application changes fd->events behind our back and
3131 * makes it non-zero, we'll be out of sync when we check the fds[] array.
3132 * (Changing fd->events after adding an FD wasn't an anticipated use of
3133 * this API, but it occurs in practice.) */
3136 fds[n_poll].fd = pollrec->fd->fd;
3137 /* In direct contradiction to the Unix98 spec, IRIX runs into
3138 * difficulty if you pass in POLLERR, POLLHUP or POLLNVAL
3139 * flags in the events field of the pollfd while it should
3140 * just ignoring them. So we mask them out here.
3142 fds[n_poll].events = pollrec->fd->events & ~(G_IO_ERR|G_IO_HUP|G_IO_NVAL);
3143 fds[n_poll].revents = 0;
3146 pollrec = pollrec->next;
3150 context->poll_changed = FALSE;
3154 *timeout = context->timeout;
3156 context->time_is_fresh = FALSE;
3159 UNLOCK_CONTEXT (context);
3165 * g_main_context_check:
3166 * @context: a #GMainContext
3167 * @max_priority: the maximum numerical priority of sources to check
3168 * @fds: (array length=n_fds): array of #GPollFD's that was passed to
3169 * the last call to g_main_context_query()
3170 * @n_fds: return value of g_main_context_query()
3172 * Passes the results of polling back to the main loop.
3174 * Return value: %TRUE if some sources are ready to be dispatched.
3177 g_main_context_check (GMainContext *context,
3188 LOCK_CONTEXT (context);
3190 if (context->in_check_or_prepare)
3192 g_warning ("g_main_context_check() called recursively from within a source's check() or "
3193 "prepare() member.");
3194 UNLOCK_CONTEXT (context);
3198 if (context->wake_up_rec.revents)
3199 g_wakeup_acknowledge (context->wakeup);
3201 /* If the set of poll file descriptors changed, bail out
3202 * and let the main loop rerun
3204 if (context->poll_changed)
3206 UNLOCK_CONTEXT (context);
3210 pollrec = context->poll_records;
3214 if (pollrec->fd->events)
3215 pollrec->fd->revents = fds[i].revents;
3217 pollrec = pollrec->next;
3221 g_source_iter_init (&iter, context, TRUE);
3222 while (g_source_iter_next (&iter, &source))
3224 if (SOURCE_DESTROYED (source) || SOURCE_BLOCKED (source))
3226 if ((n_ready > 0) && (source->priority > max_priority))
3229 if (!(source->flags & G_SOURCE_READY))
3232 gboolean (*check) (GSource *source);
3234 check = source->source_funcs->check;
3236 context->in_check_or_prepare++;
3237 UNLOCK_CONTEXT (context);
3239 result = (*check) (source);
3241 LOCK_CONTEXT (context);
3242 context->in_check_or_prepare--;
3246 GSource *ready_source = source;
3248 while (ready_source)
3250 ready_source->flags |= G_SOURCE_READY;
3251 ready_source = ready_source->priv->parent_source;
3256 if (source->flags & G_SOURCE_READY)
3258 source->ref_count++;
3259 g_ptr_array_add (context->pending_dispatches, source);
3263 /* never dispatch sources with less priority than the first
3264 * one we choose to dispatch
3266 max_priority = source->priority;
3269 g_source_iter_clear (&iter);
3271 UNLOCK_CONTEXT (context);
3277 * g_main_context_dispatch:
3278 * @context: a #GMainContext
3280 * Dispatches all pending sources.
3283 g_main_context_dispatch (GMainContext *context)
3285 LOCK_CONTEXT (context);
3287 if (context->pending_dispatches->len > 0)
3289 g_main_dispatch (context);
3292 UNLOCK_CONTEXT (context);
3295 /* HOLDS context lock */
3297 g_main_context_iterate (GMainContext *context,
3304 gboolean some_ready;
3305 gint nfds, allocated_nfds;
3306 GPollFD *fds = NULL;
3308 UNLOCK_CONTEXT (context);
3310 if (!g_main_context_acquire (context))
3312 gboolean got_ownership;
3314 LOCK_CONTEXT (context);
3319 got_ownership = g_main_context_wait (context,
3327 LOCK_CONTEXT (context);
3329 if (!context->cached_poll_array)
3331 context->cached_poll_array_size = context->n_poll_records;
3332 context->cached_poll_array = g_new (GPollFD, context->n_poll_records);
3335 allocated_nfds = context->cached_poll_array_size;
3336 fds = context->cached_poll_array;
3338 UNLOCK_CONTEXT (context);
3340 g_main_context_prepare (context, &max_priority);
3342 while ((nfds = g_main_context_query (context, max_priority, &timeout, fds,
3343 allocated_nfds)) > allocated_nfds)
3345 LOCK_CONTEXT (context);
3347 context->cached_poll_array_size = allocated_nfds = nfds;
3348 context->cached_poll_array = fds = g_new (GPollFD, nfds);
3349 UNLOCK_CONTEXT (context);
3355 g_main_context_poll (context, timeout, max_priority, fds, nfds);
3357 some_ready = g_main_context_check (context, max_priority, fds, nfds);
3360 g_main_context_dispatch (context);
3362 g_main_context_release (context);
3364 LOCK_CONTEXT (context);
3370 * g_main_context_pending:
3371 * @context: (allow-none): a #GMainContext (if %NULL, the default context will be used)
3373 * Checks if any sources have pending events for the given context.
3375 * Return value: %TRUE if events are pending.
3378 g_main_context_pending (GMainContext *context)
3383 context = g_main_context_default();
3385 LOCK_CONTEXT (context);
3386 retval = g_main_context_iterate (context, FALSE, FALSE, G_THREAD_SELF);
3387 UNLOCK_CONTEXT (context);
3393 * g_main_context_iteration:
3394 * @context: (allow-none): a #GMainContext (if %NULL, the default context will be used)
3395 * @may_block: whether the call may block.
3397 * Runs a single iteration for the given main loop. This involves
3398 * checking to see if any event sources are ready to be processed,
3399 * then if no events sources are ready and @may_block is %TRUE, waiting
3400 * for a source to become ready, then dispatching the highest priority
3401 * events sources that are ready. Otherwise, if @may_block is %FALSE
3402 * sources are not waited to become ready, only those highest priority
3403 * events sources will be dispatched (if any), that are ready at this
3404 * given moment without further waiting.
3406 * Note that even when @may_block is %TRUE, it is still possible for
3407 * g_main_context_iteration() to return %FALSE, since the wait may
3408 * be interrupted for other reasons than an event source becoming ready.
3410 * Return value: %TRUE if events were dispatched.
3413 g_main_context_iteration (GMainContext *context, gboolean may_block)
3418 context = g_main_context_default();
3420 LOCK_CONTEXT (context);
3421 retval = g_main_context_iterate (context, may_block, TRUE, G_THREAD_SELF);
3422 UNLOCK_CONTEXT (context);
3429 * @context: (allow-none): a #GMainContext (if %NULL, the default context will be used).
3430 * @is_running: set to %TRUE to indicate that the loop is running. This
3431 * is not very important since calling g_main_loop_run() will set this to
3434 * Creates a new #GMainLoop structure.
3436 * Return value: a new #GMainLoop.
3439 g_main_loop_new (GMainContext *context,
3440 gboolean is_running)
3445 context = g_main_context_default();
3447 g_main_context_ref (context);
3449 loop = g_new0 (GMainLoop, 1);
3450 loop->context = context;
3451 loop->is_running = is_running != FALSE;
3452 loop->ref_count = 1;
3459 * @loop: a #GMainLoop
3461 * Increases the reference count on a #GMainLoop object by one.
3463 * Return value: @loop
3466 g_main_loop_ref (GMainLoop *loop)
3468 g_return_val_if_fail (loop != NULL, NULL);
3469 g_return_val_if_fail (g_atomic_int_get (&loop->ref_count) > 0, NULL);
3471 g_atomic_int_inc (&loop->ref_count);
3477 * g_main_loop_unref:
3478 * @loop: a #GMainLoop
3480 * Decreases the reference count on a #GMainLoop object by one. If
3481 * the result is zero, free the loop and free all associated memory.
3484 g_main_loop_unref (GMainLoop *loop)
3486 g_return_if_fail (loop != NULL);
3487 g_return_if_fail (g_atomic_int_get (&loop->ref_count) > 0);
3489 if (!g_atomic_int_dec_and_test (&loop->ref_count))
3492 g_main_context_unref (loop->context);
3498 * @loop: a #GMainLoop
3500 * Runs a main loop until g_main_loop_quit() is called on the loop.
3501 * If this is called for the thread of the loop's #GMainContext,
3502 * it will process events from the loop, otherwise it will
3506 g_main_loop_run (GMainLoop *loop)
3508 GThread *self = G_THREAD_SELF;
3510 g_return_if_fail (loop != NULL);
3511 g_return_if_fail (g_atomic_int_get (&loop->ref_count) > 0);
3513 if (!g_main_context_acquire (loop->context))
3515 gboolean got_ownership = FALSE;
3517 /* Another thread owns this context */
3518 LOCK_CONTEXT (loop->context);
3520 g_atomic_int_inc (&loop->ref_count);
3522 if (!loop->is_running)
3523 loop->is_running = TRUE;
3525 while (loop->is_running && !got_ownership)
3526 got_ownership = g_main_context_wait (loop->context,
3527 &loop->context->cond,
3528 &loop->context->mutex);
3530 if (!loop->is_running)
3532 UNLOCK_CONTEXT (loop->context);
3534 g_main_context_release (loop->context);
3535 g_main_loop_unref (loop);
3539 g_assert (got_ownership);
3542 LOCK_CONTEXT (loop->context);
3544 if (loop->context->in_check_or_prepare)
3546 g_warning ("g_main_loop_run(): called recursively from within a source's "
3547 "check() or prepare() member, iteration not possible.");
3551 g_atomic_int_inc (&loop->ref_count);
3552 loop->is_running = TRUE;
3553 while (loop->is_running)
3554 g_main_context_iterate (loop->context, TRUE, TRUE, self);
3556 UNLOCK_CONTEXT (loop->context);
3558 g_main_context_release (loop->context);
3560 g_main_loop_unref (loop);
3565 * @loop: a #GMainLoop
3567 * Stops a #GMainLoop from running. Any calls to g_main_loop_run()
3568 * for the loop will return.
3570 * Note that sources that have already been dispatched when
3571 * g_main_loop_quit() is called will still be executed.
3574 g_main_loop_quit (GMainLoop *loop)
3576 g_return_if_fail (loop != NULL);
3577 g_return_if_fail (g_atomic_int_get (&loop->ref_count) > 0);
3579 LOCK_CONTEXT (loop->context);
3580 loop->is_running = FALSE;
3581 g_wakeup_signal (loop->context->wakeup);
3583 g_cond_broadcast (&loop->context->cond);
3585 UNLOCK_CONTEXT (loop->context);
3589 * g_main_loop_is_running:
3590 * @loop: a #GMainLoop.
3592 * Checks to see if the main loop is currently being run via g_main_loop_run().
3594 * Return value: %TRUE if the mainloop is currently being run.
3597 g_main_loop_is_running (GMainLoop *loop)
3599 g_return_val_if_fail (loop != NULL, FALSE);
3600 g_return_val_if_fail (g_atomic_int_get (&loop->ref_count) > 0, FALSE);
3602 return loop->is_running;
3606 * g_main_loop_get_context:
3607 * @loop: a #GMainLoop.
3609 * Returns the #GMainContext of @loop.
3611 * Return value: (transfer none): the #GMainContext of @loop
3614 g_main_loop_get_context (GMainLoop *loop)
3616 g_return_val_if_fail (loop != NULL, NULL);
3617 g_return_val_if_fail (g_atomic_int_get (&loop->ref_count) > 0, NULL);
3619 return loop->context;
3622 /* HOLDS: context's lock */
3624 g_main_context_poll (GMainContext *context,
3630 #ifdef G_MAIN_POLL_DEBUG
3636 GPollFunc poll_func;
3638 if (n_fds || timeout != 0)
3640 #ifdef G_MAIN_POLL_DEBUG
3641 if (_g_main_poll_debug)
3643 g_print ("polling context=%p n=%d timeout=%d\n",
3644 context, n_fds, timeout);
3645 poll_timer = g_timer_new ();
3649 LOCK_CONTEXT (context);
3651 poll_func = context->poll_func;
3653 UNLOCK_CONTEXT (context);
3654 if ((*poll_func) (fds, n_fds, timeout) < 0 && errno != EINTR)
3657 g_warning ("poll(2) failed due to: %s.",
3658 g_strerror (errno));
3660 /* If g_poll () returns -1, it has already called g_warning() */
3664 #ifdef G_MAIN_POLL_DEBUG
3665 if (_g_main_poll_debug)
3667 LOCK_CONTEXT (context);
3669 g_print ("g_main_poll(%d) timeout: %d - elapsed %12.10f seconds",
3672 g_timer_elapsed (poll_timer, NULL));
3673 g_timer_destroy (poll_timer);
3674 pollrec = context->poll_records;
3676 while (pollrec != NULL)
3681 if (fds[i].fd == pollrec->fd->fd &&
3682 pollrec->fd->events &&
3685 g_print (" [" G_POLLFD_FORMAT " :", fds[i].fd);
3686 if (fds[i].revents & G_IO_IN)
3688 if (fds[i].revents & G_IO_OUT)
3690 if (fds[i].revents & G_IO_PRI)
3692 if (fds[i].revents & G_IO_ERR)
3694 if (fds[i].revents & G_IO_HUP)
3696 if (fds[i].revents & G_IO_NVAL)
3702 pollrec = pollrec->next;
3706 UNLOCK_CONTEXT (context);
3709 } /* if (n_fds || timeout != 0) */
3713 * g_main_context_add_poll:
3714 * @context: (allow-none): a #GMainContext (or %NULL for the default context)
3715 * @fd: a #GPollFD structure holding information about a file
3716 * descriptor to watch.
3717 * @priority: the priority for this file descriptor which should be
3718 * the same as the priority used for g_source_attach() to ensure that the
3719 * file descriptor is polled whenever the results may be needed.
3721 * Adds a file descriptor to the set of file descriptors polled for
3722 * this context. This will very seldom be used directly. Instead
3723 * a typical event source will use g_source_add_poll() instead.
3726 g_main_context_add_poll (GMainContext *context,
3731 context = g_main_context_default ();
3733 g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
3734 g_return_if_fail (fd);
3736 LOCK_CONTEXT (context);
3737 g_main_context_add_poll_unlocked (context, priority, fd);
3738 UNLOCK_CONTEXT (context);
3741 /* HOLDS: main_loop_lock */
3743 g_main_context_add_poll_unlocked (GMainContext *context,
3747 GPollRec *prevrec, *nextrec;
3748 GPollRec *newrec = g_slice_new (GPollRec);
3750 /* This file descriptor may be checked before we ever poll */
3753 newrec->priority = priority;
3755 prevrec = context->poll_records_tail;
3757 while (prevrec && priority < prevrec->priority)
3760 prevrec = prevrec->prev;
3764 prevrec->next = newrec;
3766 context->poll_records = newrec;
3768 newrec->prev = prevrec;
3769 newrec->next = nextrec;
3772 nextrec->prev = newrec;
3774 context->poll_records_tail = newrec;
3776 context->n_poll_records++;
3778 context->poll_changed = TRUE;
3780 /* Now wake up the main loop if it is waiting in the poll() */
3781 g_wakeup_signal (context->wakeup);
3785 * g_main_context_remove_poll:
3786 * @context:a #GMainContext
3787 * @fd: a #GPollFD descriptor previously added with g_main_context_add_poll()
3789 * Removes file descriptor from the set of file descriptors to be
3790 * polled for a particular context.
3793 g_main_context_remove_poll (GMainContext *context,
3797 context = g_main_context_default ();
3799 g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
3800 g_return_if_fail (fd);
3802 LOCK_CONTEXT (context);
3803 g_main_context_remove_poll_unlocked (context, fd);
3804 UNLOCK_CONTEXT (context);
3808 g_main_context_remove_poll_unlocked (GMainContext *context,
3811 GPollRec *pollrec, *prevrec, *nextrec;
3814 pollrec = context->poll_records;
3818 nextrec = pollrec->next;
3819 if (pollrec->fd == fd)
3821 if (prevrec != NULL)
3822 prevrec->next = nextrec;
3824 context->poll_records = nextrec;
3826 if (nextrec != NULL)
3827 nextrec->prev = prevrec;
3829 context->poll_records_tail = prevrec;
3831 g_slice_free (GPollRec, pollrec);
3833 context->n_poll_records--;
3840 context->poll_changed = TRUE;
3842 /* Now wake up the main loop if it is waiting in the poll() */
3843 g_wakeup_signal (context->wakeup);
3847 * g_source_get_current_time:
3848 * @source: a #GSource
3849 * @timeval: #GTimeVal structure in which to store current time.
3851 * This function ignores @source and is otherwise the same as
3852 * g_get_current_time().
3854 * Deprecated: 2.28: use g_source_get_time() instead
3857 g_source_get_current_time (GSource *source,
3860 g_get_current_time (timeval);
3864 * g_source_get_time:
3865 * @source: a #GSource
3867 * Gets the time to be used when checking this source. The advantage of
3868 * calling this function over calling g_get_monotonic_time() directly is
3869 * that when checking multiple sources, GLib can cache a single value
3870 * instead of having to repeatedly get the system monotonic time.
3872 * The time here is the system monotonic time, if available, or some
3873 * other reasonable alternative otherwise. See g_get_monotonic_time().
3875 * Returns: the monotonic time in microseconds
3880 g_source_get_time (GSource *source)
3882 GMainContext *context;
3885 g_return_val_if_fail (source->context != NULL, 0);
3887 context = source->context;
3889 LOCK_CONTEXT (context);
3891 if (!context->time_is_fresh)
3893 context->time = g_get_monotonic_time ();
3894 context->time_is_fresh = TRUE;
3897 result = context->time;
3899 UNLOCK_CONTEXT (context);
3905 * g_main_context_set_poll_func:
3906 * @context: a #GMainContext
3907 * @func: the function to call to poll all file descriptors
3909 * Sets the function to use to handle polling of file descriptors. It
3910 * will be used instead of the poll() system call
3911 * (or GLib's replacement function, which is used where
3912 * poll() isn't available).
3914 * This function could possibly be used to integrate the GLib event
3915 * loop with an external event loop.
3918 g_main_context_set_poll_func (GMainContext *context,
3922 context = g_main_context_default ();
3924 g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
3926 LOCK_CONTEXT (context);
3929 context->poll_func = func;
3931 context->poll_func = g_poll;
3933 UNLOCK_CONTEXT (context);
3937 * g_main_context_get_poll_func:
3938 * @context: a #GMainContext
3940 * Gets the poll function set by g_main_context_set_poll_func().
3942 * Return value: the poll function
3945 g_main_context_get_poll_func (GMainContext *context)
3950 context = g_main_context_default ();
3952 g_return_val_if_fail (g_atomic_int_get (&context->ref_count) > 0, NULL);
3954 LOCK_CONTEXT (context);
3955 result = context->poll_func;
3956 UNLOCK_CONTEXT (context);
3962 * g_main_context_wakeup:
3963 * @context: a #GMainContext
3965 * If @context is currently waiting in a poll(), interrupt
3966 * the poll(), and continue the iteration process.
3969 g_main_context_wakeup (GMainContext *context)
3972 context = g_main_context_default ();
3974 g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
3976 g_wakeup_signal (context->wakeup);
3980 * g_main_context_is_owner:
3981 * @context: a #GMainContext
3983 * Determines whether this thread holds the (recursive)
3984 * ownership of this #GMainContext. This is useful to
3985 * know before waiting on another thread that may be
3986 * blocking to get ownership of @context.
3988 * Returns: %TRUE if current thread is owner of @context.
3993 g_main_context_is_owner (GMainContext *context)
3998 context = g_main_context_default ();
4000 LOCK_CONTEXT (context);
4001 is_owner = context->owner == G_THREAD_SELF;
4002 UNLOCK_CONTEXT (context);
4010 g_timeout_set_expiration (GTimeoutSource *timeout_source,
4011 gint64 current_time)
4013 timeout_source->expiration = current_time +
4014 (guint64) timeout_source->interval * 1000;
4016 if (timeout_source->seconds)
4019 static gint timer_perturb = -1;
4021 if (timer_perturb == -1)
4024 * we want a per machine/session unique 'random' value; try the dbus
4025 * address first, that has a UUID in it. If there is no dbus, use the
4026 * hostname for hashing.
4028 const char *session_bus_address = g_getenv ("DBUS_SESSION_BUS_ADDRESS");
4029 if (!session_bus_address)
4030 session_bus_address = g_getenv ("HOSTNAME");
4031 if (session_bus_address)
4032 timer_perturb = ABS ((gint) g_str_hash (session_bus_address)) % 1000000;
4037 /* We want the microseconds part of the timeout to land on the
4038 * 'timer_perturb' mark, but we need to make sure we don't try to
4039 * set the timeout in the past. We do this by ensuring that we
4040 * always only *increase* the expiration time by adding a full
4041 * second in the case that the microsecond portion decreases.
4043 timeout_source->expiration -= timer_perturb;
4045 remainder = timeout_source->expiration % 1000000;
4046 if (remainder >= 1000000/4)
4047 timeout_source->expiration += 1000000;
4049 timeout_source->expiration -= remainder;
4050 timeout_source->expiration += timer_perturb;
4055 g_timeout_prepare (GSource *source,
4058 GTimeoutSource *timeout_source = (GTimeoutSource *) source;
4059 gint64 now = g_source_get_time (source);
4061 if (now < timeout_source->expiration)
4063 /* Round up to ensure that we don't try again too early */
4064 *timeout = (timeout_source->expiration - now + 999) / 1000;
4073 g_timeout_check (GSource *source)
4075 GTimeoutSource *timeout_source = (GTimeoutSource *) source;
4076 gint64 now = g_source_get_time (source);
4078 return timeout_source->expiration <= now;
4082 g_timeout_dispatch (GSource *source,
4083 GSourceFunc callback,
4086 GTimeoutSource *timeout_source = (GTimeoutSource *)source;
4091 g_warning ("Timeout source dispatched without callback\n"
4092 "You must call g_source_set_callback().");
4096 again = callback (user_data);
4099 g_timeout_set_expiration (timeout_source, g_source_get_time (source));
4105 * g_timeout_source_new:
4106 * @interval: the timeout interval in milliseconds.
4108 * Creates a new timeout source.
4110 * The source will not initially be associated with any #GMainContext
4111 * and must be added to one with g_source_attach() before it will be
4114 * The interval given is in terms of monotonic time, not wall clock
4115 * time. See g_get_monotonic_time().
4117 * Return value: the newly-created timeout source
4120 g_timeout_source_new (guint interval)
4122 GSource *source = g_source_new (&g_timeout_funcs, sizeof (GTimeoutSource));
4123 GTimeoutSource *timeout_source = (GTimeoutSource *)source;
4125 timeout_source->interval = interval;
4126 g_timeout_set_expiration (timeout_source, g_get_monotonic_time ());
4132 * g_timeout_source_new_seconds:
4133 * @interval: the timeout interval in seconds
4135 * Creates a new timeout source.
4137 * The source will not initially be associated with any #GMainContext
4138 * and must be added to one with g_source_attach() before it will be
4141 * The scheduling granularity/accuracy of this timeout source will be
4144 * The interval given in terms of monotonic time, not wall clock time.
4145 * See g_get_monotonic_time().
4147 * Return value: the newly-created timeout source
4152 g_timeout_source_new_seconds (guint interval)
4154 GSource *source = g_source_new (&g_timeout_funcs, sizeof (GTimeoutSource));
4155 GTimeoutSource *timeout_source = (GTimeoutSource *)source;
4157 timeout_source->interval = 1000 * interval;
4158 timeout_source->seconds = TRUE;
4160 g_timeout_set_expiration (timeout_source, g_get_monotonic_time ());
4167 * g_timeout_add_full:
4168 * @priority: the priority of the timeout source. Typically this will be in
4169 * the range between #G_PRIORITY_DEFAULT and #G_PRIORITY_HIGH.
4170 * @interval: the time between calls to the function, in milliseconds
4171 * (1/1000ths of a second)
4172 * @function: function to call
4173 * @data: data to pass to @function
4174 * @notify: (allow-none): function to call when the timeout is removed, or %NULL
4176 * Sets a function to be called at regular intervals, with the given
4177 * priority. The function is called repeatedly until it returns
4178 * %FALSE, at which point the timeout is automatically destroyed and
4179 * the function will not be called again. The @notify function is
4180 * called when the timeout is destroyed. The first call to the
4181 * function will be at the end of the first @interval.
4183 * Note that timeout functions may be delayed, due to the processing of other
4184 * event sources. Thus they should not be relied on for precise timing.
4185 * After each call to the timeout function, the time of the next
4186 * timeout is recalculated based on the current time and the given interval
4187 * (it does not try to 'catch up' time lost in delays).
4189 * This internally creates a main loop source using g_timeout_source_new()
4190 * and attaches it to the main loop context using g_source_attach(). You can
4191 * do these steps manually if you need greater control.
4193 * The interval given in terms of monotonic time, not wall clock time.
4194 * See g_get_monotonic_time().
4196 * Return value: the ID (greater than 0) of the event source.
4197 * Rename to: g_timeout_add
4200 g_timeout_add_full (gint priority,
4202 GSourceFunc function,
4204 GDestroyNotify notify)
4209 g_return_val_if_fail (function != NULL, 0);
4211 source = g_timeout_source_new (interval);
4213 if (priority != G_PRIORITY_DEFAULT)
4214 g_source_set_priority (source, priority);
4216 g_source_set_callback (source, function, data, notify);
4217 id = g_source_attach (source, NULL);
4218 g_source_unref (source);
4225 * @interval: the time between calls to the function, in milliseconds
4226 * (1/1000ths of a second)
4227 * @function: function to call
4228 * @data: data to pass to @function
4230 * Sets a function to be called at regular intervals, with the default
4231 * priority, #G_PRIORITY_DEFAULT. The function is called repeatedly
4232 * until it returns %FALSE, at which point the timeout is automatically
4233 * destroyed and the function will not be called again. The first call
4234 * to the function will be at the end of the first @interval.
4236 * Note that timeout functions may be delayed, due to the processing of other
4237 * event sources. Thus they should not be relied on for precise timing.
4238 * After each call to the timeout function, the time of the next
4239 * timeout is recalculated based on the current time and the given interval
4240 * (it does not try to 'catch up' time lost in delays).
4242 * If you want to have a timer in the "seconds" range and do not care
4243 * about the exact time of the first call of the timer, use the
4244 * g_timeout_add_seconds() function; this function allows for more
4245 * optimizations and more efficient system power usage.
4247 * This internally creates a main loop source using g_timeout_source_new()
4248 * and attaches it to the main loop context using g_source_attach(). You can
4249 * do these steps manually if you need greater control.
4251 * The interval given is in terms of monotonic time, not wall clock
4252 * time. See g_get_monotonic_time().
4254 * Return value: the ID (greater than 0) of the event source.
4257 g_timeout_add (guint32 interval,
4258 GSourceFunc function,
4261 return g_timeout_add_full (G_PRIORITY_DEFAULT,
4262 interval, function, data, NULL);
4266 * g_timeout_add_seconds_full:
4267 * @priority: the priority of the timeout source. Typically this will be in
4268 * the range between #G_PRIORITY_DEFAULT and #G_PRIORITY_HIGH.
4269 * @interval: the time between calls to the function, in seconds
4270 * @function: function to call
4271 * @data: data to pass to @function
4272 * @notify: (allow-none): function to call when the timeout is removed, or %NULL
4274 * Sets a function to be called at regular intervals, with @priority.
4275 * The function is called repeatedly until it returns %FALSE, at which
4276 * point the timeout is automatically destroyed and the function will
4277 * not be called again.
4279 * Unlike g_timeout_add(), this function operates at whole second granularity.
4280 * The initial starting point of the timer is determined by the implementation
4281 * and the implementation is expected to group multiple timers together so that
4282 * they fire all at the same time.
4283 * To allow this grouping, the @interval to the first timer is rounded
4284 * and can deviate up to one second from the specified interval.
4285 * Subsequent timer iterations will generally run at the specified interval.
4287 * Note that timeout functions may be delayed, due to the processing of other
4288 * event sources. Thus they should not be relied on for precise timing.
4289 * After each call to the timeout function, the time of the next
4290 * timeout is recalculated based on the current time and the given @interval
4292 * If you want timing more precise than whole seconds, use g_timeout_add()
4295 * The grouping of timers to fire at the same time results in a more power
4296 * and CPU efficient behavior so if your timer is in multiples of seconds
4297 * and you don't require the first timer exactly one second from now, the
4298 * use of g_timeout_add_seconds() is preferred over g_timeout_add().
4300 * This internally creates a main loop source using
4301 * g_timeout_source_new_seconds() and attaches it to the main loop context
4302 * using g_source_attach(). You can do these steps manually if you need
4305 * The interval given is in terms of monotonic time, not wall clock
4306 * time. See g_get_monotonic_time().
4308 * Return value: the ID (greater than 0) of the event source.
4310 * Rename to: g_timeout_add_seconds
4314 g_timeout_add_seconds_full (gint priority,
4316 GSourceFunc function,
4318 GDestroyNotify notify)
4323 g_return_val_if_fail (function != NULL, 0);
4325 source = g_timeout_source_new_seconds (interval);
4327 if (priority != G_PRIORITY_DEFAULT)
4328 g_source_set_priority (source, priority);
4330 g_source_set_callback (source, function, data, notify);
4331 id = g_source_attach (source, NULL);
4332 g_source_unref (source);
4338 * g_timeout_add_seconds:
4339 * @interval: the time between calls to the function, in seconds
4340 * @function: function to call
4341 * @data: data to pass to @function
4343 * Sets a function to be called at regular intervals with the default
4344 * priority, #G_PRIORITY_DEFAULT. The function is called repeatedly until
4345 * it returns %FALSE, at which point the timeout is automatically destroyed
4346 * and the function will not be called again.
4348 * This internally creates a main loop source using
4349 * g_timeout_source_new_seconds() and attaches it to the main loop context
4350 * using g_source_attach(). You can do these steps manually if you need
4351 * greater control. Also see g_timeout_add_seconds_full().
4353 * Note that the first call of the timer may not be precise for timeouts
4354 * of one second. If you need finer precision and have such a timeout,
4355 * you may want to use g_timeout_add() instead.
4357 * The interval given is in terms of monotonic time, not wall clock
4358 * time. See g_get_monotonic_time().
4360 * Return value: the ID (greater than 0) of the event source.
4365 g_timeout_add_seconds (guint interval,
4366 GSourceFunc function,
4369 g_return_val_if_fail (function != NULL, 0);
4371 return g_timeout_add_seconds_full (G_PRIORITY_DEFAULT, interval, function, data, NULL);
4374 /* Child watch functions */
4379 g_child_watch_prepare (GSource *source,
4387 g_child_watch_check (GSource *source)
4389 GChildWatchSource *child_watch_source;
4390 gboolean child_exited;
4392 child_watch_source = (GChildWatchSource *) source;
4394 child_exited = child_watch_source->poll.revents & G_IO_IN;
4401 * Note: We do _not_ check for the special value of STILL_ACTIVE
4402 * since we know that the process has exited and doing so runs into
4403 * problems if the child process "happens to return STILL_ACTIVE(259)"
4404 * as Microsoft's Platform SDK puts it.
4406 if (!GetExitCodeProcess (child_watch_source->pid, &child_status))
4408 gchar *emsg = g_win32_error_message (GetLastError ());
4409 g_warning (G_STRLOC ": GetExitCodeProcess() failed: %s", emsg);
4412 child_watch_source->child_status = -1;
4415 child_watch_source->child_status = child_status;
4418 return child_exited;
4422 g_child_watch_finalize (GSource *source)
4426 #else /* G_OS_WIN32 */
4429 wake_source (GSource *source)
4431 GMainContext *context;
4433 /* This should be thread-safe:
4435 * - if the source is currently being added to a context, that
4436 * context will be woken up anyway
4438 * - if the source is currently being destroyed, we simply need not
4441 * - the memory for the source will remain valid until after the
4442 * source finalize function was called (which would remove the
4443 * source from the global list which we are currently holding the
4446 * - the GMainContext will either be NULL or point to a live
4449 * - the GMainContext will remain valid since we hold the
4450 * main_context_list lock
4452 * Since we are holding a lot of locks here, don't try to enter any
4453 * more GMainContext functions for fear of dealock -- just hit the
4454 * GWakeup and run. Even if that's safe now, it could easily become
4455 * unsafe with some very minor changes in the future, and signal
4456 * handling is not the most well-tested codepath.
4458 G_LOCK(main_context_list);
4459 context = source->context;
4461 g_wakeup_signal (context->wakeup);
4462 G_UNLOCK(main_context_list);
4465 /* This is a hack; we want to use the newer waitid() call, but the use
4466 * of the waitpid() status code API is baked into the GChildWatchSource
4467 * callback signature, so we need to synthesize it from the siginfo_t
4468 * we get from waitid().
4471 #define __G_MAKE_EXITSTATUS(ecode, signum) ((ecode) << 8 | (signum))
4473 waitpid_status_from_siginfo (siginfo_t *siginfo)
4475 G_STATIC_ASSERT(((WIFEXITED (__G_MAKE_EXITSTATUS (1, 0))) && \
4476 !(WIFSIGNALED (__G_MAKE_EXITSTATUS (1, 0))) && \
4477 (WEXITSTATUS (__G_MAKE_EXITSTATUS (1, 0)) == 1)));
4478 G_STATIC_ASSERT((!WIFEXITED (__G_MAKE_EXITSTATUS (0, 1))) && \
4479 (WIFSIGNALED (__G_MAKE_EXITSTATUS (0, 1))) && \
4480 (WTERMSIG (__G_MAKE_EXITSTATUS (0, 1)) == 1));
4481 if (siginfo->si_code == CLD_EXITED)
4482 return __G_MAKE_EXITSTATUS(siginfo->si_status, 0);
4483 else if (siginfo->si_code == CLD_KILLED || siginfo->si_code == CLD_DUMPED)
4484 return __G_MAKE_EXITSTATUS(0, siginfo->si_status);
4486 return __G_MAKE_EXITSTATUS(0xFF, 0);
4488 #undef __G_MAKE_EXITSTATUS
4489 #endif /* HAVE_WAITID */
4491 /* Returns TRUE if we need to wake the source */
4493 unix_child_watch_source_waitpid (GChildWatchSource *source)
4497 if (source->child_exited)
4501 if (source->wnowait)
4508 r = waitid (P_PID, (id_t)source->pid, &siginfo, WEXITED | WNOHANG | WNOWAIT);
4509 while (r == -1 && errno == EINTR);
4511 if (r == 0 && siginfo.si_pid == source->pid)
4513 source->child_exited = TRUE;
4514 source->child_status = waitpid_status_from_siginfo (&siginfo);
4521 pid = waitpid (source->pid, &source->child_status, WNOHANG);
4522 while (pid == -1 && errno == EINTR);
4526 source->child_exited = TRUE;
4529 else if (pid == -1 && errno == ECHILD)
4531 g_warning ("GChildWatchSource: Exit status of a child process was requested but ECHILD was received by waitpid(). Most likely the process is ignoring SIGCHLD, or some other thread is invoking waitpid() with a nonpositive first argument; either behavior can break applications that use g_child_watch_add()/g_spawn_sync() either directly or indirectly.");
4532 source->child_exited = TRUE;
4533 source->child_status = 0;
4542 dispatch_unix_signals (void)
4546 /* clear this first incase another one arrives while we're processing */
4547 any_unix_signal_pending = FALSE;
4549 G_LOCK(unix_signal_lock);
4551 /* handle GChildWatchSource instances */
4552 if (unix_signal_pending[SIGCHLD])
4554 unix_signal_pending[SIGCHLD] = FALSE;
4556 /* The only way we can do this is to scan all of the children.
4558 * The docs promise that we will not reap children that we are not
4559 * explicitly watching, so that ties our hands from calling
4560 * waitpid(-1). We also can't use siginfo's si_pid field since if
4561 * multiple SIGCHLD arrive at the same time, one of them can be
4562 * dropped (since a given UNIX signal can only be pending once).
4564 for (node = unix_child_watches; node; node = node->next)
4566 GChildWatchSource *source = node->data;
4568 if (unix_child_watch_source_waitpid (source))
4569 wake_source ((GSource *) source);
4573 /* handle GUnixSignalWatchSource instances */
4574 for (node = unix_signal_watches; node; node = node->next)
4576 GUnixSignalWatchSource *source = node->data;
4578 if (!source->pending)
4580 if (unix_signal_pending[source->signum])
4582 unix_signal_pending[source->signum] = FALSE;
4583 source->pending = TRUE;
4585 wake_source ((GSource *) source);
4590 G_UNLOCK(unix_signal_lock);
4594 g_child_watch_prepare (GSource *source,
4597 GChildWatchSource *child_watch_source;
4599 child_watch_source = (GChildWatchSource *) source;
4601 return child_watch_source->child_exited;
4605 g_child_watch_check (GSource *source)
4607 GChildWatchSource *child_watch_source;
4609 child_watch_source = (GChildWatchSource *) source;
4611 return child_watch_source->child_exited;
4615 g_unix_signal_watch_prepare (GSource *source,
4618 GUnixSignalWatchSource *unix_signal_source;
4620 unix_signal_source = (GUnixSignalWatchSource *) source;
4622 return unix_signal_source->pending;
4626 g_unix_signal_watch_check (GSource *source)
4628 GUnixSignalWatchSource *unix_signal_source;
4630 unix_signal_source = (GUnixSignalWatchSource *) source;
4632 return unix_signal_source->pending;
4636 g_unix_signal_watch_dispatch (GSource *source,
4637 GSourceFunc callback,
4640 GUnixSignalWatchSource *unix_signal_source;
4643 unix_signal_source = (GUnixSignalWatchSource *) source;
4647 g_warning ("Unix signal source dispatched without callback\n"
4648 "You must call g_source_set_callback().");
4652 again = (callback) (user_data);
4654 unix_signal_source->pending = FALSE;
4660 ensure_unix_signal_handler_installed_unlocked (int signum)
4662 static sigset_t installed_signal_mask;
4663 static gboolean initialized;
4664 struct sigaction action;
4668 sigemptyset (&installed_signal_mask);
4669 g_get_worker_context ();
4673 if (sigismember (&installed_signal_mask, signum))
4676 sigaddset (&installed_signal_mask, signum);
4678 action.sa_handler = g_unix_signal_handler;
4679 sigemptyset (&action.sa_mask);
4680 action.sa_flags = SA_RESTART | SA_NOCLDSTOP;
4681 sigaction (signum, &action, NULL);
4685 _g_main_create_unix_signal_watch (int signum)
4688 GUnixSignalWatchSource *unix_signal_source;
4690 source = g_source_new (&g_unix_signal_funcs, sizeof (GUnixSignalWatchSource));
4691 unix_signal_source = (GUnixSignalWatchSource *) source;
4693 unix_signal_source->signum = signum;
4694 unix_signal_source->pending = FALSE;
4696 G_LOCK (unix_signal_lock);
4697 ensure_unix_signal_handler_installed_unlocked (signum);
4698 unix_signal_watches = g_slist_prepend (unix_signal_watches, unix_signal_source);
4699 if (unix_signal_pending[signum])
4700 unix_signal_source->pending = TRUE;
4701 unix_signal_pending[signum] = FALSE;
4702 G_UNLOCK (unix_signal_lock);
4708 g_unix_signal_watch_finalize (GSource *source)
4710 G_LOCK (unix_signal_lock);
4711 unix_signal_watches = g_slist_remove (unix_signal_watches, source);
4712 G_UNLOCK (unix_signal_lock);
4716 g_child_watch_finalize (GSource *source)
4718 G_LOCK (unix_signal_lock);
4719 unix_child_watches = g_slist_remove (unix_child_watches, source);
4720 G_UNLOCK (unix_signal_lock);
4723 #endif /* G_OS_WIN32 */
4726 g_child_watch_dispatch (GSource *source,
4727 GSourceFunc callback,
4730 GChildWatchSource *child_watch_source;
4731 GChildWatchFunc child_watch_callback = (GChildWatchFunc) callback;
4733 child_watch_source = (GChildWatchSource *) source;
4737 g_warning ("Child watch source dispatched without callback\n"
4738 "You must call g_source_set_callback().");
4742 (child_watch_callback) (child_watch_source->pid, child_watch_source->child_status, user_data);
4744 /* We never keep a child watch source around as the child is gone */
4751 g_unix_signal_handler (int signum)
4753 unix_signal_pending[signum] = TRUE;
4754 any_unix_signal_pending = TRUE;
4756 g_wakeup_signal (glib_worker_context->wakeup);
4759 #endif /* !G_OS_WIN32 */
4762 g_child_watch_source_new_internal (GPid pid,
4766 GChildWatchSource *child_watch_source;
4768 #if defined(G_OS_UNIX) && !defined(HAVE_WAITID)
4772 source = g_source_new (&g_child_watch_funcs, sizeof (GChildWatchSource));
4773 child_watch_source = (GChildWatchSource *)source;
4775 child_watch_source->pid = pid;
4776 #if defined(G_OS_UNIX) && defined(HAVE_WAITID)
4778 child_watch_source->wnowait = TRUE;
4782 child_watch_source->poll.fd = (gintptr) pid;
4783 child_watch_source->poll.events = G_IO_IN;
4785 g_source_add_poll (source, &child_watch_source->poll);
4786 #else /* G_OS_WIN32 */
4787 G_LOCK (unix_signal_lock);
4788 ensure_unix_signal_handler_installed_unlocked (SIGCHLD);
4789 unix_child_watches = g_slist_prepend (unix_child_watches, child_watch_source);
4790 unix_child_watch_source_waitpid (child_watch_source);
4791 G_UNLOCK (unix_signal_lock);
4792 #endif /* G_OS_WIN32 */
4799 * Create a child watch, using @wnowait to enable a mode
4800 * where the child won't be reaped. This is used by
4801 * GSubprocess to ensure that the pid is valid for
4802 * the lifetime of the GSubprocess object. Otherwise
4803 * there'd be a possible race condition where we reap
4804 * the child with waitpid() in the worker thread,
4805 * while the main thread is calling kill() on it.
4808 g_child_watch_source_new_nowait (GPid pid)
4810 return g_child_watch_source_new_internal (pid, TRUE);
4814 * g_child_watch_source_new:
4815 * @pid: process to watch. On POSIX the pid of a child process. On
4816 * Windows a handle for a process (which doesn't have to be a child).
4818 * Creates a new child_watch source.
4820 * The source will not initially be associated with any #GMainContext
4821 * and must be added to one with g_source_attach() before it will be
4824 * Note that child watch sources can only be used in conjunction with
4825 * <literal>g_spawn...</literal> when the %G_SPAWN_DO_NOT_REAP_CHILD
4828 * Note that on platforms where #GPid must be explicitly closed
4829 * (see g_spawn_close_pid()) @pid must not be closed while the
4830 * source is still active. Typically, you will want to call
4831 * g_spawn_close_pid() in the callback function for the source.
4833 * Note further that using g_child_watch_source_new() is not
4834 * compatible with calling <literal>waitpid</literal> with a
4835 * nonpositive first argument in the application. Calling waitpid()
4836 * for individual pids will still work fine.
4838 * Return value: the newly-created child watch source
4843 g_child_watch_source_new (GPid pid)
4845 return g_child_watch_source_new_internal (pid, FALSE);
4849 * g_child_watch_add_full:
4850 * @priority: the priority of the idle source. Typically this will be in the
4851 * range between #G_PRIORITY_DEFAULT_IDLE and #G_PRIORITY_HIGH_IDLE.
4852 * @pid: process to watch. On POSIX the pid of a child process. On
4853 * Windows a handle for a process (which doesn't have to be a child).
4854 * @function: function to call
4855 * @data: data to pass to @function
4856 * @notify: (allow-none): function to call when the idle is removed, or %NULL
4858 * Sets a function to be called when the child indicated by @pid
4859 * exits, at the priority @priority.
4861 * If you obtain @pid from g_spawn_async() or g_spawn_async_with_pipes()
4862 * you will need to pass #G_SPAWN_DO_NOT_REAP_CHILD as flag to
4863 * the spawn function for the child watching to work.
4865 * In many programs, you will want to call g_spawn_check_exit_status()
4866 * in the callback to determine whether or not the child exited
4869 * Also, note that on platforms where #GPid must be explicitly closed
4870 * (see g_spawn_close_pid()) @pid must not be closed while the source
4871 * is still active. Typically, you should invoke g_spawn_close_pid()
4872 * in the callback function for the source.
4874 * GLib supports only a single callback per process id.
4876 * This internally creates a main loop source using
4877 * g_child_watch_source_new() and attaches it to the main loop context
4878 * using g_source_attach(). You can do these steps manually if you
4879 * need greater control.
4881 * Return value: the ID (greater than 0) of the event source.
4883 * Rename to: g_child_watch_add
4887 g_child_watch_add_full (gint priority,
4889 GChildWatchFunc function,
4891 GDestroyNotify notify)
4896 g_return_val_if_fail (function != NULL, 0);
4898 source = g_child_watch_source_new (pid);
4900 if (priority != G_PRIORITY_DEFAULT)
4901 g_source_set_priority (source, priority);
4903 g_source_set_callback (source, (GSourceFunc) function, data, notify);
4904 id = g_source_attach (source, NULL);
4905 g_source_unref (source);
4911 * g_child_watch_add:
4912 * @pid: process id to watch. On POSIX the pid of a child process. On
4913 * Windows a handle for a process (which doesn't have to be a child).
4914 * @function: function to call
4915 * @data: data to pass to @function
4917 * Sets a function to be called when the child indicated by @pid
4918 * exits, at a default priority, #G_PRIORITY_DEFAULT.
4920 * If you obtain @pid from g_spawn_async() or g_spawn_async_with_pipes()
4921 * you will need to pass #G_SPAWN_DO_NOT_REAP_CHILD as flag to
4922 * the spawn function for the child watching to work.
4924 * Note that on platforms where #GPid must be explicitly closed
4925 * (see g_spawn_close_pid()) @pid must not be closed while the
4926 * source is still active. Typically, you will want to call
4927 * g_spawn_close_pid() in the callback function for the source.
4929 * GLib supports only a single callback per process id.
4931 * This internally creates a main loop source using
4932 * g_child_watch_source_new() and attaches it to the main loop context
4933 * using g_source_attach(). You can do these steps manually if you
4934 * need greater control.
4936 * Return value: the ID (greater than 0) of the event source.
4941 g_child_watch_add (GPid pid,
4942 GChildWatchFunc function,
4945 return g_child_watch_add_full (G_PRIORITY_DEFAULT, pid, function, data, NULL);
4949 /* Idle functions */
4952 g_idle_prepare (GSource *source,
4961 g_idle_check (GSource *source)
4967 g_idle_dispatch (GSource *source,
4968 GSourceFunc callback,
4973 g_warning ("Idle source dispatched without callback\n"
4974 "You must call g_source_set_callback().");
4978 return callback (user_data);
4982 * g_idle_source_new:
4984 * Creates a new idle source.
4986 * The source will not initially be associated with any #GMainContext
4987 * and must be added to one with g_source_attach() before it will be
4988 * executed. Note that the default priority for idle sources is
4989 * %G_PRIORITY_DEFAULT_IDLE, as compared to other sources which
4990 * have a default priority of %G_PRIORITY_DEFAULT.
4992 * Return value: the newly-created idle source
4995 g_idle_source_new (void)
4999 source = g_source_new (&g_idle_funcs, sizeof (GSource));
5000 g_source_set_priority (source, G_PRIORITY_DEFAULT_IDLE);
5007 * @priority: the priority of the idle source. Typically this will be in the
5008 * range between #G_PRIORITY_DEFAULT_IDLE and #G_PRIORITY_HIGH_IDLE.
5009 * @function: function to call
5010 * @data: data to pass to @function
5011 * @notify: (allow-none): function to call when the idle is removed, or %NULL
5013 * Adds a function to be called whenever there are no higher priority
5014 * events pending. If the function returns %FALSE it is automatically
5015 * removed from the list of event sources and will not be called again.
5017 * This internally creates a main loop source using g_idle_source_new()
5018 * and attaches it to the main loop context using g_source_attach().
5019 * You can do these steps manually if you need greater control.
5021 * Return value: the ID (greater than 0) of the event source.
5022 * Rename to: g_idle_add
5025 g_idle_add_full (gint priority,
5026 GSourceFunc function,
5028 GDestroyNotify notify)
5033 g_return_val_if_fail (function != NULL, 0);
5035 source = g_idle_source_new ();
5037 if (priority != G_PRIORITY_DEFAULT_IDLE)
5038 g_source_set_priority (source, priority);
5040 g_source_set_callback (source, function, data, notify);
5041 id = g_source_attach (source, NULL);
5042 g_source_unref (source);
5049 * @function: function to call
5050 * @data: data to pass to @function.
5052 * Adds a function to be called whenever there are no higher priority
5053 * events pending to the default main loop. The function is given the
5054 * default idle priority, #G_PRIORITY_DEFAULT_IDLE. If the function
5055 * returns %FALSE it is automatically removed from the list of event
5056 * sources and will not be called again.
5058 * This internally creates a main loop source using g_idle_source_new()
5059 * and attaches it to the main loop context using g_source_attach().
5060 * You can do these steps manually if you need greater control.
5062 * Return value: the ID (greater than 0) of the event source.
5065 g_idle_add (GSourceFunc function,
5068 return g_idle_add_full (G_PRIORITY_DEFAULT_IDLE, function, data, NULL);
5072 * g_idle_remove_by_data:
5073 * @data: the data for the idle source's callback.
5075 * Removes the idle function with the given data.
5077 * Return value: %TRUE if an idle source was found and removed.
5080 g_idle_remove_by_data (gpointer data)
5082 return g_source_remove_by_funcs_user_data (&g_idle_funcs, data);
5086 * g_main_context_invoke:
5087 * @context: (allow-none): a #GMainContext, or %NULL
5088 * @function: function to call
5089 * @data: data to pass to @function
5091 * Invokes a function in such a way that @context is owned during the
5092 * invocation of @function.
5094 * If @context is %NULL then the global default main context — as
5095 * returned by g_main_context_default() — is used.
5097 * If @context is owned by the current thread, @function is called
5098 * directly. Otherwise, if @context is the thread-default main context
5099 * of the current thread and g_main_context_acquire() succeeds, then
5100 * @function is called and g_main_context_release() is called
5103 * In any other case, an idle source is created to call @function and
5104 * that source is attached to @context (presumably to be run in another
5105 * thread). The idle source is attached with #G_PRIORITY_DEFAULT
5106 * priority. If you want a different priority, use
5107 * g_main_context_invoke_full().
5109 * Note that, as with normal idle functions, @function should probably
5110 * return %FALSE. If it returns %TRUE, it will be continuously run in a
5111 * loop (and may prevent this call from returning).
5116 g_main_context_invoke (GMainContext *context,
5117 GSourceFunc function,
5120 g_main_context_invoke_full (context,
5122 function, data, NULL);
5126 * g_main_context_invoke_full:
5127 * @context: (allow-none): a #GMainContext, or %NULL
5128 * @priority: the priority at which to run @function
5129 * @function: function to call
5130 * @data: data to pass to @function
5131 * @notify: (allow-none): a function to call when @data is no longer in use, or %NULL.
5133 * Invokes a function in such a way that @context is owned during the
5134 * invocation of @function.
5136 * This function is the same as g_main_context_invoke() except that it
5137 * lets you specify the priority incase @function ends up being
5138 * scheduled as an idle and also lets you give a #GDestroyNotify for @data.
5140 * @notify should not assume that it is called from any particular
5141 * thread or with any particular context acquired.
5146 g_main_context_invoke_full (GMainContext *context,
5148 GSourceFunc function,
5150 GDestroyNotify notify)
5152 g_return_if_fail (function != NULL);
5155 context = g_main_context_default ();
5157 if (g_main_context_is_owner (context))
5159 while (function (data));
5166 GMainContext *thread_default;
5168 thread_default = g_main_context_get_thread_default ();
5170 if (!thread_default)
5171 thread_default = g_main_context_default ();
5173 if (thread_default == context && g_main_context_acquire (context))
5175 while (function (data));
5177 g_main_context_release (context);
5186 source = g_idle_source_new ();
5187 g_source_set_priority (source, priority);
5188 g_source_set_callback (source, function, data, notify);
5189 g_source_attach (source, context);
5190 g_source_unref (source);
5196 glib_worker_main (gpointer data)
5200 g_main_context_iteration (glib_worker_context, TRUE);
5203 if (any_unix_signal_pending)
5204 dispatch_unix_signals ();
5208 return NULL; /* worst GCC warning message ever... */
5212 g_get_worker_context (void)
5214 static gsize initialised;
5216 if (g_once_init_enter (&initialised))
5218 /* mask all signals in the worker thread */
5224 pthread_sigmask (SIG_SETMASK, &all, &prev_mask);
5226 glib_worker_context = g_main_context_new ();
5227 g_thread_new ("gmain", glib_worker_main, NULL);
5229 pthread_sigmask (SIG_SETMASK, &prev_mask, NULL);
5231 g_once_init_leave (&initialised, TRUE);
5234 return glib_worker_context;