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.1 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, see <http://www.gnu.org/licenses/>.
22 * Modified by the GLib Team and others 1997-2000. See the AUTHORS
23 * file for a list of people on the GLib Team. See the ChangeLog
24 * files for a list of changes. These files are distributed with
25 * GLib at ftp://ftp.gtk.org/pub/gtk/.
33 #include "glibconfig.h"
34 #include "glib_trace.h"
36 /* Uncomment the next line (and the corresponding line in gpoll.c) to
37 * enable debugging printouts if the environment variable
38 * G_MAIN_POLL_DEBUG is set to some value.
40 /* #define G_MAIN_POLL_DEBUG */
43 /* Always enable debugging printout on Windows, as it is more often
46 #define G_MAIN_POLL_DEBUG
50 #include "glib-unix.h"
53 #include <sys/eventfd.h>
58 #include <sys/types.h>
61 #ifdef HAVE_SYS_TIME_H
63 #endif /* HAVE_SYS_TIME_H */
66 #endif /* G_OS_UNIX */
73 #endif /* G_OS_WIN32 */
75 #ifdef HAVE_MACH_MACH_TIME_H
76 #include <mach/mach_time.h>
79 #include "glib_trace.h"
84 #include "giochannel.h"
88 #include "gstrfuncs.h"
89 #include "gtestutils.h"
90 #include "gthreadprivate.h"
91 #include "gtrace-private.h"
97 #ifdef G_MAIN_POLL_DEBUG
102 #include "gmain-internal.h"
103 #include "glib-init.h"
104 #include "glib-private.h"
108 * @title: The Main Event Loop
109 * @short_description: manages all available sources of events
111 * The main event loop manages all the available sources of events for
112 * GLib and GTK+ applications. These events can come from any number of
113 * different types of sources such as file descriptors (plain files,
114 * pipes or sockets) and timeouts. New types of event sources can also
115 * be added using g_source_attach().
117 * To allow multiple independent sets of sources to be handled in
118 * different threads, each source is associated with a #GMainContext.
119 * A #GMainContext can only be running in a single thread, but
120 * sources can be added to it and removed from it from other threads. All
121 * functions which operate on a #GMainContext or a built-in #GSource are
124 * Each event source is assigned a priority. The default priority,
125 * #G_PRIORITY_DEFAULT, is 0. Values less than 0 denote higher priorities.
126 * Values greater than 0 denote lower priorities. Events from high priority
127 * sources are always processed before events from lower priority sources.
129 * Idle functions can also be added, and assigned a priority. These will
130 * be run whenever no events with a higher priority are ready to be processed.
132 * The #GMainLoop data type represents a main event loop. A GMainLoop is
133 * created with g_main_loop_new(). After adding the initial event sources,
134 * g_main_loop_run() is called. This continuously checks for new events from
135 * each of the event sources and dispatches them. Finally, the processing of
136 * an event from one of the sources leads to a call to g_main_loop_quit() to
137 * exit the main loop, and g_main_loop_run() returns.
139 * It is possible to create new instances of #GMainLoop recursively.
140 * This is often used in GTK+ applications when showing modal dialog
141 * boxes. Note that event sources are associated with a particular
142 * #GMainContext, and will be checked and dispatched for all main
143 * loops associated with that GMainContext.
145 * GTK+ contains wrappers of some of these functions, e.g. gtk_main(),
146 * gtk_main_quit() and gtk_events_pending().
148 * ## Creating new source types
150 * One of the unusual features of the #GMainLoop functionality
151 * is that new types of event source can be created and used in
152 * addition to the builtin type of event source. A new event source
153 * type is used for handling GDK events. A new source type is created
154 * by "deriving" from the #GSource structure. The derived type of
155 * source is represented by a structure that has the #GSource structure
156 * as a first element, and other elements specific to the new source
157 * type. To create an instance of the new source type, call
158 * g_source_new() passing in the size of the derived structure and
159 * a table of functions. These #GSourceFuncs determine the behavior of
160 * the new source type.
162 * New source types basically interact with the main context
163 * in two ways. Their prepare function in #GSourceFuncs can set a timeout
164 * to determine the maximum amount of time that the main loop will sleep
165 * before checking the source again. In addition, or as well, the source
166 * can add file descriptors to the set that the main context checks using
167 * g_source_add_poll().
169 * ## Customizing the main loop iteration
171 * Single iterations of a #GMainContext can be run with
172 * g_main_context_iteration(). In some cases, more detailed control
173 * of exactly how the details of the main loop work is desired, for
174 * instance, when integrating the #GMainLoop with an external main loop.
175 * In such cases, you can call the component functions of
176 * g_main_context_iteration() directly. These functions are
177 * g_main_context_prepare(), g_main_context_query(),
178 * g_main_context_check() and g_main_context_dispatch().
180 * ## State of a Main Context # {#mainloop-states}
182 * The operation of these functions can best be seen in terms
183 * of a state diagram, as shown in this image.
185 * ![](mainloop-states.gif)
187 * On UNIX, the GLib mainloop is incompatible with fork(). Any program
188 * using the mainloop must either exec() or exit() from the child
189 * without returning to the mainloop.
191 * ## Memory management of sources # {#mainloop-memory-management}
193 * There are two options for memory management of the user data passed to a
194 * #GSource to be passed to its callback on invocation. This data is provided
195 * in calls to g_timeout_add(), g_timeout_add_full(), g_idle_add(), etc. and
196 * more generally, using g_source_set_callback(). This data is typically an
197 * object which ‘owns’ the timeout or idle callback, such as a widget or a
198 * network protocol implementation. In many cases, it is an error for the
199 * callback to be invoked after this owning object has been destroyed, as that
200 * results in use of freed memory.
202 * The first, and preferred, option is to store the source ID returned by
203 * functions such as g_timeout_add() or g_source_attach(), and explicitly
204 * remove that source from the main context using g_source_remove() when the
205 * owning object is finalized. This ensures that the callback can only be
206 * invoked while the object is still alive.
208 * The second option is to hold a strong reference to the object in the
209 * callback, and to release it in the callback’s #GDestroyNotify. This ensures
210 * that the object is kept alive until after the source is finalized, which is
211 * guaranteed to be after it is invoked for the final time. The #GDestroyNotify
212 * is another callback passed to the ‘full’ variants of #GSource functions (for
213 * example, g_timeout_add_full()). It is called when the source is finalized,
214 * and is designed for releasing references like this.
216 * One important caveat of this second approach is that it will keep the object
217 * alive indefinitely if the main loop is stopped before the #GSource is
218 * invoked, which may be undesirable.
223 typedef struct _GTimeoutSource GTimeoutSource;
224 typedef struct _GChildWatchSource GChildWatchSource;
225 typedef struct _GUnixSignalWatchSource GUnixSignalWatchSource;
226 typedef struct _GPollRec GPollRec;
227 typedef struct _GSourceCallback GSourceCallback;
231 G_SOURCE_READY = 1 << G_HOOK_FLAG_USER_SHIFT,
232 G_SOURCE_CAN_RECURSE = 1 << (G_HOOK_FLAG_USER_SHIFT + 1),
233 G_SOURCE_BLOCKED = 1 << (G_HOOK_FLAG_USER_SHIFT + 2)
236 typedef struct _GSourceList GSourceList;
240 GSource *head, *tail;
244 typedef struct _GMainWaiter GMainWaiter;
252 typedef struct _GMainDispatch GMainDispatch;
254 struct _GMainDispatch
260 #ifdef G_MAIN_POLL_DEBUG
261 gboolean _g_main_poll_debug = FALSE;
266 /* The following lock is used for both the list of sources
267 * and the list of poll records
275 gint ref_count; /* (atomic) */
277 GHashTable *sources; /* guint -> GSource */
279 GPtrArray *pending_dispatches;
280 gint timeout; /* Timeout for current iteration */
284 gint in_check_or_prepare;
286 GPollRec *poll_records;
287 guint n_poll_records;
288 GPollFD *cached_poll_array;
289 guint cached_poll_array_size;
295 /* Flag indicating whether the set of fd's changed during a poll */
296 gboolean poll_changed;
301 gboolean time_is_fresh;
304 struct _GSourceCallback
306 gint ref_count; /* (atomic) */
309 GDestroyNotify notify;
314 GMainContext *context;
315 gboolean is_running; /* (atomic) */
316 gint ref_count; /* (atomic) */
319 struct _GTimeoutSource
322 /* Measured in seconds if 'seconds' is TRUE, or milliseconds otherwise. */
327 struct _GChildWatchSource
334 #else /* G_OS_WIN32 */
335 gboolean child_exited; /* (atomic) */
336 #endif /* G_OS_WIN32 */
339 struct _GUnixSignalWatchSource
343 gboolean pending; /* (atomic) */
354 struct _GSourcePrivate
356 GSList *child_sources;
357 GSource *parent_source;
361 /* This is currently only used on UNIX, but we always declare it (and
362 * let it remain empty on Windows) to avoid #ifdef all over the place.
366 GSourceDisposeFunc dispose;
369 typedef struct _GSourceIter
371 GMainContext *context;
377 #define LOCK_CONTEXT(context) g_mutex_lock (&context->mutex)
378 #define UNLOCK_CONTEXT(context) g_mutex_unlock (&context->mutex)
379 #define G_THREAD_SELF g_thread_self ()
381 #define SOURCE_DESTROYED(source) (((source)->flags & G_HOOK_FLAG_ACTIVE) == 0)
382 #define SOURCE_BLOCKED(source) (((source)->flags & G_SOURCE_BLOCKED) != 0)
384 /* Forward declarations */
386 static void g_source_unref_internal (GSource *source,
387 GMainContext *context,
389 static void g_source_destroy_internal (GSource *source,
390 GMainContext *context,
392 static void g_source_set_priority_unlocked (GSource *source,
393 GMainContext *context,
395 static void g_child_source_remove_internal (GSource *child_source,
396 GMainContext *context);
398 static void g_main_context_poll (GMainContext *context,
403 static void g_main_context_add_poll_unlocked (GMainContext *context,
406 static void g_main_context_remove_poll_unlocked (GMainContext *context,
409 static void g_source_iter_init (GSourceIter *iter,
410 GMainContext *context,
411 gboolean may_modify);
412 static gboolean g_source_iter_next (GSourceIter *iter,
414 static void g_source_iter_clear (GSourceIter *iter);
416 static gboolean g_timeout_dispatch (GSource *source,
417 GSourceFunc callback,
419 static gboolean g_child_watch_prepare (GSource *source,
421 static gboolean g_child_watch_check (GSource *source);
422 static gboolean g_child_watch_dispatch (GSource *source,
423 GSourceFunc callback,
425 static void g_child_watch_finalize (GSource *source);
427 static void g_unix_signal_handler (int signum);
428 static gboolean g_unix_signal_watch_prepare (GSource *source,
430 static gboolean g_unix_signal_watch_check (GSource *source);
431 static gboolean g_unix_signal_watch_dispatch (GSource *source,
432 GSourceFunc callback,
434 static void g_unix_signal_watch_finalize (GSource *source);
436 static gboolean g_idle_prepare (GSource *source,
438 static gboolean g_idle_check (GSource *source);
439 static gboolean g_idle_dispatch (GSource *source,
440 GSourceFunc callback,
443 static void block_source (GSource *source);
445 static GMainContext *glib_worker_context;
450 /* UNIX signals work by marking one of these variables then waking the
451 * worker context to check on them and dispatch accordingly.
453 * Both variables must be accessed using atomic primitives, unless those atomic
454 * primitives are implemented using fallback mutexes (as those aren’t safe in
455 * an interrupt context).
457 * If using atomic primitives, the variables must be of type `int` (so they’re
458 * the right size for the atomic primitives). Otherwise, use `sig_atomic_t` if
459 * it’s available, which is guaranteed to be async-signal-safe (but it’s *not*
460 * guaranteed to be thread-safe, which is why we use atomic primitives if
463 * Typically, `sig_atomic_t` is a typedef to `int`, but that’s not the case on
464 * FreeBSD, so we can’t use it unconditionally if it’s defined.
466 #if (defined(G_ATOMIC_LOCK_FREE) && defined(__GCC_HAVE_SYNC_COMPARE_AND_SWAP_4)) || !defined(HAVE_SIG_ATOMIC_T)
467 static volatile int unix_signal_pending[NSIG];
468 static volatile int any_unix_signal_pending;
470 static volatile sig_atomic_t unix_signal_pending[NSIG];
471 static volatile sig_atomic_t any_unix_signal_pending;
474 /* Guards all the data below */
475 G_LOCK_DEFINE_STATIC (unix_signal_lock);
476 static guint unix_signal_refcount[NSIG];
477 static GSList *unix_signal_watches;
478 static GSList *unix_child_watches;
480 GSourceFuncs g_unix_signal_funcs =
482 g_unix_signal_watch_prepare,
483 g_unix_signal_watch_check,
484 g_unix_signal_watch_dispatch,
485 g_unix_signal_watch_finalize,
488 #endif /* !G_OS_WIN32 */
489 G_LOCK_DEFINE_STATIC (main_context_list);
490 static GSList *main_context_list = NULL;
492 GSourceFuncs g_timeout_funcs =
500 GSourceFuncs g_child_watch_funcs =
502 g_child_watch_prepare,
504 g_child_watch_dispatch,
505 g_child_watch_finalize,
509 GSourceFuncs g_idle_funcs =
518 * g_main_context_ref:
519 * @context: a #GMainContext
521 * Increases the reference count on a #GMainContext object by one.
523 * Returns: the @context that was passed in (since 2.6)
526 g_main_context_ref (GMainContext *context)
528 g_return_val_if_fail (context != NULL, NULL);
529 g_return_val_if_fail (g_atomic_int_get (&context->ref_count) > 0, NULL);
531 g_atomic_int_inc (&context->ref_count);
537 poll_rec_list_free (GMainContext *context,
540 g_slice_free_chain (GPollRec, list, next);
544 * g_main_context_unref:
545 * @context: a #GMainContext
547 * Decreases the reference count on a #GMainContext object by one. If
548 * the result is zero, free the context and free all associated memory.
551 g_main_context_unref (GMainContext *context)
556 GSList *s_iter, *remaining_sources = NULL;
560 g_return_if_fail (context != NULL);
561 g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
563 if (!g_atomic_int_dec_and_test (&context->ref_count))
566 G_LOCK (main_context_list);
567 main_context_list = g_slist_remove (main_context_list, context);
568 G_UNLOCK (main_context_list);
570 /* Free pending dispatches */
571 for (i = 0; i < context->pending_dispatches->len; i++)
572 g_source_unref_internal (context->pending_dispatches->pdata[i], context, FALSE);
574 /* g_source_iter_next() assumes the context is locked. */
575 LOCK_CONTEXT (context);
577 /* First collect all remaining sources from the sources lists and store a
578 * new reference in a separate list. Also set the context of the sources
579 * to NULL so that they can't access a partially destroyed context anymore.
581 * We have to do this first so that we have a strong reference to all
582 * sources and destroying them below does not also free them, and so that
583 * none of the sources can access the context from their finalize/dispose
585 g_source_iter_init (&iter, context, FALSE);
586 while (g_source_iter_next (&iter, &source))
588 source->context = NULL;
589 remaining_sources = g_slist_prepend (remaining_sources, g_source_ref (source));
591 g_source_iter_clear (&iter);
593 /* Next destroy all sources. As we still hold a reference to all of them,
594 * this won't cause any of them to be freed yet and especially prevents any
595 * source that unrefs another source from its finalize function to be freed.
597 for (s_iter = remaining_sources; s_iter; s_iter = s_iter->next)
599 source = s_iter->data;
600 g_source_destroy_internal (source, context, TRUE);
603 for (sl_iter = context->source_lists; sl_iter; sl_iter = sl_iter->next)
605 list = sl_iter->data;
606 g_slice_free (GSourceList, list);
608 g_list_free (context->source_lists);
610 g_hash_table_destroy (context->sources);
612 UNLOCK_CONTEXT (context);
613 g_mutex_clear (&context->mutex);
615 g_ptr_array_free (context->pending_dispatches, TRUE);
616 g_free (context->cached_poll_array);
618 poll_rec_list_free (context, context->poll_records);
620 g_wakeup_free (context->wakeup);
621 g_cond_clear (&context->cond);
625 /* And now finally get rid of our references to the sources. This will cause
626 * them to be freed unless something else still has a reference to them. Due
627 * to setting the context pointers in the sources to NULL above, this won't
628 * ever access the context or the internal linked list inside the GSource.
629 * We already removed the sources completely from the context above. */
630 for (s_iter = remaining_sources; s_iter; s_iter = s_iter->next)
632 source = s_iter->data;
633 g_source_unref_internal (source, NULL, FALSE);
635 g_slist_free (remaining_sources);
638 /* Helper function used by mainloop/overflow test.
641 g_main_context_new_with_next_id (guint next_id)
643 GMainContext *ret = g_main_context_new ();
645 ret->next_id = next_id;
651 * g_main_context_new:
653 * Creates a new #GMainContext structure.
655 * Returns: the new #GMainContext
658 g_main_context_new (void)
660 static gsize initialised;
661 GMainContext *context;
663 if (g_once_init_enter (&initialised))
665 #ifdef G_MAIN_POLL_DEBUG
666 if (g_getenv ("G_MAIN_POLL_DEBUG") != NULL)
667 _g_main_poll_debug = TRUE;
670 g_once_init_leave (&initialised, TRUE);
673 context = g_new0 (GMainContext, 1);
675 TRACE (GLIB_MAIN_CONTEXT_NEW (context));
677 g_mutex_init (&context->mutex);
678 g_cond_init (&context->cond);
680 context->sources = g_hash_table_new (NULL, NULL);
681 context->owner = NULL;
682 context->waiters = NULL;
684 context->ref_count = 1;
686 context->next_id = 1;
688 context->source_lists = NULL;
690 context->poll_func = g_poll;
692 context->cached_poll_array = NULL;
693 context->cached_poll_array_size = 0;
695 context->pending_dispatches = g_ptr_array_new ();
697 context->time_is_fresh = FALSE;
699 context->wakeup = g_wakeup_new ();
700 g_wakeup_get_pollfd (context->wakeup, &context->wake_up_rec);
701 g_main_context_add_poll_unlocked (context, 0, &context->wake_up_rec);
703 G_LOCK (main_context_list);
704 main_context_list = g_slist_append (main_context_list, context);
706 #ifdef G_MAIN_POLL_DEBUG
707 if (_g_main_poll_debug)
708 g_print ("created context=%p\n", context);
711 G_UNLOCK (main_context_list);
717 * g_main_context_default:
719 * Returns the global default main context. This is the main context
720 * used for main loop functions when a main loop is not explicitly
721 * specified, and corresponds to the "main" main loop. See also
722 * g_main_context_get_thread_default().
724 * Returns: (transfer none): the global default main context.
727 g_main_context_default (void)
729 static GMainContext *default_main_context = NULL;
731 if (g_once_init_enter (&default_main_context))
733 GMainContext *context;
735 context = g_main_context_new ();
737 TRACE (GLIB_MAIN_CONTEXT_DEFAULT (context));
739 #ifdef G_MAIN_POLL_DEBUG
740 if (_g_main_poll_debug)
741 g_print ("default context=%p\n", context);
744 g_once_init_leave (&default_main_context, context);
747 return default_main_context;
751 free_context (gpointer data)
753 GMainContext *context = data;
755 TRACE (GLIB_MAIN_CONTEXT_FREE (context));
757 g_main_context_release (context);
759 g_main_context_unref (context);
763 free_context_stack (gpointer data)
765 g_queue_free_full((GQueue *) data, (GDestroyNotify) free_context);
768 static GPrivate thread_context_stack = G_PRIVATE_INIT (free_context_stack);
771 * g_main_context_push_thread_default:
772 * @context: (nullable): a #GMainContext, or %NULL for the global default context
774 * Acquires @context and sets it as the thread-default context for the
775 * current thread. This will cause certain asynchronous operations
776 * (such as most [gio][gio]-based I/O) which are
777 * started in this thread to run under @context and deliver their
778 * results to its main loop, rather than running under the global
779 * default context in the main thread. Note that calling this function
780 * changes the context returned by g_main_context_get_thread_default(),
781 * not the one returned by g_main_context_default(), so it does not affect
782 * the context used by functions like g_idle_add().
784 * Normally you would call this function shortly after creating a new
785 * thread, passing it a #GMainContext which will be run by a
786 * #GMainLoop in that thread, to set a new default context for all
787 * async operations in that thread. In this case you may not need to
788 * ever call g_main_context_pop_thread_default(), assuming you want the
789 * new #GMainContext to be the default for the whole lifecycle of the
792 * If you don't have control over how the new thread was created (e.g.
793 * in the new thread isn't newly created, or if the thread life
794 * cycle is managed by a #GThreadPool), it is always suggested to wrap
795 * the logic that needs to use the new #GMainContext inside a
796 * g_main_context_push_thread_default() / g_main_context_pop_thread_default()
797 * pair, otherwise threads that are re-used will end up never explicitly
798 * releasing the #GMainContext reference they hold.
800 * In some cases you may want to schedule a single operation in a
801 * non-default context, or temporarily use a non-default context in
802 * the main thread. In that case, you can wrap the call to the
803 * asynchronous operation inside a
804 * g_main_context_push_thread_default() /
805 * g_main_context_pop_thread_default() pair, but it is up to you to
806 * ensure that no other asynchronous operations accidentally get
807 * started while the non-default context is active.
809 * Beware that libraries that predate this function may not correctly
810 * handle being used from a thread with a thread-default context. Eg,
811 * see g_file_supports_thread_contexts().
816 g_main_context_push_thread_default (GMainContext *context)
819 gboolean acquired_context;
821 acquired_context = g_main_context_acquire (context);
822 g_return_if_fail (acquired_context);
824 if (context == g_main_context_default ())
827 g_main_context_ref (context);
829 stack = g_private_get (&thread_context_stack);
832 stack = g_queue_new ();
833 g_private_set (&thread_context_stack, stack);
836 g_queue_push_head (stack, context);
838 TRACE (GLIB_MAIN_CONTEXT_PUSH_THREAD_DEFAULT (context));
842 * g_main_context_pop_thread_default:
843 * @context: (nullable): a #GMainContext object, or %NULL
845 * Pops @context off the thread-default context stack (verifying that
846 * it was on the top of the stack).
851 g_main_context_pop_thread_default (GMainContext *context)
855 if (context == g_main_context_default ())
858 stack = g_private_get (&thread_context_stack);
860 g_return_if_fail (stack != NULL);
861 g_return_if_fail (g_queue_peek_head (stack) == context);
863 TRACE (GLIB_MAIN_CONTEXT_POP_THREAD_DEFAULT (context));
865 g_queue_pop_head (stack);
867 g_main_context_release (context);
869 g_main_context_unref (context);
873 * g_main_context_get_thread_default:
875 * Gets the thread-default #GMainContext for this thread. Asynchronous
876 * operations that want to be able to be run in contexts other than
877 * the default one should call this method or
878 * g_main_context_ref_thread_default() to get a #GMainContext to add
879 * their #GSources to. (Note that even in single-threaded
880 * programs applications may sometimes want to temporarily push a
881 * non-default context, so it is not safe to assume that this will
882 * always return %NULL if you are running in the default thread.)
884 * If you need to hold a reference on the context, use
885 * g_main_context_ref_thread_default() instead.
887 * Returns: (transfer none) (nullable): the thread-default #GMainContext, or
888 * %NULL if the thread-default context is the global default context.
893 g_main_context_get_thread_default (void)
897 stack = g_private_get (&thread_context_stack);
899 return g_queue_peek_head (stack);
905 * g_main_context_ref_thread_default:
907 * Gets the thread-default #GMainContext for this thread, as with
908 * g_main_context_get_thread_default(), but also adds a reference to
909 * it with g_main_context_ref(). In addition, unlike
910 * g_main_context_get_thread_default(), if the thread-default context
911 * is the global default context, this will return that #GMainContext
912 * (with a ref added to it) rather than returning %NULL.
914 * Returns: (transfer full): the thread-default #GMainContext. Unref
915 * with g_main_context_unref() when you are done with it.
920 g_main_context_ref_thread_default (void)
922 GMainContext *context;
924 context = g_main_context_get_thread_default ();
926 context = g_main_context_default ();
927 return g_main_context_ref (context);
930 /* Hooks for adding to the main loop */
934 * @source_funcs: structure containing functions that implement
935 * the sources behavior.
936 * @struct_size: size of the #GSource structure to create.
938 * Creates a new #GSource structure. The size is specified to
939 * allow creating structures derived from #GSource that contain
940 * additional data. The size passed in must be at least
941 * `sizeof (GSource)`.
943 * The source will not initially be associated with any #GMainContext
944 * and must be added to one with g_source_attach() before it will be
947 * Returns: the newly-created #GSource.
950 g_source_new (GSourceFuncs *source_funcs,
955 g_return_val_if_fail (source_funcs != NULL, NULL);
956 g_return_val_if_fail (struct_size >= sizeof (GSource), NULL);
958 source = (GSource*) g_malloc0 (struct_size);
959 source->priv = g_slice_new0 (GSourcePrivate);
960 source->source_funcs = source_funcs;
961 source->ref_count = 1;
963 source->priority = G_PRIORITY_DEFAULT;
965 source->flags = G_HOOK_FLAG_ACTIVE;
967 source->priv->ready_time = -1;
969 /* NULL/0 initialization for all other fields */
971 TRACE (GLIB_SOURCE_NEW (source, source_funcs->prepare, source_funcs->check,
972 source_funcs->dispatch, source_funcs->finalize,
979 * g_source_set_dispose_function:
980 * @source: A #GSource to set the dispose function on
981 * @dispose: #GSourceDisposeFunc to set on the source
983 * Set @dispose as dispose function on @source. @dispose will be called once
984 * the reference count of @source reaches 0 but before any of the state of the
985 * source is freed, especially before the finalize function is called.
987 * This means that at this point @source is still a valid #GSource and it is
988 * allow for the reference count to increase again until @dispose returns.
990 * The dispose function can be used to clear any "weak" references to the
991 * @source in other data structures in a thread-safe way where it is possible
992 * for another thread to increase the reference count of @source again while
995 * The finalize function can not be used for this purpose as at that point
996 * @source is already partially freed and not valid anymore.
998 * This should only ever be called from #GSource implementations.
1003 g_source_set_dispose_function (GSource *source,
1004 GSourceDisposeFunc dispose)
1006 g_return_if_fail (source != NULL);
1007 g_return_if_fail (source->priv->dispose == NULL);
1008 g_return_if_fail (g_atomic_int_get (&source->ref_count) > 0);
1009 source->priv->dispose = dispose;
1012 /* Holds context's lock */
1014 g_source_iter_init (GSourceIter *iter,
1015 GMainContext *context,
1016 gboolean may_modify)
1018 iter->context = context;
1019 iter->current_list = NULL;
1020 iter->source = NULL;
1021 iter->may_modify = may_modify;
1024 /* Holds context's lock */
1026 g_source_iter_next (GSourceIter *iter, GSource **source)
1028 GSource *next_source;
1031 next_source = iter->source->next;
1037 if (iter->current_list)
1038 iter->current_list = iter->current_list->next;
1040 iter->current_list = iter->context->source_lists;
1042 if (iter->current_list)
1044 GSourceList *source_list = iter->current_list->data;
1046 next_source = source_list->head;
1050 /* Note: unreffing iter->source could potentially cause its
1051 * GSourceList to be removed from source_lists (if iter->source is
1052 * the only source in its list, and it is destroyed), so we have to
1053 * keep it reffed until after we advance iter->current_list, above.
1055 * Also we first have to ref the next source before unreffing the
1056 * previous one as unreffing the previous source can potentially
1057 * free the next one.
1059 if (next_source && iter->may_modify)
1060 g_source_ref (next_source);
1062 if (iter->source && iter->may_modify)
1063 g_source_unref_internal (iter->source, iter->context, TRUE);
1064 iter->source = next_source;
1066 *source = iter->source;
1067 return *source != NULL;
1070 /* Holds context's lock. Only necessary to call if you broke out of
1071 * the g_source_iter_next() loop early.
1074 g_source_iter_clear (GSourceIter *iter)
1076 if (iter->source && iter->may_modify)
1078 g_source_unref_internal (iter->source, iter->context, TRUE);
1079 iter->source = NULL;
1083 /* Holds context's lock
1085 static GSourceList *
1086 find_source_list_for_priority (GMainContext *context,
1091 GSourceList *source_list;
1094 for (iter = context->source_lists; iter != NULL; last = iter, iter = iter->next)
1096 source_list = iter->data;
1098 if (source_list->priority == priority)
1101 if (source_list->priority > priority)
1106 source_list = g_slice_new0 (GSourceList);
1107 source_list->priority = priority;
1108 context->source_lists = g_list_insert_before (context->source_lists,
1118 source_list = g_slice_new0 (GSourceList);
1119 source_list->priority = priority;
1122 context->source_lists = g_list_append (NULL, source_list);
1125 /* This just appends source_list to the end of
1126 * context->source_lists without having to walk the list again.
1128 last = g_list_append (last, source_list);
1134 /* Holds context's lock
1137 source_add_to_context (GSource *source,
1138 GMainContext *context)
1140 GSourceList *source_list;
1141 GSource *prev, *next;
1143 source_list = find_source_list_for_priority (context, source->priority, TRUE);
1145 if (source->priv->parent_source)
1147 g_assert (source_list->head != NULL);
1149 /* Put the source immediately before its parent */
1150 prev = source->priv->parent_source->prev;
1151 next = source->priv->parent_source;
1155 prev = source_list->tail;
1159 source->next = next;
1161 next->prev = source;
1163 source_list->tail = source;
1165 source->prev = prev;
1167 prev->next = source;
1169 source_list->head = source;
1172 /* Holds context's lock
1175 source_remove_from_context (GSource *source,
1176 GMainContext *context)
1178 GSourceList *source_list;
1180 source_list = find_source_list_for_priority (context, source->priority, FALSE);
1181 g_return_if_fail (source_list != NULL);
1184 source->prev->next = source->next;
1186 source_list->head = source->next;
1189 source->next->prev = source->prev;
1191 source_list->tail = source->prev;
1193 source->prev = NULL;
1194 source->next = NULL;
1196 if (source_list->head == NULL)
1198 context->source_lists = g_list_remove (context->source_lists, source_list);
1199 g_slice_free (GSourceList, source_list);
1204 g_source_attach_unlocked (GSource *source,
1205 GMainContext *context,
1211 /* The counter may have wrapped, so we must ensure that we do not
1212 * reuse the source id of an existing source.
1215 id = context->next_id++;
1216 while (id == 0 || g_hash_table_contains (context->sources, GUINT_TO_POINTER (id)));
1218 source->context = context;
1219 source->source_id = id;
1220 g_source_ref (source);
1222 g_hash_table_insert (context->sources, GUINT_TO_POINTER (id), source);
1224 source_add_to_context (source, context);
1226 if (!SOURCE_BLOCKED (source))
1228 tmp_list = source->poll_fds;
1231 g_main_context_add_poll_unlocked (context, source->priority, tmp_list->data);
1232 tmp_list = tmp_list->next;
1235 for (tmp_list = source->priv->fds; tmp_list; tmp_list = tmp_list->next)
1236 g_main_context_add_poll_unlocked (context, source->priority, tmp_list->data);
1239 tmp_list = source->priv->child_sources;
1242 g_source_attach_unlocked (tmp_list->data, context, FALSE);
1243 tmp_list = tmp_list->next;
1246 /* If another thread has acquired the context, wake it up since it
1247 * might be in poll() right now.
1249 if (do_wakeup && context->owner && context->owner != G_THREAD_SELF)
1250 g_wakeup_signal (context->wakeup);
1252 g_trace_mark (G_TRACE_CURRENT_TIME, 0,
1253 "GLib", "g_source_attach",
1255 (g_source_get_name (source) != NULL) ? g_source_get_name (source) : "(unnamed)",
1258 return source->source_id;
1263 * @source: a #GSource
1264 * @context: (nullable): a #GMainContext (if %NULL, the default context will be used)
1266 * Adds a #GSource to a @context so that it will be executed within
1267 * that context. Remove it by calling g_source_destroy().
1269 * This function is safe to call from any thread, regardless of which thread
1270 * the @context is running in.
1272 * Returns: the ID (greater than 0) for the source within the
1276 g_source_attach (GSource *source,
1277 GMainContext *context)
1281 g_return_val_if_fail (source != NULL, 0);
1282 g_return_val_if_fail (g_atomic_int_get (&source->ref_count) > 0, 0);
1283 g_return_val_if_fail (source->context == NULL, 0);
1284 g_return_val_if_fail (!SOURCE_DESTROYED (source), 0);
1287 context = g_main_context_default ();
1289 LOCK_CONTEXT (context);
1291 result = g_source_attach_unlocked (source, context, TRUE);
1293 TRACE (GLIB_MAIN_SOURCE_ATTACH (g_source_get_name (source), source, context,
1296 UNLOCK_CONTEXT (context);
1302 g_source_destroy_internal (GSource *source,
1303 GMainContext *context,
1306 TRACE (GLIB_MAIN_SOURCE_DESTROY (g_source_get_name (source), source,
1310 LOCK_CONTEXT (context);
1312 if (!SOURCE_DESTROYED (source))
1315 gpointer old_cb_data;
1316 GSourceCallbackFuncs *old_cb_funcs;
1318 source->flags &= ~G_HOOK_FLAG_ACTIVE;
1320 old_cb_data = source->callback_data;
1321 old_cb_funcs = source->callback_funcs;
1323 source->callback_data = NULL;
1324 source->callback_funcs = NULL;
1328 UNLOCK_CONTEXT (context);
1329 old_cb_funcs->unref (old_cb_data);
1330 LOCK_CONTEXT (context);
1333 if (!SOURCE_BLOCKED (source))
1335 tmp_list = source->poll_fds;
1338 g_main_context_remove_poll_unlocked (context, tmp_list->data);
1339 tmp_list = tmp_list->next;
1342 for (tmp_list = source->priv->fds; tmp_list; tmp_list = tmp_list->next)
1343 g_main_context_remove_poll_unlocked (context, tmp_list->data);
1346 while (source->priv->child_sources)
1347 g_child_source_remove_internal (source->priv->child_sources->data, context);
1349 if (source->priv->parent_source)
1350 g_child_source_remove_internal (source, context);
1352 g_source_unref_internal (source, context, TRUE);
1356 UNLOCK_CONTEXT (context);
1361 * @source: a #GSource
1363 * Removes a source from its #GMainContext, if any, and mark it as
1364 * destroyed. The source cannot be subsequently added to another
1365 * context. It is safe to call this on sources which have already been
1366 * removed from their context.
1368 * This does not unref the #GSource: if you still hold a reference, use
1369 * g_source_unref() to drop it.
1371 * This function is safe to call from any thread, regardless of which thread
1372 * the #GMainContext is running in.
1375 g_source_destroy (GSource *source)
1377 GMainContext *context;
1379 g_return_if_fail (source != NULL);
1380 g_return_if_fail (g_atomic_int_get (&source->ref_count) > 0);
1382 context = source->context;
1385 g_source_destroy_internal (source, context, FALSE);
1387 source->flags &= ~G_HOOK_FLAG_ACTIVE;
1392 * @source: a #GSource
1394 * Returns the numeric ID for a particular source. The ID of a source
1395 * is a positive integer which is unique within a particular main loop
1396 * context. The reverse
1397 * mapping from ID to source is done by g_main_context_find_source_by_id().
1399 * You can only call this function while the source is associated to a
1400 * #GMainContext instance; calling this function before g_source_attach()
1401 * or after g_source_destroy() yields undefined behavior. The ID returned
1402 * is unique within the #GMainContext instance passed to g_source_attach().
1404 * Returns: the ID (greater than 0) for the source
1407 g_source_get_id (GSource *source)
1411 g_return_val_if_fail (source != NULL, 0);
1412 g_return_val_if_fail (g_atomic_int_get (&source->ref_count) > 0, 0);
1413 g_return_val_if_fail (source->context != NULL, 0);
1415 LOCK_CONTEXT (source->context);
1416 result = source->source_id;
1417 UNLOCK_CONTEXT (source->context);
1423 * g_source_get_context:
1424 * @source: a #GSource
1426 * Gets the #GMainContext with which the source is associated.
1428 * You can call this on a source that has been destroyed, provided
1429 * that the #GMainContext it was attached to still exists (in which
1430 * case it will return that #GMainContext). In particular, you can
1431 * always call this function on the source returned from
1432 * g_main_current_source(). But calling this function on a source
1433 * whose #GMainContext has been destroyed is an error.
1435 * Returns: (transfer none) (nullable): the #GMainContext with which the
1436 * source is associated, or %NULL if the context has not
1437 * yet been added to a source.
1440 g_source_get_context (GSource *source)
1442 g_return_val_if_fail (source != NULL, NULL);
1443 g_return_val_if_fail (g_atomic_int_get (&source->ref_count) > 0, NULL);
1444 g_return_val_if_fail (source->context != NULL || !SOURCE_DESTROYED (source), NULL);
1446 return source->context;
1450 * g_source_add_poll:
1451 * @source:a #GSource
1452 * @fd: a #GPollFD structure holding information about a file
1453 * descriptor to watch.
1455 * Adds a file descriptor to the set of file descriptors polled for
1456 * this source. This is usually combined with g_source_new() to add an
1457 * event source. The event source's check function will typically test
1458 * the @revents field in the #GPollFD struct and return %TRUE if events need
1461 * This API is only intended to be used by implementations of #GSource.
1462 * Do not call this API on a #GSource that you did not create.
1464 * Using this API forces the linear scanning of event sources on each
1465 * main loop iteration. Newly-written event sources should try to use
1466 * g_source_add_unix_fd() instead of this API.
1469 g_source_add_poll (GSource *source,
1472 GMainContext *context;
1474 g_return_if_fail (source != NULL);
1475 g_return_if_fail (g_atomic_int_get (&source->ref_count) > 0);
1476 g_return_if_fail (fd != NULL);
1477 g_return_if_fail (!SOURCE_DESTROYED (source));
1479 context = source->context;
1482 LOCK_CONTEXT (context);
1484 source->poll_fds = g_slist_prepend (source->poll_fds, fd);
1488 if (!SOURCE_BLOCKED (source))
1489 g_main_context_add_poll_unlocked (context, source->priority, fd);
1490 UNLOCK_CONTEXT (context);
1495 * g_source_remove_poll:
1496 * @source:a #GSource
1497 * @fd: a #GPollFD structure previously passed to g_source_add_poll().
1499 * Removes a file descriptor from the set of file descriptors polled for
1502 * This API is only intended to be used by implementations of #GSource.
1503 * Do not call this API on a #GSource that you did not create.
1506 g_source_remove_poll (GSource *source,
1509 GMainContext *context;
1511 g_return_if_fail (source != NULL);
1512 g_return_if_fail (g_atomic_int_get (&source->ref_count) > 0);
1513 g_return_if_fail (fd != NULL);
1514 g_return_if_fail (!SOURCE_DESTROYED (source));
1516 context = source->context;
1519 LOCK_CONTEXT (context);
1521 source->poll_fds = g_slist_remove (source->poll_fds, fd);
1525 if (!SOURCE_BLOCKED (source))
1526 g_main_context_remove_poll_unlocked (context, fd);
1527 UNLOCK_CONTEXT (context);
1532 * g_source_add_child_source:
1533 * @source:a #GSource
1534 * @child_source: a second #GSource that @source should "poll"
1536 * Adds @child_source to @source as a "polled" source; when @source is
1537 * added to a #GMainContext, @child_source will be automatically added
1538 * with the same priority, when @child_source is triggered, it will
1539 * cause @source to dispatch (in addition to calling its own
1540 * callback), and when @source is destroyed, it will destroy
1541 * @child_source as well. (@source will also still be dispatched if
1542 * its own prepare/check functions indicate that it is ready.)
1544 * If you don't need @child_source to do anything on its own when it
1545 * triggers, you can call g_source_set_dummy_callback() on it to set a
1546 * callback that does nothing (except return %TRUE if appropriate).
1548 * @source will hold a reference on @child_source while @child_source
1549 * is attached to it.
1551 * This API is only intended to be used by implementations of #GSource.
1552 * Do not call this API on a #GSource that you did not create.
1557 g_source_add_child_source (GSource *source,
1558 GSource *child_source)
1560 GMainContext *context;
1562 g_return_if_fail (source != NULL);
1563 g_return_if_fail (g_atomic_int_get (&source->ref_count) > 0);
1564 g_return_if_fail (child_source != NULL);
1565 g_return_if_fail (g_atomic_int_get (&child_source->ref_count) > 0);
1566 g_return_if_fail (!SOURCE_DESTROYED (source));
1567 g_return_if_fail (!SOURCE_DESTROYED (child_source));
1568 g_return_if_fail (child_source->context == NULL);
1569 g_return_if_fail (child_source->priv->parent_source == NULL);
1571 context = source->context;
1574 LOCK_CONTEXT (context);
1576 TRACE (GLIB_SOURCE_ADD_CHILD_SOURCE (source, child_source));
1578 source->priv->child_sources = g_slist_prepend (source->priv->child_sources,
1579 g_source_ref (child_source));
1580 child_source->priv->parent_source = source;
1581 g_source_set_priority_unlocked (child_source, NULL, source->priority);
1582 if (SOURCE_BLOCKED (source))
1583 block_source (child_source);
1587 g_source_attach_unlocked (child_source, context, TRUE);
1588 UNLOCK_CONTEXT (context);
1593 g_child_source_remove_internal (GSource *child_source,
1594 GMainContext *context)
1596 GSource *parent_source = child_source->priv->parent_source;
1598 parent_source->priv->child_sources =
1599 g_slist_remove (parent_source->priv->child_sources, child_source);
1600 child_source->priv->parent_source = NULL;
1602 g_source_destroy_internal (child_source, context, TRUE);
1603 g_source_unref_internal (child_source, context, TRUE);
1607 * g_source_remove_child_source:
1608 * @source:a #GSource
1609 * @child_source: a #GSource previously passed to
1610 * g_source_add_child_source().
1612 * Detaches @child_source from @source and destroys it.
1614 * This API is only intended to be used by implementations of #GSource.
1615 * Do not call this API on a #GSource that you did not create.
1620 g_source_remove_child_source (GSource *source,
1621 GSource *child_source)
1623 GMainContext *context;
1625 g_return_if_fail (source != NULL);
1626 g_return_if_fail (g_atomic_int_get (&source->ref_count) > 0);
1627 g_return_if_fail (child_source != NULL);
1628 g_return_if_fail (g_atomic_int_get (&child_source->ref_count) > 0);
1629 g_return_if_fail (child_source->priv->parent_source == source);
1630 g_return_if_fail (!SOURCE_DESTROYED (source));
1631 g_return_if_fail (!SOURCE_DESTROYED (child_source));
1633 context = source->context;
1636 LOCK_CONTEXT (context);
1638 g_child_source_remove_internal (child_source, context);
1641 UNLOCK_CONTEXT (context);
1645 g_source_callback_ref (gpointer cb_data)
1647 GSourceCallback *callback = cb_data;
1649 g_atomic_int_inc (&callback->ref_count);
1653 g_source_callback_unref (gpointer cb_data)
1655 GSourceCallback *callback = cb_data;
1657 if (g_atomic_int_dec_and_test (&callback->ref_count))
1659 if (callback->notify)
1660 callback->notify (callback->data);
1666 g_source_callback_get (gpointer cb_data,
1671 GSourceCallback *callback = cb_data;
1673 *func = callback->func;
1674 *data = callback->data;
1677 static GSourceCallbackFuncs g_source_callback_funcs = {
1678 g_source_callback_ref,
1679 g_source_callback_unref,
1680 g_source_callback_get,
1684 * g_source_set_callback_indirect:
1685 * @source: the source
1686 * @callback_data: pointer to callback data "object"
1687 * @callback_funcs: functions for reference counting @callback_data
1688 * and getting the callback and data
1690 * Sets the callback function storing the data as a refcounted callback
1691 * "object". This is used internally. Note that calling
1692 * g_source_set_callback_indirect() assumes
1693 * an initial reference count on @callback_data, and thus
1694 * @callback_funcs->unref will eventually be called once more
1695 * than @callback_funcs->ref.
1697 * It is safe to call this function multiple times on a source which has already
1698 * been attached to a context. The changes will take effect for the next time
1699 * the source is dispatched after this call returns.
1702 g_source_set_callback_indirect (GSource *source,
1703 gpointer callback_data,
1704 GSourceCallbackFuncs *callback_funcs)
1706 GMainContext *context;
1707 gpointer old_cb_data;
1708 GSourceCallbackFuncs *old_cb_funcs;
1710 g_return_if_fail (source != NULL);
1711 g_return_if_fail (g_atomic_int_get (&source->ref_count) > 0);
1712 g_return_if_fail (callback_funcs != NULL || callback_data == NULL);
1714 context = source->context;
1717 LOCK_CONTEXT (context);
1719 if (callback_funcs != &g_source_callback_funcs)
1721 TRACE (GLIB_SOURCE_SET_CALLBACK_INDIRECT (source, callback_data,
1722 callback_funcs->ref,
1723 callback_funcs->unref,
1724 callback_funcs->get));
1727 old_cb_data = source->callback_data;
1728 old_cb_funcs = source->callback_funcs;
1730 source->callback_data = callback_data;
1731 source->callback_funcs = callback_funcs;
1734 UNLOCK_CONTEXT (context);
1737 old_cb_funcs->unref (old_cb_data);
1741 * g_source_set_callback:
1742 * @source: the source
1743 * @func: a callback function
1744 * @data: the data to pass to callback function
1745 * @notify: (nullable): a function to call when @data is no longer in use, or %NULL.
1747 * Sets the callback function for a source. The callback for a source is
1748 * called from the source's dispatch function.
1750 * The exact type of @func depends on the type of source; ie. you
1751 * should not count on @func being called with @data as its first
1752 * parameter. Cast @func with G_SOURCE_FUNC() to avoid warnings about
1753 * incompatible function types.
1755 * See [memory management of sources][mainloop-memory-management] for details
1756 * on how to handle memory management of @data.
1758 * Typically, you won't use this function. Instead use functions specific
1759 * to the type of source you are using, such as g_idle_add() or g_timeout_add().
1761 * It is safe to call this function multiple times on a source which has already
1762 * been attached to a context. The changes will take effect for the next time
1763 * the source is dispatched after this call returns.
1766 g_source_set_callback (GSource *source,
1769 GDestroyNotify notify)
1771 GSourceCallback *new_callback;
1773 g_return_if_fail (source != NULL);
1774 g_return_if_fail (g_atomic_int_get (&source->ref_count) > 0);
1776 TRACE (GLIB_SOURCE_SET_CALLBACK (source, func, data, notify));
1778 new_callback = g_new (GSourceCallback, 1);
1780 new_callback->ref_count = 1;
1781 new_callback->func = func;
1782 new_callback->data = data;
1783 new_callback->notify = notify;
1785 g_source_set_callback_indirect (source, new_callback, &g_source_callback_funcs);
1790 * g_source_set_funcs:
1791 * @source: a #GSource
1792 * @funcs: the new #GSourceFuncs
1794 * Sets the source functions (can be used to override
1795 * default implementations) of an unattached source.
1800 g_source_set_funcs (GSource *source,
1801 GSourceFuncs *funcs)
1803 g_return_if_fail (source != NULL);
1804 g_return_if_fail (source->context == NULL);
1805 g_return_if_fail (g_atomic_int_get (&source->ref_count) > 0);
1806 g_return_if_fail (funcs != NULL);
1808 source->source_funcs = funcs;
1812 g_source_set_priority_unlocked (GSource *source,
1813 GMainContext *context,
1818 g_return_if_fail (source->priv->parent_source == NULL ||
1819 source->priv->parent_source->priority == priority);
1821 TRACE (GLIB_SOURCE_SET_PRIORITY (source, context, priority));
1825 /* Remove the source from the context's source and then
1826 * add it back after so it is sorted in the correct place
1828 source_remove_from_context (source, source->context);
1831 source->priority = priority;
1835 source_add_to_context (source, source->context);
1837 if (!SOURCE_BLOCKED (source))
1839 tmp_list = source->poll_fds;
1842 g_main_context_remove_poll_unlocked (context, tmp_list->data);
1843 g_main_context_add_poll_unlocked (context, priority, tmp_list->data);
1845 tmp_list = tmp_list->next;
1848 for (tmp_list = source->priv->fds; tmp_list; tmp_list = tmp_list->next)
1850 g_main_context_remove_poll_unlocked (context, tmp_list->data);
1851 g_main_context_add_poll_unlocked (context, priority, tmp_list->data);
1856 if (source->priv->child_sources)
1858 tmp_list = source->priv->child_sources;
1861 g_source_set_priority_unlocked (tmp_list->data, context, priority);
1862 tmp_list = tmp_list->next;
1868 * g_source_set_priority:
1869 * @source: a #GSource
1870 * @priority: the new priority.
1872 * Sets the priority of a source. While the main loop is being run, a
1873 * source will be dispatched if it is ready to be dispatched and no
1874 * sources at a higher (numerically smaller) priority are ready to be
1877 * A child source always has the same priority as its parent. It is not
1878 * permitted to change the priority of a source once it has been added
1879 * as a child of another source.
1882 g_source_set_priority (GSource *source,
1885 GMainContext *context;
1887 g_return_if_fail (source != NULL);
1888 g_return_if_fail (g_atomic_int_get (&source->ref_count) > 0);
1889 g_return_if_fail (source->priv->parent_source == NULL);
1891 context = source->context;
1894 LOCK_CONTEXT (context);
1895 g_source_set_priority_unlocked (source, context, priority);
1897 UNLOCK_CONTEXT (context);
1901 * g_source_get_priority:
1902 * @source: a #GSource
1904 * Gets the priority of a source.
1906 * Returns: the priority of the source
1909 g_source_get_priority (GSource *source)
1911 g_return_val_if_fail (source != NULL, 0);
1912 g_return_val_if_fail (g_atomic_int_get (&source->ref_count) > 0, 0);
1914 return source->priority;
1918 * g_source_set_ready_time:
1919 * @source: a #GSource
1920 * @ready_time: the monotonic time at which the source will be ready,
1921 * 0 for "immediately", -1 for "never"
1923 * Sets a #GSource to be dispatched when the given monotonic time is
1924 * reached (or passed). If the monotonic time is in the past (as it
1925 * always will be if @ready_time is 0) then the source will be
1926 * dispatched immediately.
1928 * If @ready_time is -1 then the source is never woken up on the basis
1929 * of the passage of time.
1931 * Dispatching the source does not reset the ready time. You should do
1932 * so yourself, from the source dispatch function.
1934 * Note that if you have a pair of sources where the ready time of one
1935 * suggests that it will be delivered first but the priority for the
1936 * other suggests that it would be delivered first, and the ready time
1937 * for both sources is reached during the same main context iteration,
1938 * then the order of dispatch is undefined.
1940 * It is a no-op to call this function on a #GSource which has already been
1941 * destroyed with g_source_destroy().
1943 * This API is only intended to be used by implementations of #GSource.
1944 * Do not call this API on a #GSource that you did not create.
1949 g_source_set_ready_time (GSource *source,
1952 GMainContext *context;
1954 g_return_if_fail (source != NULL);
1955 g_return_if_fail (g_atomic_int_get (&source->ref_count) > 0);
1957 context = source->context;
1960 LOCK_CONTEXT (context);
1962 if (source->priv->ready_time == ready_time)
1965 UNLOCK_CONTEXT (context);
1970 source->priv->ready_time = ready_time;
1972 TRACE (GLIB_SOURCE_SET_READY_TIME (source, ready_time));
1976 /* Quite likely that we need to change the timeout on the poll */
1977 if (!SOURCE_BLOCKED (source))
1978 g_wakeup_signal (context->wakeup);
1979 UNLOCK_CONTEXT (context);
1984 * g_source_get_ready_time:
1985 * @source: a #GSource
1987 * Gets the "ready time" of @source, as set by
1988 * g_source_set_ready_time().
1990 * Any time before the current monotonic time (including 0) is an
1991 * indication that the source will fire immediately.
1993 * Returns: the monotonic ready time, -1 for "never"
1996 g_source_get_ready_time (GSource *source)
1998 g_return_val_if_fail (source != NULL, -1);
1999 g_return_val_if_fail (g_atomic_int_get (&source->ref_count) > 0, -1);
2001 return source->priv->ready_time;
2005 * g_source_set_can_recurse:
2006 * @source: a #GSource
2007 * @can_recurse: whether recursion is allowed for this source
2009 * Sets whether a source can be called recursively. If @can_recurse is
2010 * %TRUE, then while the source is being dispatched then this source
2011 * will be processed normally. Otherwise, all processing of this
2012 * source is blocked until the dispatch function returns.
2015 g_source_set_can_recurse (GSource *source,
2016 gboolean can_recurse)
2018 GMainContext *context;
2020 g_return_if_fail (source != NULL);
2021 g_return_if_fail (g_atomic_int_get (&source->ref_count) > 0);
2023 context = source->context;
2026 LOCK_CONTEXT (context);
2029 source->flags |= G_SOURCE_CAN_RECURSE;
2031 source->flags &= ~G_SOURCE_CAN_RECURSE;
2034 UNLOCK_CONTEXT (context);
2038 * g_source_get_can_recurse:
2039 * @source: a #GSource
2041 * Checks whether a source is allowed to be called recursively.
2042 * see g_source_set_can_recurse().
2044 * Returns: whether recursion is allowed.
2047 g_source_get_can_recurse (GSource *source)
2049 g_return_val_if_fail (source != NULL, FALSE);
2050 g_return_val_if_fail (g_atomic_int_get (&source->ref_count) > 0, FALSE);
2052 return (source->flags & G_SOURCE_CAN_RECURSE) != 0;
2057 * g_source_set_name:
2058 * @source: a #GSource
2059 * @name: debug name for the source
2061 * Sets a name for the source, used in debugging and profiling.
2062 * The name defaults to #NULL.
2064 * The source name should describe in a human-readable way
2065 * what the source does. For example, "X11 event queue"
2066 * or "GTK+ repaint idle handler" or whatever it is.
2068 * It is permitted to call this function multiple times, but is not
2069 * recommended due to the potential performance impact. For example,
2070 * one could change the name in the "check" function of a #GSourceFuncs
2071 * to include details like the event type in the source name.
2073 * Use caution if changing the name while another thread may be
2074 * accessing it with g_source_get_name(); that function does not copy
2075 * the value, and changing the value will free it while the other thread
2076 * may be attempting to use it.
2081 g_source_set_name (GSource *source,
2084 GMainContext *context;
2086 g_return_if_fail (source != NULL);
2087 g_return_if_fail (g_atomic_int_get (&source->ref_count) > 0);
2089 context = source->context;
2092 LOCK_CONTEXT (context);
2094 TRACE (GLIB_SOURCE_SET_NAME (source, name));
2096 /* setting back to NULL is allowed, just because it's
2097 * weird if get_name can return NULL but you can't
2101 g_free (source->name);
2102 source->name = g_strdup (name);
2105 UNLOCK_CONTEXT (context);
2109 * g_source_get_name:
2110 * @source: a #GSource
2112 * Gets a name for the source, used in debugging and profiling. The
2113 * name may be #NULL if it has never been set with g_source_set_name().
2115 * Returns: (nullable): the name of the source
2120 g_source_get_name (GSource *source)
2122 g_return_val_if_fail (source != NULL, NULL);
2123 g_return_val_if_fail (g_atomic_int_get (&source->ref_count) > 0, NULL);
2125 return source->name;
2129 * g_source_set_name_by_id:
2130 * @tag: a #GSource ID
2131 * @name: debug name for the source
2133 * Sets the name of a source using its ID.
2135 * This is a convenience utility to set source names from the return
2136 * value of g_idle_add(), g_timeout_add(), etc.
2138 * It is a programmer error to attempt to set the name of a non-existent
2141 * More specifically: source IDs can be reissued after a source has been
2142 * destroyed and therefore it is never valid to use this function with a
2143 * source ID which may have already been removed. An example is when
2144 * scheduling an idle to run in another thread with g_idle_add(): the
2145 * idle may already have run and been removed by the time this function
2146 * is called on its (now invalid) source ID. This source ID may have
2147 * been reissued, leading to the operation being performed against the
2153 g_source_set_name_by_id (guint tag,
2158 g_return_if_fail (tag > 0);
2160 source = g_main_context_find_source_by_id (NULL, tag);
2164 g_source_set_name (source, name);
2170 * @source: a #GSource
2172 * Increases the reference count on a source by one.
2177 g_source_ref (GSource *source)
2179 g_return_val_if_fail (source != NULL, NULL);
2180 /* We allow ref_count == 0 here to allow the dispose function to resurrect
2181 * the GSource if needed */
2182 g_return_val_if_fail (g_atomic_int_get (&source->ref_count) >= 0, NULL);
2184 g_atomic_int_inc (&source->ref_count);
2189 /* g_source_unref() but possible to call within context lock
2192 g_source_unref_internal (GSource *source,
2193 GMainContext *context,
2196 gpointer old_cb_data = NULL;
2197 GSourceCallbackFuncs *old_cb_funcs = NULL;
2199 g_return_if_fail (source != NULL);
2201 if (!have_lock && context)
2202 LOCK_CONTEXT (context);
2204 if (g_atomic_int_dec_and_test (&source->ref_count))
2206 /* If there's a dispose function, call this first */
2207 if (source->priv->dispose)
2209 /* Temporarily increase the ref count again so that GSource methods
2210 * can be called from dispose(). */
2211 g_atomic_int_inc (&source->ref_count);
2213 UNLOCK_CONTEXT (context);
2214 source->priv->dispose (source);
2216 LOCK_CONTEXT (context);
2218 /* Now the reference count might be bigger than 0 again, in which
2219 * case we simply return from here before freeing the source */
2220 if (!g_atomic_int_dec_and_test (&source->ref_count))
2222 if (!have_lock && context)
2223 UNLOCK_CONTEXT (context);
2228 TRACE (GLIB_SOURCE_BEFORE_FREE (source, context,
2229 source->source_funcs->finalize));
2231 old_cb_data = source->callback_data;
2232 old_cb_funcs = source->callback_funcs;
2234 source->callback_data = NULL;
2235 source->callback_funcs = NULL;
2239 if (!SOURCE_DESTROYED (source))
2240 g_warning (G_STRLOC ": ref_count == 0, but source was still attached to a context!");
2241 source_remove_from_context (source, context);
2243 g_hash_table_remove (context->sources, GUINT_TO_POINTER (source->source_id));
2246 if (source->source_funcs->finalize)
2250 /* Temporarily increase the ref count again so that GSource methods
2251 * can be called from finalize(). */
2252 g_atomic_int_inc (&source->ref_count);
2254 UNLOCK_CONTEXT (context);
2255 source->source_funcs->finalize (source);
2257 LOCK_CONTEXT (context);
2258 old_ref_count = g_atomic_int_add (&source->ref_count, -1);
2259 g_warn_if_fail (old_ref_count == 1);
2266 /* Temporarily increase the ref count again so that GSource methods
2267 * can be called from callback_funcs.unref(). */
2268 g_atomic_int_inc (&source->ref_count);
2270 UNLOCK_CONTEXT (context);
2272 old_cb_funcs->unref (old_cb_data);
2275 LOCK_CONTEXT (context);
2276 old_ref_count = g_atomic_int_add (&source->ref_count, -1);
2277 g_warn_if_fail (old_ref_count == 1);
2280 g_free (source->name);
2281 source->name = NULL;
2283 g_slist_free (source->poll_fds);
2284 source->poll_fds = NULL;
2286 g_slist_free_full (source->priv->fds, g_free);
2288 while (source->priv->child_sources)
2290 GSource *child_source = source->priv->child_sources->data;
2292 source->priv->child_sources =
2293 g_slist_remove (source->priv->child_sources, child_source);
2294 child_source->priv->parent_source = NULL;
2296 g_source_unref_internal (child_source, context, TRUE);
2299 g_slice_free (GSourcePrivate, source->priv);
2300 source->priv = NULL;
2305 if (!have_lock && context)
2306 UNLOCK_CONTEXT (context);
2311 * @source: a #GSource
2313 * Decreases the reference count of a source by one. If the
2314 * resulting reference count is zero the source and associated
2315 * memory will be destroyed.
2318 g_source_unref (GSource *source)
2320 g_return_if_fail (source != NULL);
2321 g_return_if_fail (g_atomic_int_get (&source->ref_count) > 0);
2323 g_source_unref_internal (source, source->context, FALSE);
2327 * g_main_context_find_source_by_id:
2328 * @context: (nullable): a #GMainContext (if %NULL, the default context will be used)
2329 * @source_id: the source ID, as returned by g_source_get_id().
2331 * Finds a #GSource given a pair of context and ID.
2333 * It is a programmer error to attempt to look up a non-existent source.
2335 * More specifically: source IDs can be reissued after a source has been
2336 * destroyed and therefore it is never valid to use this function with a
2337 * source ID which may have already been removed. An example is when
2338 * scheduling an idle to run in another thread with g_idle_add(): the
2339 * idle may already have run and been removed by the time this function
2340 * is called on its (now invalid) source ID. This source ID may have
2341 * been reissued, leading to the operation being performed against the
2344 * Returns: (transfer none): the #GSource
2347 g_main_context_find_source_by_id (GMainContext *context,
2352 g_return_val_if_fail (source_id > 0, NULL);
2354 if (context == NULL)
2355 context = g_main_context_default ();
2357 LOCK_CONTEXT (context);
2358 source = g_hash_table_lookup (context->sources, GUINT_TO_POINTER (source_id));
2359 UNLOCK_CONTEXT (context);
2361 if (source && SOURCE_DESTROYED (source))
2368 * g_main_context_find_source_by_funcs_user_data:
2369 * @context: (nullable): a #GMainContext (if %NULL, the default context will be used).
2370 * @funcs: the @source_funcs passed to g_source_new().
2371 * @user_data: the user data from the callback.
2373 * Finds a source with the given source functions and user data. If
2374 * multiple sources exist with the same source function and user data,
2375 * the first one found will be returned.
2377 * Returns: (transfer none): the source, if one was found, otherwise %NULL
2380 g_main_context_find_source_by_funcs_user_data (GMainContext *context,
2381 GSourceFuncs *funcs,
2387 g_return_val_if_fail (funcs != NULL, NULL);
2389 if (context == NULL)
2390 context = g_main_context_default ();
2392 LOCK_CONTEXT (context);
2394 g_source_iter_init (&iter, context, FALSE);
2395 while (g_source_iter_next (&iter, &source))
2397 if (!SOURCE_DESTROYED (source) &&
2398 source->source_funcs == funcs &&
2399 source->callback_funcs)
2401 GSourceFunc callback;
2402 gpointer callback_data;
2404 source->callback_funcs->get (source->callback_data, source, &callback, &callback_data);
2406 if (callback_data == user_data)
2410 g_source_iter_clear (&iter);
2412 UNLOCK_CONTEXT (context);
2418 * g_main_context_find_source_by_user_data:
2419 * @context: a #GMainContext
2420 * @user_data: the user_data for the callback.
2422 * Finds a source with the given user data for the callback. If
2423 * multiple sources exist with the same user data, the first
2424 * one found will be returned.
2426 * Returns: (transfer none): the source, if one was found, otherwise %NULL
2429 g_main_context_find_source_by_user_data (GMainContext *context,
2435 if (context == NULL)
2436 context = g_main_context_default ();
2438 LOCK_CONTEXT (context);
2440 g_source_iter_init (&iter, context, FALSE);
2441 while (g_source_iter_next (&iter, &source))
2443 if (!SOURCE_DESTROYED (source) &&
2444 source->callback_funcs)
2446 GSourceFunc callback;
2447 gpointer callback_data = NULL;
2449 source->callback_funcs->get (source->callback_data, source, &callback, &callback_data);
2451 if (callback_data == user_data)
2455 g_source_iter_clear (&iter);
2457 UNLOCK_CONTEXT (context);
2464 * @tag: the ID of the source to remove.
2466 * Removes the source with the given ID from the default main context. You must
2467 * use g_source_destroy() for sources added to a non-default main context.
2469 * The ID of a #GSource is given by g_source_get_id(), or will be
2470 * returned by the functions g_source_attach(), g_idle_add(),
2471 * g_idle_add_full(), g_timeout_add(), g_timeout_add_full(),
2472 * g_child_watch_add(), g_child_watch_add_full(), g_io_add_watch(), and
2473 * g_io_add_watch_full().
2475 * It is a programmer error to attempt to remove a non-existent source.
2477 * More specifically: source IDs can be reissued after a source has been
2478 * destroyed and therefore it is never valid to use this function with a
2479 * source ID which may have already been removed. An example is when
2480 * scheduling an idle to run in another thread with g_idle_add(): the
2481 * idle may already have run and been removed by the time this function
2482 * is called on its (now invalid) source ID. This source ID may have
2483 * been reissued, leading to the operation being performed against the
2486 * Returns: For historical reasons, this function always returns %TRUE
2489 g_source_remove (guint tag)
2493 g_return_val_if_fail (tag > 0, FALSE);
2495 source = g_main_context_find_source_by_id (NULL, tag);
2497 g_source_destroy (source);
2499 g_critical ("Source ID %u was not found when attempting to remove it", tag);
2501 return source != NULL;
2505 * g_source_remove_by_user_data:
2506 * @user_data: the user_data for the callback.
2508 * Removes a source from the default main loop context given the user
2509 * data for the callback. If multiple sources exist with the same user
2510 * data, only one will be destroyed.
2512 * Returns: %TRUE if a source was found and removed.
2515 g_source_remove_by_user_data (gpointer user_data)
2519 source = g_main_context_find_source_by_user_data (NULL, user_data);
2522 g_source_destroy (source);
2530 * g_source_remove_by_funcs_user_data:
2531 * @funcs: The @source_funcs passed to g_source_new()
2532 * @user_data: the user data for the callback
2534 * Removes a source from the default main loop context given the
2535 * source functions and user data. If multiple sources exist with the
2536 * same source functions and user data, only one will be destroyed.
2538 * Returns: %TRUE if a source was found and removed.
2541 g_source_remove_by_funcs_user_data (GSourceFuncs *funcs,
2546 g_return_val_if_fail (funcs != NULL, FALSE);
2548 source = g_main_context_find_source_by_funcs_user_data (NULL, funcs, user_data);
2551 g_source_destroy (source);
2559 * g_clear_handle_id: (skip)
2560 * @tag_ptr: (not nullable): a pointer to the handler ID
2561 * @clear_func: (not nullable): the function to call to clear the handler
2563 * Clears a numeric handler, such as a #GSource ID.
2565 * @tag_ptr must be a valid pointer to the variable holding the handler.
2567 * If the ID is zero then this function does nothing.
2568 * Otherwise, clear_func() is called with the ID as a parameter, and the tag is
2571 * A macro is also included that allows this function to be used without
2576 #undef g_clear_handle_id
2578 g_clear_handle_id (guint *tag_ptr,
2579 GClearHandleFunc clear_func)
2583 _handle_id = *tag_ptr;
2587 clear_func (_handle_id);
2593 * g_source_add_unix_fd:
2594 * @source: a #GSource
2595 * @fd: the fd to monitor
2596 * @events: an event mask
2598 * Monitors @fd for the IO events in @events.
2600 * The tag returned by this function can be used to remove or modify the
2601 * monitoring of the fd using g_source_remove_unix_fd() or
2602 * g_source_modify_unix_fd().
2604 * It is not necessary to remove the fd before destroying the source; it
2605 * will be cleaned up automatically.
2607 * This API is only intended to be used by implementations of #GSource.
2608 * Do not call this API on a #GSource that you did not create.
2610 * As the name suggests, this function is not available on Windows.
2612 * Returns: (not nullable): an opaque tag
2617 g_source_add_unix_fd (GSource *source,
2619 GIOCondition events)
2621 GMainContext *context;
2624 g_return_val_if_fail (source != NULL, NULL);
2625 g_return_val_if_fail (g_atomic_int_get (&source->ref_count) > 0, NULL);
2626 g_return_val_if_fail (!SOURCE_DESTROYED (source), NULL);
2628 poll_fd = g_new (GPollFD, 1);
2630 poll_fd->events = events;
2631 poll_fd->revents = 0;
2633 context = source->context;
2636 LOCK_CONTEXT (context);
2638 source->priv->fds = g_slist_prepend (source->priv->fds, poll_fd);
2642 if (!SOURCE_BLOCKED (source))
2643 g_main_context_add_poll_unlocked (context, source->priority, poll_fd);
2644 UNLOCK_CONTEXT (context);
2651 * g_source_modify_unix_fd:
2652 * @source: a #GSource
2653 * @tag: (not nullable): the tag from g_source_add_unix_fd()
2654 * @new_events: the new event mask to watch
2656 * Updates the event mask to watch for the fd identified by @tag.
2658 * @tag is the tag returned from g_source_add_unix_fd().
2660 * If you want to remove a fd, don't set its event mask to zero.
2661 * Instead, call g_source_remove_unix_fd().
2663 * This API is only intended to be used by implementations of #GSource.
2664 * Do not call this API on a #GSource that you did not create.
2666 * As the name suggests, this function is not available on Windows.
2671 g_source_modify_unix_fd (GSource *source,
2673 GIOCondition new_events)
2675 GMainContext *context;
2678 g_return_if_fail (source != NULL);
2679 g_return_if_fail (g_atomic_int_get (&source->ref_count) > 0);
2680 g_return_if_fail (g_slist_find (source->priv->fds, tag));
2682 context = source->context;
2685 poll_fd->events = new_events;
2688 g_main_context_wakeup (context);
2692 * g_source_remove_unix_fd:
2693 * @source: a #GSource
2694 * @tag: (not nullable): the tag from g_source_add_unix_fd()
2696 * Reverses the effect of a previous call to g_source_add_unix_fd().
2698 * You only need to call this if you want to remove an fd from being
2699 * watched while keeping the same source around. In the normal case you
2700 * will just want to destroy the source.
2702 * This API is only intended to be used by implementations of #GSource.
2703 * Do not call this API on a #GSource that you did not create.
2705 * As the name suggests, this function is not available on Windows.
2710 g_source_remove_unix_fd (GSource *source,
2713 GMainContext *context;
2716 g_return_if_fail (source != NULL);
2717 g_return_if_fail (g_atomic_int_get (&source->ref_count) > 0);
2718 g_return_if_fail (g_slist_find (source->priv->fds, tag));
2720 context = source->context;
2724 LOCK_CONTEXT (context);
2726 source->priv->fds = g_slist_remove (source->priv->fds, poll_fd);
2730 if (!SOURCE_BLOCKED (source))
2731 g_main_context_remove_poll_unlocked (context, poll_fd);
2733 UNLOCK_CONTEXT (context);
2740 * g_source_query_unix_fd:
2741 * @source: a #GSource
2742 * @tag: (not nullable): the tag from g_source_add_unix_fd()
2744 * Queries the events reported for the fd corresponding to @tag on
2745 * @source during the last poll.
2747 * The return value of this function is only defined when the function
2748 * is called from the check or dispatch functions for @source.
2750 * This API is only intended to be used by implementations of #GSource.
2751 * Do not call this API on a #GSource that you did not create.
2753 * As the name suggests, this function is not available on Windows.
2755 * Returns: the conditions reported on the fd
2760 g_source_query_unix_fd (GSource *source,
2765 g_return_val_if_fail (source != NULL, 0);
2766 g_return_val_if_fail (g_atomic_int_get (&source->ref_count) > 0, 0);
2767 g_return_val_if_fail (g_slist_find (source->priv->fds, tag), 0);
2771 return poll_fd->revents;
2773 #endif /* G_OS_UNIX */
2776 * g_get_current_time:
2777 * @result: #GTimeVal structure in which to store current time.
2779 * Equivalent to the UNIX gettimeofday() function, but portable.
2781 * You may find g_get_real_time() to be more convenient.
2783 * Deprecated: 2.62: #GTimeVal is not year-2038-safe. Use g_get_real_time()
2786 G_GNUC_BEGIN_IGNORE_DEPRECATIONS
2788 g_get_current_time (GTimeVal *result)
2792 g_return_if_fail (result != NULL);
2794 tv = g_get_real_time ();
2796 result->tv_sec = tv / 1000000;
2797 result->tv_usec = tv % 1000000;
2799 G_GNUC_END_IGNORE_DEPRECATIONS
2804 * Queries the system wall-clock time.
2806 * This call is functionally equivalent to g_get_current_time() except
2807 * that the return value is often more convenient than dealing with a
2810 * You should only use this call if you are actually interested in the real
2811 * wall-clock time. g_get_monotonic_time() is probably more useful for
2812 * measuring intervals.
2814 * Returns: the number of microseconds since January 1, 1970 UTC.
2819 g_get_real_time (void)
2824 /* this is required on alpha, there the timeval structs are ints
2825 * not longs and a cast only would fail horribly */
2826 gettimeofday (&r, NULL);
2828 return (((gint64) r.tv_sec) * 1000000) + r.tv_usec;
2833 GetSystemTimeAsFileTime (&ft);
2834 memmove (&time64, &ft, sizeof (FILETIME));
2836 /* Convert from 100s of nanoseconds since 1601-01-01
2837 * to Unix epoch. This is Y2038 safe.
2839 time64 -= G_GINT64_CONSTANT (116444736000000000);
2847 * g_get_monotonic_time:
2849 * Queries the system monotonic time.
2851 * The monotonic clock will always increase and doesn't suffer
2852 * discontinuities when the user (or NTP) changes the system time. It
2853 * may or may not continue to tick during times where the machine is
2856 * We try to use the clock that corresponds as closely as possible to
2857 * the passage of time as measured by system calls such as poll() but it
2858 * may not always be possible to do this.
2860 * Returns: the monotonic time, in microseconds
2864 #if defined (G_OS_WIN32)
2866 * time_usec = ticks_since_boot * usec_per_sec / ticks_per_sec
2868 * Doing (ticks_since_boot * usec_per_sec) before the division can overflow 64 bits
2869 * (ticks_since_boot / ticks_per_sec) and then multiply would not be accurate enough.
2870 * So for now we calculate (usec_per_sec / ticks_per_sec) and use floating point
2872 static gdouble g_monotonic_usec_per_tick = 0;
2875 g_clock_win32_init (void)
2879 if (!QueryPerformanceFrequency (&freq) || freq.QuadPart == 0)
2881 /* The documentation says that this should never happen */
2882 g_assert_not_reached ();
2886 g_monotonic_usec_per_tick = (gdouble)G_USEC_PER_SEC / freq.QuadPart;
2890 g_get_monotonic_time (void)
2892 if (G_LIKELY (g_monotonic_usec_per_tick != 0))
2894 LARGE_INTEGER ticks;
2896 if (QueryPerformanceCounter (&ticks))
2897 return (gint64)(ticks.QuadPart * g_monotonic_usec_per_tick);
2899 g_warning ("QueryPerformanceCounter Failed (%lu)", GetLastError ());
2900 g_monotonic_usec_per_tick = 0;
2905 #elif defined(HAVE_MACH_MACH_TIME_H) /* Mac OS */
2907 g_get_monotonic_time (void)
2909 mach_timebase_info_data_t timebase_info;
2912 /* we get nanoseconds from mach_absolute_time() using timebase_info */
2913 mach_timebase_info (&timebase_info);
2914 val = mach_absolute_time ();
2916 if (timebase_info.numer != timebase_info.denom)
2918 #ifdef HAVE_UINT128_T
2919 val = ((__uint128_t) val * (__uint128_t) timebase_info.numer) / timebase_info.denom / 1000;
2921 guint64 t_high, t_low;
2922 guint64 result_high, result_low;
2924 /* 64 bit x 32 bit / 32 bit with 96-bit intermediate
2925 * algorithm lifted from qemu */
2926 t_low = (val & 0xffffffffLL) * (guint64) timebase_info.numer;
2927 t_high = (val >> 32) * (guint64) timebase_info.numer;
2928 t_high += (t_low >> 32);
2929 result_high = t_high / (guint64) timebase_info.denom;
2930 result_low = (((t_high % (guint64) timebase_info.denom) << 32) +
2931 (t_low & 0xffffffff)) /
2932 (guint64) timebase_info.denom;
2933 val = ((result_high << 32) | result_low) / 1000;
2938 /* nanoseconds to microseconds */
2946 g_get_monotonic_time (void)
2951 result = clock_gettime (CLOCK_MONOTONIC, &ts);
2953 if G_UNLIKELY (result != 0)
2954 g_error ("GLib requires working CLOCK_MONOTONIC");
2956 return (((gint64) ts.tv_sec) * 1000000) + (ts.tv_nsec / 1000);
2961 g_main_dispatch_free (gpointer dispatch)
2966 /* Running the main loop */
2968 static GMainDispatch *
2971 static GPrivate depth_private = G_PRIVATE_INIT (g_main_dispatch_free);
2972 GMainDispatch *dispatch;
2974 dispatch = g_private_get (&depth_private);
2977 dispatch = g_private_set_alloc0 (&depth_private, sizeof (GMainDispatch));
2985 * Returns the depth of the stack of calls to
2986 * g_main_context_dispatch() on any #GMainContext in the current thread.
2987 * That is, when called from the toplevel, it gives 0. When
2988 * called from within a callback from g_main_context_iteration()
2989 * (or g_main_loop_run(), etc.) it returns 1. When called from within
2990 * a callback to a recursive call to g_main_context_iteration(),
2991 * it returns 2. And so forth.
2993 * This function is useful in a situation like the following:
2994 * Imagine an extremely simple "garbage collected" system.
2996 * |[<!-- language="C" -->
2997 * static GList *free_list;
3000 * allocate_memory (gsize size)
3002 * gpointer result = g_malloc (size);
3003 * free_list = g_list_prepend (free_list, result);
3008 * free_allocated_memory (void)
3011 * for (l = free_list; l; l = l->next);
3013 * g_list_free (free_list);
3021 * g_main_context_iteration (NULL, TRUE);
3022 * free_allocated_memory();
3026 * This works from an application, however, if you want to do the same
3027 * thing from a library, it gets more difficult, since you no longer
3028 * control the main loop. You might think you can simply use an idle
3029 * function to make the call to free_allocated_memory(), but that
3030 * doesn't work, since the idle function could be called from a
3031 * recursive callback. This can be fixed by using g_main_depth()
3033 * |[<!-- language="C" -->
3035 * allocate_memory (gsize size)
3037 * FreeListBlock *block = g_new (FreeListBlock, 1);
3038 * block->mem = g_malloc (size);
3039 * block->depth = g_main_depth ();
3040 * free_list = g_list_prepend (free_list, block);
3041 * return block->mem;
3045 * free_allocated_memory (void)
3049 * int depth = g_main_depth ();
3050 * for (l = free_list; l; );
3052 * GList *next = l->next;
3053 * FreeListBlock *block = l->data;
3054 * if (block->depth > depth)
3056 * g_free (block->mem);
3058 * free_list = g_list_delete_link (free_list, l);
3066 * There is a temptation to use g_main_depth() to solve
3067 * problems with reentrancy. For instance, while waiting for data
3068 * to be received from the network in response to a menu item,
3069 * the menu item might be selected again. It might seem that
3070 * one could make the menu item's callback return immediately
3071 * and do nothing if g_main_depth() returns a value greater than 1.
3072 * However, this should be avoided since the user then sees selecting
3073 * the menu item do nothing. Furthermore, you'll find yourself adding
3074 * these checks all over your code, since there are doubtless many,
3075 * many things that the user could do. Instead, you can use the
3076 * following techniques:
3078 * 1. Use gtk_widget_set_sensitive() or modal dialogs to prevent
3079 * the user from interacting with elements while the main
3080 * loop is recursing.
3082 * 2. Avoid main loop recursion in situations where you can't handle
3083 * arbitrary callbacks. Instead, structure your code so that you
3084 * simply return to the main loop and then get called again when
3085 * there is more work to do.
3087 * Returns: The main loop recursion level in the current thread
3092 GMainDispatch *dispatch = get_dispatch ();
3093 return dispatch->depth;
3097 * g_main_current_source:
3099 * Returns the currently firing source for this thread.
3101 * Returns: (transfer none) (nullable): The currently firing source or %NULL.
3106 g_main_current_source (void)
3108 GMainDispatch *dispatch = get_dispatch ();
3109 return dispatch->source;
3113 * g_source_is_destroyed:
3114 * @source: a #GSource
3116 * Returns whether @source has been destroyed.
3118 * This is important when you operate upon your objects
3119 * from within idle handlers, but may have freed the object
3120 * before the dispatch of your idle handler.
3122 * |[<!-- language="C" -->
3124 * idle_callback (gpointer data)
3126 * SomeWidget *self = data;
3128 * GDK_THREADS_ENTER ();
3129 * // do stuff with self
3130 * self->idle_id = 0;
3131 * GDK_THREADS_LEAVE ();
3133 * return G_SOURCE_REMOVE;
3137 * some_widget_do_stuff_later (SomeWidget *self)
3139 * self->idle_id = g_idle_add (idle_callback, self);
3143 * some_widget_finalize (GObject *object)
3145 * SomeWidget *self = SOME_WIDGET (object);
3147 * if (self->idle_id)
3148 * g_source_remove (self->idle_id);
3150 * G_OBJECT_CLASS (parent_class)->finalize (object);
3154 * This will fail in a multi-threaded application if the
3155 * widget is destroyed before the idle handler fires due
3156 * to the use after free in the callback. A solution, to
3157 * this particular problem, is to check to if the source
3158 * has already been destroy within the callback.
3160 * |[<!-- language="C" -->
3162 * idle_callback (gpointer data)
3164 * SomeWidget *self = data;
3166 * GDK_THREADS_ENTER ();
3167 * if (!g_source_is_destroyed (g_main_current_source ()))
3169 * // do stuff with self
3171 * GDK_THREADS_LEAVE ();
3177 * Calls to this function from a thread other than the one acquired by the
3178 * #GMainContext the #GSource is attached to are typically redundant, as the
3179 * source could be destroyed immediately after this function returns. However,
3180 * once a source is destroyed it cannot be un-destroyed, so this function can be
3181 * used for opportunistic checks from any thread.
3183 * Returns: %TRUE if the source has been destroyed
3188 g_source_is_destroyed (GSource *source)
3190 g_return_val_if_fail (source != NULL, TRUE);
3191 g_return_val_if_fail (g_atomic_int_get (&source->ref_count) > 0, TRUE);
3192 return SOURCE_DESTROYED (source);
3195 /* Temporarily remove all this source's file descriptors from the
3196 * poll(), so that if data comes available for one of the file descriptors
3197 * we don't continually spin in the poll()
3199 /* HOLDS: source->context's lock */
3201 block_source (GSource *source)
3205 g_return_if_fail (!SOURCE_BLOCKED (source));
3207 source->flags |= G_SOURCE_BLOCKED;
3209 if (source->context)
3211 tmp_list = source->poll_fds;
3214 g_main_context_remove_poll_unlocked (source->context, tmp_list->data);
3215 tmp_list = tmp_list->next;
3218 for (tmp_list = source->priv->fds; tmp_list; tmp_list = tmp_list->next)
3219 g_main_context_remove_poll_unlocked (source->context, tmp_list->data);
3222 if (source->priv && source->priv->child_sources)
3224 tmp_list = source->priv->child_sources;
3227 block_source (tmp_list->data);
3228 tmp_list = tmp_list->next;
3233 /* HOLDS: source->context's lock */
3235 unblock_source (GSource *source)
3239 g_return_if_fail (SOURCE_BLOCKED (source)); /* Source already unblocked */
3240 g_return_if_fail (!SOURCE_DESTROYED (source));
3242 source->flags &= ~G_SOURCE_BLOCKED;
3244 tmp_list = source->poll_fds;
3247 g_main_context_add_poll_unlocked (source->context, source->priority, tmp_list->data);
3248 tmp_list = tmp_list->next;
3251 for (tmp_list = source->priv->fds; tmp_list; tmp_list = tmp_list->next)
3252 g_main_context_add_poll_unlocked (source->context, source->priority, tmp_list->data);
3254 if (source->priv && source->priv->child_sources)
3256 tmp_list = source->priv->child_sources;
3259 unblock_source (tmp_list->data);
3260 tmp_list = tmp_list->next;
3265 /* HOLDS: context's lock */
3267 g_main_dispatch (GMainContext *context)
3269 GMainDispatch *current = get_dispatch ();
3272 for (i = 0; i < context->pending_dispatches->len; i++)
3274 GSource *source = context->pending_dispatches->pdata[i];
3276 context->pending_dispatches->pdata[i] = NULL;
3279 source->flags &= ~G_SOURCE_READY;
3281 if (!SOURCE_DESTROYED (source))
3283 gboolean was_in_call;
3284 gpointer user_data = NULL;
3285 GSourceFunc callback = NULL;
3286 GSourceCallbackFuncs *cb_funcs;
3288 gboolean need_destroy;
3290 gboolean (*dispatch) (GSource *,
3293 GSource *prev_source;
3294 gint64 begin_time_nsec G_GNUC_UNUSED;
3296 dispatch = source->source_funcs->dispatch;
3297 cb_funcs = source->callback_funcs;
3298 cb_data = source->callback_data;
3301 cb_funcs->ref (cb_data);
3303 if ((source->flags & G_SOURCE_CAN_RECURSE) == 0)
3304 block_source (source);
3306 was_in_call = source->flags & G_HOOK_FLAG_IN_CALL;
3307 source->flags |= G_HOOK_FLAG_IN_CALL;
3310 cb_funcs->get (cb_data, source, &callback, &user_data);
3312 UNLOCK_CONTEXT (context);
3314 /* These operations are safe because 'current' is thread-local
3315 * and not modified from anywhere but this function.
3317 prev_source = current->source;
3318 current->source = source;
3321 begin_time_nsec = G_TRACE_CURRENT_TIME;
3323 TRACE (GLIB_MAIN_BEFORE_DISPATCH (g_source_get_name (source), source,
3324 dispatch, callback, user_data));
3325 need_destroy = !(* dispatch) (source, callback, user_data);
3326 TRACE (GLIB_MAIN_AFTER_DISPATCH (g_source_get_name (source), source,
3327 dispatch, need_destroy));
3329 g_trace_mark (begin_time_nsec, G_TRACE_CURRENT_TIME - begin_time_nsec,
3330 "GLib", "GSource.dispatch",
3332 (g_source_get_name (source) != NULL) ? g_source_get_name (source) : "(unnamed)",
3333 need_destroy ? "destroy" : "keep");
3335 current->source = prev_source;
3339 cb_funcs->unref (cb_data);
3341 LOCK_CONTEXT (context);
3344 source->flags &= ~G_HOOK_FLAG_IN_CALL;
3346 if (SOURCE_BLOCKED (source) && !SOURCE_DESTROYED (source))
3347 unblock_source (source);
3349 /* Note: this depends on the fact that we can't switch
3350 * sources from one main context to another
3352 if (need_destroy && !SOURCE_DESTROYED (source))
3354 g_assert (source->context == context);
3355 g_source_destroy_internal (source, context, TRUE);
3359 g_source_unref_internal (source, context, TRUE);
3362 g_ptr_array_set_size (context->pending_dispatches, 0);
3366 * g_main_context_acquire:
3367 * @context: a #GMainContext
3369 * Tries to become the owner of the specified context.
3370 * If some other thread is the owner of the context,
3371 * returns %FALSE immediately. Ownership is properly
3372 * recursive: the owner can require ownership again
3373 * and will release ownership when g_main_context_release()
3374 * is called as many times as g_main_context_acquire().
3376 * You must be the owner of a context before you
3377 * can call g_main_context_prepare(), g_main_context_query(),
3378 * g_main_context_check(), g_main_context_dispatch().
3380 * Returns: %TRUE if the operation succeeded, and
3381 * this thread is now the owner of @context.
3384 g_main_context_acquire (GMainContext *context)
3386 gboolean result = FALSE;
3387 GThread *self = G_THREAD_SELF;
3389 if (context == NULL)
3390 context = g_main_context_default ();
3392 LOCK_CONTEXT (context);
3394 if (!context->owner)
3396 context->owner = self;
3397 g_assert (context->owner_count == 0);
3398 TRACE (GLIB_MAIN_CONTEXT_ACQUIRE (context, TRUE /* success */));
3401 if (context->owner == self)
3403 context->owner_count++;
3408 TRACE (GLIB_MAIN_CONTEXT_ACQUIRE (context, FALSE /* failure */));
3411 UNLOCK_CONTEXT (context);
3417 * g_main_context_release:
3418 * @context: a #GMainContext
3420 * Releases ownership of a context previously acquired by this thread
3421 * with g_main_context_acquire(). If the context was acquired multiple
3422 * times, the ownership will be released only when g_main_context_release()
3423 * is called as many times as it was acquired.
3426 g_main_context_release (GMainContext *context)
3428 if (context == NULL)
3429 context = g_main_context_default ();
3431 LOCK_CONTEXT (context);
3433 context->owner_count--;
3434 if (context->owner_count == 0)
3436 TRACE (GLIB_MAIN_CONTEXT_RELEASE (context));
3438 context->owner = NULL;
3440 if (context->waiters)
3442 GMainWaiter *waiter = context->waiters->data;
3443 gboolean loop_internal_waiter = (waiter->mutex == &context->mutex);
3444 context->waiters = g_slist_delete_link (context->waiters,
3446 if (!loop_internal_waiter)
3447 g_mutex_lock (waiter->mutex);
3449 g_cond_signal (waiter->cond);
3451 if (!loop_internal_waiter)
3452 g_mutex_unlock (waiter->mutex);
3456 UNLOCK_CONTEXT (context);
3460 g_main_context_wait_internal (GMainContext *context,
3464 gboolean result = FALSE;
3465 GThread *self = G_THREAD_SELF;
3466 gboolean loop_internal_waiter;
3468 if (context == NULL)
3469 context = g_main_context_default ();
3471 loop_internal_waiter = (mutex == &context->mutex);
3473 if (!loop_internal_waiter)
3474 LOCK_CONTEXT (context);
3476 if (context->owner && context->owner != self)
3481 waiter.mutex = mutex;
3483 context->waiters = g_slist_append (context->waiters, &waiter);
3485 if (!loop_internal_waiter)
3486 UNLOCK_CONTEXT (context);
3487 g_cond_wait (cond, mutex);
3488 if (!loop_internal_waiter)
3489 LOCK_CONTEXT (context);
3491 context->waiters = g_slist_remove (context->waiters, &waiter);
3494 if (!context->owner)
3496 context->owner = self;
3497 g_assert (context->owner_count == 0);
3500 if (context->owner == self)
3502 context->owner_count++;
3506 if (!loop_internal_waiter)
3507 UNLOCK_CONTEXT (context);
3513 * g_main_context_wait:
3514 * @context: a #GMainContext
3515 * @cond: a condition variable
3516 * @mutex: a mutex, currently held
3518 * Tries to become the owner of the specified context,
3519 * as with g_main_context_acquire(). But if another thread
3520 * is the owner, atomically drop @mutex and wait on @cond until
3521 * that owner releases ownership or until @cond is signaled, then
3522 * try again (once) to become the owner.
3524 * Returns: %TRUE if the operation succeeded, and
3525 * this thread is now the owner of @context.
3526 * Deprecated: 2.58: Use g_main_context_is_owner() and separate locking instead.
3529 g_main_context_wait (GMainContext *context,
3533 if (context == NULL)
3534 context = g_main_context_default ();
3536 if (G_UNLIKELY (cond != &context->cond || mutex != &context->mutex))
3538 static gboolean warned;
3542 g_critical ("WARNING!! g_main_context_wait() will be removed in a future release. "
3543 "If you see this message, please file a bug immediately.");
3548 return g_main_context_wait_internal (context, cond, mutex);
3552 * g_main_context_prepare:
3553 * @context: a #GMainContext
3554 * @priority: (out) (optional): location to store priority of highest priority
3555 * source already ready.
3557 * Prepares to poll sources within a main loop. The resulting information
3558 * for polling is determined by calling g_main_context_query ().
3560 * You must have successfully acquired the context with
3561 * g_main_context_acquire() before you may call this function.
3563 * Returns: %TRUE if some source is ready to be dispatched
3567 g_main_context_prepare (GMainContext *context,
3572 gint current_priority = G_MAXINT;
3576 if (context == NULL)
3577 context = g_main_context_default ();
3579 LOCK_CONTEXT (context);
3581 context->time_is_fresh = FALSE;
3583 if (context->in_check_or_prepare)
3585 g_warning ("g_main_context_prepare() called recursively from within a source's check() or "
3586 "prepare() member.");
3587 UNLOCK_CONTEXT (context);
3591 TRACE (GLIB_MAIN_CONTEXT_BEFORE_PREPARE (context));
3594 /* If recursing, finish up current dispatch, before starting over */
3595 if (context->pending_dispatches)
3598 g_main_dispatch (context, ¤t_time);
3600 UNLOCK_CONTEXT (context);
3605 /* If recursing, clear list of pending dispatches */
3607 for (i = 0; i < context->pending_dispatches->len; i++)
3609 if (context->pending_dispatches->pdata[i])
3610 g_source_unref_internal ((GSource *)context->pending_dispatches->pdata[i], context, TRUE);
3612 g_ptr_array_set_size (context->pending_dispatches, 0);
3614 /* Prepare all sources */
3616 context->timeout = -1;
3618 g_source_iter_init (&iter, context, TRUE);
3619 while (g_source_iter_next (&iter, &source))
3621 gint source_timeout = -1;
3623 if (SOURCE_DESTROYED (source) || SOURCE_BLOCKED (source))
3625 if ((n_ready > 0) && (source->priority > current_priority))
3628 if (!(source->flags & G_SOURCE_READY))
3631 gboolean (* prepare) (GSource *source,
3634 prepare = source->source_funcs->prepare;
3638 gint64 begin_time_nsec G_GNUC_UNUSED;
3640 context->in_check_or_prepare++;
3641 UNLOCK_CONTEXT (context);
3643 begin_time_nsec = G_TRACE_CURRENT_TIME;
3645 result = (* prepare) (source, &source_timeout);
3646 TRACE (GLIB_MAIN_AFTER_PREPARE (source, prepare, source_timeout));
3648 g_trace_mark (begin_time_nsec, G_TRACE_CURRENT_TIME - begin_time_nsec,
3649 "GLib", "GSource.prepare",
3651 (g_source_get_name (source) != NULL) ? g_source_get_name (source) : "(unnamed)",
3652 result ? "ready" : "unready");
3654 LOCK_CONTEXT (context);
3655 context->in_check_or_prepare--;
3659 source_timeout = -1;
3663 if (result == FALSE && source->priv->ready_time != -1)
3665 if (!context->time_is_fresh)
3667 context->time = g_get_monotonic_time ();
3668 context->time_is_fresh = TRUE;
3671 if (source->priv->ready_time <= context->time)
3680 /* rounding down will lead to spinning, so always round up */
3681 timeout = (source->priv->ready_time - context->time + 999) / 1000;
3683 if (source_timeout < 0 || timeout < source_timeout)
3684 source_timeout = MIN (timeout, G_MAXINT);
3690 GSource *ready_source = source;
3692 while (ready_source)
3694 ready_source->flags |= G_SOURCE_READY;
3695 ready_source = ready_source->priv->parent_source;
3700 if (source->flags & G_SOURCE_READY)
3703 current_priority = source->priority;
3704 context->timeout = 0;
3707 if (source_timeout >= 0)
3709 if (context->timeout < 0)
3710 context->timeout = source_timeout;
3712 context->timeout = MIN (context->timeout, source_timeout);
3715 g_source_iter_clear (&iter);
3717 TRACE (GLIB_MAIN_CONTEXT_AFTER_PREPARE (context, current_priority, n_ready));
3719 UNLOCK_CONTEXT (context);
3722 *priority = current_priority;
3724 return (n_ready > 0);
3728 * g_main_context_query:
3729 * @context: a #GMainContext
3730 * @max_priority: maximum priority source to check
3731 * @timeout_: (out): location to store timeout to be used in polling
3732 * @fds: (out caller-allocates) (array length=n_fds): location to
3733 * store #GPollFD records that need to be polled.
3734 * @n_fds: (in): length of @fds.
3736 * Determines information necessary to poll this main loop. You should
3737 * be careful to pass the resulting @fds array and its length @n_fds
3738 * as is when calling g_main_context_check(), as this function relies
3739 * on assumptions made when the array is filled.
3741 * You must have successfully acquired the context with
3742 * g_main_context_acquire() before you may call this function.
3744 * Returns: the number of records actually stored in @fds,
3745 * or, if more than @n_fds records need to be stored, the number
3746 * of records that need to be stored.
3749 g_main_context_query (GMainContext *context,
3756 GPollRec *pollrec, *lastpollrec;
3759 LOCK_CONTEXT (context);
3761 TRACE (GLIB_MAIN_CONTEXT_BEFORE_QUERY (context, max_priority));
3763 /* fds is filled sequentially from poll_records. Since poll_records
3764 * are incrementally sorted by file descriptor identifier, fds will
3765 * also be incrementally sorted.
3769 for (pollrec = context->poll_records; pollrec; pollrec = pollrec->next)
3771 if (pollrec->priority > max_priority)
3774 /* In direct contradiction to the Unix98 spec, IRIX runs into
3775 * difficulty if you pass in POLLERR, POLLHUP or POLLNVAL
3776 * flags in the events field of the pollfd while it should
3777 * just ignoring them. So we mask them out here.
3779 events = pollrec->fd->events & ~(G_IO_ERR|G_IO_HUP|G_IO_NVAL);
3781 /* This optimization --using the same GPollFD to poll for more
3782 * than one poll record-- relies on the poll records being
3783 * incrementally sorted.
3785 if (lastpollrec && pollrec->fd->fd == lastpollrec->fd->fd)
3787 if (n_poll - 1 < n_fds)
3788 fds[n_poll - 1].events |= events;
3794 fds[n_poll].fd = pollrec->fd->fd;
3795 fds[n_poll].events = events;
3796 fds[n_poll].revents = 0;
3802 lastpollrec = pollrec;
3805 context->poll_changed = FALSE;
3809 *timeout = context->timeout;
3811 context->time_is_fresh = FALSE;
3814 TRACE (GLIB_MAIN_CONTEXT_AFTER_QUERY (context, context->timeout,
3817 UNLOCK_CONTEXT (context);
3823 * g_main_context_check:
3824 * @context: a #GMainContext
3825 * @max_priority: the maximum numerical priority of sources to check
3826 * @fds: (array length=n_fds): array of #GPollFD's that was passed to
3827 * the last call to g_main_context_query()
3828 * @n_fds: return value of g_main_context_query()
3830 * Passes the results of polling back to the main loop. You should be
3831 * careful to pass @fds and its length @n_fds as received from
3832 * g_main_context_query(), as this functions relies on assumptions
3833 * on how @fds is filled.
3835 * You must have successfully acquired the context with
3836 * g_main_context_acquire() before you may call this function.
3838 * Returns: %TRUE if some sources are ready to be dispatched.
3841 g_main_context_check (GMainContext *context,
3852 LOCK_CONTEXT (context);
3854 if (context->in_check_or_prepare)
3856 g_warning ("g_main_context_check() called recursively from within a source's check() or "
3857 "prepare() member.");
3858 UNLOCK_CONTEXT (context);
3862 TRACE (GLIB_MAIN_CONTEXT_BEFORE_CHECK (context, max_priority, fds, n_fds));
3864 for (i = 0; i < n_fds; i++)
3866 if (fds[i].fd == context->wake_up_rec.fd)
3870 TRACE (GLIB_MAIN_CONTEXT_WAKEUP_ACKNOWLEDGE (context));
3871 g_wakeup_acknowledge (context->wakeup);
3877 /* If the set of poll file descriptors changed, bail out
3878 * and let the main loop rerun
3880 if (context->poll_changed)
3882 TRACE (GLIB_MAIN_CONTEXT_AFTER_CHECK (context, 0));
3884 UNLOCK_CONTEXT (context);
3888 /* The linear iteration below relies on the assumption that both
3889 * poll records and the fds array are incrementally sorted by file
3890 * descriptor identifier.
3892 pollrec = context->poll_records;
3894 while (pollrec && i < n_fds)
3896 /* Make sure that fds is sorted by file descriptor identifier. */
3897 g_assert (i <= 0 || fds[i - 1].fd < fds[i].fd);
3899 /* Skip until finding the first GPollRec matching the current GPollFD. */
3900 while (pollrec && pollrec->fd->fd != fds[i].fd)
3901 pollrec = pollrec->next;
3903 /* Update all consecutive GPollRecs that match. */
3904 while (pollrec && pollrec->fd->fd == fds[i].fd)
3906 if (pollrec->priority <= max_priority)
3908 pollrec->fd->revents =
3909 fds[i].revents & (pollrec->fd->events | G_IO_ERR | G_IO_HUP | G_IO_NVAL);
3911 pollrec = pollrec->next;
3914 /* Iterate to next GPollFD. */
3918 g_source_iter_init (&iter, context, TRUE);
3919 while (g_source_iter_next (&iter, &source))
3921 if (SOURCE_DESTROYED (source) || SOURCE_BLOCKED (source))
3923 if ((n_ready > 0) && (source->priority > max_priority))
3926 if (!(source->flags & G_SOURCE_READY))
3929 gboolean (* check) (GSource *source);
3931 check = source->source_funcs->check;
3935 gint64 begin_time_nsec G_GNUC_UNUSED;
3937 /* If the check function is set, call it. */
3938 context->in_check_or_prepare++;
3939 UNLOCK_CONTEXT (context);
3941 begin_time_nsec = G_TRACE_CURRENT_TIME;
3943 result = (* check) (source);
3945 TRACE (GLIB_MAIN_AFTER_CHECK (source, check, result));
3947 g_trace_mark (begin_time_nsec, G_TRACE_CURRENT_TIME - begin_time_nsec,
3948 "GLib", "GSource.check",
3950 (g_source_get_name (source) != NULL) ? g_source_get_name (source) : "(unnamed)",
3951 result ? "dispatch" : "ignore");
3953 LOCK_CONTEXT (context);
3954 context->in_check_or_prepare--;
3959 if (result == FALSE)
3963 /* If not already explicitly flagged ready by ->check()
3964 * (or if we have no check) then we can still be ready if
3965 * any of our fds poll as ready.
3967 for (tmp_list = source->priv->fds; tmp_list; tmp_list = tmp_list->next)
3969 GPollFD *pollfd = tmp_list->data;
3971 if (pollfd->revents)
3979 if (result == FALSE && source->priv->ready_time != -1)
3981 if (!context->time_is_fresh)
3983 context->time = g_get_monotonic_time ();
3984 context->time_is_fresh = TRUE;
3987 if (source->priv->ready_time <= context->time)
3993 GSource *ready_source = source;
3995 while (ready_source)
3997 ready_source->flags |= G_SOURCE_READY;
3998 ready_source = ready_source->priv->parent_source;
4003 if (source->flags & G_SOURCE_READY)
4005 g_source_ref (source);
4006 g_ptr_array_add (context->pending_dispatches, source);
4010 /* never dispatch sources with less priority than the first
4011 * one we choose to dispatch
4013 max_priority = source->priority;
4016 g_source_iter_clear (&iter);
4018 TRACE (GLIB_MAIN_CONTEXT_AFTER_CHECK (context, n_ready));
4020 UNLOCK_CONTEXT (context);
4026 * g_main_context_dispatch:
4027 * @context: a #GMainContext
4029 * Dispatches all pending sources.
4031 * You must have successfully acquired the context with
4032 * g_main_context_acquire() before you may call this function.
4035 g_main_context_dispatch (GMainContext *context)
4037 LOCK_CONTEXT (context);
4039 TRACE (GLIB_MAIN_CONTEXT_BEFORE_DISPATCH (context));
4041 if (context->pending_dispatches->len > 0)
4043 g_main_dispatch (context);
4046 TRACE (GLIB_MAIN_CONTEXT_AFTER_DISPATCH (context));
4048 UNLOCK_CONTEXT (context);
4051 /* HOLDS context lock */
4053 g_main_context_iterate (GMainContext *context,
4060 gboolean some_ready;
4061 gint nfds, allocated_nfds;
4062 GPollFD *fds = NULL;
4063 gint64 begin_time_nsec G_GNUC_UNUSED;
4065 UNLOCK_CONTEXT (context);
4067 begin_time_nsec = G_TRACE_CURRENT_TIME;
4069 if (!g_main_context_acquire (context))
4071 gboolean got_ownership;
4073 LOCK_CONTEXT (context);
4078 got_ownership = g_main_context_wait_internal (context,
4086 LOCK_CONTEXT (context);
4088 if (!context->cached_poll_array)
4090 context->cached_poll_array_size = context->n_poll_records;
4091 context->cached_poll_array = g_new (GPollFD, context->n_poll_records);
4094 allocated_nfds = context->cached_poll_array_size;
4095 fds = context->cached_poll_array;
4097 UNLOCK_CONTEXT (context);
4099 g_main_context_prepare (context, &max_priority);
4101 while ((nfds = g_main_context_query (context, max_priority, &timeout, fds,
4102 allocated_nfds)) > allocated_nfds)
4104 LOCK_CONTEXT (context);
4106 context->cached_poll_array_size = allocated_nfds = nfds;
4107 context->cached_poll_array = fds = g_new (GPollFD, nfds);
4108 UNLOCK_CONTEXT (context);
4114 g_main_context_poll (context, timeout, max_priority, fds, nfds);
4116 some_ready = g_main_context_check (context, max_priority, fds, nfds);
4119 g_main_context_dispatch (context);
4121 g_main_context_release (context);
4123 g_trace_mark (begin_time_nsec, G_TRACE_CURRENT_TIME - begin_time_nsec,
4124 "GLib", "g_main_context_iterate",
4125 "Context %p, %s ⇒ %s", context, block ? "blocking" : "non-blocking", some_ready ? "dispatched" : "nothing");
4127 LOCK_CONTEXT (context);
4133 * g_main_context_pending:
4134 * @context: (nullable): a #GMainContext (if %NULL, the default context will be used)
4136 * Checks if any sources have pending events for the given context.
4138 * Returns: %TRUE if events are pending.
4141 g_main_context_pending (GMainContext *context)
4146 context = g_main_context_default();
4148 LOCK_CONTEXT (context);
4149 retval = g_main_context_iterate (context, FALSE, FALSE, G_THREAD_SELF);
4150 UNLOCK_CONTEXT (context);
4156 * g_main_context_iteration:
4157 * @context: (nullable): a #GMainContext (if %NULL, the default context will be used)
4158 * @may_block: whether the call may block.
4160 * Runs a single iteration for the given main loop. This involves
4161 * checking to see if any event sources are ready to be processed,
4162 * then if no events sources are ready and @may_block is %TRUE, waiting
4163 * for a source to become ready, then dispatching the highest priority
4164 * events sources that are ready. Otherwise, if @may_block is %FALSE
4165 * sources are not waited to become ready, only those highest priority
4166 * events sources will be dispatched (if any), that are ready at this
4167 * given moment without further waiting.
4169 * Note that even when @may_block is %TRUE, it is still possible for
4170 * g_main_context_iteration() to return %FALSE, since the wait may
4171 * be interrupted for other reasons than an event source becoming ready.
4173 * Returns: %TRUE if events were dispatched.
4176 g_main_context_iteration (GMainContext *context, gboolean may_block)
4181 context = g_main_context_default();
4183 LOCK_CONTEXT (context);
4184 retval = g_main_context_iterate (context, may_block, TRUE, G_THREAD_SELF);
4185 UNLOCK_CONTEXT (context);
4192 * @context: (nullable): a #GMainContext (if %NULL, the default context will be used).
4193 * @is_running: set to %TRUE to indicate that the loop is running. This
4194 * is not very important since calling g_main_loop_run() will set this to
4197 * Creates a new #GMainLoop structure.
4199 * Returns: a new #GMainLoop.
4202 g_main_loop_new (GMainContext *context,
4203 gboolean is_running)
4208 context = g_main_context_default();
4210 g_main_context_ref (context);
4212 loop = g_new0 (GMainLoop, 1);
4213 loop->context = context;
4214 loop->is_running = is_running != FALSE;
4215 loop->ref_count = 1;
4217 TRACE (GLIB_MAIN_LOOP_NEW (loop, context));
4224 * @loop: a #GMainLoop
4226 * Increases the reference count on a #GMainLoop object by one.
4231 g_main_loop_ref (GMainLoop *loop)
4233 g_return_val_if_fail (loop != NULL, NULL);
4234 g_return_val_if_fail (g_atomic_int_get (&loop->ref_count) > 0, NULL);
4236 g_atomic_int_inc (&loop->ref_count);
4242 * g_main_loop_unref:
4243 * @loop: a #GMainLoop
4245 * Decreases the reference count on a #GMainLoop object by one. If
4246 * the result is zero, free the loop and free all associated memory.
4249 g_main_loop_unref (GMainLoop *loop)
4251 g_return_if_fail (loop != NULL);
4252 g_return_if_fail (g_atomic_int_get (&loop->ref_count) > 0);
4254 if (!g_atomic_int_dec_and_test (&loop->ref_count))
4257 g_main_context_unref (loop->context);
4263 * @loop: a #GMainLoop
4265 * Runs a main loop until g_main_loop_quit() is called on the loop.
4266 * If this is called for the thread of the loop's #GMainContext,
4267 * it will process events from the loop, otherwise it will
4271 g_main_loop_run (GMainLoop *loop)
4273 GThread *self = G_THREAD_SELF;
4275 g_return_if_fail (loop != NULL);
4276 g_return_if_fail (g_atomic_int_get (&loop->ref_count) > 0);
4278 if (!g_main_context_acquire (loop->context))
4280 gboolean got_ownership = FALSE;
4282 /* Another thread owns this context */
4283 LOCK_CONTEXT (loop->context);
4285 g_atomic_int_inc (&loop->ref_count);
4286 g_atomic_int_set (&loop->is_running, TRUE);
4288 while (g_atomic_int_get (&loop->is_running) && !got_ownership)
4289 got_ownership = g_main_context_wait_internal (loop->context,
4290 &loop->context->cond,
4291 &loop->context->mutex);
4293 if (!g_atomic_int_get (&loop->is_running))
4295 UNLOCK_CONTEXT (loop->context);
4297 g_main_context_release (loop->context);
4298 g_main_loop_unref (loop);
4302 g_assert (got_ownership);
4305 LOCK_CONTEXT (loop->context);
4307 if (loop->context->in_check_or_prepare)
4309 g_warning ("g_main_loop_run(): called recursively from within a source's "
4310 "check() or prepare() member, iteration not possible.");
4314 g_atomic_int_inc (&loop->ref_count);
4315 g_atomic_int_set (&loop->is_running, TRUE);
4316 while (g_atomic_int_get (&loop->is_running))
4317 g_main_context_iterate (loop->context, TRUE, TRUE, self);
4319 UNLOCK_CONTEXT (loop->context);
4321 g_main_context_release (loop->context);
4323 g_main_loop_unref (loop);
4328 * @loop: a #GMainLoop
4330 * Stops a #GMainLoop from running. Any calls to g_main_loop_run()
4331 * for the loop will return.
4333 * Note that sources that have already been dispatched when
4334 * g_main_loop_quit() is called will still be executed.
4337 g_main_loop_quit (GMainLoop *loop)
4339 g_return_if_fail (loop != NULL);
4340 g_return_if_fail (g_atomic_int_get (&loop->ref_count) > 0);
4342 LOCK_CONTEXT (loop->context);
4343 g_atomic_int_set (&loop->is_running, FALSE);
4344 g_wakeup_signal (loop->context->wakeup);
4346 g_cond_broadcast (&loop->context->cond);
4348 UNLOCK_CONTEXT (loop->context);
4350 TRACE (GLIB_MAIN_LOOP_QUIT (loop));
4354 * g_main_loop_is_running:
4355 * @loop: a #GMainLoop.
4357 * Checks to see if the main loop is currently being run via g_main_loop_run().
4359 * Returns: %TRUE if the mainloop is currently being run.
4362 g_main_loop_is_running (GMainLoop *loop)
4364 g_return_val_if_fail (loop != NULL, FALSE);
4365 g_return_val_if_fail (g_atomic_int_get (&loop->ref_count) > 0, FALSE);
4367 return g_atomic_int_get (&loop->is_running);
4371 * g_main_loop_get_context:
4372 * @loop: a #GMainLoop.
4374 * Returns the #GMainContext of @loop.
4376 * Returns: (transfer none): the #GMainContext of @loop
4379 g_main_loop_get_context (GMainLoop *loop)
4381 g_return_val_if_fail (loop != NULL, NULL);
4382 g_return_val_if_fail (g_atomic_int_get (&loop->ref_count) > 0, NULL);
4384 return loop->context;
4387 /* HOLDS: context's lock */
4389 g_main_context_poll (GMainContext *context,
4395 #ifdef G_MAIN_POLL_DEBUG
4401 GPollFunc poll_func;
4403 if (n_fds || timeout != 0)
4407 #ifdef G_MAIN_POLL_DEBUG
4409 if (_g_main_poll_debug)
4411 g_print ("polling context=%p n=%d timeout=%d\n",
4412 context, n_fds, timeout);
4413 poll_timer = g_timer_new ();
4417 LOCK_CONTEXT (context);
4419 poll_func = context->poll_func;
4421 UNLOCK_CONTEXT (context);
4422 ret = (*poll_func) (fds, n_fds, timeout);
4424 if (ret < 0 && errsv != EINTR)
4427 g_warning ("poll(2) failed due to: %s.",
4428 g_strerror (errsv));
4430 /* If g_poll () returns -1, it has already called g_warning() */
4434 #ifdef G_MAIN_POLL_DEBUG
4435 if (_g_main_poll_debug)
4437 LOCK_CONTEXT (context);
4439 g_print ("g_main_poll(%d) timeout: %d - elapsed %12.10f seconds",
4442 g_timer_elapsed (poll_timer, NULL));
4443 g_timer_destroy (poll_timer);
4444 pollrec = context->poll_records;
4446 while (pollrec != NULL)
4451 if (fds[i].fd == pollrec->fd->fd &&
4452 pollrec->fd->events &&
4455 g_print (" [" G_POLLFD_FORMAT " :", fds[i].fd);
4456 if (fds[i].revents & G_IO_IN)
4458 if (fds[i].revents & G_IO_OUT)
4460 if (fds[i].revents & G_IO_PRI)
4462 if (fds[i].revents & G_IO_ERR)
4464 if (fds[i].revents & G_IO_HUP)
4466 if (fds[i].revents & G_IO_NVAL)
4472 pollrec = pollrec->next;
4476 UNLOCK_CONTEXT (context);
4479 } /* if (n_fds || timeout != 0) */
4483 * g_main_context_add_poll:
4484 * @context: (nullable): a #GMainContext (or %NULL for the default context)
4485 * @fd: a #GPollFD structure holding information about a file
4486 * descriptor to watch.
4487 * @priority: the priority for this file descriptor which should be
4488 * the same as the priority used for g_source_attach() to ensure that the
4489 * file descriptor is polled whenever the results may be needed.
4491 * Adds a file descriptor to the set of file descriptors polled for
4492 * this context. This will very seldom be used directly. Instead
4493 * a typical event source will use g_source_add_unix_fd() instead.
4496 g_main_context_add_poll (GMainContext *context,
4501 context = g_main_context_default ();
4503 g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
4504 g_return_if_fail (fd);
4506 LOCK_CONTEXT (context);
4507 g_main_context_add_poll_unlocked (context, priority, fd);
4508 UNLOCK_CONTEXT (context);
4511 /* HOLDS: main_loop_lock */
4513 g_main_context_add_poll_unlocked (GMainContext *context,
4517 GPollRec *prevrec, *nextrec;
4518 GPollRec *newrec = g_slice_new (GPollRec);
4520 /* This file descriptor may be checked before we ever poll */
4523 newrec->priority = priority;
4525 /* Poll records are incrementally sorted by file descriptor identifier. */
4527 nextrec = context->poll_records;
4530 if (nextrec->fd->fd > fd->fd)
4533 nextrec = nextrec->next;
4537 prevrec->next = newrec;
4539 context->poll_records = newrec;
4541 newrec->prev = prevrec;
4542 newrec->next = nextrec;
4545 nextrec->prev = newrec;
4547 context->n_poll_records++;
4549 context->poll_changed = TRUE;
4551 /* Now wake up the main loop if it is waiting in the poll() */
4552 g_wakeup_signal (context->wakeup);
4556 * g_main_context_remove_poll:
4557 * @context:a #GMainContext
4558 * @fd: a #GPollFD descriptor previously added with g_main_context_add_poll()
4560 * Removes file descriptor from the set of file descriptors to be
4561 * polled for a particular context.
4564 g_main_context_remove_poll (GMainContext *context,
4568 context = g_main_context_default ();
4570 g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
4571 g_return_if_fail (fd);
4573 LOCK_CONTEXT (context);
4574 g_main_context_remove_poll_unlocked (context, fd);
4575 UNLOCK_CONTEXT (context);
4579 g_main_context_remove_poll_unlocked (GMainContext *context,
4582 GPollRec *pollrec, *prevrec, *nextrec;
4585 pollrec = context->poll_records;
4589 nextrec = pollrec->next;
4590 if (pollrec->fd == fd)
4592 if (prevrec != NULL)
4593 prevrec->next = nextrec;
4595 context->poll_records = nextrec;
4597 if (nextrec != NULL)
4598 nextrec->prev = prevrec;
4600 g_slice_free (GPollRec, pollrec);
4602 context->n_poll_records--;
4609 context->poll_changed = TRUE;
4611 /* Now wake up the main loop if it is waiting in the poll() */
4612 g_wakeup_signal (context->wakeup);
4616 * g_source_get_current_time:
4617 * @source: a #GSource
4618 * @timeval: #GTimeVal structure in which to store current time.
4620 * This function ignores @source and is otherwise the same as
4621 * g_get_current_time().
4623 * Deprecated: 2.28: use g_source_get_time() instead
4625 G_GNUC_BEGIN_IGNORE_DEPRECATIONS
4627 g_source_get_current_time (GSource *source,
4630 g_get_current_time (timeval);
4632 G_GNUC_END_IGNORE_DEPRECATIONS
4635 * g_source_get_time:
4636 * @source: a #GSource
4638 * Gets the time to be used when checking this source. The advantage of
4639 * calling this function over calling g_get_monotonic_time() directly is
4640 * that when checking multiple sources, GLib can cache a single value
4641 * instead of having to repeatedly get the system monotonic time.
4643 * The time here is the system monotonic time, if available, or some
4644 * other reasonable alternative otherwise. See g_get_monotonic_time().
4646 * Returns: the monotonic time in microseconds
4651 g_source_get_time (GSource *source)
4653 GMainContext *context;
4656 g_return_val_if_fail (source != NULL, 0);
4657 g_return_val_if_fail (g_atomic_int_get (&source->ref_count) > 0, 0);
4658 g_return_val_if_fail (source->context != NULL, 0);
4660 context = source->context;
4662 LOCK_CONTEXT (context);
4664 if (!context->time_is_fresh)
4666 context->time = g_get_monotonic_time ();
4667 context->time_is_fresh = TRUE;
4670 result = context->time;
4672 UNLOCK_CONTEXT (context);
4678 * g_main_context_set_poll_func:
4679 * @context: a #GMainContext
4680 * @func: the function to call to poll all file descriptors
4682 * Sets the function to use to handle polling of file descriptors. It
4683 * will be used instead of the poll() system call
4684 * (or GLib's replacement function, which is used where
4685 * poll() isn't available).
4687 * This function could possibly be used to integrate the GLib event
4688 * loop with an external event loop.
4691 g_main_context_set_poll_func (GMainContext *context,
4695 context = g_main_context_default ();
4697 g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
4699 LOCK_CONTEXT (context);
4702 context->poll_func = func;
4704 context->poll_func = g_poll;
4706 UNLOCK_CONTEXT (context);
4710 * g_main_context_get_poll_func:
4711 * @context: a #GMainContext
4713 * Gets the poll function set by g_main_context_set_poll_func().
4715 * Returns: the poll function
4718 g_main_context_get_poll_func (GMainContext *context)
4723 context = g_main_context_default ();
4725 g_return_val_if_fail (g_atomic_int_get (&context->ref_count) > 0, NULL);
4727 LOCK_CONTEXT (context);
4728 result = context->poll_func;
4729 UNLOCK_CONTEXT (context);
4735 * g_main_context_wakeup:
4736 * @context: a #GMainContext
4738 * If @context is currently blocking in g_main_context_iteration()
4739 * waiting for a source to become ready, cause it to stop blocking
4740 * and return. Otherwise, cause the next invocation of
4741 * g_main_context_iteration() to return without blocking.
4743 * This API is useful for low-level control over #GMainContext; for
4744 * example, integrating it with main loop implementations such as
4747 * Another related use for this function is when implementing a main
4748 * loop with a termination condition, computed from multiple threads:
4750 * |[<!-- language="C" -->
4751 * #define NUM_TASKS 10
4752 * static gint tasks_remaining = NUM_TASKS; // (atomic)
4755 * while (g_atomic_int_get (&tasks_remaining) != 0)
4756 * g_main_context_iteration (NULL, TRUE);
4760 * |[<!-- language="C" -->
4763 * if (g_atomic_int_dec_and_test (&tasks_remaining))
4764 * g_main_context_wakeup (NULL);
4768 g_main_context_wakeup (GMainContext *context)
4771 context = g_main_context_default ();
4773 g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
4775 TRACE (GLIB_MAIN_CONTEXT_WAKEUP (context));
4777 g_wakeup_signal (context->wakeup);
4781 * g_main_context_is_owner:
4782 * @context: a #GMainContext
4784 * Determines whether this thread holds the (recursive)
4785 * ownership of this #GMainContext. This is useful to
4786 * know before waiting on another thread that may be
4787 * blocking to get ownership of @context.
4789 * Returns: %TRUE if current thread is owner of @context.
4794 g_main_context_is_owner (GMainContext *context)
4799 context = g_main_context_default ();
4801 LOCK_CONTEXT (context);
4802 is_owner = context->owner == G_THREAD_SELF;
4803 UNLOCK_CONTEXT (context);
4811 g_timeout_set_expiration (GTimeoutSource *timeout_source,
4812 gint64 current_time)
4816 if (timeout_source->seconds)
4819 static gint timer_perturb = -1;
4821 if (timer_perturb == -1)
4824 * we want a per machine/session unique 'random' value; try the dbus
4825 * address first, that has a UUID in it. If there is no dbus, use the
4826 * hostname for hashing.
4828 const char *session_bus_address = g_getenv ("DBUS_SESSION_BUS_ADDRESS");
4829 if (!session_bus_address)
4830 session_bus_address = g_getenv ("HOSTNAME");
4831 if (session_bus_address)
4832 timer_perturb = ABS ((gint) g_str_hash (session_bus_address)) % 1000000;
4837 expiration = current_time + (guint64) timeout_source->interval * 1000 * 1000;
4839 /* We want the microseconds part of the timeout to land on the
4840 * 'timer_perturb' mark, but we need to make sure we don't try to
4841 * set the timeout in the past. We do this by ensuring that we
4842 * always only *increase* the expiration time by adding a full
4843 * second in the case that the microsecond portion decreases.
4845 expiration -= timer_perturb;
4847 remainder = expiration % 1000000;
4848 if (remainder >= 1000000/4)
4849 expiration += 1000000;
4851 expiration -= remainder;
4852 expiration += timer_perturb;
4856 expiration = current_time + (guint64) timeout_source->interval * 1000;
4859 g_source_set_ready_time ((GSource *) timeout_source, expiration);
4863 g_timeout_dispatch (GSource *source,
4864 GSourceFunc callback,
4867 GTimeoutSource *timeout_source = (GTimeoutSource *)source;
4872 g_warning ("Timeout source dispatched without callback. "
4873 "You must call g_source_set_callback().");
4877 again = callback (user_data);
4879 TRACE (GLIB_TIMEOUT_DISPATCH (source, source->context, callback, user_data, again));
4882 g_timeout_set_expiration (timeout_source, g_source_get_time (source));
4888 * g_timeout_source_new:
4889 * @interval: the timeout interval in milliseconds.
4891 * Creates a new timeout source.
4893 * The source will not initially be associated with any #GMainContext
4894 * and must be added to one with g_source_attach() before it will be
4897 * The interval given is in terms of monotonic time, not wall clock
4898 * time. See g_get_monotonic_time().
4900 * Returns: the newly-created timeout source
4903 g_timeout_source_new (guint interval)
4905 GSource *source = g_source_new (&g_timeout_funcs, sizeof (GTimeoutSource));
4906 GTimeoutSource *timeout_source = (GTimeoutSource *)source;
4908 timeout_source->interval = interval;
4909 g_timeout_set_expiration (timeout_source, g_get_monotonic_time ());
4915 * g_timeout_source_new_seconds:
4916 * @interval: the timeout interval in seconds
4918 * Creates a new timeout source.
4920 * The source will not initially be associated with any #GMainContext
4921 * and must be added to one with g_source_attach() before it will be
4924 * The scheduling granularity/accuracy of this timeout source will be
4927 * The interval given is in terms of monotonic time, not wall clock time.
4928 * See g_get_monotonic_time().
4930 * Returns: the newly-created timeout source
4935 g_timeout_source_new_seconds (guint interval)
4937 GSource *source = g_source_new (&g_timeout_funcs, sizeof (GTimeoutSource));
4938 GTimeoutSource *timeout_source = (GTimeoutSource *)source;
4940 timeout_source->interval = interval;
4941 timeout_source->seconds = TRUE;
4943 g_timeout_set_expiration (timeout_source, g_get_monotonic_time ());
4950 * g_timeout_add_full: (rename-to g_timeout_add)
4951 * @priority: the priority of the timeout source. Typically this will be in
4952 * the range between #G_PRIORITY_DEFAULT and #G_PRIORITY_HIGH.
4953 * @interval: the time between calls to the function, in milliseconds
4954 * (1/1000ths of a second)
4955 * @function: function to call
4956 * @data: data to pass to @function
4957 * @notify: (nullable): function to call when the timeout is removed, or %NULL
4959 * Sets a function to be called at regular intervals, with the given
4960 * priority. The function is called repeatedly until it returns
4961 * %FALSE, at which point the timeout is automatically destroyed and
4962 * the function will not be called again. The @notify function is
4963 * called when the timeout is destroyed. The first call to the
4964 * function will be at the end of the first @interval.
4966 * Note that timeout functions may be delayed, due to the processing of other
4967 * event sources. Thus they should not be relied on for precise timing.
4968 * After each call to the timeout function, the time of the next
4969 * timeout is recalculated based on the current time and the given interval
4970 * (it does not try to 'catch up' time lost in delays).
4972 * See [memory management of sources][mainloop-memory-management] for details
4973 * on how to handle the return value and memory management of @data.
4975 * This internally creates a main loop source using g_timeout_source_new()
4976 * and attaches it to the global #GMainContext using g_source_attach(), so
4977 * the callback will be invoked in whichever thread is running that main
4978 * context. You can do these steps manually if you need greater control or to
4979 * use a custom main context.
4981 * The interval given is in terms of monotonic time, not wall clock time.
4982 * See g_get_monotonic_time().
4984 * Returns: the ID (greater than 0) of the event source.
4987 g_timeout_add_full (gint priority,
4989 GSourceFunc function,
4991 GDestroyNotify notify)
4996 g_return_val_if_fail (function != NULL, 0);
4998 source = g_timeout_source_new (interval);
5000 if (priority != G_PRIORITY_DEFAULT)
5001 g_source_set_priority (source, priority);
5003 g_source_set_callback (source, function, data, notify);
5004 id = g_source_attach (source, NULL);
5006 TRACE (GLIB_TIMEOUT_ADD (source, g_main_context_default (), id, priority, interval, function, data));
5008 g_source_unref (source);
5015 * @interval: the time between calls to the function, in milliseconds
5016 * (1/1000ths of a second)
5017 * @function: function to call
5018 * @data: data to pass to @function
5020 * Sets a function to be called at regular intervals, with the default
5021 * priority, #G_PRIORITY_DEFAULT. The function is called repeatedly
5022 * until it returns %FALSE, at which point the timeout is automatically
5023 * destroyed and the function will not be called again. The first call
5024 * to the function will be at the end of the first @interval.
5026 * Note that timeout functions may be delayed, due to the processing of other
5027 * event sources. Thus they should not be relied on for precise timing.
5028 * After each call to the timeout function, the time of the next
5029 * timeout is recalculated based on the current time and the given interval
5030 * (it does not try to 'catch up' time lost in delays).
5032 * See [memory management of sources][mainloop-memory-management] for details
5033 * on how to handle the return value and memory management of @data.
5035 * If you want to have a timer in the "seconds" range and do not care
5036 * about the exact time of the first call of the timer, use the
5037 * g_timeout_add_seconds() function; this function allows for more
5038 * optimizations and more efficient system power usage.
5040 * This internally creates a main loop source using g_timeout_source_new()
5041 * and attaches it to the global #GMainContext using g_source_attach(), so
5042 * the callback will be invoked in whichever thread is running that main
5043 * context. You can do these steps manually if you need greater control or to
5044 * use a custom main context.
5046 * It is safe to call this function from any thread.
5048 * The interval given is in terms of monotonic time, not wall clock
5049 * time. See g_get_monotonic_time().
5051 * Returns: the ID (greater than 0) of the event source.
5054 g_timeout_add (guint32 interval,
5055 GSourceFunc function,
5058 return g_timeout_add_full (G_PRIORITY_DEFAULT,
5059 interval, function, data, NULL);
5063 * g_timeout_add_seconds_full: (rename-to g_timeout_add_seconds)
5064 * @priority: the priority of the timeout source. Typically this will be in
5065 * the range between #G_PRIORITY_DEFAULT and #G_PRIORITY_HIGH.
5066 * @interval: the time between calls to the function, in seconds
5067 * @function: function to call
5068 * @data: data to pass to @function
5069 * @notify: (nullable): function to call when the timeout is removed, or %NULL
5071 * Sets a function to be called at regular intervals, with @priority.
5072 * The function is called repeatedly until it returns %FALSE, at which
5073 * point the timeout is automatically destroyed and the function will
5074 * not be called again.
5076 * Unlike g_timeout_add(), this function operates at whole second granularity.
5077 * The initial starting point of the timer is determined by the implementation
5078 * and the implementation is expected to group multiple timers together so that
5079 * they fire all at the same time.
5080 * To allow this grouping, the @interval to the first timer is rounded
5081 * and can deviate up to one second from the specified interval.
5082 * Subsequent timer iterations will generally run at the specified interval.
5084 * Note that timeout functions may be delayed, due to the processing of other
5085 * event sources. Thus they should not be relied on for precise timing.
5086 * After each call to the timeout function, the time of the next
5087 * timeout is recalculated based on the current time and the given @interval
5089 * See [memory management of sources][mainloop-memory-management] for details
5090 * on how to handle the return value and memory management of @data.
5092 * If you want timing more precise than whole seconds, use g_timeout_add()
5095 * The grouping of timers to fire at the same time results in a more power
5096 * and CPU efficient behavior so if your timer is in multiples of seconds
5097 * and you don't require the first timer exactly one second from now, the
5098 * use of g_timeout_add_seconds() is preferred over g_timeout_add().
5100 * This internally creates a main loop source using
5101 * g_timeout_source_new_seconds() and attaches it to the main loop context
5102 * using g_source_attach(). You can do these steps manually if you need
5105 * It is safe to call this function from any thread.
5107 * The interval given is in terms of monotonic time, not wall clock
5108 * time. See g_get_monotonic_time().
5110 * Returns: the ID (greater than 0) of the event source.
5115 g_timeout_add_seconds_full (gint priority,
5117 GSourceFunc function,
5119 GDestroyNotify notify)
5124 g_return_val_if_fail (function != NULL, 0);
5126 source = g_timeout_source_new_seconds (interval);
5128 if (priority != G_PRIORITY_DEFAULT)
5129 g_source_set_priority (source, priority);
5131 g_source_set_callback (source, function, data, notify);
5132 id = g_source_attach (source, NULL);
5133 g_source_unref (source);
5139 * g_timeout_add_seconds:
5140 * @interval: the time between calls to the function, in seconds
5141 * @function: function to call
5142 * @data: data to pass to @function
5144 * Sets a function to be called at regular intervals with the default
5145 * priority, #G_PRIORITY_DEFAULT. The function is called repeatedly until
5146 * it returns %FALSE, at which point the timeout is automatically destroyed
5147 * and the function will not be called again.
5149 * This internally creates a main loop source using
5150 * g_timeout_source_new_seconds() and attaches it to the main loop context
5151 * using g_source_attach(). You can do these steps manually if you need
5152 * greater control. Also see g_timeout_add_seconds_full().
5154 * It is safe to call this function from any thread.
5156 * Note that the first call of the timer may not be precise for timeouts
5157 * of one second. If you need finer precision and have such a timeout,
5158 * you may want to use g_timeout_add() instead.
5160 * See [memory management of sources][mainloop-memory-management] for details
5161 * on how to handle the return value and memory management of @data.
5163 * The interval given is in terms of monotonic time, not wall clock
5164 * time. See g_get_monotonic_time().
5166 * Returns: the ID (greater than 0) of the event source.
5171 g_timeout_add_seconds (guint interval,
5172 GSourceFunc function,
5175 g_return_val_if_fail (function != NULL, 0);
5177 return g_timeout_add_seconds_full (G_PRIORITY_DEFAULT, interval, function, data, NULL);
5180 /* Child watch functions */
5185 g_child_watch_prepare (GSource *source,
5193 g_child_watch_check (GSource *source)
5195 GChildWatchSource *child_watch_source;
5196 gboolean child_exited;
5198 child_watch_source = (GChildWatchSource *) source;
5200 child_exited = child_watch_source->poll.revents & G_IO_IN;
5207 * Note: We do _not_ check for the special value of STILL_ACTIVE
5208 * since we know that the process has exited and doing so runs into
5209 * problems if the child process "happens to return STILL_ACTIVE(259)"
5210 * as Microsoft's Platform SDK puts it.
5212 if (!GetExitCodeProcess (child_watch_source->pid, &child_status))
5214 gchar *emsg = g_win32_error_message (GetLastError ());
5215 g_warning (G_STRLOC ": GetExitCodeProcess() failed: %s", emsg);
5218 child_watch_source->child_status = -1;
5221 child_watch_source->child_status = child_status;
5224 return child_exited;
5228 g_child_watch_finalize (GSource *source)
5232 #else /* G_OS_WIN32 */
5235 wake_source (GSource *source)
5237 GMainContext *context;
5239 /* This should be thread-safe:
5241 * - if the source is currently being added to a context, that
5242 * context will be woken up anyway
5244 * - if the source is currently being destroyed, we simply need not
5247 * - the memory for the source will remain valid until after the
5248 * source finalize function was called (which would remove the
5249 * source from the global list which we are currently holding the
5252 * - the GMainContext will either be NULL or point to a live
5255 * - the GMainContext will remain valid since we hold the
5256 * main_context_list lock
5258 * Since we are holding a lot of locks here, don't try to enter any
5259 * more GMainContext functions for fear of dealock -- just hit the
5260 * GWakeup and run. Even if that's safe now, it could easily become
5261 * unsafe with some very minor changes in the future, and signal
5262 * handling is not the most well-tested codepath.
5264 G_LOCK(main_context_list);
5265 context = source->context;
5267 g_wakeup_signal (context->wakeup);
5268 G_UNLOCK(main_context_list);
5272 dispatch_unix_signals_unlocked (void)
5274 gboolean pending[NSIG];
5278 /* clear this first in case another one arrives while we're processing */
5279 g_atomic_int_set (&any_unix_signal_pending, 0);
5281 /* We atomically test/clear the bit from the global array in case
5282 * other signals arrive while we are dispatching.
5284 * We then can safely use our own array below without worrying about
5287 for (i = 0; i < NSIG; i++)
5289 /* Be very careful with (the volatile) unix_signal_pending.
5291 * We must ensure that it's not possible that we clear it without
5292 * handling the signal. We therefore must ensure that our pending
5293 * array has a field set (ie: we will do something about the
5294 * signal) before we clear the item in unix_signal_pending.
5296 * Note specifically: we must check _our_ array.
5298 pending[i] = g_atomic_int_compare_and_exchange (&unix_signal_pending[i], 1, 0);
5301 /* handle GChildWatchSource instances */
5302 if (pending[SIGCHLD])
5304 /* The only way we can do this is to scan all of the children.
5306 * The docs promise that we will not reap children that we are not
5307 * explicitly watching, so that ties our hands from calling
5308 * waitpid(-1). We also can't use siginfo's si_pid field since if
5309 * multiple SIGCHLD arrive at the same time, one of them can be
5310 * dropped (since a given UNIX signal can only be pending once).
5312 for (node = unix_child_watches; node; node = node->next)
5314 GChildWatchSource *source = node->data;
5316 if (!g_atomic_int_get (&source->child_exited))
5321 g_assert (source->pid > 0);
5323 pid = waitpid (source->pid, &source->child_status, WNOHANG);
5326 g_atomic_int_set (&source->child_exited, TRUE);
5327 wake_source ((GSource *) source);
5329 else if (pid == -1 && errno == ECHILD)
5331 g_warning ("GChildWatchSource: Exit status of a child process was requested but ECHILD was received by waitpid(). See the documentation of g_child_watch_source_new() for possible causes.");
5332 source->child_status = 0;
5333 g_atomic_int_set (&source->child_exited, TRUE);
5334 wake_source ((GSource *) source);
5337 while (pid == -1 && errno == EINTR);
5342 /* handle GUnixSignalWatchSource instances */
5343 for (node = unix_signal_watches; node; node = node->next)
5345 GUnixSignalWatchSource *source = node->data;
5347 if (pending[source->signum] &&
5348 g_atomic_int_compare_and_exchange (&source->pending, FALSE, TRUE))
5350 wake_source ((GSource *) source);
5357 dispatch_unix_signals (void)
5359 G_LOCK(unix_signal_lock);
5360 dispatch_unix_signals_unlocked ();
5361 G_UNLOCK(unix_signal_lock);
5365 g_child_watch_prepare (GSource *source,
5368 GChildWatchSource *child_watch_source;
5370 child_watch_source = (GChildWatchSource *) source;
5372 return g_atomic_int_get (&child_watch_source->child_exited);
5376 g_child_watch_check (GSource *source)
5378 GChildWatchSource *child_watch_source;
5380 child_watch_source = (GChildWatchSource *) source;
5382 return g_atomic_int_get (&child_watch_source->child_exited);
5386 g_unix_signal_watch_prepare (GSource *source,
5389 GUnixSignalWatchSource *unix_signal_source;
5391 unix_signal_source = (GUnixSignalWatchSource *) source;
5393 return g_atomic_int_get (&unix_signal_source->pending);
5397 g_unix_signal_watch_check (GSource *source)
5399 GUnixSignalWatchSource *unix_signal_source;
5401 unix_signal_source = (GUnixSignalWatchSource *) source;
5403 return g_atomic_int_get (&unix_signal_source->pending);
5407 g_unix_signal_watch_dispatch (GSource *source,
5408 GSourceFunc callback,
5411 GUnixSignalWatchSource *unix_signal_source;
5414 unix_signal_source = (GUnixSignalWatchSource *) source;
5418 g_warning ("Unix signal source dispatched without callback. "
5419 "You must call g_source_set_callback().");
5423 g_atomic_int_set (&unix_signal_source->pending, FALSE);
5425 again = (callback) (user_data);
5431 ref_unix_signal_handler_unlocked (int signum)
5433 /* Ensure we have the worker context */
5434 g_get_worker_context ();
5435 unix_signal_refcount[signum]++;
5436 if (unix_signal_refcount[signum] == 1)
5438 struct sigaction action;
5439 action.sa_handler = g_unix_signal_handler;
5440 sigemptyset (&action.sa_mask);
5442 action.sa_flags = SA_RESTART | SA_NOCLDSTOP;
5444 action.sa_flags = SA_NOCLDSTOP;
5446 sigaction (signum, &action, NULL);
5451 unref_unix_signal_handler_unlocked (int signum)
5453 unix_signal_refcount[signum]--;
5454 if (unix_signal_refcount[signum] == 0)
5456 struct sigaction action;
5457 memset (&action, 0, sizeof (action));
5458 action.sa_handler = SIG_DFL;
5459 sigemptyset (&action.sa_mask);
5460 sigaction (signum, &action, NULL);
5464 /* Return a const string to avoid allocations. We lose precision in the case the
5465 * @signum is unrecognised, but that’ll do. */
5466 static const gchar *
5467 signum_to_string (int signum)
5469 /* See `man 0P signal.h` */
5472 return ("GUnixSignalSource: " #s);
5475 /* These signals are guaranteed to exist by POSIX. */
5482 /* Frustratingly, these are not, and hence for brevity the list is
5521 return "GUnixSignalSource: Unrecognized signal";
5527 _g_main_create_unix_signal_watch (int signum)
5530 GUnixSignalWatchSource *unix_signal_source;
5532 source = g_source_new (&g_unix_signal_funcs, sizeof (GUnixSignalWatchSource));
5533 unix_signal_source = (GUnixSignalWatchSource *) source;
5535 unix_signal_source->signum = signum;
5536 unix_signal_source->pending = FALSE;
5538 /* Set a default name on the source, just in case the caller does not. */
5539 g_source_set_name (source, signum_to_string (signum));
5541 G_LOCK (unix_signal_lock);
5542 ref_unix_signal_handler_unlocked (signum);
5543 unix_signal_watches = g_slist_prepend (unix_signal_watches, unix_signal_source);
5544 dispatch_unix_signals_unlocked ();
5545 G_UNLOCK (unix_signal_lock);
5551 g_unix_signal_watch_finalize (GSource *source)
5553 GUnixSignalWatchSource *unix_signal_source;
5555 unix_signal_source = (GUnixSignalWatchSource *) source;
5557 G_LOCK (unix_signal_lock);
5558 unref_unix_signal_handler_unlocked (unix_signal_source->signum);
5559 unix_signal_watches = g_slist_remove (unix_signal_watches, source);
5560 G_UNLOCK (unix_signal_lock);
5564 g_child_watch_finalize (GSource *source)
5566 G_LOCK (unix_signal_lock);
5567 unix_child_watches = g_slist_remove (unix_child_watches, source);
5568 unref_unix_signal_handler_unlocked (SIGCHLD);
5569 G_UNLOCK (unix_signal_lock);
5572 #endif /* G_OS_WIN32 */
5575 g_child_watch_dispatch (GSource *source,
5576 GSourceFunc callback,
5579 GChildWatchSource *child_watch_source;
5580 GChildWatchFunc child_watch_callback = (GChildWatchFunc) callback;
5582 child_watch_source = (GChildWatchSource *) source;
5586 g_warning ("Child watch source dispatched without callback. "
5587 "You must call g_source_set_callback().");
5591 (child_watch_callback) (child_watch_source->pid, child_watch_source->child_status, user_data);
5593 /* We never keep a child watch source around as the child is gone */
5600 g_unix_signal_handler (int signum)
5602 gint saved_errno = errno;
5604 #if defined(G_ATOMIC_LOCK_FREE) && defined(__GCC_HAVE_SYNC_COMPARE_AND_SWAP_4)
5605 g_atomic_int_set (&unix_signal_pending[signum], 1);
5606 g_atomic_int_set (&any_unix_signal_pending, 1);
5608 #warning "Can't use atomics in g_unix_signal_handler(): Unix signal handling will be racy"
5609 unix_signal_pending[signum] = 1;
5610 any_unix_signal_pending = 1;
5613 g_wakeup_signal (glib_worker_context->wakeup);
5615 errno = saved_errno;
5618 #endif /* !G_OS_WIN32 */
5621 * g_child_watch_source_new:
5622 * @pid: process to watch. On POSIX the positive pid of a child process. On
5623 * Windows a handle for a process (which doesn't have to be a child).
5625 * Creates a new child_watch source.
5627 * The source will not initially be associated with any #GMainContext
5628 * and must be added to one with g_source_attach() before it will be
5631 * Note that child watch sources can only be used in conjunction with
5632 * `g_spawn...` when the %G_SPAWN_DO_NOT_REAP_CHILD flag is used.
5634 * Note that on platforms where #GPid must be explicitly closed
5635 * (see g_spawn_close_pid()) @pid must not be closed while the
5636 * source is still active. Typically, you will want to call
5637 * g_spawn_close_pid() in the callback function for the source.
5639 * On POSIX platforms, the following restrictions apply to this API
5640 * due to limitations in POSIX process interfaces:
5642 * * @pid must be a child of this process
5643 * * @pid must be positive
5644 * * the application must not call `waitpid` with a non-positive
5645 * first argument, for instance in another thread
5646 * * the application must not wait for @pid to exit by any other
5647 * mechanism, including `waitpid(pid, ...)` or a second child-watch
5648 * source for the same @pid
5649 * * the application must not ignore `SIGCHLD`
5651 * If any of those conditions are not met, this and related APIs will
5652 * not work correctly. This can often be diagnosed via a GLib warning
5653 * stating that `ECHILD` was received by `waitpid`.
5655 * Calling `waitpid` for specific processes other than @pid remains a
5656 * valid thing to do.
5658 * Returns: the newly-created child watch source
5663 g_child_watch_source_new (GPid pid)
5666 GChildWatchSource *child_watch_source;
5669 g_return_val_if_fail (pid > 0, NULL);
5672 source = g_source_new (&g_child_watch_funcs, sizeof (GChildWatchSource));
5673 child_watch_source = (GChildWatchSource *)source;
5675 /* Set a default name on the source, just in case the caller does not. */
5676 g_source_set_name (source, "GChildWatchSource");
5678 child_watch_source->pid = pid;
5681 child_watch_source->poll.fd = (gintptr) pid;
5682 child_watch_source->poll.events = G_IO_IN;
5684 g_source_add_poll (source, &child_watch_source->poll);
5685 #else /* G_OS_WIN32 */
5686 G_LOCK (unix_signal_lock);
5687 ref_unix_signal_handler_unlocked (SIGCHLD);
5688 unix_child_watches = g_slist_prepend (unix_child_watches, child_watch_source);
5689 if (waitpid (pid, &child_watch_source->child_status, WNOHANG) > 0)
5690 child_watch_source->child_exited = TRUE;
5691 G_UNLOCK (unix_signal_lock);
5692 #endif /* G_OS_WIN32 */
5698 * g_child_watch_add_full: (rename-to g_child_watch_add)
5699 * @priority: the priority of the idle source. Typically this will be in the
5700 * range between #G_PRIORITY_DEFAULT_IDLE and #G_PRIORITY_HIGH_IDLE.
5701 * @pid: process to watch. On POSIX the positive pid of a child process. On
5702 * Windows a handle for a process (which doesn't have to be a child).
5703 * @function: function to call
5704 * @data: data to pass to @function
5705 * @notify: (nullable): function to call when the idle is removed, or %NULL
5707 * Sets a function to be called when the child indicated by @pid
5708 * exits, at the priority @priority.
5710 * If you obtain @pid from g_spawn_async() or g_spawn_async_with_pipes()
5711 * you will need to pass #G_SPAWN_DO_NOT_REAP_CHILD as flag to
5712 * the spawn function for the child watching to work.
5714 * In many programs, you will want to call g_spawn_check_exit_status()
5715 * in the callback to determine whether or not the child exited
5718 * Also, note that on platforms where #GPid must be explicitly closed
5719 * (see g_spawn_close_pid()) @pid must not be closed while the source
5720 * is still active. Typically, you should invoke g_spawn_close_pid()
5721 * in the callback function for the source.
5723 * GLib supports only a single callback per process id.
5724 * On POSIX platforms, the same restrictions mentioned for
5725 * g_child_watch_source_new() apply to this function.
5727 * This internally creates a main loop source using
5728 * g_child_watch_source_new() and attaches it to the main loop context
5729 * using g_source_attach(). You can do these steps manually if you
5730 * need greater control.
5732 * Returns: the ID (greater than 0) of the event source.
5737 g_child_watch_add_full (gint priority,
5739 GChildWatchFunc function,
5741 GDestroyNotify notify)
5746 g_return_val_if_fail (function != NULL, 0);
5748 g_return_val_if_fail (pid > 0, 0);
5751 source = g_child_watch_source_new (pid);
5753 if (priority != G_PRIORITY_DEFAULT)
5754 g_source_set_priority (source, priority);
5756 g_source_set_callback (source, (GSourceFunc) function, data, notify);
5757 id = g_source_attach (source, NULL);
5758 g_source_unref (source);
5764 * g_child_watch_add:
5765 * @pid: process id to watch. On POSIX the positive pid of a child
5766 * process. On Windows a handle for a process (which doesn't have to be
5768 * @function: function to call
5769 * @data: data to pass to @function
5771 * Sets a function to be called when the child indicated by @pid
5772 * exits, at a default priority, #G_PRIORITY_DEFAULT.
5774 * If you obtain @pid from g_spawn_async() or g_spawn_async_with_pipes()
5775 * you will need to pass #G_SPAWN_DO_NOT_REAP_CHILD as flag to
5776 * the spawn function for the child watching to work.
5778 * Note that on platforms where #GPid must be explicitly closed
5779 * (see g_spawn_close_pid()) @pid must not be closed while the
5780 * source is still active. Typically, you will want to call
5781 * g_spawn_close_pid() in the callback function for the source.
5783 * GLib supports only a single callback per process id.
5784 * On POSIX platforms, the same restrictions mentioned for
5785 * g_child_watch_source_new() apply to this function.
5787 * This internally creates a main loop source using
5788 * g_child_watch_source_new() and attaches it to the main loop context
5789 * using g_source_attach(). You can do these steps manually if you
5790 * need greater control.
5792 * Returns: the ID (greater than 0) of the event source.
5797 g_child_watch_add (GPid pid,
5798 GChildWatchFunc function,
5801 return g_child_watch_add_full (G_PRIORITY_DEFAULT, pid, function, data, NULL);
5805 /* Idle functions */
5808 g_idle_prepare (GSource *source,
5817 g_idle_check (GSource *source)
5823 g_idle_dispatch (GSource *source,
5824 GSourceFunc callback,
5831 g_warning ("Idle source dispatched without callback. "
5832 "You must call g_source_set_callback().");
5836 again = callback (user_data);
5838 TRACE (GLIB_IDLE_DISPATCH (source, source->context, callback, user_data, again));
5844 * g_idle_source_new:
5846 * Creates a new idle source.
5848 * The source will not initially be associated with any #GMainContext
5849 * and must be added to one with g_source_attach() before it will be
5850 * executed. Note that the default priority for idle sources is
5851 * %G_PRIORITY_DEFAULT_IDLE, as compared to other sources which
5852 * have a default priority of %G_PRIORITY_DEFAULT.
5854 * Returns: the newly-created idle source
5857 g_idle_source_new (void)
5861 source = g_source_new (&g_idle_funcs, sizeof (GSource));
5862 g_source_set_priority (source, G_PRIORITY_DEFAULT_IDLE);
5864 /* Set a default name on the source, just in case the caller does not. */
5865 g_source_set_name (source, "GIdleSource");
5871 * g_idle_add_full: (rename-to g_idle_add)
5872 * @priority: the priority of the idle source. Typically this will be in the
5873 * range between #G_PRIORITY_DEFAULT_IDLE and #G_PRIORITY_HIGH_IDLE.
5874 * @function: function to call
5875 * @data: data to pass to @function
5876 * @notify: (nullable): function to call when the idle is removed, or %NULL
5878 * Adds a function to be called whenever there are no higher priority
5879 * events pending. If the function returns %FALSE it is automatically
5880 * removed from the list of event sources and will not be called again.
5882 * See [memory management of sources][mainloop-memory-management] for details
5883 * on how to handle the return value and memory management of @data.
5885 * This internally creates a main loop source using g_idle_source_new()
5886 * and attaches it to the global #GMainContext using g_source_attach(), so
5887 * the callback will be invoked in whichever thread is running that main
5888 * context. You can do these steps manually if you need greater control or to
5889 * use a custom main context.
5891 * Returns: the ID (greater than 0) of the event source.
5894 g_idle_add_full (gint priority,
5895 GSourceFunc function,
5897 GDestroyNotify notify)
5902 g_return_val_if_fail (function != NULL, 0);
5904 source = g_idle_source_new ();
5906 if (priority != G_PRIORITY_DEFAULT_IDLE)
5907 g_source_set_priority (source, priority);
5909 g_source_set_callback (source, function, data, notify);
5910 id = g_source_attach (source, NULL);
5912 TRACE (GLIB_IDLE_ADD (source, g_main_context_default (), id, priority, function, data));
5914 g_source_unref (source);
5921 * @function: function to call
5922 * @data: data to pass to @function.
5924 * Adds a function to be called whenever there are no higher priority
5925 * events pending to the default main loop. The function is given the
5926 * default idle priority, #G_PRIORITY_DEFAULT_IDLE. If the function
5927 * returns %FALSE it is automatically removed from the list of event
5928 * sources and will not be called again.
5930 * See [memory management of sources][mainloop-memory-management] for details
5931 * on how to handle the return value and memory management of @data.
5933 * This internally creates a main loop source using g_idle_source_new()
5934 * and attaches it to the global #GMainContext using g_source_attach(), so
5935 * the callback will be invoked in whichever thread is running that main
5936 * context. You can do these steps manually if you need greater control or to
5937 * use a custom main context.
5939 * Returns: the ID (greater than 0) of the event source.
5942 g_idle_add (GSourceFunc function,
5945 return g_idle_add_full (G_PRIORITY_DEFAULT_IDLE, function, data, NULL);
5949 * g_idle_remove_by_data:
5950 * @data: the data for the idle source's callback.
5952 * Removes the idle function with the given data.
5954 * Returns: %TRUE if an idle source was found and removed.
5957 g_idle_remove_by_data (gpointer data)
5959 return g_source_remove_by_funcs_user_data (&g_idle_funcs, data);
5963 * g_main_context_invoke:
5964 * @context: (nullable): a #GMainContext, or %NULL
5965 * @function: function to call
5966 * @data: data to pass to @function
5968 * Invokes a function in such a way that @context is owned during the
5969 * invocation of @function.
5971 * If @context is %NULL then the global default main context — as
5972 * returned by g_main_context_default() — is used.
5974 * If @context is owned by the current thread, @function is called
5975 * directly. Otherwise, if @context is the thread-default main context
5976 * of the current thread and g_main_context_acquire() succeeds, then
5977 * @function is called and g_main_context_release() is called
5980 * In any other case, an idle source is created to call @function and
5981 * that source is attached to @context (presumably to be run in another
5982 * thread). The idle source is attached with #G_PRIORITY_DEFAULT
5983 * priority. If you want a different priority, use
5984 * g_main_context_invoke_full().
5986 * Note that, as with normal idle functions, @function should probably
5987 * return %FALSE. If it returns %TRUE, it will be continuously run in a
5988 * loop (and may prevent this call from returning).
5993 g_main_context_invoke (GMainContext *context,
5994 GSourceFunc function,
5997 g_main_context_invoke_full (context,
5999 function, data, NULL);
6003 * g_main_context_invoke_full:
6004 * @context: (nullable): a #GMainContext, or %NULL
6005 * @priority: the priority at which to run @function
6006 * @function: function to call
6007 * @data: data to pass to @function
6008 * @notify: (nullable): a function to call when @data is no longer in use, or %NULL.
6010 * Invokes a function in such a way that @context is owned during the
6011 * invocation of @function.
6013 * This function is the same as g_main_context_invoke() except that it
6014 * lets you specify the priority in case @function ends up being
6015 * scheduled as an idle and also lets you give a #GDestroyNotify for @data.
6017 * @notify should not assume that it is called from any particular
6018 * thread or with any particular context acquired.
6023 g_main_context_invoke_full (GMainContext *context,
6025 GSourceFunc function,
6027 GDestroyNotify notify)
6029 g_return_if_fail (function != NULL);
6032 context = g_main_context_default ();
6034 if (g_main_context_is_owner (context))
6036 while (function (data));
6043 GMainContext *thread_default;
6045 thread_default = g_main_context_get_thread_default ();
6047 if (!thread_default)
6048 thread_default = g_main_context_default ();
6050 if (thread_default == context && g_main_context_acquire (context))
6052 while (function (data));
6054 g_main_context_release (context);
6063 source = g_idle_source_new ();
6064 g_source_set_priority (source, priority);
6065 g_source_set_callback (source, function, data, notify);
6066 g_source_attach (source, context);
6067 g_source_unref (source);
6073 glib_worker_main (gpointer data)
6077 g_main_context_iteration (glib_worker_context, TRUE);
6080 if (g_atomic_int_get (&any_unix_signal_pending))
6081 dispatch_unix_signals ();
6085 return NULL; /* worst GCC warning message ever... */
6089 g_get_worker_context (void)
6091 static gsize initialised;
6093 if (g_once_init_enter (&initialised))
6095 /* mask all signals in the worker thread */
6101 pthread_sigmask (SIG_SETMASK, &all, &prev_mask);
6103 glib_worker_context = g_main_context_new ();
6104 g_thread_new ("gmain", glib_worker_main, NULL);
6106 pthread_sigmask (SIG_SETMASK, &prev_mask, NULL);
6108 g_once_init_leave (&initialised, TRUE);
6111 return glib_worker_context;