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-init.h"
102 #include "glib-private.h"
106 * @title: The Main Event Loop
107 * @short_description: manages all available sources of events
109 * The main event loop manages all the available sources of events for
110 * GLib and GTK+ applications. These events can come from any number of
111 * different types of sources such as file descriptors (plain files,
112 * pipes or sockets) and timeouts. New types of event sources can also
113 * be added using g_source_attach().
115 * To allow multiple independent sets of sources to be handled in
116 * different threads, each source is associated with a #GMainContext.
117 * A GMainContext can only be running in a single thread, but
118 * sources can be added to it and removed from it from other threads.
120 * Each event source is assigned a priority. The default priority,
121 * #G_PRIORITY_DEFAULT, is 0. Values less than 0 denote higher priorities.
122 * Values greater than 0 denote lower priorities. Events from high priority
123 * sources are always processed before events from lower priority sources.
125 * Idle functions can also be added, and assigned a priority. These will
126 * be run whenever no events with a higher priority are ready to be processed.
128 * The #GMainLoop data type represents a main event loop. A GMainLoop is
129 * created with g_main_loop_new(). After adding the initial event sources,
130 * g_main_loop_run() is called. This continuously checks for new events from
131 * each of the event sources and dispatches them. Finally, the processing of
132 * an event from one of the sources leads to a call to g_main_loop_quit() to
133 * exit the main loop, and g_main_loop_run() returns.
135 * It is possible to create new instances of #GMainLoop recursively.
136 * This is often used in GTK+ applications when showing modal dialog
137 * boxes. Note that event sources are associated with a particular
138 * #GMainContext, and will be checked and dispatched for all main
139 * loops associated with that GMainContext.
141 * GTK+ contains wrappers of some of these functions, e.g. gtk_main(),
142 * gtk_main_quit() and gtk_events_pending().
144 * <refsect2><title>Creating new source types</title>
145 * <para>One of the unusual features of the #GMainLoop functionality
146 * is that new types of event source can be created and used in
147 * addition to the builtin type of event source. A new event source
148 * type is used for handling GDK events. A new source type is created
149 * by <firstterm>deriving</firstterm> from the #GSource structure.
150 * The derived type of source is represented by a structure that has
151 * the #GSource structure as a first element, and other elements specific
152 * to the new source type. To create an instance of the new source type,
153 * call g_source_new() passing in the size of the derived structure and
154 * a table of functions. These #GSourceFuncs determine the behavior of
155 * the new source type.</para>
156 * <para>New source types basically interact with the main context
157 * in two ways. Their prepare function in #GSourceFuncs can set a timeout
158 * to determine the maximum amount of time that the main loop will sleep
159 * before checking the source again. In addition, or as well, the source
160 * can add file descriptors to the set that the main context checks using
161 * g_source_add_poll().</para>
163 * <refsect2><title>Customizing the main loop iteration</title>
164 * <para>Single iterations of a #GMainContext can be run with
165 * g_main_context_iteration(). In some cases, more detailed control
166 * of exactly how the details of the main loop work is desired, for
167 * instance, when integrating the #GMainLoop with an external main loop.
168 * In such cases, you can call the component functions of
169 * g_main_context_iteration() directly. These functions are
170 * g_main_context_prepare(), g_main_context_query(),
171 * g_main_context_check() and g_main_context_dispatch().</para>
172 * <para>The operation of these functions can best be seen in terms
173 * of a state diagram, as shown in <xref linkend="mainloop-states"/>.</para>
174 * <figure id="mainloop-states"><title>States of a Main Context</title>
175 * <graphic fileref="mainloop-states.gif" format="GIF"></graphic>
179 * On Unix, the GLib mainloop is incompatible with fork(). Any program
180 * using the mainloop must either exec() or exit() from the child
181 * without returning to the mainloop.
186 typedef struct _GTimeoutSource GTimeoutSource;
187 typedef struct _GChildWatchSource GChildWatchSource;
188 typedef struct _GUnixSignalWatchSource GUnixSignalWatchSource;
189 typedef struct _GPollRec GPollRec;
190 typedef struct _GSourceCallback GSourceCallback;
194 G_SOURCE_READY = 1 << G_HOOK_FLAG_USER_SHIFT,
195 G_SOURCE_CAN_RECURSE = 1 << (G_HOOK_FLAG_USER_SHIFT + 1),
196 G_SOURCE_BLOCKED = 1 << (G_HOOK_FLAG_USER_SHIFT + 2)
199 typedef struct _GSourceList GSourceList;
203 GSource *head, *tail;
207 typedef struct _GMainWaiter GMainWaiter;
215 typedef struct _GMainDispatch GMainDispatch;
217 struct _GMainDispatch
220 GSList *dispatching_sources; /* stack of current sources */
223 #ifdef G_MAIN_POLL_DEBUG
224 gboolean _g_main_poll_debug = FALSE;
229 /* The following lock is used for both the list of sources
230 * and the list of poll records
240 GPtrArray *pending_dispatches;
241 gint timeout; /* Timeout for current iteration */
244 GHashTable *overflow_used_source_ids; /* set<guint> */
246 gint in_check_or_prepare;
248 GPollRec *poll_records, *poll_records_tail;
249 guint n_poll_records;
250 GPollFD *cached_poll_array;
251 guint cached_poll_array_size;
257 /* Flag indicating whether the set of fd's changed during a poll */
258 gboolean poll_changed;
263 gboolean time_is_fresh;
266 struct _GSourceCallback
271 GDestroyNotify notify;
276 GMainContext *context;
281 struct _GTimeoutSource
288 struct _GChildWatchSource
295 #else /* G_OS_WIN32 */
296 gboolean child_exited;
297 #endif /* G_OS_WIN32 */
300 struct _GUnixSignalWatchSource
315 struct _GSourcePrivate
317 GSList *child_sources;
318 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_dispatch (GSource *source,
380 GSourceFunc callback,
382 static gboolean g_child_watch_prepare (GSource *source,
384 static gboolean g_child_watch_check (GSource *source);
385 static gboolean g_child_watch_dispatch (GSource *source,
386 GSourceFunc callback,
388 static void g_child_watch_finalize (GSource *source);
390 static void g_unix_signal_handler (int signum);
391 static gboolean g_unix_signal_watch_prepare (GSource *source,
393 static gboolean g_unix_signal_watch_check (GSource *source);
394 static gboolean g_unix_signal_watch_dispatch (GSource *source,
395 GSourceFunc callback,
397 static void g_unix_signal_watch_finalize (GSource *source);
399 static gboolean g_idle_prepare (GSource *source,
401 static gboolean g_idle_check (GSource *source);
402 static gboolean g_idle_dispatch (GSource *source,
403 GSourceFunc callback,
406 static void block_source (GSource *source);
408 static GMainContext *glib_worker_context;
410 G_LOCK_DEFINE_STATIC (main_loop);
411 static GMainContext *default_main_context;
416 /* UNIX signals work by marking one of these variables then waking the
417 * worker context to check on them and dispatch accordingly.
419 #ifdef HAVE_SIG_ATOMIC_T
420 static volatile sig_atomic_t unix_signal_pending[NSIG];
421 static volatile sig_atomic_t any_unix_signal_pending;
423 static volatile int unix_signal_pending[NSIG];
424 static volatile int any_unix_signal_pending;
427 /* Guards all the data below */
428 G_LOCK_DEFINE_STATIC (unix_signal_lock);
429 static GSList *unix_signal_watches;
430 static GSList *unix_child_watches;
432 static GSourceFuncs g_unix_signal_funcs =
434 g_unix_signal_watch_prepare,
435 g_unix_signal_watch_check,
436 g_unix_signal_watch_dispatch,
437 g_unix_signal_watch_finalize
439 #endif /* !G_OS_WIN32 */
440 G_LOCK_DEFINE_STATIC (main_context_list);
441 static GSList *main_context_list = NULL;
443 GSourceFuncs g_timeout_funcs =
451 GSourceFuncs g_child_watch_funcs =
453 g_child_watch_prepare,
455 g_child_watch_dispatch,
456 g_child_watch_finalize
459 GSourceFuncs g_idle_funcs =
468 * g_main_context_ref:
469 * @context: a #GMainContext
471 * Increases the reference count on a #GMainContext object by one.
473 * Returns: the @context that was passed in (since 2.6)
476 g_main_context_ref (GMainContext *context)
478 g_return_val_if_fail (context != NULL, NULL);
479 g_return_val_if_fail (g_atomic_int_get (&context->ref_count) > 0, NULL);
481 g_atomic_int_inc (&context->ref_count);
487 poll_rec_list_free (GMainContext *context,
490 g_slice_free_chain (GPollRec, list, next);
494 * g_main_context_unref:
495 * @context: a #GMainContext
497 * Decreases the reference count on a #GMainContext object by one. If
498 * the result is zero, free the context and free all associated memory.
501 g_main_context_unref (GMainContext *context)
508 g_return_if_fail (context != NULL);
509 g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
511 if (!g_atomic_int_dec_and_test (&context->ref_count))
514 G_LOCK (main_context_list);
515 main_context_list = g_slist_remove (main_context_list, context);
516 G_UNLOCK (main_context_list);
518 g_source_iter_init (&iter, context, TRUE);
519 while (g_source_iter_next (&iter, &source))
521 source->context = NULL;
522 g_source_destroy_internal (source, context, FALSE);
524 for (sl_iter = context->source_lists; sl_iter; sl_iter = sl_iter->next)
526 list = sl_iter->data;
527 g_slice_free (GSourceList, list);
529 g_list_free (context->source_lists);
531 if (context->overflow_used_source_ids)
532 g_hash_table_destroy (context->overflow_used_source_ids);
534 g_mutex_clear (&context->mutex);
536 g_ptr_array_free (context->pending_dispatches, TRUE);
537 g_free (context->cached_poll_array);
539 poll_rec_list_free (context, context->poll_records);
541 g_wakeup_free (context->wakeup);
542 g_cond_clear (&context->cond);
547 /* Helper function used by mainloop/overflow test.
550 g_main_context_new_with_next_id (guint next_id)
552 GMainContext *ret = g_main_context_new ();
554 ret->next_id = next_id;
560 * g_main_context_new:
562 * Creates a new #GMainContext structure.
564 * Return value: the new #GMainContext
567 g_main_context_new (void)
569 static gsize initialised;
570 GMainContext *context;
572 if (g_once_init_enter (&initialised))
574 #ifdef G_MAIN_POLL_DEBUG
575 if (getenv ("G_MAIN_POLL_DEBUG") != NULL)
576 _g_main_poll_debug = TRUE;
579 g_once_init_leave (&initialised, TRUE);
582 context = g_new0 (GMainContext, 1);
584 g_mutex_init (&context->mutex);
585 g_cond_init (&context->cond);
587 context->owner = NULL;
588 context->waiters = NULL;
590 context->ref_count = 1;
592 context->next_id = 1;
594 context->source_lists = NULL;
596 context->poll_func = g_poll;
598 context->cached_poll_array = NULL;
599 context->cached_poll_array_size = 0;
601 context->pending_dispatches = g_ptr_array_new ();
603 context->time_is_fresh = FALSE;
605 context->wakeup = g_wakeup_new ();
606 g_wakeup_get_pollfd (context->wakeup, &context->wake_up_rec);
607 g_main_context_add_poll_unlocked (context, 0, &context->wake_up_rec);
609 G_LOCK (main_context_list);
610 main_context_list = g_slist_append (main_context_list, context);
612 #ifdef G_MAIN_POLL_DEBUG
613 if (_g_main_poll_debug)
614 g_print ("created context=%p\n", context);
617 G_UNLOCK (main_context_list);
623 * g_main_context_default:
625 * Returns the global default main context. This is the main context
626 * used for main loop functions when a main loop is not explicitly
627 * specified, and corresponds to the "main" main loop. See also
628 * g_main_context_get_thread_default().
630 * Return value: (transfer none): the global default main context.
633 g_main_context_default (void)
639 if (!default_main_context)
641 default_main_context = g_main_context_new ();
642 #ifdef G_MAIN_POLL_DEBUG
643 if (_g_main_poll_debug)
644 g_print ("default context=%p\n", default_main_context);
648 G_UNLOCK (main_loop);
650 return default_main_context;
654 free_context (gpointer data)
656 GMainContext *context = data;
658 g_main_context_release (context);
660 g_main_context_unref (context);
664 free_context_stack (gpointer data)
666 g_queue_free_full((GQueue *) data, (GDestroyNotify) free_context);
669 static GPrivate thread_context_stack = G_PRIVATE_INIT (free_context_stack);
672 * g_main_context_push_thread_default:
673 * @context: (allow-none): a #GMainContext, or %NULL for the global default context
675 * Acquires @context and sets it as the thread-default context for the
676 * current thread. This will cause certain asynchronous operations
677 * (such as most <link linkend="gio">gio</link>-based I/O) which are
678 * started in this thread to run under @context and deliver their
679 * results to its main loop, rather than running under the global
680 * default context in the main thread. Note that calling this function
681 * changes the context returned by
682 * g_main_context_get_thread_default(), <emphasis>not</emphasis> the
683 * one returned by g_main_context_default(), so it does not affect the
684 * context used by functions like g_idle_add().
686 * Normally you would call this function shortly after creating a new
687 * thread, passing it a #GMainContext which will be run by a
688 * #GMainLoop in that thread, to set a new default context for all
689 * async operations in that thread. (In this case, you don't need to
690 * ever call g_main_context_pop_thread_default().) In some cases
691 * however, you may want to schedule a single operation in a
692 * non-default context, or temporarily use a non-default context in
693 * the main thread. In that case, you can wrap the call to the
694 * asynchronous operation inside a
695 * g_main_context_push_thread_default() /
696 * g_main_context_pop_thread_default() pair, but it is up to you to
697 * ensure that no other asynchronous operations accidentally get
698 * started while the non-default context is active.
700 * Beware that libraries that predate this function may not correctly
701 * handle being used from a thread with a thread-default context. Eg,
702 * see g_file_supports_thread_contexts().
707 g_main_context_push_thread_default (GMainContext *context)
710 gboolean acquired_context;
712 acquired_context = g_main_context_acquire (context);
713 g_return_if_fail (acquired_context);
715 if (context == g_main_context_default ())
718 g_main_context_ref (context);
720 stack = g_private_get (&thread_context_stack);
723 stack = g_queue_new ();
724 g_private_set (&thread_context_stack, stack);
727 g_queue_push_head (stack, context);
731 * g_main_context_pop_thread_default:
732 * @context: (allow-none): a #GMainContext object, or %NULL
734 * Pops @context off the thread-default context stack (verifying that
735 * it was on the top of the stack).
740 g_main_context_pop_thread_default (GMainContext *context)
744 if (context == g_main_context_default ())
747 stack = g_private_get (&thread_context_stack);
749 g_return_if_fail (stack != NULL);
750 g_return_if_fail (g_queue_peek_head (stack) == context);
752 g_queue_pop_head (stack);
754 g_main_context_release (context);
756 g_main_context_unref (context);
760 * g_main_context_get_thread_default:
762 * Gets the thread-default #GMainContext for this thread. Asynchronous
763 * operations that want to be able to be run in contexts other than
764 * the default one should call this method or
765 * g_main_context_ref_thread_default() to get a #GMainContext to add
766 * their #GSource<!-- -->s to. (Note that even in single-threaded
767 * programs applications may sometimes want to temporarily push a
768 * non-default context, so it is not safe to assume that this will
769 * always return %NULL if you are running in the default thread.)
771 * If you need to hold a reference on the context, use
772 * g_main_context_ref_thread_default() instead.
774 * Returns: (transfer none): the thread-default #GMainContext, or
775 * %NULL if the thread-default context is the global default context.
780 g_main_context_get_thread_default (void)
784 stack = g_private_get (&thread_context_stack);
786 return g_queue_peek_head (stack);
792 * g_main_context_ref_thread_default:
794 * Gets the thread-default #GMainContext for this thread, as with
795 * g_main_context_get_thread_default(), but also adds a reference to
796 * it with g_main_context_ref(). In addition, unlike
797 * g_main_context_get_thread_default(), if the thread-default context
798 * is the global default context, this will return that #GMainContext
799 * (with a ref added to it) rather than returning %NULL.
801 * Returns: (transfer full): the thread-default #GMainContext. Unref
802 * with g_main_context_unref() when you are done with it.
807 g_main_context_ref_thread_default (void)
809 GMainContext *context;
811 context = g_main_context_get_thread_default ();
813 context = g_main_context_default ();
814 return g_main_context_ref (context);
817 /* Hooks for adding to the main loop */
821 * @source_funcs: structure containing functions that implement
822 * the sources behavior.
823 * @struct_size: size of the #GSource structure to create.
825 * Creates a new #GSource structure. The size is specified to
826 * allow creating structures derived from #GSource that contain
827 * additional data. The size passed in must be at least
828 * <literal>sizeof (GSource)</literal>.
830 * The source will not initially be associated with any #GMainContext
831 * and must be added to one with g_source_attach() before it will be
834 * Return value: the newly-created #GSource.
837 g_source_new (GSourceFuncs *source_funcs,
842 g_return_val_if_fail (source_funcs != NULL, NULL);
843 g_return_val_if_fail (struct_size >= sizeof (GSource), NULL);
845 source = (GSource*) g_malloc0 (struct_size);
846 source->priv = g_slice_new0 (GSourcePrivate);
847 source->source_funcs = source_funcs;
848 source->ref_count = 1;
850 source->priority = G_PRIORITY_DEFAULT;
852 source->flags = G_HOOK_FLAG_ACTIVE;
854 source->priv->ready_time = -1;
856 /* NULL/0 initialization for all other fields */
861 /* Holds context's lock */
863 g_source_iter_init (GSourceIter *iter,
864 GMainContext *context,
867 iter->context = context;
868 iter->current_list = NULL;
870 iter->may_modify = may_modify;
873 /* Holds context's lock */
875 g_source_iter_next (GSourceIter *iter, GSource **source)
877 GSource *next_source;
880 next_source = iter->source->next;
886 if (iter->current_list)
887 iter->current_list = iter->current_list->next;
889 iter->current_list = iter->context->source_lists;
891 if (iter->current_list)
893 GSourceList *source_list = iter->current_list->data;
895 next_source = source_list->head;
899 /* Note: unreffing iter->source could potentially cause its
900 * GSourceList to be removed from source_lists (if iter->source is
901 * the only source in its list, and it is destroyed), so we have to
902 * keep it reffed until after we advance iter->current_list, above.
905 if (iter->source && iter->may_modify)
906 SOURCE_UNREF (iter->source, iter->context);
907 iter->source = next_source;
908 if (iter->source && iter->may_modify)
909 iter->source->ref_count++;
911 *source = iter->source;
912 return *source != NULL;
915 /* Holds context's lock. Only necessary to call if you broke out of
916 * the g_source_iter_next() loop early.
919 g_source_iter_clear (GSourceIter *iter)
921 if (iter->source && iter->may_modify)
923 SOURCE_UNREF (iter->source, iter->context);
928 /* Holds context's lock
931 find_source_list_for_priority (GMainContext *context,
936 GSourceList *source_list;
939 for (iter = context->source_lists; iter != NULL; last = iter, iter = iter->next)
941 source_list = iter->data;
943 if (source_list->priority == priority)
946 if (source_list->priority > priority)
951 source_list = g_slice_new0 (GSourceList);
952 source_list->priority = priority;
953 context->source_lists = g_list_insert_before (context->source_lists,
963 source_list = g_slice_new0 (GSourceList);
964 source_list->priority = priority;
967 context->source_lists = g_list_append (NULL, source_list);
970 /* This just appends source_list to the end of
971 * context->source_lists without having to walk the list again.
973 last = g_list_append (last, source_list);
978 /* Holds context's lock
981 source_add_to_context (GSource *source,
982 GMainContext *context)
984 GSourceList *source_list;
985 GSource *prev, *next;
987 source_list = find_source_list_for_priority (context, source->priority, TRUE);
989 if (source->priv->parent_source)
991 g_assert (source_list->head != NULL);
993 /* Put the source immediately before its parent */
994 prev = source->priv->parent_source->prev;
995 next = source->priv->parent_source;
999 prev = source_list->tail;
1003 source->next = next;
1005 next->prev = source;
1007 source_list->tail = source;
1009 source->prev = prev;
1011 prev->next = source;
1013 source_list->head = source;
1016 /* Holds context's lock
1019 source_remove_from_context (GSource *source,
1020 GMainContext *context)
1022 GSourceList *source_list;
1024 source_list = find_source_list_for_priority (context, source->priority, FALSE);
1025 g_return_if_fail (source_list != NULL);
1028 source->prev->next = source->next;
1030 source_list->head = source->next;
1033 source->next->prev = source->prev;
1035 source_list->tail = source->prev;
1037 source->prev = NULL;
1038 source->next = NULL;
1040 if (source_list->head == NULL)
1042 context->source_lists = g_list_remove (context->source_lists, source_list);
1043 g_slice_free (GSourceList, source_list);
1046 if (context->overflow_used_source_ids)
1047 g_hash_table_remove (context->overflow_used_source_ids,
1048 GUINT_TO_POINTER (source->source_id));
1053 assign_source_id_unlocked (GMainContext *context,
1058 /* Are we about to overflow back to 0?
1059 * See https://bugzilla.gnome.org/show_bug.cgi?id=687098
1061 if (G_UNLIKELY (context->next_id == G_MAXUINT &&
1062 context->overflow_used_source_ids == NULL))
1067 context->overflow_used_source_ids = g_hash_table_new (NULL, NULL);
1069 g_source_iter_init (&iter, context, FALSE);
1070 while (g_source_iter_next (&iter, &source))
1072 g_hash_table_add (context->overflow_used_source_ids,
1073 GUINT_TO_POINTER (source->source_id));
1077 else if (context->overflow_used_source_ids == NULL)
1079 id = context->next_id++;
1084 * If we overran G_MAXUINT, we fall back to randomly probing the
1085 * source ids for the current context. This will be slower the more
1086 * sources there are, but we're mainly concerned right now about
1087 * correctness and code size. There's time for a more clever solution
1091 id = g_random_int ();
1093 g_hash_table_contains (context->overflow_used_source_ids,
1094 GUINT_TO_POINTER (id)));
1095 g_hash_table_add (context->overflow_used_source_ids, GUINT_TO_POINTER (id));
1098 source->source_id = id;
1102 g_source_attach_unlocked (GSource *source,
1103 GMainContext *context)
1107 source->context = context;
1108 assign_source_id_unlocked (context, source);
1109 source->ref_count++;
1110 source_add_to_context (source, context);
1112 tmp_list = source->poll_fds;
1115 g_main_context_add_poll_unlocked (context, source->priority, tmp_list->data);
1116 tmp_list = tmp_list->next;
1119 tmp_list = source->priv->child_sources;
1122 g_source_attach_unlocked (tmp_list->data, context);
1123 tmp_list = tmp_list->next;
1126 return source->source_id;
1131 * @source: a #GSource
1132 * @context: (allow-none): a #GMainContext (if %NULL, the default context will be used)
1134 * Adds a #GSource to a @context so that it will be executed within
1135 * that context. Remove it by calling g_source_destroy().
1137 * Return value: the ID (greater than 0) for the source within the
1141 g_source_attach (GSource *source,
1142 GMainContext *context)
1146 g_return_val_if_fail (source->context == NULL, 0);
1147 g_return_val_if_fail (!SOURCE_DESTROYED (source), 0);
1150 context = g_main_context_default ();
1152 LOCK_CONTEXT (context);
1154 result = g_source_attach_unlocked (source, context);
1156 /* If another thread has acquired the context, wake it up since it
1157 * might be in poll() right now.
1159 if (context->owner && context->owner != G_THREAD_SELF)
1160 g_wakeup_signal (context->wakeup);
1162 UNLOCK_CONTEXT (context);
1168 g_source_destroy_internal (GSource *source,
1169 GMainContext *context,
1173 LOCK_CONTEXT (context);
1175 if (!SOURCE_DESTROYED (source))
1178 gpointer old_cb_data;
1179 GSourceCallbackFuncs *old_cb_funcs;
1181 source->flags &= ~G_HOOK_FLAG_ACTIVE;
1183 old_cb_data = source->callback_data;
1184 old_cb_funcs = source->callback_funcs;
1186 source->callback_data = NULL;
1187 source->callback_funcs = NULL;
1191 UNLOCK_CONTEXT (context);
1192 old_cb_funcs->unref (old_cb_data);
1193 LOCK_CONTEXT (context);
1196 if (!SOURCE_BLOCKED (source))
1198 tmp_list = source->poll_fds;
1201 g_main_context_remove_poll_unlocked (context, tmp_list->data);
1202 tmp_list = tmp_list->next;
1206 while (source->priv->child_sources)
1207 g_child_source_remove_internal (source->priv->child_sources->data, context);
1209 if (source->priv->parent_source)
1210 g_child_source_remove_internal (source, context);
1212 g_source_unref_internal (source, context, TRUE);
1216 UNLOCK_CONTEXT (context);
1221 * @source: a #GSource
1223 * Removes a source from its #GMainContext, if any, and mark it as
1224 * destroyed. The source cannot be subsequently added to another
1228 g_source_destroy (GSource *source)
1230 GMainContext *context;
1232 g_return_if_fail (source != NULL);
1234 context = source->context;
1237 g_source_destroy_internal (source, context, FALSE);
1239 source->flags &= ~G_HOOK_FLAG_ACTIVE;
1244 * @source: a #GSource
1246 * Returns the numeric ID for a particular source. The ID of a source
1247 * is a positive integer which is unique within a particular main loop
1248 * context. The reverse
1249 * mapping from ID to source is done by g_main_context_find_source_by_id().
1251 * Return value: the ID (greater than 0) for the source
1254 g_source_get_id (GSource *source)
1258 g_return_val_if_fail (source != NULL, 0);
1259 g_return_val_if_fail (source->context != NULL, 0);
1261 LOCK_CONTEXT (source->context);
1262 result = source->source_id;
1263 UNLOCK_CONTEXT (source->context);
1269 * g_source_get_context:
1270 * @source: a #GSource
1272 * Gets the #GMainContext with which the source is associated.
1274 * You can call this on a source that has been destroyed, provided
1275 * that the #GMainContext it was attached to still exists (in which
1276 * case it will return that #GMainContext). In particular, you can
1277 * always call this function on the source returned from
1278 * g_main_current_source(). But calling this function on a source
1279 * whose #GMainContext has been destroyed is an error.
1281 * Return value: (transfer none) (allow-none): the #GMainContext with which the
1282 * source is associated, or %NULL if the context has not
1283 * yet been added to a source.
1286 g_source_get_context (GSource *source)
1288 g_return_val_if_fail (source->context != NULL || !SOURCE_DESTROYED (source), NULL);
1290 return source->context;
1294 * g_source_add_poll:
1295 * @source:a #GSource
1296 * @fd: a #GPollFD structure holding information about a file
1297 * descriptor to watch.
1299 * Adds a file descriptor to the set of file descriptors polled for
1300 * this source. This is usually combined with g_source_new() to add an
1301 * event source. The event source's check function will typically test
1302 * the @revents field in the #GPollFD struct and return %TRUE if events need
1306 g_source_add_poll (GSource *source,
1309 GMainContext *context;
1311 g_return_if_fail (source != NULL);
1312 g_return_if_fail (fd != NULL);
1313 g_return_if_fail (!SOURCE_DESTROYED (source));
1315 context = source->context;
1318 LOCK_CONTEXT (context);
1320 source->poll_fds = g_slist_prepend (source->poll_fds, fd);
1324 if (!SOURCE_BLOCKED (source))
1325 g_main_context_add_poll_unlocked (context, source->priority, fd);
1326 UNLOCK_CONTEXT (context);
1331 * g_source_remove_poll:
1332 * @source:a #GSource
1333 * @fd: a #GPollFD structure previously passed to g_source_add_poll().
1335 * Removes a file descriptor from the set of file descriptors polled for
1339 g_source_remove_poll (GSource *source,
1342 GMainContext *context;
1344 g_return_if_fail (source != NULL);
1345 g_return_if_fail (fd != NULL);
1346 g_return_if_fail (!SOURCE_DESTROYED (source));
1348 context = source->context;
1351 LOCK_CONTEXT (context);
1353 source->poll_fds = g_slist_remove (source->poll_fds, fd);
1357 if (!SOURCE_BLOCKED (source))
1358 g_main_context_remove_poll_unlocked (context, fd);
1359 UNLOCK_CONTEXT (context);
1364 * g_source_add_child_source:
1365 * @source:a #GSource
1366 * @child_source: a second #GSource that @source should "poll"
1368 * Adds @child_source to @source as a "polled" source; when @source is
1369 * added to a #GMainContext, @child_source will be automatically added
1370 * with the same priority, when @child_source is triggered, it will
1371 * cause @source to dispatch (in addition to calling its own
1372 * callback), and when @source is destroyed, it will destroy
1373 * @child_source as well. (@source will also still be dispatched if
1374 * its own prepare/check functions indicate that it is ready.)
1376 * If you don't need @child_source to do anything on its own when it
1377 * triggers, you can call g_source_set_dummy_callback() on it to set a
1378 * callback that does nothing (except return %TRUE if appropriate).
1380 * @source will hold a reference on @child_source while @child_source
1381 * is attached to it.
1386 g_source_add_child_source (GSource *source,
1387 GSource *child_source)
1389 GMainContext *context;
1391 g_return_if_fail (source != NULL);
1392 g_return_if_fail (child_source != NULL);
1393 g_return_if_fail (!SOURCE_DESTROYED (source));
1394 g_return_if_fail (!SOURCE_DESTROYED (child_source));
1395 g_return_if_fail (child_source->context == NULL);
1396 g_return_if_fail (child_source->priv->parent_source == NULL);
1398 context = source->context;
1401 LOCK_CONTEXT (context);
1403 source->priv->child_sources = g_slist_prepend (source->priv->child_sources,
1404 g_source_ref (child_source));
1405 child_source->priv->parent_source = source;
1406 g_source_set_priority_unlocked (child_source, NULL, source->priority);
1407 if (SOURCE_BLOCKED (source))
1408 block_source (child_source);
1412 UNLOCK_CONTEXT (context);
1413 g_source_attach (child_source, context);
1418 g_child_source_remove_internal (GSource *child_source,
1419 GMainContext *context)
1421 GSource *parent_source = child_source->priv->parent_source;
1423 parent_source->priv->child_sources =
1424 g_slist_remove (parent_source->priv->child_sources, child_source);
1425 child_source->priv->parent_source = NULL;
1427 g_source_destroy_internal (child_source, context, TRUE);
1428 g_source_unref_internal (child_source, context, TRUE);
1432 * g_source_remove_child_source:
1433 * @source:a #GSource
1434 * @child_source: a #GSource previously passed to
1435 * g_source_add_child_source().
1437 * Detaches @child_source from @source and destroys it.
1442 g_source_remove_child_source (GSource *source,
1443 GSource *child_source)
1445 GMainContext *context;
1447 g_return_if_fail (source != NULL);
1448 g_return_if_fail (child_source != NULL);
1449 g_return_if_fail (child_source->priv->parent_source == source);
1450 g_return_if_fail (!SOURCE_DESTROYED (source));
1451 g_return_if_fail (!SOURCE_DESTROYED (child_source));
1453 context = source->context;
1456 LOCK_CONTEXT (context);
1458 g_child_source_remove_internal (child_source, context);
1461 UNLOCK_CONTEXT (context);
1465 * g_source_set_callback_indirect:
1466 * @source: the source
1467 * @callback_data: pointer to callback data "object"
1468 * @callback_funcs: functions for reference counting @callback_data
1469 * and getting the callback and data
1471 * Sets the callback function storing the data as a refcounted callback
1472 * "object". This is used internally. Note that calling
1473 * g_source_set_callback_indirect() assumes
1474 * an initial reference count on @callback_data, and thus
1475 * @callback_funcs->unref will eventually be called once more
1476 * than @callback_funcs->ref.
1479 g_source_set_callback_indirect (GSource *source,
1480 gpointer callback_data,
1481 GSourceCallbackFuncs *callback_funcs)
1483 GMainContext *context;
1484 gpointer old_cb_data;
1485 GSourceCallbackFuncs *old_cb_funcs;
1487 g_return_if_fail (source != NULL);
1488 g_return_if_fail (callback_funcs != NULL || callback_data == NULL);
1490 context = source->context;
1493 LOCK_CONTEXT (context);
1495 old_cb_data = source->callback_data;
1496 old_cb_funcs = source->callback_funcs;
1498 source->callback_data = callback_data;
1499 source->callback_funcs = callback_funcs;
1502 UNLOCK_CONTEXT (context);
1505 old_cb_funcs->unref (old_cb_data);
1509 g_source_callback_ref (gpointer cb_data)
1511 GSourceCallback *callback = cb_data;
1513 callback->ref_count++;
1518 g_source_callback_unref (gpointer cb_data)
1520 GSourceCallback *callback = cb_data;
1522 callback->ref_count--;
1523 if (callback->ref_count == 0)
1525 if (callback->notify)
1526 callback->notify (callback->data);
1532 g_source_callback_get (gpointer cb_data,
1537 GSourceCallback *callback = cb_data;
1539 *func = callback->func;
1540 *data = callback->data;
1543 static GSourceCallbackFuncs g_source_callback_funcs = {
1544 g_source_callback_ref,
1545 g_source_callback_unref,
1546 g_source_callback_get,
1550 * g_source_set_callback:
1551 * @source: the source
1552 * @func: a callback function
1553 * @data: the data to pass to callback function
1554 * @notify: (allow-none): a function to call when @data is no longer in use, or %NULL.
1556 * Sets the callback function for a source. The callback for a source is
1557 * called from the source's dispatch function.
1559 * The exact type of @func depends on the type of source; ie. you
1560 * should not count on @func being called with @data as its first
1563 * Typically, you won't use this function. Instead use functions specific
1564 * to the type of source you are using.
1567 g_source_set_callback (GSource *source,
1570 GDestroyNotify notify)
1572 GSourceCallback *new_callback;
1574 g_return_if_fail (source != NULL);
1576 new_callback = g_new (GSourceCallback, 1);
1578 new_callback->ref_count = 1;
1579 new_callback->func = func;
1580 new_callback->data = data;
1581 new_callback->notify = notify;
1583 g_source_set_callback_indirect (source, new_callback, &g_source_callback_funcs);
1588 * g_source_set_funcs:
1589 * @source: a #GSource
1590 * @funcs: the new #GSourceFuncs
1592 * Sets the source functions (can be used to override
1593 * default implementations) of an unattached source.
1598 g_source_set_funcs (GSource *source,
1599 GSourceFuncs *funcs)
1601 g_return_if_fail (source != NULL);
1602 g_return_if_fail (source->context == NULL);
1603 g_return_if_fail (source->ref_count > 0);
1604 g_return_if_fail (funcs != NULL);
1606 source->source_funcs = funcs;
1610 g_source_set_priority_unlocked (GSource *source,
1611 GMainContext *context,
1616 g_return_if_fail (source->priv->parent_source == NULL ||
1617 source->priv->parent_source->priority == priority);
1621 /* Remove the source from the context's source and then
1622 * add it back after so it is sorted in the correct place
1624 source_remove_from_context (source, source->context);
1627 source->priority = priority;
1631 source_add_to_context (source, source->context);
1633 if (!SOURCE_BLOCKED (source))
1635 tmp_list = source->poll_fds;
1638 g_main_context_remove_poll_unlocked (context, tmp_list->data);
1639 g_main_context_add_poll_unlocked (context, priority, tmp_list->data);
1641 tmp_list = tmp_list->next;
1646 if (source->priv->child_sources)
1648 tmp_list = source->priv->child_sources;
1651 g_source_set_priority_unlocked (tmp_list->data, context, priority);
1652 tmp_list = tmp_list->next;
1658 * g_source_set_priority:
1659 * @source: a #GSource
1660 * @priority: the new priority.
1662 * Sets the priority of a source. While the main loop is being run, a
1663 * source will be dispatched if it is ready to be dispatched and no
1664 * sources at a higher (numerically smaller) priority are ready to be
1668 g_source_set_priority (GSource *source,
1671 GMainContext *context;
1673 g_return_if_fail (source != NULL);
1675 context = source->context;
1678 LOCK_CONTEXT (context);
1679 g_source_set_priority_unlocked (source, context, priority);
1681 UNLOCK_CONTEXT (source->context);
1685 * g_source_get_priority:
1686 * @source: a #GSource
1688 * Gets the priority of a source.
1690 * Return value: the priority of the source
1693 g_source_get_priority (GSource *source)
1695 g_return_val_if_fail (source != NULL, 0);
1697 return source->priority;
1701 * g_source_set_ready_time:
1702 * @source: a #GSource
1703 * @ready_time: the monotonic time at which the source will be ready,
1704 * 0 for "immediately", -1 for "never"
1706 * Sets a #GSource to be dispatched when the given monotonic time is
1707 * reached (or passed). If the monotonic time is in the past (as it
1708 * always will be if @ready_time is 0) then the source will be
1709 * dispatched immediately.
1711 * If @ready_time is -1 then the source is never woken up on the basis
1712 * of the passage of time.
1714 * Dispatching the source does not reset the ready time. You should do
1715 * so yourself, from the source dispatch function.
1720 g_source_set_ready_time (GSource *source,
1723 GMainContext *context;
1725 g_return_if_fail (source != NULL);
1726 g_return_if_fail (source->ref_count > 0);
1728 if (source->priv->ready_time == ready_time)
1731 context = source->context;
1734 LOCK_CONTEXT (context);
1736 source->priv->ready_time = ready_time;
1740 /* Quite likely that we need to change the timeout on the poll */
1741 if (!SOURCE_BLOCKED (source))
1742 g_wakeup_signal (context->wakeup);
1743 UNLOCK_CONTEXT (context);
1748 * g_source_get_ready_time:
1749 * @source: a #GSource
1751 * Gets the "ready time" of @source, as set by
1752 * g_source_set_ready_time().
1754 * Any time before the current monotonic time (including 0) is an
1755 * indication that the source will fire immediately.
1757 * Returns: the monotonic ready time, -1 for "never"
1760 g_source_get_ready_time (GSource *source)
1762 g_return_val_if_fail (source != NULL, -1);
1764 return source->priv->ready_time;
1768 * g_source_set_can_recurse:
1769 * @source: a #GSource
1770 * @can_recurse: whether recursion is allowed for this source
1772 * Sets whether a source can be called recursively. If @can_recurse is
1773 * %TRUE, then while the source is being dispatched then this source
1774 * will be processed normally. Otherwise, all processing of this
1775 * source is blocked until the dispatch function returns.
1778 g_source_set_can_recurse (GSource *source,
1779 gboolean can_recurse)
1781 GMainContext *context;
1783 g_return_if_fail (source != NULL);
1785 context = source->context;
1788 LOCK_CONTEXT (context);
1791 source->flags |= G_SOURCE_CAN_RECURSE;
1793 source->flags &= ~G_SOURCE_CAN_RECURSE;
1796 UNLOCK_CONTEXT (context);
1800 * g_source_get_can_recurse:
1801 * @source: a #GSource
1803 * Checks whether a source is allowed to be called recursively.
1804 * see g_source_set_can_recurse().
1806 * Return value: whether recursion is allowed.
1809 g_source_get_can_recurse (GSource *source)
1811 g_return_val_if_fail (source != NULL, FALSE);
1813 return (source->flags & G_SOURCE_CAN_RECURSE) != 0;
1818 * g_source_set_name:
1819 * @source: a #GSource
1820 * @name: debug name for the source
1822 * Sets a name for the source, used in debugging and profiling.
1823 * The name defaults to #NULL.
1825 * The source name should describe in a human-readable way
1826 * what the source does. For example, "X11 event queue"
1827 * or "GTK+ repaint idle handler" or whatever it is.
1829 * It is permitted to call this function multiple times, but is not
1830 * recommended due to the potential performance impact. For example,
1831 * one could change the name in the "check" function of a #GSourceFuncs
1832 * to include details like the event type in the source name.
1837 g_source_set_name (GSource *source,
1840 g_return_if_fail (source != NULL);
1842 /* setting back to NULL is allowed, just because it's
1843 * weird if get_name can return NULL but you can't
1847 g_free (source->name);
1848 source->name = g_strdup (name);
1852 * g_source_get_name:
1853 * @source: a #GSource
1855 * Gets a name for the source, used in debugging and profiling.
1856 * The name may be #NULL if it has never been set with
1857 * g_source_set_name().
1859 * Return value: the name of the source
1863 g_source_get_name (GSource *source)
1865 g_return_val_if_fail (source != NULL, NULL);
1867 return source->name;
1871 * g_source_set_name_by_id:
1872 * @tag: a #GSource ID
1873 * @name: debug name for the source
1875 * Sets the name of a source using its ID.
1877 * This is a convenience utility to set source names from the return
1878 * value of g_idle_add(), g_timeout_add(), etc.
1883 g_source_set_name_by_id (guint tag,
1888 g_return_if_fail (tag > 0);
1890 source = g_main_context_find_source_by_id (NULL, tag);
1894 g_source_set_name (source, name);
1900 * @source: a #GSource
1902 * Increases the reference count on a source by one.
1904 * Return value: @source
1907 g_source_ref (GSource *source)
1909 GMainContext *context;
1911 g_return_val_if_fail (source != NULL, NULL);
1913 context = source->context;
1916 LOCK_CONTEXT (context);
1918 source->ref_count++;
1921 UNLOCK_CONTEXT (context);
1926 /* g_source_unref() but possible to call within context lock
1929 g_source_unref_internal (GSource *source,
1930 GMainContext *context,
1933 gpointer old_cb_data = NULL;
1934 GSourceCallbackFuncs *old_cb_funcs = NULL;
1936 g_return_if_fail (source != NULL);
1938 if (!have_lock && context)
1939 LOCK_CONTEXT (context);
1941 source->ref_count--;
1942 if (source->ref_count == 0)
1944 old_cb_data = source->callback_data;
1945 old_cb_funcs = source->callback_funcs;
1947 source->callback_data = NULL;
1948 source->callback_funcs = NULL;
1952 if (!SOURCE_DESTROYED (source))
1953 g_warning (G_STRLOC ": ref_count == 0, but source was still attached to a context!");
1954 source_remove_from_context (source, context);
1957 if (source->source_funcs->finalize)
1960 UNLOCK_CONTEXT (context);
1961 source->source_funcs->finalize (source);
1963 LOCK_CONTEXT (context);
1966 g_free (source->name);
1967 source->name = NULL;
1969 g_slist_free (source->poll_fds);
1970 source->poll_fds = NULL;
1972 g_slice_free (GSourcePrivate, source->priv);
1973 source->priv = NULL;
1978 if (!have_lock && context)
1979 UNLOCK_CONTEXT (context);
1984 UNLOCK_CONTEXT (context);
1986 old_cb_funcs->unref (old_cb_data);
1989 LOCK_CONTEXT (context);
1995 * @source: a #GSource
1997 * Decreases the reference count of a source by one. If the
1998 * resulting reference count is zero the source and associated
1999 * memory will be destroyed.
2002 g_source_unref (GSource *source)
2004 g_return_if_fail (source != NULL);
2006 g_source_unref_internal (source, source->context, FALSE);
2010 * g_main_context_find_source_by_id:
2011 * @context: (allow-none): a #GMainContext (if %NULL, the default context will be used)
2012 * @source_id: the source ID, as returned by g_source_get_id().
2014 * Finds a #GSource given a pair of context and ID.
2016 * Return value: (transfer none): the #GSource if found, otherwise, %NULL
2019 g_main_context_find_source_by_id (GMainContext *context,
2025 g_return_val_if_fail (source_id > 0, NULL);
2027 if (context == NULL)
2028 context = g_main_context_default ();
2030 LOCK_CONTEXT (context);
2032 g_source_iter_init (&iter, context, FALSE);
2033 while (g_source_iter_next (&iter, &source))
2035 if (!SOURCE_DESTROYED (source) &&
2036 source->source_id == source_id)
2039 g_source_iter_clear (&iter);
2041 UNLOCK_CONTEXT (context);
2047 * g_main_context_find_source_by_funcs_user_data:
2048 * @context: (allow-none): a #GMainContext (if %NULL, the default context will be used).
2049 * @funcs: the @source_funcs passed to g_source_new().
2050 * @user_data: the user data from the callback.
2052 * Finds a source with the given source functions and user data. If
2053 * multiple sources exist with the same source function and user data,
2054 * the first one found will be returned.
2056 * Return value: (transfer none): the source, if one was found, otherwise %NULL
2059 g_main_context_find_source_by_funcs_user_data (GMainContext *context,
2060 GSourceFuncs *funcs,
2066 g_return_val_if_fail (funcs != NULL, NULL);
2068 if (context == NULL)
2069 context = g_main_context_default ();
2071 LOCK_CONTEXT (context);
2073 g_source_iter_init (&iter, context, FALSE);
2074 while (g_source_iter_next (&iter, &source))
2076 if (!SOURCE_DESTROYED (source) &&
2077 source->source_funcs == funcs &&
2078 source->callback_funcs)
2080 GSourceFunc callback;
2081 gpointer callback_data;
2083 source->callback_funcs->get (source->callback_data, source, &callback, &callback_data);
2085 if (callback_data == user_data)
2089 g_source_iter_clear (&iter);
2091 UNLOCK_CONTEXT (context);
2097 * g_main_context_find_source_by_user_data:
2098 * @context: a #GMainContext
2099 * @user_data: the user_data for the callback.
2101 * Finds a source with the given user data for the callback. If
2102 * multiple sources exist with the same user data, the first
2103 * one found will be returned.
2105 * Return value: (transfer none): the source, if one was found, otherwise %NULL
2108 g_main_context_find_source_by_user_data (GMainContext *context,
2114 if (context == NULL)
2115 context = g_main_context_default ();
2117 LOCK_CONTEXT (context);
2119 g_source_iter_init (&iter, context, FALSE);
2120 while (g_source_iter_next (&iter, &source))
2122 if (!SOURCE_DESTROYED (source) &&
2123 source->callback_funcs)
2125 GSourceFunc callback;
2126 gpointer callback_data = NULL;
2128 source->callback_funcs->get (source->callback_data, source, &callback, &callback_data);
2130 if (callback_data == user_data)
2134 g_source_iter_clear (&iter);
2136 UNLOCK_CONTEXT (context);
2143 * @tag: the ID of the source to remove.
2145 * Removes the source with the given id from the default main context.
2147 * a #GSource is given by g_source_get_id(), or will be returned by the
2148 * functions g_source_attach(), g_idle_add(), g_idle_add_full(),
2149 * g_timeout_add(), g_timeout_add_full(), g_child_watch_add(),
2150 * g_child_watch_add_full(), g_io_add_watch(), and g_io_add_watch_full().
2152 * See also g_source_destroy(). You must use g_source_destroy() for sources
2153 * added to a non-default main context.
2155 * Return value: %TRUE if the source was found and removed.
2158 g_source_remove (guint tag)
2162 g_return_val_if_fail (tag > 0, FALSE);
2164 source = g_main_context_find_source_by_id (NULL, tag);
2166 g_source_destroy (source);
2168 return source != NULL;
2172 * g_source_remove_by_user_data:
2173 * @user_data: the user_data for the callback.
2175 * Removes a source from the default main loop context given the user
2176 * data for the callback. If multiple sources exist with the same user
2177 * data, only one will be destroyed.
2179 * Return value: %TRUE if a source was found and removed.
2182 g_source_remove_by_user_data (gpointer user_data)
2186 source = g_main_context_find_source_by_user_data (NULL, user_data);
2189 g_source_destroy (source);
2197 * g_source_remove_by_funcs_user_data:
2198 * @funcs: The @source_funcs passed to g_source_new()
2199 * @user_data: the user data for the callback
2201 * Removes a source from the default main loop context given the
2202 * source functions and user data. If multiple sources exist with the
2203 * same source functions and user data, only one will be destroyed.
2205 * Return value: %TRUE if a source was found and removed.
2208 g_source_remove_by_funcs_user_data (GSourceFuncs *funcs,
2213 g_return_val_if_fail (funcs != NULL, FALSE);
2215 source = g_main_context_find_source_by_funcs_user_data (NULL, funcs, user_data);
2218 g_source_destroy (source);
2226 * g_get_current_time:
2227 * @result: #GTimeVal structure in which to store current time.
2229 * Equivalent to the UNIX gettimeofday() function, but portable.
2231 * You may find g_get_real_time() to be more convenient.
2234 g_get_current_time (GTimeVal *result)
2239 g_return_if_fail (result != NULL);
2241 /*this is required on alpha, there the timeval structs are int's
2242 not longs and a cast only would fail horribly*/
2243 gettimeofday (&r, NULL);
2244 result->tv_sec = r.tv_sec;
2245 result->tv_usec = r.tv_usec;
2250 g_return_if_fail (result != NULL);
2252 GetSystemTimeAsFileTime (&ft);
2253 memmove (&time64, &ft, sizeof (FILETIME));
2255 /* Convert from 100s of nanoseconds since 1601-01-01
2256 * to Unix epoch. Yes, this is Y2038 unsafe.
2258 time64 -= G_GINT64_CONSTANT (116444736000000000);
2261 result->tv_sec = time64 / 1000000;
2262 result->tv_usec = time64 % 1000000;
2269 * Queries the system wall-clock time.
2271 * This call is functionally equivalent to g_get_current_time() except
2272 * that the return value is often more convenient than dealing with a
2275 * You should only use this call if you are actually interested in the real
2276 * wall-clock time. g_get_monotonic_time() is probably more useful for
2277 * measuring intervals.
2279 * Returns: the number of microseconds since January 1, 1970 UTC.
2284 g_get_real_time (void)
2288 g_get_current_time (&tv);
2290 return (((gint64) tv.tv_sec) * 1000000) + tv.tv_usec;
2294 static ULONGLONG (*g_GetTickCount64) (void) = NULL;
2295 static guint32 g_win32_tick_epoch = 0;
2297 G_GNUC_INTERNAL void
2298 g_clock_win32_init (void)
2302 g_GetTickCount64 = NULL;
2303 kernel32 = GetModuleHandle ("KERNEL32.DLL");
2304 if (kernel32 != NULL)
2305 g_GetTickCount64 = (void *) GetProcAddress (kernel32, "GetTickCount64");
2306 g_win32_tick_epoch = ((guint32)GetTickCount()) >> 31;
2311 * g_get_monotonic_time:
2313 * Queries the system monotonic time, if available.
2315 * On POSIX systems with clock_gettime() and <literal>CLOCK_MONOTONIC</literal> this call
2316 * is a very shallow wrapper for that. Otherwise, we make a best effort
2317 * that probably involves returning the wall clock time (with at least
2318 * microsecond accuracy, subject to the limitations of the OS kernel).
2320 * It's important to note that POSIX <literal>CLOCK_MONOTONIC</literal> does
2321 * not count time spent while the machine is suspended.
2323 * On Windows, "limitations of the OS kernel" is a rather substantial
2324 * statement. Depending on the configuration of the system, the wall
2325 * clock time is updated as infrequently as 64 times a second (which
2326 * is approximately every 16ms). Also, on XP (but not on Vista or later)
2327 * the monotonic clock is locally monotonic, but may differ in exact
2328 * value between processes due to timer wrap handling.
2330 * Returns: the monotonic time, in microseconds
2335 g_get_monotonic_time (void)
2337 #ifdef HAVE_CLOCK_GETTIME
2338 /* librt clock_gettime() is our first choice */
2341 #ifdef CLOCK_MONOTONIC
2342 clock_gettime (CLOCK_MONOTONIC, &ts);
2344 clock_gettime (CLOCK_REALTIME, &ts);
2347 /* In theory monotonic time can have any epoch.
2349 * glib presently assumes the following:
2351 * 1) The epoch comes some time after the birth of Jesus of Nazareth, but
2352 * not more than 10000 years later.
2354 * 2) The current time also falls sometime within this range.
2356 * These two reasonable assumptions leave us with a maximum deviation from
2357 * the epoch of 10000 years, or 315569520000000000 seconds.
2359 * If we restrict ourselves to this range then the number of microseconds
2360 * will always fit well inside the constraints of a int64 (by a factor of
2363 * If you actually hit the following assertion, probably you should file a
2364 * bug against your operating system for being excessively silly.
2366 g_assert (G_GINT64_CONSTANT (-315569520000000000) < ts.tv_sec &&
2367 ts.tv_sec < G_GINT64_CONSTANT (315569520000000000));
2369 return (((gint64) ts.tv_sec) * 1000000) + (ts.tv_nsec / 1000);
2371 #elif defined (G_OS_WIN32)
2375 /* There are four sources for the monotonic time on Windows:
2377 * Three are based on a (1 msec accuracy, but only read periodically) clock chip:
2378 * - GetTickCount (GTC)
2379 * 32bit msec counter, updated each ~15msec, wraps in ~50 days
2380 * - GetTickCount64 (GTC64)
2381 * Same as GetTickCount, but extended to 64bit, so no wrap
2382 * Only available in Vista or later
2383 * - timeGetTime (TGT)
2384 * similar to GetTickCount by default: 15msec, 50 day wrap.
2385 * available in winmm.dll (thus known as the multimedia timers)
2386 * However apps can raise the system timer clock frequency using timeBeginPeriod()
2387 * increasing the accuracy up to 1 msec, at a cost in general system performance
2390 * One is based on high precision clocks:
2391 * - QueryPrecisionCounter (QPC)
2392 * This has much higher accuracy, but is not guaranteed monotonic, and
2393 * has lots of complications like clock jumps and different times on different
2394 * CPUs. It also has lower long term accuracy (i.e. it will drift compared to
2395 * the low precision clocks.
2397 * Additionally, the precision available in the timer-based wakeup such as
2398 * MsgWaitForMultipleObjectsEx (which is what the mainloop is based on) is based
2399 * on the TGT resolution, so by default it is ~15msec, but can be increased by apps.
2401 * The QPC timer has too many issues to be used as is. The only way it could be used
2402 * is to use it to interpolate the lower precision clocks. Firefox does something like
2404 * https://bugzilla.mozilla.org/show_bug.cgi?id=363258
2406 * However this seems quite complicated, so we're not doing this right now.
2408 * The approach we take instead is to use the TGT timer, extending it to 64bit
2409 * either by using the GTC64 value, or if that is not available, a process local
2410 * time epoch that we increment when we detect a timer wrap (assumes that we read
2411 * the time at least once every 50 days).
2414 * - We have a globally consistent monotonic clock on Vista and later
2415 * - We have a locally monotonic clock on XP
2416 * - Apps that need higher precision in timeouts and clock reads can call
2417 * timeBeginPeriod() to increase it as much as they want
2420 if (g_GetTickCount64 != NULL)
2422 guint32 ticks_as_32bit;
2424 ticks = g_GetTickCount64 ();
2425 ticks32 = timeGetTime();
2427 /* GTC64 and TGT are sampled at different times, however they
2428 * have the same base and source (msecs since system boot).
2429 * They can differ by as much as -16 to +16 msecs.
2430 * We can't just inject the low bits into the 64bit counter
2431 * as one of the counters can have wrapped in 32bit space and
2432 * the other not. Instead we calculate the signed difference
2433 * in 32bit space and apply that difference to the 64bit counter.
2435 ticks_as_32bit = (guint32)ticks;
2437 /* We could do some 2's complement hack, but we play it safe */
2438 if (ticks32 - ticks_as_32bit <= G_MAXINT32)
2439 ticks += ticks32 - ticks_as_32bit;
2441 ticks -= ticks_as_32bit - ticks32;
2447 epoch = g_atomic_int_get (&g_win32_tick_epoch);
2449 /* Must read ticks after the epoch. Then we're guaranteed
2450 * that the ticks value we read is higher or equal to any
2451 * previous ones that lead to the writing of the epoch.
2453 ticks32 = timeGetTime();
2455 /* We store the MSB of the current time as the LSB
2456 * of the epoch. Comparing these bits lets us detect when
2457 * the 32bit counter has wrapped so we can increase the
2460 * This will work as long as this function is called at
2461 * least once every ~24 days, which is half the wrap time
2462 * of a 32bit msec counter. I think this is pretty likely.
2464 * Note that g_win32_tick_epoch is a process local state,
2465 * so the monotonic clock will not be the same between
2468 if ((ticks32 >> 31) != (epoch & 1))
2471 g_atomic_int_set (&g_win32_tick_epoch, epoch);
2475 ticks = (guint64)ticks32 | ((guint64)epoch) << 31;
2478 return ticks * 1000;
2480 #else /* !HAVE_CLOCK_GETTIME && ! G_OS_WIN32*/
2484 g_get_current_time (&tv);
2486 return (((gint64) tv.tv_sec) * 1000000) + tv.tv_usec;
2491 g_main_dispatch_free (gpointer dispatch)
2493 g_slice_free (GMainDispatch, dispatch);
2496 /* Running the main loop */
2498 static GMainDispatch *
2501 static GPrivate depth_private = G_PRIVATE_INIT (g_main_dispatch_free);
2502 GMainDispatch *dispatch;
2504 dispatch = g_private_get (&depth_private);
2508 dispatch = g_slice_new0 (GMainDispatch);
2509 g_private_set (&depth_private, dispatch);
2518 * Returns the depth of the stack of calls to
2519 * g_main_context_dispatch() on any #GMainContext in the current thread.
2520 * That is, when called from the toplevel, it gives 0. When
2521 * called from within a callback from g_main_context_iteration()
2522 * (or g_main_loop_run(), etc.) it returns 1. When called from within
2523 * a callback to a recursive call to g_main_context_iteration(),
2524 * it returns 2. And so forth.
2526 * This function is useful in a situation like the following:
2527 * Imagine an extremely simple "garbage collected" system.
2530 * static GList *free_list;
2533 * allocate_memory (gsize size)
2535 * gpointer result = g_malloc (size);
2536 * free_list = g_list_prepend (free_list, result);
2541 * free_allocated_memory (void)
2544 * for (l = free_list; l; l = l->next);
2546 * g_list_free (free_list);
2554 * g_main_context_iteration (NULL, TRUE);
2555 * free_allocated_memory();
2559 * This works from an application, however, if you want to do the same
2560 * thing from a library, it gets more difficult, since you no longer
2561 * control the main loop. You might think you can simply use an idle
2562 * function to make the call to free_allocated_memory(), but that
2563 * doesn't work, since the idle function could be called from a
2564 * recursive callback. This can be fixed by using g_main_depth()
2568 * allocate_memory (gsize size)
2570 * FreeListBlock *block = g_new (FreeListBlock, 1);
2571 * block->mem = g_malloc (size);
2572 * block->depth = g_main_depth ();
2573 * free_list = g_list_prepend (free_list, block);
2574 * return block->mem;
2578 * free_allocated_memory (void)
2582 * int depth = g_main_depth ();
2583 * for (l = free_list; l; );
2585 * GList *next = l->next;
2586 * FreeListBlock *block = l->data;
2587 * if (block->depth > depth)
2589 * g_free (block->mem);
2591 * free_list = g_list_delete_link (free_list, l);
2599 * There is a temptation to use g_main_depth() to solve
2600 * problems with reentrancy. For instance, while waiting for data
2601 * to be received from the network in response to a menu item,
2602 * the menu item might be selected again. It might seem that
2603 * one could make the menu item's callback return immediately
2604 * and do nothing if g_main_depth() returns a value greater than 1.
2605 * However, this should be avoided since the user then sees selecting
2606 * the menu item do nothing. Furthermore, you'll find yourself adding
2607 * these checks all over your code, since there are doubtless many,
2608 * many things that the user could do. Instead, you can use the
2609 * following techniques:
2614 * Use gtk_widget_set_sensitive() or modal dialogs to prevent
2615 * the user from interacting with elements while the main
2616 * loop is recursing.
2621 * Avoid main loop recursion in situations where you can't handle
2622 * arbitrary callbacks. Instead, structure your code so that you
2623 * simply return to the main loop and then get called again when
2624 * there is more work to do.
2629 * Return value: The main loop recursion level in the current thread
2634 GMainDispatch *dispatch = get_dispatch ();
2635 return dispatch->depth;
2639 * g_main_current_source:
2641 * Returns the currently firing source for this thread.
2643 * Return value: (transfer none): The currently firing source or %NULL.
2648 g_main_current_source (void)
2650 GMainDispatch *dispatch = get_dispatch ();
2651 return dispatch->dispatching_sources ? dispatch->dispatching_sources->data : NULL;
2655 * g_source_is_destroyed:
2656 * @source: a #GSource
2658 * Returns whether @source has been destroyed.
2660 * This is important when you operate upon your objects
2661 * from within idle handlers, but may have freed the object
2662 * before the dispatch of your idle handler.
2666 * idle_callback (gpointer data)
2668 * SomeWidget *self = data;
2670 * GDK_THREADS_ENTER (<!-- -->);
2671 * /<!-- -->* do stuff with self *<!-- -->/
2672 * self->idle_id = 0;
2673 * GDK_THREADS_LEAVE (<!-- -->);
2675 * return G_SOURCE_REMOVE;
2679 * some_widget_do_stuff_later (SomeWidget *self)
2681 * self->idle_id = g_idle_add (idle_callback, self);
2685 * some_widget_finalize (GObject *object)
2687 * SomeWidget *self = SOME_WIDGET (object);
2689 * if (self->idle_id)
2690 * g_source_remove (self->idle_id);
2692 * G_OBJECT_CLASS (parent_class)->finalize (object);
2696 * This will fail in a multi-threaded application if the
2697 * widget is destroyed before the idle handler fires due
2698 * to the use after free in the callback. A solution, to
2699 * this particular problem, is to check to if the source
2700 * has already been destroy within the callback.
2704 * idle_callback (gpointer data)
2706 * SomeWidget *self = data;
2708 * GDK_THREADS_ENTER ();
2709 * if (!g_source_is_destroyed (g_main_current_source ()))
2711 * /<!-- -->* do stuff with self *<!-- -->/
2713 * GDK_THREADS_LEAVE ();
2719 * Return value: %TRUE if the source has been destroyed
2724 g_source_is_destroyed (GSource *source)
2726 return SOURCE_DESTROYED (source);
2729 /* Temporarily remove all this source's file descriptors from the
2730 * poll(), so that if data comes available for one of the file descriptors
2731 * we don't continually spin in the poll()
2733 /* HOLDS: source->context's lock */
2735 block_source (GSource *source)
2739 g_return_if_fail (!SOURCE_BLOCKED (source));
2741 source->flags |= G_SOURCE_BLOCKED;
2743 tmp_list = source->poll_fds;
2746 g_main_context_remove_poll_unlocked (source->context, tmp_list->data);
2747 tmp_list = tmp_list->next;
2750 if (source->priv && source->priv->child_sources)
2752 tmp_list = source->priv->child_sources;
2755 block_source (tmp_list->data);
2756 tmp_list = tmp_list->next;
2761 /* HOLDS: source->context's lock */
2763 unblock_source (GSource *source)
2767 g_return_if_fail (SOURCE_BLOCKED (source)); /* Source already unblocked */
2768 g_return_if_fail (!SOURCE_DESTROYED (source));
2770 source->flags &= ~G_SOURCE_BLOCKED;
2772 tmp_list = source->poll_fds;
2775 g_main_context_add_poll_unlocked (source->context, source->priority, tmp_list->data);
2776 tmp_list = tmp_list->next;
2779 if (source->priv && source->priv->child_sources)
2781 tmp_list = source->priv->child_sources;
2784 unblock_source (tmp_list->data);
2785 tmp_list = tmp_list->next;
2790 /* HOLDS: context's lock */
2792 g_main_dispatch (GMainContext *context)
2794 GMainDispatch *current = get_dispatch ();
2797 for (i = 0; i < context->pending_dispatches->len; i++)
2799 GSource *source = context->pending_dispatches->pdata[i];
2801 context->pending_dispatches->pdata[i] = NULL;
2804 source->flags &= ~G_SOURCE_READY;
2806 if (!SOURCE_DESTROYED (source))
2808 gboolean was_in_call;
2809 gpointer user_data = NULL;
2810 GSourceFunc callback = NULL;
2811 GSourceCallbackFuncs *cb_funcs;
2813 gboolean need_destroy;
2815 gboolean (*dispatch) (GSource *,
2818 GSList current_source_link;
2820 dispatch = source->source_funcs->dispatch;
2821 cb_funcs = source->callback_funcs;
2822 cb_data = source->callback_data;
2825 cb_funcs->ref (cb_data);
2827 if ((source->flags & G_SOURCE_CAN_RECURSE) == 0)
2828 block_source (source);
2830 was_in_call = source->flags & G_HOOK_FLAG_IN_CALL;
2831 source->flags |= G_HOOK_FLAG_IN_CALL;
2834 cb_funcs->get (cb_data, source, &callback, &user_data);
2836 UNLOCK_CONTEXT (context);
2839 /* The on-stack allocation of the GSList is unconventional, but
2840 * we know that the lifetime of the link is bounded to this
2841 * function as the link is kept in a thread specific list and
2842 * not manipulated outside of this function and its descendants.
2843 * Avoiding the overhead of a g_slist_alloc() is useful as many
2844 * applications do little more than dispatch events.
2846 * This is a performance hack - do not revert to g_slist_prepend()!
2848 current_source_link.data = source;
2849 current_source_link.next = current->dispatching_sources;
2850 current->dispatching_sources = ¤t_source_link;
2851 need_destroy = ! dispatch (source,
2854 g_assert (current->dispatching_sources == ¤t_source_link);
2855 current->dispatching_sources = current_source_link.next;
2859 cb_funcs->unref (cb_data);
2861 LOCK_CONTEXT (context);
2864 source->flags &= ~G_HOOK_FLAG_IN_CALL;
2866 if (SOURCE_BLOCKED (source) && !SOURCE_DESTROYED (source))
2867 unblock_source (source);
2869 /* Note: this depends on the fact that we can't switch
2870 * sources from one main context to another
2872 if (need_destroy && !SOURCE_DESTROYED (source))
2874 g_assert (source->context == context);
2875 g_source_destroy_internal (source, context, TRUE);
2879 SOURCE_UNREF (source, context);
2882 g_ptr_array_set_size (context->pending_dispatches, 0);
2886 * g_main_context_acquire:
2887 * @context: a #GMainContext
2889 * Tries to become the owner of the specified context.
2890 * If some other thread is the owner of the context,
2891 * returns %FALSE immediately. Ownership is properly
2892 * recursive: the owner can require ownership again
2893 * and will release ownership when g_main_context_release()
2894 * is called as many times as g_main_context_acquire().
2896 * You must be the owner of a context before you
2897 * can call g_main_context_prepare(), g_main_context_query(),
2898 * g_main_context_check(), g_main_context_dispatch().
2900 * Return value: %TRUE if the operation succeeded, and
2901 * this thread is now the owner of @context.
2904 g_main_context_acquire (GMainContext *context)
2906 gboolean result = FALSE;
2907 GThread *self = G_THREAD_SELF;
2909 if (context == NULL)
2910 context = g_main_context_default ();
2912 LOCK_CONTEXT (context);
2914 if (!context->owner)
2916 context->owner = self;
2917 g_assert (context->owner_count == 0);
2920 if (context->owner == self)
2922 context->owner_count++;
2926 UNLOCK_CONTEXT (context);
2932 * g_main_context_release:
2933 * @context: a #GMainContext
2935 * Releases ownership of a context previously acquired by this thread
2936 * with g_main_context_acquire(). If the context was acquired multiple
2937 * times, the ownership will be released only when g_main_context_release()
2938 * is called as many times as it was acquired.
2941 g_main_context_release (GMainContext *context)
2943 if (context == NULL)
2944 context = g_main_context_default ();
2946 LOCK_CONTEXT (context);
2948 context->owner_count--;
2949 if (context->owner_count == 0)
2951 context->owner = NULL;
2953 if (context->waiters)
2955 GMainWaiter *waiter = context->waiters->data;
2956 gboolean loop_internal_waiter = (waiter->mutex == &context->mutex);
2957 context->waiters = g_slist_delete_link (context->waiters,
2959 if (!loop_internal_waiter)
2960 g_mutex_lock (waiter->mutex);
2962 g_cond_signal (waiter->cond);
2964 if (!loop_internal_waiter)
2965 g_mutex_unlock (waiter->mutex);
2969 UNLOCK_CONTEXT (context);
2973 * g_main_context_wait:
2974 * @context: a #GMainContext
2975 * @cond: a condition variable
2976 * @mutex: a mutex, currently held
2978 * Tries to become the owner of the specified context,
2979 * as with g_main_context_acquire(). But if another thread
2980 * is the owner, atomically drop @mutex and wait on @cond until
2981 * that owner releases ownership or until @cond is signaled, then
2982 * try again (once) to become the owner.
2984 * Return value: %TRUE if the operation succeeded, and
2985 * this thread is now the owner of @context.
2988 g_main_context_wait (GMainContext *context,
2992 gboolean result = FALSE;
2993 GThread *self = G_THREAD_SELF;
2994 gboolean loop_internal_waiter;
2996 if (context == NULL)
2997 context = g_main_context_default ();
2999 loop_internal_waiter = (mutex == &context->mutex);
3001 if (!loop_internal_waiter)
3002 LOCK_CONTEXT (context);
3004 if (context->owner && context->owner != self)
3009 waiter.mutex = mutex;
3011 context->waiters = g_slist_append (context->waiters, &waiter);
3013 if (!loop_internal_waiter)
3014 UNLOCK_CONTEXT (context);
3015 g_cond_wait (cond, mutex);
3016 if (!loop_internal_waiter)
3017 LOCK_CONTEXT (context);
3019 context->waiters = g_slist_remove (context->waiters, &waiter);
3022 if (!context->owner)
3024 context->owner = self;
3025 g_assert (context->owner_count == 0);
3028 if (context->owner == self)
3030 context->owner_count++;
3034 if (!loop_internal_waiter)
3035 UNLOCK_CONTEXT (context);
3041 * g_main_context_prepare:
3042 * @context: a #GMainContext
3043 * @priority: location to store priority of highest priority
3044 * source already ready.
3046 * Prepares to poll sources within a main loop. The resulting information
3047 * for polling is determined by calling g_main_context_query ().
3049 * Return value: %TRUE if some source is ready to be dispatched
3053 g_main_context_prepare (GMainContext *context,
3058 gint current_priority = G_MAXINT;
3062 if (context == NULL)
3063 context = g_main_context_default ();
3065 LOCK_CONTEXT (context);
3067 context->time_is_fresh = FALSE;
3069 if (context->in_check_or_prepare)
3071 g_warning ("g_main_context_prepare() called recursively from within a source's check() or "
3072 "prepare() member.");
3073 UNLOCK_CONTEXT (context);
3078 /* If recursing, finish up current dispatch, before starting over */
3079 if (context->pending_dispatches)
3082 g_main_dispatch (context, ¤t_time);
3084 UNLOCK_CONTEXT (context);
3089 /* If recursing, clear list of pending dispatches */
3091 for (i = 0; i < context->pending_dispatches->len; i++)
3093 if (context->pending_dispatches->pdata[i])
3094 SOURCE_UNREF ((GSource *)context->pending_dispatches->pdata[i], context);
3096 g_ptr_array_set_size (context->pending_dispatches, 0);
3098 /* Prepare all sources */
3100 context->timeout = -1;
3102 g_source_iter_init (&iter, context, TRUE);
3103 while (g_source_iter_next (&iter, &source))
3105 gint source_timeout = -1;
3107 if (SOURCE_DESTROYED (source) || SOURCE_BLOCKED (source))
3109 if ((n_ready > 0) && (source->priority > current_priority))
3112 if (!(source->flags & G_SOURCE_READY))
3115 gboolean (* prepare) (GSource *source,
3118 prepare = source->source_funcs->prepare;
3122 context->in_check_or_prepare++;
3123 UNLOCK_CONTEXT (context);
3125 result = (* prepare) (source, &source_timeout);
3127 LOCK_CONTEXT (context);
3128 context->in_check_or_prepare--;
3132 source_timeout = -1;
3136 if (result == FALSE && source->priv->ready_time != -1)
3138 if (!context->time_is_fresh)
3140 context->time = g_get_monotonic_time ();
3141 context->time_is_fresh = TRUE;
3144 if (source->priv->ready_time <= context->time)
3153 /* rounding down will lead to spinning, so always round up */
3154 timeout = (source->priv->ready_time - context->time + 999) / 1000;
3156 if (source_timeout < 0 || timeout < source_timeout)
3157 source_timeout = timeout;
3163 GSource *ready_source = source;
3165 while (ready_source)
3167 ready_source->flags |= G_SOURCE_READY;
3168 ready_source = ready_source->priv->parent_source;
3173 if (source->flags & G_SOURCE_READY)
3176 current_priority = source->priority;
3177 context->timeout = 0;
3180 if (source_timeout >= 0)
3182 if (context->timeout < 0)
3183 context->timeout = source_timeout;
3185 context->timeout = MIN (context->timeout, source_timeout);
3188 g_source_iter_clear (&iter);
3190 UNLOCK_CONTEXT (context);
3193 *priority = current_priority;
3195 return (n_ready > 0);
3199 * g_main_context_query:
3200 * @context: a #GMainContext
3201 * @max_priority: maximum priority source to check
3202 * @timeout_: (out): location to store timeout to be used in polling
3203 * @fds: (out caller-allocates) (array length=n_fds): location to
3204 * store #GPollFD records that need to be polled.
3205 * @n_fds: length of @fds.
3207 * Determines information necessary to poll this main loop.
3209 * Return value: the number of records actually stored in @fds,
3210 * or, if more than @n_fds records need to be stored, the number
3211 * of records that need to be stored.
3214 g_main_context_query (GMainContext *context,
3223 LOCK_CONTEXT (context);
3225 pollrec = context->poll_records;
3227 while (pollrec && max_priority >= pollrec->priority)
3229 /* We need to include entries with fd->events == 0 in the array because
3230 * otherwise if the application changes fd->events behind our back and
3231 * makes it non-zero, we'll be out of sync when we check the fds[] array.
3232 * (Changing fd->events after adding an FD wasn't an anticipated use of
3233 * this API, but it occurs in practice.) */
3236 fds[n_poll].fd = pollrec->fd->fd;
3237 /* In direct contradiction to the Unix98 spec, IRIX runs into
3238 * difficulty if you pass in POLLERR, POLLHUP or POLLNVAL
3239 * flags in the events field of the pollfd while it should
3240 * just ignoring them. So we mask them out here.
3242 fds[n_poll].events = pollrec->fd->events & ~(G_IO_ERR|G_IO_HUP|G_IO_NVAL);
3243 fds[n_poll].revents = 0;
3246 pollrec = pollrec->next;
3250 context->poll_changed = FALSE;
3254 *timeout = context->timeout;
3256 context->time_is_fresh = FALSE;
3259 UNLOCK_CONTEXT (context);
3265 * g_main_context_check:
3266 * @context: a #GMainContext
3267 * @max_priority: the maximum numerical priority of sources to check
3268 * @fds: (array length=n_fds): array of #GPollFD's that was passed to
3269 * the last call to g_main_context_query()
3270 * @n_fds: return value of g_main_context_query()
3272 * Passes the results of polling back to the main loop.
3274 * Return value: %TRUE if some sources are ready to be dispatched.
3277 g_main_context_check (GMainContext *context,
3288 LOCK_CONTEXT (context);
3290 if (context->in_check_or_prepare)
3292 g_warning ("g_main_context_check() called recursively from within a source's check() or "
3293 "prepare() member.");
3294 UNLOCK_CONTEXT (context);
3298 if (context->wake_up_rec.revents)
3299 g_wakeup_acknowledge (context->wakeup);
3301 /* If the set of poll file descriptors changed, bail out
3302 * and let the main loop rerun
3304 if (context->poll_changed)
3306 UNLOCK_CONTEXT (context);
3310 pollrec = context->poll_records;
3314 if (pollrec->fd->events)
3315 pollrec->fd->revents = fds[i].revents;
3317 pollrec = pollrec->next;
3321 g_source_iter_init (&iter, context, TRUE);
3322 while (g_source_iter_next (&iter, &source))
3324 if (SOURCE_DESTROYED (source) || SOURCE_BLOCKED (source))
3326 if ((n_ready > 0) && (source->priority > max_priority))
3329 if (!(source->flags & G_SOURCE_READY))
3332 gboolean (* check) (GSource *source);
3334 check = source->source_funcs->check;
3338 /* If the check function is set, call it. */
3339 context->in_check_or_prepare++;
3340 UNLOCK_CONTEXT (context);
3342 result = (* check) (source);
3344 LOCK_CONTEXT (context);
3345 context->in_check_or_prepare--;
3350 if (result == FALSE && source->priv->ready_time != -1)
3352 if (!context->time_is_fresh)
3354 context->time = g_get_monotonic_time ();
3355 context->time_is_fresh = TRUE;
3358 if (source->priv->ready_time <= context->time)
3364 GSource *ready_source = source;
3366 while (ready_source)
3368 ready_source->flags |= G_SOURCE_READY;
3369 ready_source = ready_source->priv->parent_source;
3374 if (source->flags & G_SOURCE_READY)
3376 source->ref_count++;
3377 g_ptr_array_add (context->pending_dispatches, source);
3381 /* never dispatch sources with less priority than the first
3382 * one we choose to dispatch
3384 max_priority = source->priority;
3387 g_source_iter_clear (&iter);
3389 UNLOCK_CONTEXT (context);
3395 * g_main_context_dispatch:
3396 * @context: a #GMainContext
3398 * Dispatches all pending sources.
3401 g_main_context_dispatch (GMainContext *context)
3403 LOCK_CONTEXT (context);
3405 if (context->pending_dispatches->len > 0)
3407 g_main_dispatch (context);
3410 UNLOCK_CONTEXT (context);
3413 /* HOLDS context lock */
3415 g_main_context_iterate (GMainContext *context,
3422 gboolean some_ready;
3423 gint nfds, allocated_nfds;
3424 GPollFD *fds = NULL;
3426 UNLOCK_CONTEXT (context);
3428 if (!g_main_context_acquire (context))
3430 gboolean got_ownership;
3432 LOCK_CONTEXT (context);
3437 got_ownership = g_main_context_wait (context,
3445 LOCK_CONTEXT (context);
3447 if (!context->cached_poll_array)
3449 context->cached_poll_array_size = context->n_poll_records;
3450 context->cached_poll_array = g_new (GPollFD, context->n_poll_records);
3453 allocated_nfds = context->cached_poll_array_size;
3454 fds = context->cached_poll_array;
3456 UNLOCK_CONTEXT (context);
3458 g_main_context_prepare (context, &max_priority);
3460 while ((nfds = g_main_context_query (context, max_priority, &timeout, fds,
3461 allocated_nfds)) > allocated_nfds)
3463 LOCK_CONTEXT (context);
3465 context->cached_poll_array_size = allocated_nfds = nfds;
3466 context->cached_poll_array = fds = g_new (GPollFD, nfds);
3467 UNLOCK_CONTEXT (context);
3473 g_main_context_poll (context, timeout, max_priority, fds, nfds);
3475 some_ready = g_main_context_check (context, max_priority, fds, nfds);
3478 g_main_context_dispatch (context);
3480 g_main_context_release (context);
3482 LOCK_CONTEXT (context);
3488 * g_main_context_pending:
3489 * @context: (allow-none): a #GMainContext (if %NULL, the default context will be used)
3491 * Checks if any sources have pending events for the given context.
3493 * Return value: %TRUE if events are pending.
3496 g_main_context_pending (GMainContext *context)
3501 context = g_main_context_default();
3503 LOCK_CONTEXT (context);
3504 retval = g_main_context_iterate (context, FALSE, FALSE, G_THREAD_SELF);
3505 UNLOCK_CONTEXT (context);
3511 * g_main_context_iteration:
3512 * @context: (allow-none): a #GMainContext (if %NULL, the default context will be used)
3513 * @may_block: whether the call may block.
3515 * Runs a single iteration for the given main loop. This involves
3516 * checking to see if any event sources are ready to be processed,
3517 * then if no events sources are ready and @may_block is %TRUE, waiting
3518 * for a source to become ready, then dispatching the highest priority
3519 * events sources that are ready. Otherwise, if @may_block is %FALSE
3520 * sources are not waited to become ready, only those highest priority
3521 * events sources will be dispatched (if any), that are ready at this
3522 * given moment without further waiting.
3524 * Note that even when @may_block is %TRUE, it is still possible for
3525 * g_main_context_iteration() to return %FALSE, since the wait may
3526 * be interrupted for other reasons than an event source becoming ready.
3528 * Return value: %TRUE if events were dispatched.
3531 g_main_context_iteration (GMainContext *context, gboolean may_block)
3536 context = g_main_context_default();
3538 LOCK_CONTEXT (context);
3539 retval = g_main_context_iterate (context, may_block, TRUE, G_THREAD_SELF);
3540 UNLOCK_CONTEXT (context);
3547 * @context: (allow-none): a #GMainContext (if %NULL, the default context will be used).
3548 * @is_running: set to %TRUE to indicate that the loop is running. This
3549 * is not very important since calling g_main_loop_run() will set this to
3552 * Creates a new #GMainLoop structure.
3554 * Return value: a new #GMainLoop.
3557 g_main_loop_new (GMainContext *context,
3558 gboolean is_running)
3563 context = g_main_context_default();
3565 g_main_context_ref (context);
3567 loop = g_new0 (GMainLoop, 1);
3568 loop->context = context;
3569 loop->is_running = is_running != FALSE;
3570 loop->ref_count = 1;
3577 * @loop: a #GMainLoop
3579 * Increases the reference count on a #GMainLoop object by one.
3581 * Return value: @loop
3584 g_main_loop_ref (GMainLoop *loop)
3586 g_return_val_if_fail (loop != NULL, NULL);
3587 g_return_val_if_fail (g_atomic_int_get (&loop->ref_count) > 0, NULL);
3589 g_atomic_int_inc (&loop->ref_count);
3595 * g_main_loop_unref:
3596 * @loop: a #GMainLoop
3598 * Decreases the reference count on a #GMainLoop object by one. If
3599 * the result is zero, free the loop and free all associated memory.
3602 g_main_loop_unref (GMainLoop *loop)
3604 g_return_if_fail (loop != NULL);
3605 g_return_if_fail (g_atomic_int_get (&loop->ref_count) > 0);
3607 if (!g_atomic_int_dec_and_test (&loop->ref_count))
3610 g_main_context_unref (loop->context);
3616 * @loop: a #GMainLoop
3618 * Runs a main loop until g_main_loop_quit() is called on the loop.
3619 * If this is called for the thread of the loop's #GMainContext,
3620 * it will process events from the loop, otherwise it will
3624 g_main_loop_run (GMainLoop *loop)
3626 GThread *self = G_THREAD_SELF;
3628 g_return_if_fail (loop != NULL);
3629 g_return_if_fail (g_atomic_int_get (&loop->ref_count) > 0);
3631 if (!g_main_context_acquire (loop->context))
3633 gboolean got_ownership = FALSE;
3635 /* Another thread owns this context */
3636 LOCK_CONTEXT (loop->context);
3638 g_atomic_int_inc (&loop->ref_count);
3640 if (!loop->is_running)
3641 loop->is_running = TRUE;
3643 while (loop->is_running && !got_ownership)
3644 got_ownership = g_main_context_wait (loop->context,
3645 &loop->context->cond,
3646 &loop->context->mutex);
3648 if (!loop->is_running)
3650 UNLOCK_CONTEXT (loop->context);
3652 g_main_context_release (loop->context);
3653 g_main_loop_unref (loop);
3657 g_assert (got_ownership);
3660 LOCK_CONTEXT (loop->context);
3662 if (loop->context->in_check_or_prepare)
3664 g_warning ("g_main_loop_run(): called recursively from within a source's "
3665 "check() or prepare() member, iteration not possible.");
3669 g_atomic_int_inc (&loop->ref_count);
3670 loop->is_running = TRUE;
3671 while (loop->is_running)
3672 g_main_context_iterate (loop->context, TRUE, TRUE, self);
3674 UNLOCK_CONTEXT (loop->context);
3676 g_main_context_release (loop->context);
3678 g_main_loop_unref (loop);
3683 * @loop: a #GMainLoop
3685 * Stops a #GMainLoop from running. Any calls to g_main_loop_run()
3686 * for the loop will return.
3688 * Note that sources that have already been dispatched when
3689 * g_main_loop_quit() is called will still be executed.
3692 g_main_loop_quit (GMainLoop *loop)
3694 g_return_if_fail (loop != NULL);
3695 g_return_if_fail (g_atomic_int_get (&loop->ref_count) > 0);
3697 LOCK_CONTEXT (loop->context);
3698 loop->is_running = FALSE;
3699 g_wakeup_signal (loop->context->wakeup);
3701 g_cond_broadcast (&loop->context->cond);
3703 UNLOCK_CONTEXT (loop->context);
3707 * g_main_loop_is_running:
3708 * @loop: a #GMainLoop.
3710 * Checks to see if the main loop is currently being run via g_main_loop_run().
3712 * Return value: %TRUE if the mainloop is currently being run.
3715 g_main_loop_is_running (GMainLoop *loop)
3717 g_return_val_if_fail (loop != NULL, FALSE);
3718 g_return_val_if_fail (g_atomic_int_get (&loop->ref_count) > 0, FALSE);
3720 return loop->is_running;
3724 * g_main_loop_get_context:
3725 * @loop: a #GMainLoop.
3727 * Returns the #GMainContext of @loop.
3729 * Return value: (transfer none): the #GMainContext of @loop
3732 g_main_loop_get_context (GMainLoop *loop)
3734 g_return_val_if_fail (loop != NULL, NULL);
3735 g_return_val_if_fail (g_atomic_int_get (&loop->ref_count) > 0, NULL);
3737 return loop->context;
3740 /* HOLDS: context's lock */
3742 g_main_context_poll (GMainContext *context,
3748 #ifdef G_MAIN_POLL_DEBUG
3754 GPollFunc poll_func;
3756 if (n_fds || timeout != 0)
3758 #ifdef G_MAIN_POLL_DEBUG
3759 if (_g_main_poll_debug)
3761 g_print ("polling context=%p n=%d timeout=%d\n",
3762 context, n_fds, timeout);
3763 poll_timer = g_timer_new ();
3767 LOCK_CONTEXT (context);
3769 poll_func = context->poll_func;
3771 UNLOCK_CONTEXT (context);
3772 if ((*poll_func) (fds, n_fds, timeout) < 0 && errno != EINTR)
3775 g_warning ("poll(2) failed due to: %s.",
3776 g_strerror (errno));
3778 /* If g_poll () returns -1, it has already called g_warning() */
3782 #ifdef G_MAIN_POLL_DEBUG
3783 if (_g_main_poll_debug)
3785 LOCK_CONTEXT (context);
3787 g_print ("g_main_poll(%d) timeout: %d - elapsed %12.10f seconds",
3790 g_timer_elapsed (poll_timer, NULL));
3791 g_timer_destroy (poll_timer);
3792 pollrec = context->poll_records;
3794 while (pollrec != NULL)
3799 if (fds[i].fd == pollrec->fd->fd &&
3800 pollrec->fd->events &&
3803 g_print (" [" G_POLLFD_FORMAT " :", fds[i].fd);
3804 if (fds[i].revents & G_IO_IN)
3806 if (fds[i].revents & G_IO_OUT)
3808 if (fds[i].revents & G_IO_PRI)
3810 if (fds[i].revents & G_IO_ERR)
3812 if (fds[i].revents & G_IO_HUP)
3814 if (fds[i].revents & G_IO_NVAL)
3820 pollrec = pollrec->next;
3824 UNLOCK_CONTEXT (context);
3827 } /* if (n_fds || timeout != 0) */
3831 * g_main_context_add_poll:
3832 * @context: (allow-none): a #GMainContext (or %NULL for the default context)
3833 * @fd: a #GPollFD structure holding information about a file
3834 * descriptor to watch.
3835 * @priority: the priority for this file descriptor which should be
3836 * the same as the priority used for g_source_attach() to ensure that the
3837 * file descriptor is polled whenever the results may be needed.
3839 * Adds a file descriptor to the set of file descriptors polled for
3840 * this context. This will very seldom be used directly. Instead
3841 * a typical event source will use g_source_add_poll() instead.
3844 g_main_context_add_poll (GMainContext *context,
3849 context = g_main_context_default ();
3851 g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
3852 g_return_if_fail (fd);
3854 LOCK_CONTEXT (context);
3855 g_main_context_add_poll_unlocked (context, priority, fd);
3856 UNLOCK_CONTEXT (context);
3859 /* HOLDS: main_loop_lock */
3861 g_main_context_add_poll_unlocked (GMainContext *context,
3865 GPollRec *prevrec, *nextrec;
3866 GPollRec *newrec = g_slice_new (GPollRec);
3868 /* This file descriptor may be checked before we ever poll */
3871 newrec->priority = priority;
3873 prevrec = context->poll_records_tail;
3875 while (prevrec && priority < prevrec->priority)
3878 prevrec = prevrec->prev;
3882 prevrec->next = newrec;
3884 context->poll_records = newrec;
3886 newrec->prev = prevrec;
3887 newrec->next = nextrec;
3890 nextrec->prev = newrec;
3892 context->poll_records_tail = newrec;
3894 context->n_poll_records++;
3896 context->poll_changed = TRUE;
3898 /* Now wake up the main loop if it is waiting in the poll() */
3899 g_wakeup_signal (context->wakeup);
3903 * g_main_context_remove_poll:
3904 * @context:a #GMainContext
3905 * @fd: a #GPollFD descriptor previously added with g_main_context_add_poll()
3907 * Removes file descriptor from the set of file descriptors to be
3908 * polled for a particular context.
3911 g_main_context_remove_poll (GMainContext *context,
3915 context = g_main_context_default ();
3917 g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
3918 g_return_if_fail (fd);
3920 LOCK_CONTEXT (context);
3921 g_main_context_remove_poll_unlocked (context, fd);
3922 UNLOCK_CONTEXT (context);
3926 g_main_context_remove_poll_unlocked (GMainContext *context,
3929 GPollRec *pollrec, *prevrec, *nextrec;
3932 pollrec = context->poll_records;
3936 nextrec = pollrec->next;
3937 if (pollrec->fd == fd)
3939 if (prevrec != NULL)
3940 prevrec->next = nextrec;
3942 context->poll_records = nextrec;
3944 if (nextrec != NULL)
3945 nextrec->prev = prevrec;
3947 context->poll_records_tail = prevrec;
3949 g_slice_free (GPollRec, pollrec);
3951 context->n_poll_records--;
3958 context->poll_changed = TRUE;
3960 /* Now wake up the main loop if it is waiting in the poll() */
3961 g_wakeup_signal (context->wakeup);
3965 * g_source_get_current_time:
3966 * @source: a #GSource
3967 * @timeval: #GTimeVal structure in which to store current time.
3969 * This function ignores @source and is otherwise the same as
3970 * g_get_current_time().
3972 * Deprecated: 2.28: use g_source_get_time() instead
3975 g_source_get_current_time (GSource *source,
3978 g_get_current_time (timeval);
3982 * g_source_get_time:
3983 * @source: a #GSource
3985 * Gets the time to be used when checking this source. The advantage of
3986 * calling this function over calling g_get_monotonic_time() directly is
3987 * that when checking multiple sources, GLib can cache a single value
3988 * instead of having to repeatedly get the system monotonic time.
3990 * The time here is the system monotonic time, if available, or some
3991 * other reasonable alternative otherwise. See g_get_monotonic_time().
3993 * Returns: the monotonic time in microseconds
3998 g_source_get_time (GSource *source)
4000 GMainContext *context;
4003 g_return_val_if_fail (source->context != NULL, 0);
4005 context = source->context;
4007 LOCK_CONTEXT (context);
4009 if (!context->time_is_fresh)
4011 context->time = g_get_monotonic_time ();
4012 context->time_is_fresh = TRUE;
4015 result = context->time;
4017 UNLOCK_CONTEXT (context);
4023 * g_main_context_set_poll_func:
4024 * @context: a #GMainContext
4025 * @func: the function to call to poll all file descriptors
4027 * Sets the function to use to handle polling of file descriptors. It
4028 * will be used instead of the poll() system call
4029 * (or GLib's replacement function, which is used where
4030 * poll() isn't available).
4032 * This function could possibly be used to integrate the GLib event
4033 * loop with an external event loop.
4036 g_main_context_set_poll_func (GMainContext *context,
4040 context = g_main_context_default ();
4042 g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
4044 LOCK_CONTEXT (context);
4047 context->poll_func = func;
4049 context->poll_func = g_poll;
4051 UNLOCK_CONTEXT (context);
4055 * g_main_context_get_poll_func:
4056 * @context: a #GMainContext
4058 * Gets the poll function set by g_main_context_set_poll_func().
4060 * Return value: the poll function
4063 g_main_context_get_poll_func (GMainContext *context)
4068 context = g_main_context_default ();
4070 g_return_val_if_fail (g_atomic_int_get (&context->ref_count) > 0, NULL);
4072 LOCK_CONTEXT (context);
4073 result = context->poll_func;
4074 UNLOCK_CONTEXT (context);
4080 * g_main_context_wakeup:
4081 * @context: a #GMainContext
4083 * If @context is currently waiting in a poll(), interrupt
4084 * the poll(), and continue the iteration process.
4087 g_main_context_wakeup (GMainContext *context)
4090 context = g_main_context_default ();
4092 g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
4094 g_wakeup_signal (context->wakeup);
4098 * g_main_context_is_owner:
4099 * @context: a #GMainContext
4101 * Determines whether this thread holds the (recursive)
4102 * ownership of this #GMainContext. This is useful to
4103 * know before waiting on another thread that may be
4104 * blocking to get ownership of @context.
4106 * Returns: %TRUE if current thread is owner of @context.
4111 g_main_context_is_owner (GMainContext *context)
4116 context = g_main_context_default ();
4118 LOCK_CONTEXT (context);
4119 is_owner = context->owner == G_THREAD_SELF;
4120 UNLOCK_CONTEXT (context);
4128 g_timeout_set_expiration (GTimeoutSource *timeout_source,
4129 gint64 current_time)
4133 expiration = current_time + (guint64) timeout_source->interval * 1000;
4135 if (timeout_source->seconds)
4138 static gint timer_perturb = -1;
4140 if (timer_perturb == -1)
4143 * we want a per machine/session unique 'random' value; try the dbus
4144 * address first, that has a UUID in it. If there is no dbus, use the
4145 * hostname for hashing.
4147 const char *session_bus_address = g_getenv ("DBUS_SESSION_BUS_ADDRESS");
4148 if (!session_bus_address)
4149 session_bus_address = g_getenv ("HOSTNAME");
4150 if (session_bus_address)
4151 timer_perturb = ABS ((gint) g_str_hash (session_bus_address)) % 1000000;
4156 /* We want the microseconds part of the timeout to land on the
4157 * 'timer_perturb' mark, but we need to make sure we don't try to
4158 * set the timeout in the past. We do this by ensuring that we
4159 * always only *increase* the expiration time by adding a full
4160 * second in the case that the microsecond portion decreases.
4162 expiration -= timer_perturb;
4164 remainder = expiration % 1000000;
4165 if (remainder >= 1000000/4)
4166 expiration += 1000000;
4168 expiration -= remainder;
4169 expiration += timer_perturb;
4172 g_source_set_ready_time ((GSource *) timeout_source, expiration);
4176 g_timeout_dispatch (GSource *source,
4177 GSourceFunc callback,
4180 GTimeoutSource *timeout_source = (GTimeoutSource *)source;
4185 g_warning ("Timeout source dispatched without callback\n"
4186 "You must call g_source_set_callback().");
4190 again = callback (user_data);
4193 g_timeout_set_expiration (timeout_source, g_source_get_time (source));
4199 * g_timeout_source_new:
4200 * @interval: the timeout interval in milliseconds.
4202 * Creates a new timeout source.
4204 * The source will not initially be associated with any #GMainContext
4205 * and must be added to one with g_source_attach() before it will be
4208 * The interval given is in terms of monotonic time, not wall clock
4209 * time. See g_get_monotonic_time().
4211 * Return value: the newly-created timeout source
4214 g_timeout_source_new (guint interval)
4216 GSource *source = g_source_new (&g_timeout_funcs, sizeof (GTimeoutSource));
4217 GTimeoutSource *timeout_source = (GTimeoutSource *)source;
4219 timeout_source->interval = interval;
4220 g_timeout_set_expiration (timeout_source, g_get_monotonic_time ());
4226 * g_timeout_source_new_seconds:
4227 * @interval: the timeout interval in seconds
4229 * Creates a new timeout source.
4231 * The source will not initially be associated with any #GMainContext
4232 * and must be added to one with g_source_attach() before it will be
4235 * The scheduling granularity/accuracy of this timeout source will be
4238 * The interval given in terms of monotonic time, not wall clock time.
4239 * See g_get_monotonic_time().
4241 * Return value: the newly-created timeout source
4246 g_timeout_source_new_seconds (guint interval)
4248 GSource *source = g_source_new (&g_timeout_funcs, sizeof (GTimeoutSource));
4249 GTimeoutSource *timeout_source = (GTimeoutSource *)source;
4251 timeout_source->interval = 1000 * interval;
4252 timeout_source->seconds = TRUE;
4254 g_timeout_set_expiration (timeout_source, g_get_monotonic_time ());
4261 * g_timeout_add_full:
4262 * @priority: the priority of the timeout source. Typically this will be in
4263 * the range between #G_PRIORITY_DEFAULT and #G_PRIORITY_HIGH.
4264 * @interval: the time between calls to the function, in milliseconds
4265 * (1/1000ths of a second)
4266 * @function: function to call
4267 * @data: data to pass to @function
4268 * @notify: (allow-none): function to call when the timeout is removed, or %NULL
4270 * Sets a function to be called at regular intervals, with the given
4271 * priority. The function is called repeatedly until it returns
4272 * %FALSE, at which point the timeout is automatically destroyed and
4273 * the function will not be called again. The @notify function is
4274 * called when the timeout is destroyed. The first call to the
4275 * function will be at the end of the first @interval.
4277 * Note that timeout functions may be delayed, due to the processing of other
4278 * event sources. Thus they should not be relied on for precise timing.
4279 * After each call to the timeout function, the time of the next
4280 * timeout is recalculated based on the current time and the given interval
4281 * (it does not try to 'catch up' time lost in delays).
4283 * This internally creates a main loop source using g_timeout_source_new()
4284 * and attaches it to the main loop context using g_source_attach(). You can
4285 * do these steps manually if you need greater control.
4287 * The interval given in terms of monotonic time, not wall clock time.
4288 * See g_get_monotonic_time().
4290 * Return value: the ID (greater than 0) of the event source.
4291 * Rename to: g_timeout_add
4294 g_timeout_add_full (gint priority,
4296 GSourceFunc function,
4298 GDestroyNotify notify)
4303 g_return_val_if_fail (function != NULL, 0);
4305 source = g_timeout_source_new (interval);
4307 if (priority != G_PRIORITY_DEFAULT)
4308 g_source_set_priority (source, priority);
4310 g_source_set_callback (source, function, data, notify);
4311 id = g_source_attach (source, NULL);
4312 g_source_unref (source);
4319 * @interval: the time between calls to the function, in milliseconds
4320 * (1/1000ths of a second)
4321 * @function: function to call
4322 * @data: data to pass to @function
4324 * Sets a function to be called at regular intervals, with the default
4325 * priority, #G_PRIORITY_DEFAULT. The function is called repeatedly
4326 * until it returns %FALSE, at which point the timeout is automatically
4327 * destroyed and the function will not be called again. The first call
4328 * to the function will be at the end of the first @interval.
4330 * Note that timeout functions may be delayed, due to the processing of other
4331 * event sources. Thus they should not be relied on for precise timing.
4332 * After each call to the timeout function, the time of the next
4333 * timeout is recalculated based on the current time and the given interval
4334 * (it does not try to 'catch up' time lost in delays).
4336 * If you want to have a timer in the "seconds" range and do not care
4337 * about the exact time of the first call of the timer, use the
4338 * g_timeout_add_seconds() function; this function allows for more
4339 * optimizations and more efficient system power usage.
4341 * This internally creates a main loop source using g_timeout_source_new()
4342 * and attaches it to the main loop context using g_source_attach(). You can
4343 * do these steps manually if you need greater control.
4345 * The interval given is in terms of monotonic time, not wall clock
4346 * time. See g_get_monotonic_time().
4348 * Return value: the ID (greater than 0) of the event source.
4351 g_timeout_add (guint32 interval,
4352 GSourceFunc function,
4355 return g_timeout_add_full (G_PRIORITY_DEFAULT,
4356 interval, function, data, NULL);
4360 * g_timeout_add_seconds_full:
4361 * @priority: the priority of the timeout source. Typically this will be in
4362 * the range between #G_PRIORITY_DEFAULT and #G_PRIORITY_HIGH.
4363 * @interval: the time between calls to the function, in seconds
4364 * @function: function to call
4365 * @data: data to pass to @function
4366 * @notify: (allow-none): function to call when the timeout is removed, or %NULL
4368 * Sets a function to be called at regular intervals, with @priority.
4369 * The function is called repeatedly until it returns %FALSE, at which
4370 * point the timeout is automatically destroyed and the function will
4371 * not be called again.
4373 * Unlike g_timeout_add(), this function operates at whole second granularity.
4374 * The initial starting point of the timer is determined by the implementation
4375 * and the implementation is expected to group multiple timers together so that
4376 * they fire all at the same time.
4377 * To allow this grouping, the @interval to the first timer is rounded
4378 * and can deviate up to one second from the specified interval.
4379 * Subsequent timer iterations will generally run at the specified interval.
4381 * Note that timeout functions may be delayed, due to the processing of other
4382 * event sources. Thus they should not be relied on for precise timing.
4383 * After each call to the timeout function, the time of the next
4384 * timeout is recalculated based on the current time and the given @interval
4386 * If you want timing more precise than whole seconds, use g_timeout_add()
4389 * The grouping of timers to fire at the same time results in a more power
4390 * and CPU efficient behavior so if your timer is in multiples of seconds
4391 * and you don't require the first timer exactly one second from now, the
4392 * use of g_timeout_add_seconds() is preferred over g_timeout_add().
4394 * This internally creates a main loop source using
4395 * g_timeout_source_new_seconds() and attaches it to the main loop context
4396 * using g_source_attach(). You can do these steps manually if you need
4399 * The interval given is in terms of monotonic time, not wall clock
4400 * time. See g_get_monotonic_time().
4402 * Return value: the ID (greater than 0) of the event source.
4404 * Rename to: g_timeout_add_seconds
4408 g_timeout_add_seconds_full (gint priority,
4410 GSourceFunc function,
4412 GDestroyNotify notify)
4417 g_return_val_if_fail (function != NULL, 0);
4419 source = g_timeout_source_new_seconds (interval);
4421 if (priority != G_PRIORITY_DEFAULT)
4422 g_source_set_priority (source, priority);
4424 g_source_set_callback (source, function, data, notify);
4425 id = g_source_attach (source, NULL);
4426 g_source_unref (source);
4432 * g_timeout_add_seconds:
4433 * @interval: the time between calls to the function, in seconds
4434 * @function: function to call
4435 * @data: data to pass to @function
4437 * Sets a function to be called at regular intervals with the default
4438 * priority, #G_PRIORITY_DEFAULT. The function is called repeatedly until
4439 * it returns %FALSE, at which point the timeout is automatically destroyed
4440 * and the function will not be called again.
4442 * This internally creates a main loop source using
4443 * g_timeout_source_new_seconds() and attaches it to the main loop context
4444 * using g_source_attach(). You can do these steps manually if you need
4445 * greater control. Also see g_timeout_add_seconds_full().
4447 * Note that the first call of the timer may not be precise for timeouts
4448 * of one second. If you need finer precision and have such a timeout,
4449 * you may want to use g_timeout_add() instead.
4451 * The interval given is in terms of monotonic time, not wall clock
4452 * time. See g_get_monotonic_time().
4454 * Return value: the ID (greater than 0) of the event source.
4459 g_timeout_add_seconds (guint interval,
4460 GSourceFunc function,
4463 g_return_val_if_fail (function != NULL, 0);
4465 return g_timeout_add_seconds_full (G_PRIORITY_DEFAULT, interval, function, data, NULL);
4468 /* Child watch functions */
4473 g_child_watch_prepare (GSource *source,
4481 g_child_watch_check (GSource *source)
4483 GChildWatchSource *child_watch_source;
4484 gboolean child_exited;
4486 child_watch_source = (GChildWatchSource *) source;
4488 child_exited = child_watch_source->poll.revents & G_IO_IN;
4495 * Note: We do _not_ check for the special value of STILL_ACTIVE
4496 * since we know that the process has exited and doing so runs into
4497 * problems if the child process "happens to return STILL_ACTIVE(259)"
4498 * as Microsoft's Platform SDK puts it.
4500 if (!GetExitCodeProcess (child_watch_source->pid, &child_status))
4502 gchar *emsg = g_win32_error_message (GetLastError ());
4503 g_warning (G_STRLOC ": GetExitCodeProcess() failed: %s", emsg);
4506 child_watch_source->child_status = -1;
4509 child_watch_source->child_status = child_status;
4512 return child_exited;
4516 g_child_watch_finalize (GSource *source)
4520 #else /* G_OS_WIN32 */
4523 wake_source (GSource *source)
4525 GMainContext *context;
4527 /* This should be thread-safe:
4529 * - if the source is currently being added to a context, that
4530 * context will be woken up anyway
4532 * - if the source is currently being destroyed, we simply need not
4535 * - the memory for the source will remain valid until after the
4536 * source finalize function was called (which would remove the
4537 * source from the global list which we are currently holding the
4540 * - the GMainContext will either be NULL or point to a live
4543 * - the GMainContext will remain valid since we hold the
4544 * main_context_list lock
4546 * Since we are holding a lot of locks here, don't try to enter any
4547 * more GMainContext functions for fear of dealock -- just hit the
4548 * GWakeup and run. Even if that's safe now, it could easily become
4549 * unsafe with some very minor changes in the future, and signal
4550 * handling is not the most well-tested codepath.
4552 G_LOCK(main_context_list);
4553 context = source->context;
4555 g_wakeup_signal (context->wakeup);
4556 G_UNLOCK(main_context_list);
4560 dispatch_unix_signals (void)
4564 /* clear this first incase another one arrives while we're processing */
4565 any_unix_signal_pending = FALSE;
4567 G_LOCK(unix_signal_lock);
4569 /* handle GChildWatchSource instances */
4570 if (unix_signal_pending[SIGCHLD])
4572 unix_signal_pending[SIGCHLD] = FALSE;
4574 /* The only way we can do this is to scan all of the children.
4576 * The docs promise that we will not reap children that we are not
4577 * explicitly watching, so that ties our hands from calling
4578 * waitpid(-1). We also can't use siginfo's si_pid field since if
4579 * multiple SIGCHLD arrive at the same time, one of them can be
4580 * dropped (since a given UNIX signal can only be pending once).
4582 for (node = unix_child_watches; node; node = node->next)
4584 GChildWatchSource *source = node->data;
4586 if (!source->child_exited)
4591 pid = waitpid (source->pid, &source->child_status, WNOHANG);
4594 source->child_exited = TRUE;
4595 wake_source ((GSource *) source);
4597 else if (pid == -1 && errno == ECHILD)
4599 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.");
4600 source->child_exited = TRUE;
4601 source->child_status = 0;
4602 wake_source ((GSource *) source);
4605 while (pid == -1 && errno == EINTR);
4610 /* handle GUnixSignalWatchSource instances */
4611 for (node = unix_signal_watches; node; node = node->next)
4613 GUnixSignalWatchSource *source = node->data;
4615 if (!source->pending)
4617 if (unix_signal_pending[source->signum])
4619 unix_signal_pending[source->signum] = FALSE;
4620 source->pending = TRUE;
4622 wake_source ((GSource *) source);
4627 G_UNLOCK(unix_signal_lock);
4631 g_child_watch_prepare (GSource *source,
4634 GChildWatchSource *child_watch_source;
4636 child_watch_source = (GChildWatchSource *) source;
4638 return child_watch_source->child_exited;
4642 g_child_watch_check (GSource *source)
4644 GChildWatchSource *child_watch_source;
4646 child_watch_source = (GChildWatchSource *) source;
4648 return child_watch_source->child_exited;
4652 g_unix_signal_watch_prepare (GSource *source,
4655 GUnixSignalWatchSource *unix_signal_source;
4657 unix_signal_source = (GUnixSignalWatchSource *) source;
4659 return unix_signal_source->pending;
4663 g_unix_signal_watch_check (GSource *source)
4665 GUnixSignalWatchSource *unix_signal_source;
4667 unix_signal_source = (GUnixSignalWatchSource *) source;
4669 return unix_signal_source->pending;
4673 g_unix_signal_watch_dispatch (GSource *source,
4674 GSourceFunc callback,
4677 GUnixSignalWatchSource *unix_signal_source;
4680 unix_signal_source = (GUnixSignalWatchSource *) source;
4684 g_warning ("Unix signal source dispatched without callback\n"
4685 "You must call g_source_set_callback().");
4689 again = (callback) (user_data);
4691 unix_signal_source->pending = FALSE;
4697 ensure_unix_signal_handler_installed_unlocked (int signum)
4699 static sigset_t installed_signal_mask;
4700 static gboolean initialized;
4701 struct sigaction action;
4705 sigemptyset (&installed_signal_mask);
4706 g_get_worker_context ();
4710 if (sigismember (&installed_signal_mask, signum))
4713 sigaddset (&installed_signal_mask, signum);
4715 action.sa_handler = g_unix_signal_handler;
4716 sigemptyset (&action.sa_mask);
4717 action.sa_flags = SA_RESTART | SA_NOCLDSTOP;
4718 sigaction (signum, &action, NULL);
4722 _g_main_create_unix_signal_watch (int signum)
4725 GUnixSignalWatchSource *unix_signal_source;
4727 source = g_source_new (&g_unix_signal_funcs, sizeof (GUnixSignalWatchSource));
4728 unix_signal_source = (GUnixSignalWatchSource *) source;
4730 unix_signal_source->signum = signum;
4731 unix_signal_source->pending = FALSE;
4733 G_LOCK (unix_signal_lock);
4734 ensure_unix_signal_handler_installed_unlocked (signum);
4735 unix_signal_watches = g_slist_prepend (unix_signal_watches, unix_signal_source);
4736 if (unix_signal_pending[signum])
4737 unix_signal_source->pending = TRUE;
4738 unix_signal_pending[signum] = FALSE;
4739 G_UNLOCK (unix_signal_lock);
4745 g_unix_signal_watch_finalize (GSource *source)
4747 G_LOCK (unix_signal_lock);
4748 unix_signal_watches = g_slist_remove (unix_signal_watches, source);
4749 G_UNLOCK (unix_signal_lock);
4753 g_child_watch_finalize (GSource *source)
4755 G_LOCK (unix_signal_lock);
4756 unix_child_watches = g_slist_remove (unix_child_watches, source);
4757 G_UNLOCK (unix_signal_lock);
4760 #endif /* G_OS_WIN32 */
4763 g_child_watch_dispatch (GSource *source,
4764 GSourceFunc callback,
4767 GChildWatchSource *child_watch_source;
4768 GChildWatchFunc child_watch_callback = (GChildWatchFunc) callback;
4770 child_watch_source = (GChildWatchSource *) source;
4774 g_warning ("Child watch source dispatched without callback\n"
4775 "You must call g_source_set_callback().");
4779 (child_watch_callback) (child_watch_source->pid, child_watch_source->child_status, user_data);
4781 /* We never keep a child watch source around as the child is gone */
4788 g_unix_signal_handler (int signum)
4790 unix_signal_pending[signum] = TRUE;
4791 any_unix_signal_pending = TRUE;
4793 g_wakeup_signal (glib_worker_context->wakeup);
4796 #endif /* !G_OS_WIN32 */
4799 * g_child_watch_source_new:
4800 * @pid: process to watch. On POSIX the pid of a child process. On
4801 * Windows a handle for a process (which doesn't have to be a child).
4803 * Creates a new child_watch source.
4805 * The source will not initially be associated with any #GMainContext
4806 * and must be added to one with g_source_attach() before it will be
4809 * Note that child watch sources can only be used in conjunction with
4810 * <literal>g_spawn...</literal> when the %G_SPAWN_DO_NOT_REAP_CHILD
4813 * Note that on platforms where #GPid must be explicitly closed
4814 * (see g_spawn_close_pid()) @pid must not be closed while the
4815 * source is still active. Typically, you will want to call
4816 * g_spawn_close_pid() in the callback function for the source.
4818 * Note further that using g_child_watch_source_new() is not
4819 * compatible with calling <literal>waitpid</literal> with a
4820 * nonpositive first argument in the application. Calling waitpid()
4821 * for individual pids will still work fine.
4823 * Return value: the newly-created child watch source
4828 g_child_watch_source_new (GPid pid)
4830 GSource *source = g_source_new (&g_child_watch_funcs, sizeof (GChildWatchSource));
4831 GChildWatchSource *child_watch_source = (GChildWatchSource *)source;
4833 child_watch_source->pid = pid;
4836 child_watch_source->poll.fd = (gintptr) pid;
4837 child_watch_source->poll.events = G_IO_IN;
4839 g_source_add_poll (source, &child_watch_source->poll);
4840 #else /* G_OS_WIN32 */
4841 G_LOCK (unix_signal_lock);
4842 ensure_unix_signal_handler_installed_unlocked (SIGCHLD);
4843 unix_child_watches = g_slist_prepend (unix_child_watches, child_watch_source);
4844 if (waitpid (pid, &child_watch_source->child_status, WNOHANG) > 0)
4845 child_watch_source->child_exited = TRUE;
4846 G_UNLOCK (unix_signal_lock);
4847 #endif /* G_OS_WIN32 */
4853 * g_child_watch_add_full:
4854 * @priority: the priority of the idle source. Typically this will be in the
4855 * range between #G_PRIORITY_DEFAULT_IDLE and #G_PRIORITY_HIGH_IDLE.
4856 * @pid: process to watch. On POSIX the pid of a child process. On
4857 * Windows a handle for a process (which doesn't have to be a child).
4858 * @function: function to call
4859 * @data: data to pass to @function
4860 * @notify: (allow-none): function to call when the idle is removed, or %NULL
4862 * Sets a function to be called when the child indicated by @pid
4863 * exits, at the priority @priority.
4865 * If you obtain @pid from g_spawn_async() or g_spawn_async_with_pipes()
4866 * you will need to pass #G_SPAWN_DO_NOT_REAP_CHILD as flag to
4867 * the spawn function for the child watching to work.
4869 * In many programs, you will want to call g_spawn_check_exit_status()
4870 * in the callback to determine whether or not the child exited
4873 * Also, note that on platforms where #GPid must be explicitly closed
4874 * (see g_spawn_close_pid()) @pid must not be closed while the source
4875 * is still active. Typically, you should invoke g_spawn_close_pid()
4876 * in the callback function for the source.
4878 * GLib supports only a single callback per process id.
4880 * This internally creates a main loop source using
4881 * g_child_watch_source_new() and attaches it to the main loop context
4882 * using g_source_attach(). You can do these steps manually if you
4883 * need greater control.
4885 * Return value: the ID (greater than 0) of the event source.
4887 * Rename to: g_child_watch_add
4891 g_child_watch_add_full (gint priority,
4893 GChildWatchFunc function,
4895 GDestroyNotify notify)
4900 g_return_val_if_fail (function != NULL, 0);
4902 source = g_child_watch_source_new (pid);
4904 if (priority != G_PRIORITY_DEFAULT)
4905 g_source_set_priority (source, priority);
4907 g_source_set_callback (source, (GSourceFunc) function, data, notify);
4908 id = g_source_attach (source, NULL);
4909 g_source_unref (source);
4915 * g_child_watch_add:
4916 * @pid: process id to watch. On POSIX the pid of a child process. On
4917 * Windows a handle for a process (which doesn't have to be a child).
4918 * @function: function to call
4919 * @data: data to pass to @function
4921 * Sets a function to be called when the child indicated by @pid
4922 * exits, at a default priority, #G_PRIORITY_DEFAULT.
4924 * If you obtain @pid from g_spawn_async() or g_spawn_async_with_pipes()
4925 * you will need to pass #G_SPAWN_DO_NOT_REAP_CHILD as flag to
4926 * the spawn function for the child watching to work.
4928 * Note that on platforms where #GPid must be explicitly closed
4929 * (see g_spawn_close_pid()) @pid must not be closed while the
4930 * source is still active. Typically, you will want to call
4931 * g_spawn_close_pid() in the callback function for the source.
4933 * GLib supports only a single callback per process id.
4935 * This internally creates a main loop source using
4936 * g_child_watch_source_new() and attaches it to the main loop context
4937 * using g_source_attach(). You can do these steps manually if you
4938 * need greater control.
4940 * Return value: the ID (greater than 0) of the event source.
4945 g_child_watch_add (GPid pid,
4946 GChildWatchFunc function,
4949 return g_child_watch_add_full (G_PRIORITY_DEFAULT, pid, function, data, NULL);
4953 /* Idle functions */
4956 g_idle_prepare (GSource *source,
4965 g_idle_check (GSource *source)
4971 g_idle_dispatch (GSource *source,
4972 GSourceFunc callback,
4977 g_warning ("Idle source dispatched without callback\n"
4978 "You must call g_source_set_callback().");
4982 return callback (user_data);
4986 * g_idle_source_new:
4988 * Creates a new idle source.
4990 * The source will not initially be associated with any #GMainContext
4991 * and must be added to one with g_source_attach() before it will be
4992 * executed. Note that the default priority for idle sources is
4993 * %G_PRIORITY_DEFAULT_IDLE, as compared to other sources which
4994 * have a default priority of %G_PRIORITY_DEFAULT.
4996 * Return value: the newly-created idle source
4999 g_idle_source_new (void)
5003 source = g_source_new (&g_idle_funcs, sizeof (GSource));
5004 g_source_set_priority (source, G_PRIORITY_DEFAULT_IDLE);
5011 * @priority: the priority of the idle source. Typically this will be in the
5012 * range between #G_PRIORITY_DEFAULT_IDLE and #G_PRIORITY_HIGH_IDLE.
5013 * @function: function to call
5014 * @data: data to pass to @function
5015 * @notify: (allow-none): function to call when the idle is removed, or %NULL
5017 * Adds a function to be called whenever there are no higher priority
5018 * events pending. If the function returns %FALSE it is automatically
5019 * removed from the list of event sources and will not be called again.
5021 * This internally creates a main loop source using g_idle_source_new()
5022 * and attaches it to the main loop context using g_source_attach().
5023 * You can do these steps manually if you need greater control.
5025 * Return value: the ID (greater than 0) of the event source.
5026 * Rename to: g_idle_add
5029 g_idle_add_full (gint priority,
5030 GSourceFunc function,
5032 GDestroyNotify notify)
5037 g_return_val_if_fail (function != NULL, 0);
5039 source = g_idle_source_new ();
5041 if (priority != G_PRIORITY_DEFAULT_IDLE)
5042 g_source_set_priority (source, priority);
5044 g_source_set_callback (source, function, data, notify);
5045 id = g_source_attach (source, NULL);
5046 g_source_unref (source);
5053 * @function: function to call
5054 * @data: data to pass to @function.
5056 * Adds a function to be called whenever there are no higher priority
5057 * events pending to the default main loop. The function is given the
5058 * default idle priority, #G_PRIORITY_DEFAULT_IDLE. If the function
5059 * returns %FALSE it is automatically removed from the list of event
5060 * sources and will not be called again.
5062 * This internally creates a main loop source using g_idle_source_new()
5063 * and attaches it to the main loop context using g_source_attach().
5064 * You can do these steps manually if you need greater control.
5066 * Return value: the ID (greater than 0) of the event source.
5069 g_idle_add (GSourceFunc function,
5072 return g_idle_add_full (G_PRIORITY_DEFAULT_IDLE, function, data, NULL);
5076 * g_idle_remove_by_data:
5077 * @data: the data for the idle source's callback.
5079 * Removes the idle function with the given data.
5081 * Return value: %TRUE if an idle source was found and removed.
5084 g_idle_remove_by_data (gpointer data)
5086 return g_source_remove_by_funcs_user_data (&g_idle_funcs, data);
5090 * g_main_context_invoke:
5091 * @context: (allow-none): a #GMainContext, or %NULL
5092 * @function: function to call
5093 * @data: data to pass to @function
5095 * Invokes a function in such a way that @context is owned during the
5096 * invocation of @function.
5098 * If @context is %NULL then the global default main context — as
5099 * returned by g_main_context_default() — is used.
5101 * If @context is owned by the current thread, @function is called
5102 * directly. Otherwise, if @context is the thread-default main context
5103 * of the current thread and g_main_context_acquire() succeeds, then
5104 * @function is called and g_main_context_release() is called
5107 * In any other case, an idle source is created to call @function and
5108 * that source is attached to @context (presumably to be run in another
5109 * thread). The idle source is attached with #G_PRIORITY_DEFAULT
5110 * priority. If you want a different priority, use
5111 * g_main_context_invoke_full().
5113 * Note that, as with normal idle functions, @function should probably
5114 * return %FALSE. If it returns %TRUE, it will be continuously run in a
5115 * loop (and may prevent this call from returning).
5120 g_main_context_invoke (GMainContext *context,
5121 GSourceFunc function,
5124 g_main_context_invoke_full (context,
5126 function, data, NULL);
5130 * g_main_context_invoke_full:
5131 * @context: (allow-none): a #GMainContext, or %NULL
5132 * @priority: the priority at which to run @function
5133 * @function: function to call
5134 * @data: data to pass to @function
5135 * @notify: (allow-none): a function to call when @data is no longer in use, or %NULL.
5137 * Invokes a function in such a way that @context is owned during the
5138 * invocation of @function.
5140 * This function is the same as g_main_context_invoke() except that it
5141 * lets you specify the priority incase @function ends up being
5142 * scheduled as an idle and also lets you give a #GDestroyNotify for @data.
5144 * @notify should not assume that it is called from any particular
5145 * thread or with any particular context acquired.
5150 g_main_context_invoke_full (GMainContext *context,
5152 GSourceFunc function,
5154 GDestroyNotify notify)
5156 g_return_if_fail (function != NULL);
5159 context = g_main_context_default ();
5161 if (g_main_context_is_owner (context))
5163 while (function (data));
5170 GMainContext *thread_default;
5172 thread_default = g_main_context_get_thread_default ();
5174 if (!thread_default)
5175 thread_default = g_main_context_default ();
5177 if (thread_default == context && g_main_context_acquire (context))
5179 while (function (data));
5181 g_main_context_release (context);
5190 source = g_idle_source_new ();
5191 g_source_set_priority (source, priority);
5192 g_source_set_callback (source, function, data, notify);
5193 g_source_attach (source, context);
5194 g_source_unref (source);
5200 glib_worker_main (gpointer data)
5204 g_main_context_iteration (glib_worker_context, TRUE);
5207 if (any_unix_signal_pending)
5208 dispatch_unix_signals ();
5212 return NULL; /* worst GCC warning message ever... */
5216 g_get_worker_context (void)
5218 static gsize initialised;
5220 if (g_once_init_enter (&initialised))
5222 /* mask all signals in the worker thread */
5228 pthread_sigmask (SIG_SETMASK, &all, &prev_mask);
5230 glib_worker_context = g_main_context_new ();
5231 g_thread_new ("gmain", glib_worker_main, NULL);
5233 pthread_sigmask (SIG_SETMASK, &prev_mask, NULL);
5235 g_once_init_leave (&initialised, TRUE);
5238 return glib_worker_context;