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"
95 #ifdef G_MAIN_POLL_DEBUG
100 #include "gmain-internal.h"
101 #include "glib-init.h"
102 #include "glib-private.h"
106 * @title: The Main Event Loop
107 * @short_description: manages all available sources of events
109 * The main event loop manages all the available sources of events for
110 * GLib and GTK+ applications. These events can come from any number of
111 * different types of sources such as file descriptors (plain files,
112 * pipes or sockets) and timeouts. New types of event sources can also
113 * be added using g_source_attach().
115 * To allow multiple independent sets of sources to be handled in
116 * different threads, each source is associated with a #GMainContext.
117 * A GMainContext can only be running in a single thread, but
118 * sources can be added to it and removed from it from other threads.
120 * Each event source is assigned a priority. The default priority,
121 * #G_PRIORITY_DEFAULT, is 0. Values less than 0 denote higher priorities.
122 * Values greater than 0 denote lower priorities. Events from high priority
123 * sources are always processed before events from lower priority sources.
125 * Idle functions can also be added, and assigned a priority. These will
126 * be run whenever no events with a higher priority are ready to be processed.
128 * The #GMainLoop data type represents a main event loop. A GMainLoop is
129 * created with g_main_loop_new(). After adding the initial event sources,
130 * g_main_loop_run() is called. This continuously checks for new events from
131 * each of the event sources and dispatches them. Finally, the processing of
132 * an event from one of the sources leads to a call to g_main_loop_quit() to
133 * exit the main loop, and g_main_loop_run() returns.
135 * It is possible to create new instances of #GMainLoop recursively.
136 * This is often used in GTK+ applications when showing modal dialog
137 * boxes. Note that event sources are associated with a particular
138 * #GMainContext, and will be checked and dispatched for all main
139 * loops associated with that GMainContext.
141 * GTK+ contains wrappers of some of these functions, e.g. gtk_main(),
142 * gtk_main_quit() and gtk_events_pending().
144 * ## Creating new source types
146 * One of the unusual features of the #GMainLoop functionality
147 * is that new types of event source can be created and used in
148 * addition to the builtin type of event source. A new event source
149 * type is used for handling GDK events. A new source type is created
150 * by "deriving" from the #GSource structure. The derived type of
151 * source is represented by a structure that has the #GSource structure
152 * as a first element, and other elements specific to the new source
153 * type. To create an instance of the new source type, call
154 * g_source_new() passing in the size of the derived structure and
155 * a table of functions. These #GSourceFuncs determine the behavior of
156 * the new source type.
158 * New source types basically interact with the main context
159 * in two ways. Their prepare function in #GSourceFuncs can set a timeout
160 * to determine the maximum amount of time that the main loop will sleep
161 * before checking the source again. In addition, or as well, the source
162 * can add file descriptors to the set that the main context checks using
163 * g_source_add_poll().
165 * ## Customizing the main loop iteration
167 * Single iterations of a #GMainContext can be run with
168 * g_main_context_iteration(). In some cases, more detailed control
169 * of exactly how the details of the main loop work is desired, for
170 * instance, when integrating the #GMainLoop with an external main loop.
171 * In such cases, you can call the component functions of
172 * g_main_context_iteration() directly. These functions are
173 * g_main_context_prepare(), g_main_context_query(),
174 * g_main_context_check() and g_main_context_dispatch().
176 * ## State of a Main Context # {#mainloop-states}
178 * The operation of these functions can best be seen in terms
179 * of a state diagram, as shown in this image.
181 * ![](mainloop-states.gif)
183 * On UNIX, the GLib mainloop is incompatible with fork(). Any program
184 * using the mainloop must either exec() or exit() from the child
185 * without returning to the mainloop.
187 * ## Memory management of sources # {#mainloop-memory-management}
189 * There are two options for memory management of the user data passed to a
190 * #GSource to be passed to its callback on invocation. This data is provided
191 * in calls to g_timeout_add(), g_timeout_add_full(), g_idle_add(), etc. and
192 * more generally, using g_source_set_callback(). This data is typically an
193 * object which ‘owns’ the timeout or idle callback, such as a widget or a
194 * network protocol implementation. In many cases, it is an error for the
195 * callback to be invoked after this owning object has been destroyed, as that
196 * results in use of freed memory.
198 * The first, and preferred, option is to store the source ID returned by
199 * functions such as g_timeout_add() or g_source_attach(), and explicitly
200 * remove that source from the main context using g_source_remove() when the
201 * owning object is finalized. This ensures that the callback can only be
202 * invoked while the object is still alive.
204 * The second option is to hold a strong reference to the object in the
205 * callback, and to release it in the callback’s #GDestroyNotify. This ensures
206 * that the object is kept alive until after the source is finalized, which is
207 * guaranteed to be after it is invoked for the final time. The #GDestroyNotify
208 * is another callback passed to the ‘full’ variants of #GSource functions (for
209 * example, g_timeout_add_full()). It is called when the source is finalized,
210 * and is designed for releasing references like this.
212 * One important caveat of this second approach is that it will keep the object
213 * alive indefinitely if the main loop is stopped before the #GSource is
214 * invoked, which may be undesirable.
219 typedef struct _GTimeoutSource GTimeoutSource
;
220 typedef struct _GChildWatchSource GChildWatchSource
;
221 typedef struct _GUnixSignalWatchSource GUnixSignalWatchSource
;
222 typedef struct _GPollRec GPollRec
;
223 typedef struct _GSourceCallback GSourceCallback
;
227 G_SOURCE_READY
= 1 << G_HOOK_FLAG_USER_SHIFT
,
228 G_SOURCE_CAN_RECURSE
= 1 << (G_HOOK_FLAG_USER_SHIFT
+ 1),
229 G_SOURCE_BLOCKED
= 1 << (G_HOOK_FLAG_USER_SHIFT
+ 2)
232 typedef struct _GSourceList GSourceList
;
236 GSource
*head
, *tail
;
240 typedef struct _GMainWaiter GMainWaiter
;
248 typedef struct _GMainDispatch GMainDispatch
;
250 struct _GMainDispatch
256 #ifdef G_MAIN_POLL_DEBUG
257 gboolean _g_main_poll_debug
= FALSE
;
262 /* The following lock is used for both the list of sources
263 * and the list of poll records
271 volatile gint ref_count
;
273 GHashTable
*sources
; /* guint -> GSource */
275 GPtrArray
*pending_dispatches
;
276 gint timeout
; /* Timeout for current iteration */
280 gint in_check_or_prepare
;
282 GPollRec
*poll_records
;
283 guint n_poll_records
;
284 GPollFD
*cached_poll_array
;
285 guint cached_poll_array_size
;
291 /* Flag indicating whether the set of fd's changed during a poll */
292 gboolean poll_changed
;
297 gboolean time_is_fresh
;
300 struct _GSourceCallback
302 volatile gint ref_count
;
305 GDestroyNotify notify
;
310 GMainContext
*context
;
312 volatile gint ref_count
;
315 struct _GTimeoutSource
322 struct _GChildWatchSource
329 #else /* G_OS_WIN32 */
330 gboolean child_exited
;
331 #endif /* G_OS_WIN32 */
334 struct _GUnixSignalWatchSource
349 struct _GSourcePrivate
351 GSList
*child_sources
;
352 GSource
*parent_source
;
356 /* This is currently only used on UNIX, but we always declare it (and
357 * let it remain empty on Windows) to avoid #ifdef all over the place.
362 typedef struct _GSourceIter
364 GMainContext
*context
;
370 #define LOCK_CONTEXT(context) g_mutex_lock (&context->mutex)
371 #define UNLOCK_CONTEXT(context) g_mutex_unlock (&context->mutex)
372 #define G_THREAD_SELF g_thread_self ()
374 #define SOURCE_DESTROYED(source) (((source)->flags & G_HOOK_FLAG_ACTIVE) == 0)
375 #define SOURCE_BLOCKED(source) (((source)->flags & G_SOURCE_BLOCKED) != 0)
377 #define SOURCE_UNREF(source, context) \
379 if ((source)->ref_count > 1) \
380 (source)->ref_count--; \
382 g_source_unref_internal ((source), (context), TRUE); \
386 /* Forward declarations */
388 static void g_source_unref_internal (GSource
*source
,
389 GMainContext
*context
,
391 static void g_source_destroy_internal (GSource
*source
,
392 GMainContext
*context
,
394 static void g_source_set_priority_unlocked (GSource
*source
,
395 GMainContext
*context
,
397 static void g_child_source_remove_internal (GSource
*child_source
,
398 GMainContext
*context
);
400 static void g_main_context_poll (GMainContext
*context
,
405 static void g_main_context_add_poll_unlocked (GMainContext
*context
,
408 static void g_main_context_remove_poll_unlocked (GMainContext
*context
,
411 static void g_source_iter_init (GSourceIter
*iter
,
412 GMainContext
*context
,
413 gboolean may_modify
);
414 static gboolean
g_source_iter_next (GSourceIter
*iter
,
416 static void g_source_iter_clear (GSourceIter
*iter
);
418 static gboolean
g_timeout_dispatch (GSource
*source
,
419 GSourceFunc callback
,
421 static gboolean
g_child_watch_prepare (GSource
*source
,
423 static gboolean
g_child_watch_check (GSource
*source
);
424 static gboolean
g_child_watch_dispatch (GSource
*source
,
425 GSourceFunc callback
,
427 static void g_child_watch_finalize (GSource
*source
);
429 static void g_unix_signal_handler (int signum
);
430 static gboolean
g_unix_signal_watch_prepare (GSource
*source
,
432 static gboolean
g_unix_signal_watch_check (GSource
*source
);
433 static gboolean
g_unix_signal_watch_dispatch (GSource
*source
,
434 GSourceFunc callback
,
436 static void g_unix_signal_watch_finalize (GSource
*source
);
438 static gboolean
g_idle_prepare (GSource
*source
,
440 static gboolean
g_idle_check (GSource
*source
);
441 static gboolean
g_idle_dispatch (GSource
*source
,
442 GSourceFunc callback
,
445 static void block_source (GSource
*source
);
447 static GMainContext
*glib_worker_context
;
449 G_LOCK_DEFINE_STATIC (main_loop
);
450 static GMainContext
*default_main_context
;
455 /* UNIX signals work by marking one of these variables then waking the
456 * worker context to check on them and dispatch accordingly.
458 #ifdef HAVE_SIG_ATOMIC_T
459 static volatile sig_atomic_t unix_signal_pending
[NSIG
];
460 static volatile sig_atomic_t any_unix_signal_pending
;
462 static volatile int unix_signal_pending
[NSIG
];
463 static volatile int any_unix_signal_pending
;
465 static volatile guint unix_signal_refcount
[NSIG
];
467 /* Guards all the data below */
468 G_LOCK_DEFINE_STATIC (unix_signal_lock
);
469 static GSList
*unix_signal_watches
;
470 static GSList
*unix_child_watches
;
472 GSourceFuncs g_unix_signal_funcs
=
474 g_unix_signal_watch_prepare
,
475 g_unix_signal_watch_check
,
476 g_unix_signal_watch_dispatch
,
477 g_unix_signal_watch_finalize
479 #endif /* !G_OS_WIN32 */
480 G_LOCK_DEFINE_STATIC (main_context_list
);
481 static GSList
*main_context_list
= NULL
;
483 GSourceFuncs g_timeout_funcs
=
491 GSourceFuncs g_child_watch_funcs
=
493 g_child_watch_prepare
,
495 g_child_watch_dispatch
,
496 g_child_watch_finalize
499 GSourceFuncs g_idle_funcs
=
508 * g_main_context_ref:
509 * @context: a #GMainContext
511 * Increases the reference count on a #GMainContext object by one.
513 * Returns: the @context that was passed in (since 2.6)
516 g_main_context_ref (GMainContext
*context
)
518 g_return_val_if_fail (context
!= NULL
, NULL
);
519 g_return_val_if_fail (g_atomic_int_get (&context
->ref_count
) > 0, NULL
);
521 g_atomic_int_inc (&context
->ref_count
);
527 poll_rec_list_free (GMainContext
*context
,
530 g_slice_free_chain (GPollRec
, list
, next
);
534 * g_main_context_unref:
535 * @context: a #GMainContext
537 * Decreases the reference count on a #GMainContext object by one. If
538 * the result is zero, free the context and free all associated memory.
541 g_main_context_unref (GMainContext
*context
)
549 g_return_if_fail (context
!= NULL
);
550 g_return_if_fail (g_atomic_int_get (&context
->ref_count
) > 0);
552 if (!g_atomic_int_dec_and_test (&context
->ref_count
))
555 G_LOCK (main_context_list
);
556 main_context_list
= g_slist_remove (main_context_list
, context
);
557 G_UNLOCK (main_context_list
);
559 /* Free pending dispatches */
560 for (i
= 0; i
< context
->pending_dispatches
->len
; i
++)
561 g_source_unref_internal (context
->pending_dispatches
->pdata
[i
], context
, FALSE
);
563 /* g_source_iter_next() assumes the context is locked. */
564 LOCK_CONTEXT (context
);
565 g_source_iter_init (&iter
, context
, TRUE
);
566 while (g_source_iter_next (&iter
, &source
))
568 source
->context
= NULL
;
569 g_source_destroy_internal (source
, context
, TRUE
);
571 UNLOCK_CONTEXT (context
);
573 for (sl_iter
= context
->source_lists
; sl_iter
; sl_iter
= sl_iter
->next
)
575 list
= sl_iter
->data
;
576 g_slice_free (GSourceList
, list
);
578 g_list_free (context
->source_lists
);
580 g_hash_table_destroy (context
->sources
);
582 g_mutex_clear (&context
->mutex
);
584 g_ptr_array_free (context
->pending_dispatches
, TRUE
);
585 g_free (context
->cached_poll_array
);
587 poll_rec_list_free (context
, context
->poll_records
);
589 g_wakeup_free (context
->wakeup
);
590 g_cond_clear (&context
->cond
);
595 /* Helper function used by mainloop/overflow test.
598 g_main_context_new_with_next_id (guint next_id
)
600 GMainContext
*ret
= g_main_context_new ();
602 ret
->next_id
= next_id
;
608 * g_main_context_new:
610 * Creates a new #GMainContext structure.
612 * Returns: the new #GMainContext
615 g_main_context_new (void)
617 static gsize initialised
;
618 GMainContext
*context
;
620 if (g_once_init_enter (&initialised
))
622 #ifdef G_MAIN_POLL_DEBUG
623 if (getenv ("G_MAIN_POLL_DEBUG") != NULL
)
624 _g_main_poll_debug
= TRUE
;
627 g_once_init_leave (&initialised
, TRUE
);
630 context
= g_new0 (GMainContext
, 1);
632 TRACE (GLIB_MAIN_CONTEXT_NEW (context
));
634 g_mutex_init (&context
->mutex
);
635 g_cond_init (&context
->cond
);
637 context
->sources
= g_hash_table_new (NULL
, NULL
);
638 context
->owner
= NULL
;
639 context
->waiters
= NULL
;
641 context
->ref_count
= 1;
643 context
->next_id
= 1;
645 context
->source_lists
= NULL
;
647 context
->poll_func
= g_poll
;
649 context
->cached_poll_array
= NULL
;
650 context
->cached_poll_array_size
= 0;
652 context
->pending_dispatches
= g_ptr_array_new ();
654 context
->time_is_fresh
= FALSE
;
656 context
->wakeup
= g_wakeup_new ();
657 g_wakeup_get_pollfd (context
->wakeup
, &context
->wake_up_rec
);
658 g_main_context_add_poll_unlocked (context
, 0, &context
->wake_up_rec
);
660 G_LOCK (main_context_list
);
661 main_context_list
= g_slist_append (main_context_list
, context
);
663 #ifdef G_MAIN_POLL_DEBUG
664 if (_g_main_poll_debug
)
665 g_print ("created context=%p\n", context
);
668 G_UNLOCK (main_context_list
);
674 * g_main_context_default:
676 * Returns the global default main context. This is the main context
677 * used for main loop functions when a main loop is not explicitly
678 * specified, and corresponds to the "main" main loop. See also
679 * g_main_context_get_thread_default().
681 * Returns: (transfer none): the global default main context.
684 g_main_context_default (void)
690 if (!default_main_context
)
692 default_main_context
= g_main_context_new ();
694 TRACE (GLIB_MAIN_CONTEXT_DEFAULT (default_main_context
));
696 #ifdef G_MAIN_POLL_DEBUG
697 if (_g_main_poll_debug
)
698 g_print ("default context=%p\n", default_main_context
);
702 G_UNLOCK (main_loop
);
704 return default_main_context
;
708 free_context (gpointer data
)
710 GMainContext
*context
= data
;
712 TRACE (GLIB_MAIN_CONTEXT_FREE (context
));
714 g_main_context_release (context
);
716 g_main_context_unref (context
);
720 free_context_stack (gpointer data
)
722 g_queue_free_full((GQueue
*) data
, (GDestroyNotify
) free_context
);
725 static GPrivate thread_context_stack
= G_PRIVATE_INIT (free_context_stack
);
728 * g_main_context_push_thread_default:
729 * @context: (nullable): a #GMainContext, or %NULL for the global default context
731 * Acquires @context and sets it as the thread-default context for the
732 * current thread. This will cause certain asynchronous operations
733 * (such as most [gio][gio]-based I/O) which are
734 * started in this thread to run under @context and deliver their
735 * results to its main loop, rather than running under the global
736 * default context in the main thread. Note that calling this function
737 * changes the context returned by g_main_context_get_thread_default(),
738 * not the one returned by g_main_context_default(), so it does not affect
739 * the context used by functions like g_idle_add().
741 * Normally you would call this function shortly after creating a new
742 * thread, passing it a #GMainContext which will be run by a
743 * #GMainLoop in that thread, to set a new default context for all
744 * async operations in that thread. In this case you may not need to
745 * ever call g_main_context_pop_thread_default(), assuming you want the
746 * new #GMainContext to be the default for the whole lifecycle of the
749 * If you don't have control over how the new thread was created (e.g.
750 * in the new thread isn't newly created, or if the thread life
751 * cycle is managed by a #GThreadPool), it is always suggested to wrap
752 * the logic that needs to use the new #GMainContext inside a
753 * g_main_context_push_thread_default() / g_main_context_pop_thread_default()
754 * pair, otherwise threads that are re-used will end up never explicitly
755 * releasing the #GMainContext reference they hold.
757 * In some cases you may want to schedule a single operation in a
758 * non-default context, or temporarily use a non-default context in
759 * the main thread. In that case, you can wrap the call to the
760 * asynchronous operation inside a
761 * g_main_context_push_thread_default() /
762 * g_main_context_pop_thread_default() pair, but it is up to you to
763 * ensure that no other asynchronous operations accidentally get
764 * started while the non-default context is active.
766 * Beware that libraries that predate this function may not correctly
767 * handle being used from a thread with a thread-default context. Eg,
768 * see g_file_supports_thread_contexts().
773 g_main_context_push_thread_default (GMainContext
*context
)
776 gboolean acquired_context
;
778 acquired_context
= g_main_context_acquire (context
);
779 g_return_if_fail (acquired_context
);
781 if (context
== g_main_context_default ())
784 g_main_context_ref (context
);
786 stack
= g_private_get (&thread_context_stack
);
789 stack
= g_queue_new ();
790 g_private_set (&thread_context_stack
, stack
);
793 g_queue_push_head (stack
, context
);
795 TRACE (GLIB_MAIN_CONTEXT_PUSH_THREAD_DEFAULT (context
));
799 * g_main_context_pop_thread_default:
800 * @context: (nullable): a #GMainContext object, or %NULL
802 * Pops @context off the thread-default context stack (verifying that
803 * it was on the top of the stack).
808 g_main_context_pop_thread_default (GMainContext
*context
)
812 if (context
== g_main_context_default ())
815 stack
= g_private_get (&thread_context_stack
);
817 g_return_if_fail (stack
!= NULL
);
818 g_return_if_fail (g_queue_peek_head (stack
) == context
);
820 TRACE (GLIB_MAIN_CONTEXT_POP_THREAD_DEFAULT (context
));
822 g_queue_pop_head (stack
);
824 g_main_context_release (context
);
826 g_main_context_unref (context
);
830 * g_main_context_get_thread_default:
832 * Gets the thread-default #GMainContext for this thread. Asynchronous
833 * operations that want to be able to be run in contexts other than
834 * the default one should call this method or
835 * g_main_context_ref_thread_default() to get a #GMainContext to add
836 * their #GSources to. (Note that even in single-threaded
837 * programs applications may sometimes want to temporarily push a
838 * non-default context, so it is not safe to assume that this will
839 * always return %NULL if you are running in the default thread.)
841 * If you need to hold a reference on the context, use
842 * g_main_context_ref_thread_default() instead.
844 * Returns: (transfer none): the thread-default #GMainContext, or
845 * %NULL if the thread-default context is the global default context.
850 g_main_context_get_thread_default (void)
854 stack
= g_private_get (&thread_context_stack
);
856 return g_queue_peek_head (stack
);
862 * g_main_context_ref_thread_default:
864 * Gets the thread-default #GMainContext for this thread, as with
865 * g_main_context_get_thread_default(), but also adds a reference to
866 * it with g_main_context_ref(). In addition, unlike
867 * g_main_context_get_thread_default(), if the thread-default context
868 * is the global default context, this will return that #GMainContext
869 * (with a ref added to it) rather than returning %NULL.
871 * Returns: (transfer full): the thread-default #GMainContext. Unref
872 * with g_main_context_unref() when you are done with it.
877 g_main_context_ref_thread_default (void)
879 GMainContext
*context
;
881 context
= g_main_context_get_thread_default ();
883 context
= g_main_context_default ();
884 return g_main_context_ref (context
);
887 /* Hooks for adding to the main loop */
891 * @source_funcs: structure containing functions that implement
892 * the sources behavior.
893 * @struct_size: size of the #GSource structure to create.
895 * Creates a new #GSource structure. The size is specified to
896 * allow creating structures derived from #GSource that contain
897 * additional data. The size passed in must be at least
898 * `sizeof (GSource)`.
900 * The source will not initially be associated with any #GMainContext
901 * and must be added to one with g_source_attach() before it will be
904 * Returns: the newly-created #GSource.
907 g_source_new (GSourceFuncs
*source_funcs
,
912 g_return_val_if_fail (source_funcs
!= NULL
, NULL
);
913 g_return_val_if_fail (struct_size
>= sizeof (GSource
), NULL
);
915 source
= (GSource
*) g_malloc0 (struct_size
);
916 source
->priv
= g_slice_new0 (GSourcePrivate
);
917 source
->source_funcs
= source_funcs
;
918 source
->ref_count
= 1;
920 source
->priority
= G_PRIORITY_DEFAULT
;
922 source
->flags
= G_HOOK_FLAG_ACTIVE
;
924 source
->priv
->ready_time
= -1;
926 /* NULL/0 initialization for all other fields */
928 TRACE (GLIB_SOURCE_NEW (source
, source_funcs
->prepare
, source_funcs
->check
,
929 source_funcs
->dispatch
, source_funcs
->finalize
,
935 /* Holds context's lock */
937 g_source_iter_init (GSourceIter
*iter
,
938 GMainContext
*context
,
941 iter
->context
= context
;
942 iter
->current_list
= NULL
;
944 iter
->may_modify
= may_modify
;
947 /* Holds context's lock */
949 g_source_iter_next (GSourceIter
*iter
, GSource
**source
)
951 GSource
*next_source
;
954 next_source
= iter
->source
->next
;
960 if (iter
->current_list
)
961 iter
->current_list
= iter
->current_list
->next
;
963 iter
->current_list
= iter
->context
->source_lists
;
965 if (iter
->current_list
)
967 GSourceList
*source_list
= iter
->current_list
->data
;
969 next_source
= source_list
->head
;
973 /* Note: unreffing iter->source could potentially cause its
974 * GSourceList to be removed from source_lists (if iter->source is
975 * the only source in its list, and it is destroyed), so we have to
976 * keep it reffed until after we advance iter->current_list, above.
979 if (iter
->source
&& iter
->may_modify
)
980 SOURCE_UNREF (iter
->source
, iter
->context
);
981 iter
->source
= next_source
;
982 if (iter
->source
&& iter
->may_modify
)
983 iter
->source
->ref_count
++;
985 *source
= iter
->source
;
986 return *source
!= NULL
;
989 /* Holds context's lock. Only necessary to call if you broke out of
990 * the g_source_iter_next() loop early.
993 g_source_iter_clear (GSourceIter
*iter
)
995 if (iter
->source
&& iter
->may_modify
)
997 SOURCE_UNREF (iter
->source
, iter
->context
);
1002 /* Holds context's lock
1004 static GSourceList
*
1005 find_source_list_for_priority (GMainContext
*context
,
1010 GSourceList
*source_list
;
1013 for (iter
= context
->source_lists
; iter
!= NULL
; last
= iter
, iter
= iter
->next
)
1015 source_list
= iter
->data
;
1017 if (source_list
->priority
== priority
)
1020 if (source_list
->priority
> priority
)
1025 source_list
= g_slice_new0 (GSourceList
);
1026 source_list
->priority
= priority
;
1027 context
->source_lists
= g_list_insert_before (context
->source_lists
,
1037 source_list
= g_slice_new0 (GSourceList
);
1038 source_list
->priority
= priority
;
1041 context
->source_lists
= g_list_append (NULL
, source_list
);
1044 /* This just appends source_list to the end of
1045 * context->source_lists without having to walk the list again.
1047 last
= g_list_append (last
, source_list
);
1052 /* Holds context's lock
1055 source_add_to_context (GSource
*source
,
1056 GMainContext
*context
)
1058 GSourceList
*source_list
;
1059 GSource
*prev
, *next
;
1061 source_list
= find_source_list_for_priority (context
, source
->priority
, TRUE
);
1063 if (source
->priv
->parent_source
)
1065 g_assert (source_list
->head
!= NULL
);
1067 /* Put the source immediately before its parent */
1068 prev
= source
->priv
->parent_source
->prev
;
1069 next
= source
->priv
->parent_source
;
1073 prev
= source_list
->tail
;
1077 source
->next
= next
;
1079 next
->prev
= source
;
1081 source_list
->tail
= source
;
1083 source
->prev
= prev
;
1085 prev
->next
= source
;
1087 source_list
->head
= source
;
1090 /* Holds context's lock
1093 source_remove_from_context (GSource
*source
,
1094 GMainContext
*context
)
1096 GSourceList
*source_list
;
1098 source_list
= find_source_list_for_priority (context
, source
->priority
, FALSE
);
1099 g_return_if_fail (source_list
!= NULL
);
1102 source
->prev
->next
= source
->next
;
1104 source_list
->head
= source
->next
;
1107 source
->next
->prev
= source
->prev
;
1109 source_list
->tail
= source
->prev
;
1111 source
->prev
= NULL
;
1112 source
->next
= NULL
;
1114 if (source_list
->head
== NULL
)
1116 context
->source_lists
= g_list_remove (context
->source_lists
, source_list
);
1117 g_slice_free (GSourceList
, source_list
);
1122 g_source_attach_unlocked (GSource
*source
,
1123 GMainContext
*context
,
1129 /* The counter may have wrapped, so we must ensure that we do not
1130 * reuse the source id of an existing source.
1133 id
= context
->next_id
++;
1134 while (id
== 0 || g_hash_table_contains (context
->sources
, GUINT_TO_POINTER (id
)));
1136 source
->context
= context
;
1137 source
->source_id
= id
;
1138 source
->ref_count
++;
1140 g_hash_table_insert (context
->sources
, GUINT_TO_POINTER (id
), source
);
1142 source_add_to_context (source
, context
);
1144 if (!SOURCE_BLOCKED (source
))
1146 tmp_list
= source
->poll_fds
;
1149 g_main_context_add_poll_unlocked (context
, source
->priority
, tmp_list
->data
);
1150 tmp_list
= tmp_list
->next
;
1153 for (tmp_list
= source
->priv
->fds
; tmp_list
; tmp_list
= tmp_list
->next
)
1154 g_main_context_add_poll_unlocked (context
, source
->priority
, tmp_list
->data
);
1157 tmp_list
= source
->priv
->child_sources
;
1160 g_source_attach_unlocked (tmp_list
->data
, context
, FALSE
);
1161 tmp_list
= tmp_list
->next
;
1164 /* If another thread has acquired the context, wake it up since it
1165 * might be in poll() right now.
1167 if (do_wakeup
&& context
->owner
&& context
->owner
!= G_THREAD_SELF
)
1168 g_wakeup_signal (context
->wakeup
);
1170 return source
->source_id
;
1175 * @source: a #GSource
1176 * @context: (nullable): a #GMainContext (if %NULL, the default context will be used)
1178 * Adds a #GSource to a @context so that it will be executed within
1179 * that context. Remove it by calling g_source_destroy().
1181 * Returns: the ID (greater than 0) for the source within the
1185 g_source_attach (GSource
*source
,
1186 GMainContext
*context
)
1190 g_return_val_if_fail (source
->context
== NULL
, 0);
1191 g_return_val_if_fail (!SOURCE_DESTROYED (source
), 0);
1194 context
= g_main_context_default ();
1196 LOCK_CONTEXT (context
);
1198 result
= g_source_attach_unlocked (source
, context
, TRUE
);
1200 TRACE (GLIB_MAIN_SOURCE_ATTACH (g_source_get_name (source
), source
, context
,
1203 UNLOCK_CONTEXT (context
);
1209 g_source_destroy_internal (GSource
*source
,
1210 GMainContext
*context
,
1213 TRACE (GLIB_MAIN_SOURCE_DESTROY (g_source_get_name (source
), source
,
1217 LOCK_CONTEXT (context
);
1219 if (!SOURCE_DESTROYED (source
))
1222 gpointer old_cb_data
;
1223 GSourceCallbackFuncs
*old_cb_funcs
;
1225 source
->flags
&= ~G_HOOK_FLAG_ACTIVE
;
1227 old_cb_data
= source
->callback_data
;
1228 old_cb_funcs
= source
->callback_funcs
;
1230 source
->callback_data
= NULL
;
1231 source
->callback_funcs
= NULL
;
1235 UNLOCK_CONTEXT (context
);
1236 old_cb_funcs
->unref (old_cb_data
);
1237 LOCK_CONTEXT (context
);
1240 if (!SOURCE_BLOCKED (source
))
1242 tmp_list
= source
->poll_fds
;
1245 g_main_context_remove_poll_unlocked (context
, tmp_list
->data
);
1246 tmp_list
= tmp_list
->next
;
1249 for (tmp_list
= source
->priv
->fds
; tmp_list
; tmp_list
= tmp_list
->next
)
1250 g_main_context_remove_poll_unlocked (context
, tmp_list
->data
);
1253 while (source
->priv
->child_sources
)
1254 g_child_source_remove_internal (source
->priv
->child_sources
->data
, context
);
1256 if (source
->priv
->parent_source
)
1257 g_child_source_remove_internal (source
, context
);
1259 g_source_unref_internal (source
, context
, TRUE
);
1263 UNLOCK_CONTEXT (context
);
1268 * @source: a #GSource
1270 * Removes a source from its #GMainContext, if any, and mark it as
1271 * destroyed. The source cannot be subsequently added to another
1272 * context. It is safe to call this on sources which have already been
1273 * removed from their context.
1276 g_source_destroy (GSource
*source
)
1278 GMainContext
*context
;
1280 g_return_if_fail (source
!= NULL
);
1282 context
= source
->context
;
1285 g_source_destroy_internal (source
, context
, FALSE
);
1287 source
->flags
&= ~G_HOOK_FLAG_ACTIVE
;
1292 * @source: a #GSource
1294 * Returns the numeric ID for a particular source. The ID of a source
1295 * is a positive integer which is unique within a particular main loop
1296 * context. The reverse
1297 * mapping from ID to source is done by g_main_context_find_source_by_id().
1299 * You can only call this function while the source is associated to a
1300 * #GMainContext instance; calling this function before g_source_attach()
1301 * or after g_source_destroy() yields undefined behavior. The ID returned
1302 * is unique within the #GMainContext instance passed to g_source_attach().
1304 * Returns: the ID (greater than 0) for the source
1307 g_source_get_id (GSource
*source
)
1311 g_return_val_if_fail (source
!= NULL
, 0);
1312 g_return_val_if_fail (source
->context
!= NULL
, 0);
1314 LOCK_CONTEXT (source
->context
);
1315 result
= source
->source_id
;
1316 UNLOCK_CONTEXT (source
->context
);
1322 * g_source_get_context:
1323 * @source: a #GSource
1325 * Gets the #GMainContext with which the source is associated.
1327 * You can call this on a source that has been destroyed, provided
1328 * that the #GMainContext it was attached to still exists (in which
1329 * case it will return that #GMainContext). In particular, you can
1330 * always call this function on the source returned from
1331 * g_main_current_source(). But calling this function on a source
1332 * whose #GMainContext has been destroyed is an error.
1334 * Returns: (transfer none) (nullable): the #GMainContext with which the
1335 * source is associated, or %NULL if the context has not
1336 * yet been added to a source.
1339 g_source_get_context (GSource
*source
)
1341 g_return_val_if_fail (source
->context
!= NULL
|| !SOURCE_DESTROYED (source
), NULL
);
1343 return source
->context
;
1347 * g_source_add_poll:
1348 * @source:a #GSource
1349 * @fd: a #GPollFD structure holding information about a file
1350 * descriptor to watch.
1352 * Adds a file descriptor to the set of file descriptors polled for
1353 * this source. This is usually combined with g_source_new() to add an
1354 * event source. The event source's check function will typically test
1355 * the @revents field in the #GPollFD struct and return %TRUE if events need
1358 * This API is only intended to be used by implementations of #GSource.
1359 * Do not call this API on a #GSource that you did not create.
1361 * Using this API forces the linear scanning of event sources on each
1362 * main loop iteration. Newly-written event sources should try to use
1363 * g_source_add_unix_fd() instead of this API.
1366 g_source_add_poll (GSource
*source
,
1369 GMainContext
*context
;
1371 g_return_if_fail (source
!= NULL
);
1372 g_return_if_fail (fd
!= NULL
);
1373 g_return_if_fail (!SOURCE_DESTROYED (source
));
1375 context
= source
->context
;
1378 LOCK_CONTEXT (context
);
1380 source
->poll_fds
= g_slist_prepend (source
->poll_fds
, fd
);
1384 if (!SOURCE_BLOCKED (source
))
1385 g_main_context_add_poll_unlocked (context
, source
->priority
, fd
);
1386 UNLOCK_CONTEXT (context
);
1391 * g_source_remove_poll:
1392 * @source:a #GSource
1393 * @fd: a #GPollFD structure previously passed to g_source_add_poll().
1395 * Removes a file descriptor from the set of file descriptors polled for
1398 * This API is only intended to be used by implementations of #GSource.
1399 * Do not call this API on a #GSource that you did not create.
1402 g_source_remove_poll (GSource
*source
,
1405 GMainContext
*context
;
1407 g_return_if_fail (source
!= NULL
);
1408 g_return_if_fail (fd
!= NULL
);
1409 g_return_if_fail (!SOURCE_DESTROYED (source
));
1411 context
= source
->context
;
1414 LOCK_CONTEXT (context
);
1416 source
->poll_fds
= g_slist_remove (source
->poll_fds
, fd
);
1420 if (!SOURCE_BLOCKED (source
))
1421 g_main_context_remove_poll_unlocked (context
, fd
);
1422 UNLOCK_CONTEXT (context
);
1427 * g_source_add_child_source:
1428 * @source:a #GSource
1429 * @child_source: a second #GSource that @source should "poll"
1431 * Adds @child_source to @source as a "polled" source; when @source is
1432 * added to a #GMainContext, @child_source will be automatically added
1433 * with the same priority, when @child_source is triggered, it will
1434 * cause @source to dispatch (in addition to calling its own
1435 * callback), and when @source is destroyed, it will destroy
1436 * @child_source as well. (@source will also still be dispatched if
1437 * its own prepare/check functions indicate that it is ready.)
1439 * If you don't need @child_source to do anything on its own when it
1440 * triggers, you can call g_source_set_dummy_callback() on it to set a
1441 * callback that does nothing (except return %TRUE if appropriate).
1443 * @source will hold a reference on @child_source while @child_source
1444 * is attached to it.
1446 * This API is only intended to be used by implementations of #GSource.
1447 * Do not call this API on a #GSource that you did not create.
1452 g_source_add_child_source (GSource
*source
,
1453 GSource
*child_source
)
1455 GMainContext
*context
;
1457 g_return_if_fail (source
!= NULL
);
1458 g_return_if_fail (child_source
!= NULL
);
1459 g_return_if_fail (!SOURCE_DESTROYED (source
));
1460 g_return_if_fail (!SOURCE_DESTROYED (child_source
));
1461 g_return_if_fail (child_source
->context
== NULL
);
1462 g_return_if_fail (child_source
->priv
->parent_source
== NULL
);
1464 context
= source
->context
;
1467 LOCK_CONTEXT (context
);
1469 TRACE (GLIB_SOURCE_ADD_CHILD_SOURCE (source
, child_source
));
1471 source
->priv
->child_sources
= g_slist_prepend (source
->priv
->child_sources
,
1472 g_source_ref (child_source
));
1473 child_source
->priv
->parent_source
= source
;
1474 g_source_set_priority_unlocked (child_source
, NULL
, source
->priority
);
1475 if (SOURCE_BLOCKED (source
))
1476 block_source (child_source
);
1480 g_source_attach_unlocked (child_source
, context
, TRUE
);
1481 UNLOCK_CONTEXT (context
);
1486 g_child_source_remove_internal (GSource
*child_source
,
1487 GMainContext
*context
)
1489 GSource
*parent_source
= child_source
->priv
->parent_source
;
1491 parent_source
->priv
->child_sources
=
1492 g_slist_remove (parent_source
->priv
->child_sources
, child_source
);
1493 child_source
->priv
->parent_source
= NULL
;
1495 g_source_destroy_internal (child_source
, context
, TRUE
);
1496 g_source_unref_internal (child_source
, context
, TRUE
);
1500 * g_source_remove_child_source:
1501 * @source:a #GSource
1502 * @child_source: a #GSource previously passed to
1503 * g_source_add_child_source().
1505 * Detaches @child_source from @source and destroys it.
1507 * This API is only intended to be used by implementations of #GSource.
1508 * Do not call this API on a #GSource that you did not create.
1513 g_source_remove_child_source (GSource
*source
,
1514 GSource
*child_source
)
1516 GMainContext
*context
;
1518 g_return_if_fail (source
!= NULL
);
1519 g_return_if_fail (child_source
!= NULL
);
1520 g_return_if_fail (child_source
->priv
->parent_source
== source
);
1521 g_return_if_fail (!SOURCE_DESTROYED (source
));
1522 g_return_if_fail (!SOURCE_DESTROYED (child_source
));
1524 context
= source
->context
;
1527 LOCK_CONTEXT (context
);
1529 g_child_source_remove_internal (child_source
, context
);
1532 UNLOCK_CONTEXT (context
);
1536 g_source_callback_ref (gpointer cb_data
)
1538 GSourceCallback
*callback
= cb_data
;
1540 g_atomic_int_inc (&callback
->ref_count
);
1544 g_source_callback_unref (gpointer cb_data
)
1546 GSourceCallback
*callback
= cb_data
;
1548 if (g_atomic_int_dec_and_test (&callback
->ref_count
))
1550 if (callback
->notify
)
1551 callback
->notify (callback
->data
);
1557 g_source_callback_get (gpointer cb_data
,
1562 GSourceCallback
*callback
= cb_data
;
1564 *func
= callback
->func
;
1565 *data
= callback
->data
;
1568 static GSourceCallbackFuncs g_source_callback_funcs
= {
1569 g_source_callback_ref
,
1570 g_source_callback_unref
,
1571 g_source_callback_get
,
1575 * g_source_set_callback_indirect:
1576 * @source: the source
1577 * @callback_data: pointer to callback data "object"
1578 * @callback_funcs: functions for reference counting @callback_data
1579 * and getting the callback and data
1581 * Sets the callback function storing the data as a refcounted callback
1582 * "object". This is used internally. Note that calling
1583 * g_source_set_callback_indirect() assumes
1584 * an initial reference count on @callback_data, and thus
1585 * @callback_funcs->unref will eventually be called once more
1586 * than @callback_funcs->ref.
1589 g_source_set_callback_indirect (GSource
*source
,
1590 gpointer callback_data
,
1591 GSourceCallbackFuncs
*callback_funcs
)
1593 GMainContext
*context
;
1594 gpointer old_cb_data
;
1595 GSourceCallbackFuncs
*old_cb_funcs
;
1597 g_return_if_fail (source
!= NULL
);
1598 g_return_if_fail (callback_funcs
!= NULL
|| callback_data
== NULL
);
1600 context
= source
->context
;
1603 LOCK_CONTEXT (context
);
1605 if (callback_funcs
!= &g_source_callback_funcs
)
1606 TRACE (GLIB_SOURCE_SET_CALLBACK_INDIRECT (source
, callback_data
,
1607 callback_funcs
->ref
,
1608 callback_funcs
->unref
,
1609 callback_funcs
->get
));
1611 old_cb_data
= source
->callback_data
;
1612 old_cb_funcs
= source
->callback_funcs
;
1614 source
->callback_data
= callback_data
;
1615 source
->callback_funcs
= callback_funcs
;
1618 UNLOCK_CONTEXT (context
);
1621 old_cb_funcs
->unref (old_cb_data
);
1625 * g_source_set_callback:
1626 * @source: the source
1627 * @func: a callback function
1628 * @data: the data to pass to callback function
1629 * @notify: (nullable): a function to call when @data is no longer in use, or %NULL.
1631 * Sets the callback function for a source. The callback for a source is
1632 * called from the source's dispatch function.
1634 * The exact type of @func depends on the type of source; ie. you
1635 * should not count on @func being called with @data as its first
1636 * parameter. Cast @func with G_SOURCE_FUNC() to avoid warnings about
1637 * incompatible function types.
1639 * See [memory management of sources][mainloop-memory-management] for details
1640 * on how to handle memory management of @data.
1642 * Typically, you won't use this function. Instead use functions specific
1643 * to the type of source you are using.
1646 g_source_set_callback (GSource
*source
,
1649 GDestroyNotify notify
)
1651 GSourceCallback
*new_callback
;
1653 g_return_if_fail (source
!= NULL
);
1655 TRACE (GLIB_SOURCE_SET_CALLBACK (source
, func
, data
, notify
));
1657 new_callback
= g_new (GSourceCallback
, 1);
1659 new_callback
->ref_count
= 1;
1660 new_callback
->func
= func
;
1661 new_callback
->data
= data
;
1662 new_callback
->notify
= notify
;
1664 g_source_set_callback_indirect (source
, new_callback
, &g_source_callback_funcs
);
1669 * g_source_set_funcs:
1670 * @source: a #GSource
1671 * @funcs: the new #GSourceFuncs
1673 * Sets the source functions (can be used to override
1674 * default implementations) of an unattached source.
1679 g_source_set_funcs (GSource
*source
,
1680 GSourceFuncs
*funcs
)
1682 g_return_if_fail (source
!= NULL
);
1683 g_return_if_fail (source
->context
== NULL
);
1684 g_return_if_fail (source
->ref_count
> 0);
1685 g_return_if_fail (funcs
!= NULL
);
1687 source
->source_funcs
= funcs
;
1691 g_source_set_priority_unlocked (GSource
*source
,
1692 GMainContext
*context
,
1697 g_return_if_fail (source
->priv
->parent_source
== NULL
||
1698 source
->priv
->parent_source
->priority
== priority
);
1700 TRACE (GLIB_SOURCE_SET_PRIORITY (source
, context
, priority
));
1704 /* Remove the source from the context's source and then
1705 * add it back after so it is sorted in the correct place
1707 source_remove_from_context (source
, source
->context
);
1710 source
->priority
= priority
;
1714 source_add_to_context (source
, source
->context
);
1716 if (!SOURCE_BLOCKED (source
))
1718 tmp_list
= source
->poll_fds
;
1721 g_main_context_remove_poll_unlocked (context
, tmp_list
->data
);
1722 g_main_context_add_poll_unlocked (context
, priority
, tmp_list
->data
);
1724 tmp_list
= tmp_list
->next
;
1727 for (tmp_list
= source
->priv
->fds
; tmp_list
; tmp_list
= tmp_list
->next
)
1729 g_main_context_remove_poll_unlocked (context
, tmp_list
->data
);
1730 g_main_context_add_poll_unlocked (context
, priority
, tmp_list
->data
);
1735 if (source
->priv
->child_sources
)
1737 tmp_list
= source
->priv
->child_sources
;
1740 g_source_set_priority_unlocked (tmp_list
->data
, context
, priority
);
1741 tmp_list
= tmp_list
->next
;
1747 * g_source_set_priority:
1748 * @source: a #GSource
1749 * @priority: the new priority.
1751 * Sets the priority of a source. While the main loop is being run, a
1752 * source will be dispatched if it is ready to be dispatched and no
1753 * sources at a higher (numerically smaller) priority are ready to be
1756 * A child source always has the same priority as its parent. It is not
1757 * permitted to change the priority of a source once it has been added
1758 * as a child of another source.
1761 g_source_set_priority (GSource
*source
,
1764 GMainContext
*context
;
1766 g_return_if_fail (source
!= NULL
);
1767 g_return_if_fail (source
->priv
->parent_source
== NULL
);
1769 context
= source
->context
;
1772 LOCK_CONTEXT (context
);
1773 g_source_set_priority_unlocked (source
, context
, priority
);
1775 UNLOCK_CONTEXT (context
);
1779 * g_source_get_priority:
1780 * @source: a #GSource
1782 * Gets the priority of a source.
1784 * Returns: the priority of the source
1787 g_source_get_priority (GSource
*source
)
1789 g_return_val_if_fail (source
!= NULL
, 0);
1791 return source
->priority
;
1795 * g_source_set_ready_time:
1796 * @source: a #GSource
1797 * @ready_time: the monotonic time at which the source will be ready,
1798 * 0 for "immediately", -1 for "never"
1800 * Sets a #GSource to be dispatched when the given monotonic time is
1801 * reached (or passed). If the monotonic time is in the past (as it
1802 * always will be if @ready_time is 0) then the source will be
1803 * dispatched immediately.
1805 * If @ready_time is -1 then the source is never woken up on the basis
1806 * of the passage of time.
1808 * Dispatching the source does not reset the ready time. You should do
1809 * so yourself, from the source dispatch function.
1811 * Note that if you have a pair of sources where the ready time of one
1812 * suggests that it will be delivered first but the priority for the
1813 * other suggests that it would be delivered first, and the ready time
1814 * for both sources is reached during the same main context iteration,
1815 * then the order of dispatch is undefined.
1817 * It is a no-op to call this function on a #GSource which has already been
1818 * destroyed with g_source_destroy().
1820 * This API is only intended to be used by implementations of #GSource.
1821 * Do not call this API on a #GSource that you did not create.
1826 g_source_set_ready_time (GSource
*source
,
1829 GMainContext
*context
;
1831 g_return_if_fail (source
!= NULL
);
1832 /* We deliberately don't check for ref_count > 0 here, because that
1833 * breaks cancellable_source_cancelled() in GCancellable: it has no
1834 * way to find out that the last-unref has happened until the
1835 * finalize() function is called, but that's too late, because the
1836 * ref_count already has already reached 0 before that time.
1837 * However, priv is only poisoned (set to NULL) after finalize(),
1838 * so we can use this as a simple guard against use-after-free.
1839 * See https://bugzilla.gnome.org/show_bug.cgi?id=791754 */
1840 g_return_if_fail (source
->priv
!= NULL
);
1842 context
= source
->context
;
1845 LOCK_CONTEXT (context
);
1847 if (source
->priv
->ready_time
== ready_time
)
1850 UNLOCK_CONTEXT (context
);
1855 source
->priv
->ready_time
= ready_time
;
1857 TRACE (GLIB_SOURCE_SET_READY_TIME (source
, ready_time
));
1861 /* Quite likely that we need to change the timeout on the poll */
1862 if (!SOURCE_BLOCKED (source
))
1863 g_wakeup_signal (context
->wakeup
);
1864 UNLOCK_CONTEXT (context
);
1869 * g_source_get_ready_time:
1870 * @source: a #GSource
1872 * Gets the "ready time" of @source, as set by
1873 * g_source_set_ready_time().
1875 * Any time before the current monotonic time (including 0) is an
1876 * indication that the source will fire immediately.
1878 * Returns: the monotonic ready time, -1 for "never"
1881 g_source_get_ready_time (GSource
*source
)
1883 g_return_val_if_fail (source
!= NULL
, -1);
1885 return source
->priv
->ready_time
;
1889 * g_source_set_can_recurse:
1890 * @source: a #GSource
1891 * @can_recurse: whether recursion is allowed for this source
1893 * Sets whether a source can be called recursively. If @can_recurse is
1894 * %TRUE, then while the source is being dispatched then this source
1895 * will be processed normally. Otherwise, all processing of this
1896 * source is blocked until the dispatch function returns.
1899 g_source_set_can_recurse (GSource
*source
,
1900 gboolean can_recurse
)
1902 GMainContext
*context
;
1904 g_return_if_fail (source
!= NULL
);
1906 context
= source
->context
;
1909 LOCK_CONTEXT (context
);
1912 source
->flags
|= G_SOURCE_CAN_RECURSE
;
1914 source
->flags
&= ~G_SOURCE_CAN_RECURSE
;
1917 UNLOCK_CONTEXT (context
);
1921 * g_source_get_can_recurse:
1922 * @source: a #GSource
1924 * Checks whether a source is allowed to be called recursively.
1925 * see g_source_set_can_recurse().
1927 * Returns: whether recursion is allowed.
1930 g_source_get_can_recurse (GSource
*source
)
1932 g_return_val_if_fail (source
!= NULL
, FALSE
);
1934 return (source
->flags
& G_SOURCE_CAN_RECURSE
) != 0;
1939 * g_source_set_name:
1940 * @source: a #GSource
1941 * @name: debug name for the source
1943 * Sets a name for the source, used in debugging and profiling.
1944 * The name defaults to #NULL.
1946 * The source name should describe in a human-readable way
1947 * what the source does. For example, "X11 event queue"
1948 * or "GTK+ repaint idle handler" or whatever it is.
1950 * It is permitted to call this function multiple times, but is not
1951 * recommended due to the potential performance impact. For example,
1952 * one could change the name in the "check" function of a #GSourceFuncs
1953 * to include details like the event type in the source name.
1955 * Use caution if changing the name while another thread may be
1956 * accessing it with g_source_get_name(); that function does not copy
1957 * the value, and changing the value will free it while the other thread
1958 * may be attempting to use it.
1963 g_source_set_name (GSource
*source
,
1966 GMainContext
*context
;
1968 g_return_if_fail (source
!= NULL
);
1970 context
= source
->context
;
1973 LOCK_CONTEXT (context
);
1975 TRACE (GLIB_SOURCE_SET_NAME (source
, name
));
1977 /* setting back to NULL is allowed, just because it's
1978 * weird if get_name can return NULL but you can't
1982 g_free (source
->name
);
1983 source
->name
= g_strdup (name
);
1986 UNLOCK_CONTEXT (context
);
1990 * g_source_get_name:
1991 * @source: a #GSource
1993 * Gets a name for the source, used in debugging and profiling. The
1994 * name may be #NULL if it has never been set with g_source_set_name().
1996 * Returns: the name of the source
2001 g_source_get_name (GSource
*source
)
2003 g_return_val_if_fail (source
!= NULL
, NULL
);
2005 return source
->name
;
2009 * g_source_set_name_by_id:
2010 * @tag: a #GSource ID
2011 * @name: debug name for the source
2013 * Sets the name of a source using its ID.
2015 * This is a convenience utility to set source names from the return
2016 * value of g_idle_add(), g_timeout_add(), etc.
2018 * It is a programmer error to attempt to set the name of a non-existent
2021 * More specifically: source IDs can be reissued after a source has been
2022 * destroyed and therefore it is never valid to use this function with a
2023 * source ID which may have already been removed. An example is when
2024 * scheduling an idle to run in another thread with g_idle_add(): the
2025 * idle may already have run and been removed by the time this function
2026 * is called on its (now invalid) source ID. This source ID may have
2027 * been reissued, leading to the operation being performed against the
2033 g_source_set_name_by_id (guint tag
,
2038 g_return_if_fail (tag
> 0);
2040 source
= g_main_context_find_source_by_id (NULL
, tag
);
2044 g_source_set_name (source
, name
);
2050 * @source: a #GSource
2052 * Increases the reference count on a source by one.
2057 g_source_ref (GSource
*source
)
2059 GMainContext
*context
;
2061 g_return_val_if_fail (source
!= NULL
, NULL
);
2063 context
= source
->context
;
2066 LOCK_CONTEXT (context
);
2068 source
->ref_count
++;
2071 UNLOCK_CONTEXT (context
);
2076 /* g_source_unref() but possible to call within context lock
2079 g_source_unref_internal (GSource
*source
,
2080 GMainContext
*context
,
2083 gpointer old_cb_data
= NULL
;
2084 GSourceCallbackFuncs
*old_cb_funcs
= NULL
;
2086 g_return_if_fail (source
!= NULL
);
2088 if (!have_lock
&& context
)
2089 LOCK_CONTEXT (context
);
2091 source
->ref_count
--;
2092 if (source
->ref_count
== 0)
2094 TRACE (GLIB_SOURCE_BEFORE_FREE (source
, context
,
2095 source
->source_funcs
->finalize
));
2097 old_cb_data
= source
->callback_data
;
2098 old_cb_funcs
= source
->callback_funcs
;
2100 source
->callback_data
= NULL
;
2101 source
->callback_funcs
= NULL
;
2105 if (!SOURCE_DESTROYED (source
))
2106 g_warning (G_STRLOC
": ref_count == 0, but source was still attached to a context!");
2107 source_remove_from_context (source
, context
);
2109 g_hash_table_remove (context
->sources
, GUINT_TO_POINTER (source
->source_id
));
2112 if (source
->source_funcs
->finalize
)
2114 /* Temporarily increase the ref count again so that GSource methods
2115 * can be called from finalize(). */
2116 source
->ref_count
++;
2118 UNLOCK_CONTEXT (context
);
2119 source
->source_funcs
->finalize (source
);
2121 LOCK_CONTEXT (context
);
2122 source
->ref_count
--;
2127 /* Temporarily increase the ref count again so that GSource methods
2128 * can be called from callback_funcs.unref(). */
2129 source
->ref_count
++;
2131 UNLOCK_CONTEXT (context
);
2133 old_cb_funcs
->unref (old_cb_data
);
2136 LOCK_CONTEXT (context
);
2137 source
->ref_count
--;
2140 g_free (source
->name
);
2141 source
->name
= NULL
;
2143 g_slist_free (source
->poll_fds
);
2144 source
->poll_fds
= NULL
;
2146 g_slist_free_full (source
->priv
->fds
, g_free
);
2148 while (source
->priv
->child_sources
)
2150 GSource
*child_source
= source
->priv
->child_sources
->data
;
2152 source
->priv
->child_sources
=
2153 g_slist_remove (source
->priv
->child_sources
, child_source
);
2154 child_source
->priv
->parent_source
= NULL
;
2156 g_source_unref_internal (child_source
, context
, have_lock
);
2159 g_slice_free (GSourcePrivate
, source
->priv
);
2160 source
->priv
= NULL
;
2165 if (!have_lock
&& context
)
2166 UNLOCK_CONTEXT (context
);
2171 * @source: a #GSource
2173 * Decreases the reference count of a source by one. If the
2174 * resulting reference count is zero the source and associated
2175 * memory will be destroyed.
2178 g_source_unref (GSource
*source
)
2180 g_return_if_fail (source
!= NULL
);
2182 g_source_unref_internal (source
, source
->context
, FALSE
);
2186 * g_main_context_find_source_by_id:
2187 * @context: (nullable): a #GMainContext (if %NULL, the default context will be used)
2188 * @source_id: the source ID, as returned by g_source_get_id().
2190 * Finds a #GSource given a pair of context and ID.
2192 * It is a programmer error to attempt to lookup a non-existent source.
2194 * More specifically: source IDs can be reissued after a source has been
2195 * destroyed and therefore it is never valid to use this function with a
2196 * source ID which may have already been removed. An example is when
2197 * scheduling an idle to run in another thread with g_idle_add(): the
2198 * idle may already have run and been removed by the time this function
2199 * is called on its (now invalid) source ID. This source ID may have
2200 * been reissued, leading to the operation being performed against the
2203 * Returns: (transfer none): the #GSource
2206 g_main_context_find_source_by_id (GMainContext
*context
,
2211 g_return_val_if_fail (source_id
> 0, NULL
);
2213 if (context
== NULL
)
2214 context
= g_main_context_default ();
2216 LOCK_CONTEXT (context
);
2217 source
= g_hash_table_lookup (context
->sources
, GUINT_TO_POINTER (source_id
));
2218 UNLOCK_CONTEXT (context
);
2220 if (source
&& SOURCE_DESTROYED (source
))
2227 * g_main_context_find_source_by_funcs_user_data:
2228 * @context: (nullable): a #GMainContext (if %NULL, the default context will be used).
2229 * @funcs: the @source_funcs passed to g_source_new().
2230 * @user_data: the user data from the callback.
2232 * Finds a source with the given source functions and user data. If
2233 * multiple sources exist with the same source function and user data,
2234 * the first one found will be returned.
2236 * Returns: (transfer none): the source, if one was found, otherwise %NULL
2239 g_main_context_find_source_by_funcs_user_data (GMainContext
*context
,
2240 GSourceFuncs
*funcs
,
2246 g_return_val_if_fail (funcs
!= NULL
, NULL
);
2248 if (context
== NULL
)
2249 context
= g_main_context_default ();
2251 LOCK_CONTEXT (context
);
2253 g_source_iter_init (&iter
, context
, FALSE
);
2254 while (g_source_iter_next (&iter
, &source
))
2256 if (!SOURCE_DESTROYED (source
) &&
2257 source
->source_funcs
== funcs
&&
2258 source
->callback_funcs
)
2260 GSourceFunc callback
;
2261 gpointer callback_data
;
2263 source
->callback_funcs
->get (source
->callback_data
, source
, &callback
, &callback_data
);
2265 if (callback_data
== user_data
)
2269 g_source_iter_clear (&iter
);
2271 UNLOCK_CONTEXT (context
);
2277 * g_main_context_find_source_by_user_data:
2278 * @context: a #GMainContext
2279 * @user_data: the user_data for the callback.
2281 * Finds a source with the given user data for the callback. If
2282 * multiple sources exist with the same user data, the first
2283 * one found will be returned.
2285 * Returns: (transfer none): the source, if one was found, otherwise %NULL
2288 g_main_context_find_source_by_user_data (GMainContext
*context
,
2294 if (context
== NULL
)
2295 context
= g_main_context_default ();
2297 LOCK_CONTEXT (context
);
2299 g_source_iter_init (&iter
, context
, FALSE
);
2300 while (g_source_iter_next (&iter
, &source
))
2302 if (!SOURCE_DESTROYED (source
) &&
2303 source
->callback_funcs
)
2305 GSourceFunc callback
;
2306 gpointer callback_data
= NULL
;
2308 source
->callback_funcs
->get (source
->callback_data
, source
, &callback
, &callback_data
);
2310 if (callback_data
== user_data
)
2314 g_source_iter_clear (&iter
);
2316 UNLOCK_CONTEXT (context
);
2323 * @tag: the ID of the source to remove.
2325 * Removes the source with the given ID from the default main context. You must
2326 * use g_source_destroy() for sources added to a non-default main context.
2328 * The ID of a #GSource is given by g_source_get_id(), or will be
2329 * returned by the functions g_source_attach(), g_idle_add(),
2330 * g_idle_add_full(), g_timeout_add(), g_timeout_add_full(),
2331 * g_child_watch_add(), g_child_watch_add_full(), g_io_add_watch(), and
2332 * g_io_add_watch_full().
2334 * It is a programmer error to attempt to remove a non-existent source.
2336 * More specifically: source IDs can be reissued after a source has been
2337 * destroyed and therefore it is never valid to use this function with a
2338 * source ID which may have already been removed. An example is when
2339 * scheduling an idle to run in another thread with g_idle_add(): the
2340 * idle may already have run and been removed by the time this function
2341 * is called on its (now invalid) source ID. This source ID may have
2342 * been reissued, leading to the operation being performed against the
2345 * Returns: For historical reasons, this function always returns %TRUE
2348 g_source_remove (guint tag
)
2352 g_return_val_if_fail (tag
> 0, FALSE
);
2354 source
= g_main_context_find_source_by_id (NULL
, tag
);
2356 g_source_destroy (source
);
2358 g_critical ("Source ID %u was not found when attempting to remove it", tag
);
2360 return source
!= NULL
;
2364 * g_source_remove_by_user_data:
2365 * @user_data: the user_data for the callback.
2367 * Removes a source from the default main loop context given the user
2368 * data for the callback. If multiple sources exist with the same user
2369 * data, only one will be destroyed.
2371 * Returns: %TRUE if a source was found and removed.
2374 g_source_remove_by_user_data (gpointer user_data
)
2378 source
= g_main_context_find_source_by_user_data (NULL
, user_data
);
2381 g_source_destroy (source
);
2389 * g_source_remove_by_funcs_user_data:
2390 * @funcs: The @source_funcs passed to g_source_new()
2391 * @user_data: the user data for the callback
2393 * Removes a source from the default main loop context given the
2394 * source functions and user data. If multiple sources exist with the
2395 * same source functions and user data, only one will be destroyed.
2397 * Returns: %TRUE if a source was found and removed.
2400 g_source_remove_by_funcs_user_data (GSourceFuncs
*funcs
,
2405 g_return_val_if_fail (funcs
!= NULL
, FALSE
);
2407 source
= g_main_context_find_source_by_funcs_user_data (NULL
, funcs
, user_data
);
2410 g_source_destroy (source
);
2418 * g_clear_handle_id: (skip)
2419 * @tag_ptr: (not nullable): a pointer to the handler ID
2420 * @clear_func: (not nullable): the function to call to clear the handler
2422 * Clears a numeric handler, such as a #GSource ID.
2424 * @tag_ptr must be a valid pointer to the variable holding the handler.
2426 * If the ID is zero then this function does nothing.
2427 * Otherwise, clear_func() is called with the ID as a parameter, and the tag is
2430 * A macro is also included that allows this function to be used without
2435 #undef g_clear_handle_id
2437 g_clear_handle_id (guint
*tag_ptr
,
2438 GClearHandleFunc clear_func
)
2442 _handle_id
= *tag_ptr
;
2446 clear_func (_handle_id
);
2452 * g_source_add_unix_fd:
2453 * @source: a #GSource
2454 * @fd: the fd to monitor
2455 * @events: an event mask
2457 * Monitors @fd for the IO events in @events.
2459 * The tag returned by this function can be used to remove or modify the
2460 * monitoring of the fd using g_source_remove_unix_fd() or
2461 * g_source_modify_unix_fd().
2463 * It is not necessary to remove the fd before destroying the source; it
2464 * will be cleaned up automatically.
2466 * This API is only intended to be used by implementations of #GSource.
2467 * Do not call this API on a #GSource that you did not create.
2469 * As the name suggests, this function is not available on Windows.
2471 * Returns: (not nullable): an opaque tag
2476 g_source_add_unix_fd (GSource
*source
,
2478 GIOCondition events
)
2480 GMainContext
*context
;
2483 g_return_val_if_fail (source
!= NULL
, NULL
);
2484 g_return_val_if_fail (!SOURCE_DESTROYED (source
), NULL
);
2486 poll_fd
= g_new (GPollFD
, 1);
2488 poll_fd
->events
= events
;
2489 poll_fd
->revents
= 0;
2491 context
= source
->context
;
2494 LOCK_CONTEXT (context
);
2496 source
->priv
->fds
= g_slist_prepend (source
->priv
->fds
, poll_fd
);
2500 if (!SOURCE_BLOCKED (source
))
2501 g_main_context_add_poll_unlocked (context
, source
->priority
, poll_fd
);
2502 UNLOCK_CONTEXT (context
);
2509 * g_source_modify_unix_fd:
2510 * @source: a #GSource
2511 * @tag: (not nullable): the tag from g_source_add_unix_fd()
2512 * @new_events: the new event mask to watch
2514 * Updates the event mask to watch for the fd identified by @tag.
2516 * @tag is the tag returned from g_source_add_unix_fd().
2518 * If you want to remove a fd, don't set its event mask to zero.
2519 * Instead, call g_source_remove_unix_fd().
2521 * This API is only intended to be used by implementations of #GSource.
2522 * Do not call this API on a #GSource that you did not create.
2524 * As the name suggests, this function is not available on Windows.
2529 g_source_modify_unix_fd (GSource
*source
,
2531 GIOCondition new_events
)
2533 GMainContext
*context
;
2536 g_return_if_fail (source
!= NULL
);
2537 g_return_if_fail (g_slist_find (source
->priv
->fds
, tag
));
2539 context
= source
->context
;
2542 poll_fd
->events
= new_events
;
2545 g_main_context_wakeup (context
);
2549 * g_source_remove_unix_fd:
2550 * @source: a #GSource
2551 * @tag: (not nullable): the tag from g_source_add_unix_fd()
2553 * Reverses the effect of a previous call to g_source_add_unix_fd().
2555 * You only need to call this if you want to remove an fd from being
2556 * watched while keeping the same source around. In the normal case you
2557 * will just want to destroy the source.
2559 * This API is only intended to be used by implementations of #GSource.
2560 * Do not call this API on a #GSource that you did not create.
2562 * As the name suggests, this function is not available on Windows.
2567 g_source_remove_unix_fd (GSource
*source
,
2570 GMainContext
*context
;
2573 g_return_if_fail (source
!= NULL
);
2574 g_return_if_fail (g_slist_find (source
->priv
->fds
, tag
));
2576 context
= source
->context
;
2580 LOCK_CONTEXT (context
);
2582 source
->priv
->fds
= g_slist_remove (source
->priv
->fds
, poll_fd
);
2586 if (!SOURCE_BLOCKED (source
))
2587 g_main_context_remove_poll_unlocked (context
, poll_fd
);
2589 UNLOCK_CONTEXT (context
);
2596 * g_source_query_unix_fd:
2597 * @source: a #GSource
2598 * @tag: (not nullable): the tag from g_source_add_unix_fd()
2600 * Queries the events reported for the fd corresponding to @tag on
2601 * @source during the last poll.
2603 * The return value of this function is only defined when the function
2604 * is called from the check or dispatch functions for @source.
2606 * This API is only intended to be used by implementations of #GSource.
2607 * Do not call this API on a #GSource that you did not create.
2609 * As the name suggests, this function is not available on Windows.
2611 * Returns: the conditions reported on the fd
2616 g_source_query_unix_fd (GSource
*source
,
2621 g_return_val_if_fail (source
!= NULL
, 0);
2622 g_return_val_if_fail (g_slist_find (source
->priv
->fds
, tag
), 0);
2626 return poll_fd
->revents
;
2628 #endif /* G_OS_UNIX */
2631 * g_get_current_time:
2632 * @result: #GTimeVal structure in which to store current time.
2634 * Equivalent to the UNIX gettimeofday() function, but portable.
2636 * You may find g_get_real_time() to be more convenient.
2639 g_get_current_time (GTimeVal
*result
)
2644 g_return_if_fail (result
!= NULL
);
2646 /*this is required on alpha, there the timeval structs are int's
2647 not longs and a cast only would fail horribly*/
2648 gettimeofday (&r
, NULL
);
2649 result
->tv_sec
= r
.tv_sec
;
2650 result
->tv_usec
= r
.tv_usec
;
2655 g_return_if_fail (result
!= NULL
);
2657 GetSystemTimeAsFileTime (&ft
);
2658 memmove (&time64
, &ft
, sizeof (FILETIME
));
2660 /* Convert from 100s of nanoseconds since 1601-01-01
2661 * to Unix epoch. Yes, this is Y2038 unsafe.
2663 time64
-= G_GINT64_CONSTANT (116444736000000000);
2666 result
->tv_sec
= time64
/ 1000000;
2667 result
->tv_usec
= time64
% 1000000;
2674 * Queries the system wall-clock time.
2676 * This call is functionally equivalent to g_get_current_time() except
2677 * that the return value is often more convenient than dealing with a
2680 * You should only use this call if you are actually interested in the real
2681 * wall-clock time. g_get_monotonic_time() is probably more useful for
2682 * measuring intervals.
2684 * Returns: the number of microseconds since January 1, 1970 UTC.
2689 g_get_real_time (void)
2693 g_get_current_time (&tv
);
2695 return (((gint64
) tv
.tv_sec
) * 1000000) + tv
.tv_usec
;
2699 * g_get_monotonic_time:
2701 * Queries the system monotonic time.
2703 * The monotonic clock will always increase and doesn't suffer
2704 * discontinuities when the user (or NTP) changes the system time. It
2705 * may or may not continue to tick during times where the machine is
2708 * We try to use the clock that corresponds as closely as possible to
2709 * the passage of time as measured by system calls such as poll() but it
2710 * may not always be possible to do this.
2712 * Returns: the monotonic time, in microseconds
2716 #if defined (G_OS_WIN32)
2718 * time_usec = ticks_since_boot * usec_per_sec / ticks_per_sec
2720 * Doing (ticks_since_boot * usec_per_sec) before the division can overflow 64 bits
2721 * (ticks_since_boot / ticks_per_sec) and then multiply would not be accurate enough.
2722 * So for now we calculate (usec_per_sec / ticks_per_sec) and use floating point
2724 static gdouble g_monotonic_usec_per_tick
= 0;
2727 g_clock_win32_init (void)
2731 if (!QueryPerformanceFrequency (&freq
) || freq
.QuadPart
== 0)
2733 /* The documentation says that this should never happen */
2734 g_assert_not_reached ();
2738 g_monotonic_usec_per_tick
= (gdouble
)G_USEC_PER_SEC
/ freq
.QuadPart
;
2742 g_get_monotonic_time (void)
2744 if (G_LIKELY (g_monotonic_usec_per_tick
!= 0))
2746 LARGE_INTEGER ticks
;
2748 if (QueryPerformanceCounter (&ticks
))
2749 return (gint64
)(ticks
.QuadPart
* g_monotonic_usec_per_tick
);
2751 g_warning ("QueryPerformanceCounter Failed (%lu)", GetLastError ());
2752 g_monotonic_usec_per_tick
= 0;
2757 #elif defined(HAVE_MACH_MACH_TIME_H) /* Mac OS */
2759 g_get_monotonic_time (void)
2761 static mach_timebase_info_data_t timebase_info
;
2763 if (timebase_info
.denom
== 0)
2765 /* This is a fraction that we must use to scale
2766 * mach_absolute_time() by in order to reach nanoseconds.
2768 * We've only ever observed this to be 1/1, but maybe it could be
2769 * 1000/1 if mach time is microseconds already, or 1/1000 if
2770 * picoseconds. Try to deal nicely with that.
2772 mach_timebase_info (&timebase_info
);
2774 /* We actually want microseconds... */
2775 if (timebase_info
.numer
% 1000 == 0)
2776 timebase_info
.numer
/= 1000;
2778 timebase_info
.denom
*= 1000;
2780 /* We want to make the numer 1 to avoid having to multiply... */
2781 if (timebase_info
.denom
% timebase_info
.numer
== 0)
2783 timebase_info
.denom
/= timebase_info
.numer
;
2784 timebase_info
.numer
= 1;
2788 /* We could just multiply by timebase_info.numer below, but why
2789 * bother for a case that may never actually exist...
2791 * Plus -- performing the multiplication would risk integer
2792 * overflow. If we ever actually end up in this situation, we
2793 * should more carefully evaluate the correct course of action.
2795 mach_timebase_info (&timebase_info
); /* Get a fresh copy for a better message */
2796 g_error ("Got weird mach timebase info of %d/%d. Please file a bug against GLib.",
2797 timebase_info
.numer
, timebase_info
.denom
);
2801 return mach_absolute_time () / timebase_info
.denom
;
2805 g_get_monotonic_time (void)
2810 result
= clock_gettime (CLOCK_MONOTONIC
, &ts
);
2812 if G_UNLIKELY (result
!= 0)
2813 g_error ("GLib requires working CLOCK_MONOTONIC");
2815 return (((gint64
) ts
.tv_sec
) * 1000000) + (ts
.tv_nsec
/ 1000);
2820 g_main_dispatch_free (gpointer dispatch
)
2822 g_slice_free (GMainDispatch
, dispatch
);
2825 /* Running the main loop */
2827 static GMainDispatch
*
2830 static GPrivate depth_private
= G_PRIVATE_INIT (g_main_dispatch_free
);
2831 GMainDispatch
*dispatch
;
2833 dispatch
= g_private_get (&depth_private
);
2837 dispatch
= g_slice_new0 (GMainDispatch
);
2838 g_private_set (&depth_private
, dispatch
);
2847 * Returns the depth of the stack of calls to
2848 * g_main_context_dispatch() on any #GMainContext in the current thread.
2849 * That is, when called from the toplevel, it gives 0. When
2850 * called from within a callback from g_main_context_iteration()
2851 * (or g_main_loop_run(), etc.) it returns 1. When called from within
2852 * a callback to a recursive call to g_main_context_iteration(),
2853 * it returns 2. And so forth.
2855 * This function is useful in a situation like the following:
2856 * Imagine an extremely simple "garbage collected" system.
2858 * |[<!-- language="C" -->
2859 * static GList *free_list;
2862 * allocate_memory (gsize size)
2864 * gpointer result = g_malloc (size);
2865 * free_list = g_list_prepend (free_list, result);
2870 * free_allocated_memory (void)
2873 * for (l = free_list; l; l = l->next);
2875 * g_list_free (free_list);
2883 * g_main_context_iteration (NULL, TRUE);
2884 * free_allocated_memory();
2888 * This works from an application, however, if you want to do the same
2889 * thing from a library, it gets more difficult, since you no longer
2890 * control the main loop. You might think you can simply use an idle
2891 * function to make the call to free_allocated_memory(), but that
2892 * doesn't work, since the idle function could be called from a
2893 * recursive callback. This can be fixed by using g_main_depth()
2895 * |[<!-- language="C" -->
2897 * allocate_memory (gsize size)
2899 * FreeListBlock *block = g_new (FreeListBlock, 1);
2900 * block->mem = g_malloc (size);
2901 * block->depth = g_main_depth ();
2902 * free_list = g_list_prepend (free_list, block);
2903 * return block->mem;
2907 * free_allocated_memory (void)
2911 * int depth = g_main_depth ();
2912 * for (l = free_list; l; );
2914 * GList *next = l->next;
2915 * FreeListBlock *block = l->data;
2916 * if (block->depth > depth)
2918 * g_free (block->mem);
2920 * free_list = g_list_delete_link (free_list, l);
2928 * There is a temptation to use g_main_depth() to solve
2929 * problems with reentrancy. For instance, while waiting for data
2930 * to be received from the network in response to a menu item,
2931 * the menu item might be selected again. It might seem that
2932 * one could make the menu item's callback return immediately
2933 * and do nothing if g_main_depth() returns a value greater than 1.
2934 * However, this should be avoided since the user then sees selecting
2935 * the menu item do nothing. Furthermore, you'll find yourself adding
2936 * these checks all over your code, since there are doubtless many,
2937 * many things that the user could do. Instead, you can use the
2938 * following techniques:
2940 * 1. Use gtk_widget_set_sensitive() or modal dialogs to prevent
2941 * the user from interacting with elements while the main
2942 * loop is recursing.
2944 * 2. Avoid main loop recursion in situations where you can't handle
2945 * arbitrary callbacks. Instead, structure your code so that you
2946 * simply return to the main loop and then get called again when
2947 * there is more work to do.
2949 * Returns: The main loop recursion level in the current thread
2954 GMainDispatch
*dispatch
= get_dispatch ();
2955 return dispatch
->depth
;
2959 * g_main_current_source:
2961 * Returns the currently firing source for this thread.
2963 * Returns: (transfer none): The currently firing source or %NULL.
2968 g_main_current_source (void)
2970 GMainDispatch
*dispatch
= get_dispatch ();
2971 return dispatch
->source
;
2975 * g_source_is_destroyed:
2976 * @source: a #GSource
2978 * Returns whether @source has been destroyed.
2980 * This is important when you operate upon your objects
2981 * from within idle handlers, but may have freed the object
2982 * before the dispatch of your idle handler.
2984 * |[<!-- language="C" -->
2986 * idle_callback (gpointer data)
2988 * SomeWidget *self = data;
2990 * GDK_THREADS_ENTER ();
2991 * // do stuff with self
2992 * self->idle_id = 0;
2993 * GDK_THREADS_LEAVE ();
2995 * return G_SOURCE_REMOVE;
2999 * some_widget_do_stuff_later (SomeWidget *self)
3001 * self->idle_id = g_idle_add (idle_callback, self);
3005 * some_widget_finalize (GObject *object)
3007 * SomeWidget *self = SOME_WIDGET (object);
3009 * if (self->idle_id)
3010 * g_source_remove (self->idle_id);
3012 * G_OBJECT_CLASS (parent_class)->finalize (object);
3016 * This will fail in a multi-threaded application if the
3017 * widget is destroyed before the idle handler fires due
3018 * to the use after free in the callback. A solution, to
3019 * this particular problem, is to check to if the source
3020 * has already been destroy within the callback.
3022 * |[<!-- language="C" -->
3024 * idle_callback (gpointer data)
3026 * SomeWidget *self = data;
3028 * GDK_THREADS_ENTER ();
3029 * if (!g_source_is_destroyed (g_main_current_source ()))
3031 * // do stuff with self
3033 * GDK_THREADS_LEAVE ();
3039 * Calls to this function from a thread other than the one acquired by the
3040 * #GMainContext the #GSource is attached to are typically redundant, as the
3041 * source could be destroyed immediately after this function returns. However,
3042 * once a source is destroyed it cannot be un-destroyed, so this function can be
3043 * used for opportunistic checks from any thread.
3045 * Returns: %TRUE if the source has been destroyed
3050 g_source_is_destroyed (GSource
*source
)
3052 return SOURCE_DESTROYED (source
);
3055 /* Temporarily remove all this source's file descriptors from the
3056 * poll(), so that if data comes available for one of the file descriptors
3057 * we don't continually spin in the poll()
3059 /* HOLDS: source->context's lock */
3061 block_source (GSource
*source
)
3065 g_return_if_fail (!SOURCE_BLOCKED (source
));
3067 source
->flags
|= G_SOURCE_BLOCKED
;
3069 if (source
->context
)
3071 tmp_list
= source
->poll_fds
;
3074 g_main_context_remove_poll_unlocked (source
->context
, tmp_list
->data
);
3075 tmp_list
= tmp_list
->next
;
3078 for (tmp_list
= source
->priv
->fds
; tmp_list
; tmp_list
= tmp_list
->next
)
3079 g_main_context_remove_poll_unlocked (source
->context
, tmp_list
->data
);
3082 if (source
->priv
&& source
->priv
->child_sources
)
3084 tmp_list
= source
->priv
->child_sources
;
3087 block_source (tmp_list
->data
);
3088 tmp_list
= tmp_list
->next
;
3093 /* HOLDS: source->context's lock */
3095 unblock_source (GSource
*source
)
3099 g_return_if_fail (SOURCE_BLOCKED (source
)); /* Source already unblocked */
3100 g_return_if_fail (!SOURCE_DESTROYED (source
));
3102 source
->flags
&= ~G_SOURCE_BLOCKED
;
3104 tmp_list
= source
->poll_fds
;
3107 g_main_context_add_poll_unlocked (source
->context
, source
->priority
, tmp_list
->data
);
3108 tmp_list
= tmp_list
->next
;
3111 for (tmp_list
= source
->priv
->fds
; tmp_list
; tmp_list
= tmp_list
->next
)
3112 g_main_context_add_poll_unlocked (source
->context
, source
->priority
, tmp_list
->data
);
3114 if (source
->priv
&& source
->priv
->child_sources
)
3116 tmp_list
= source
->priv
->child_sources
;
3119 unblock_source (tmp_list
->data
);
3120 tmp_list
= tmp_list
->next
;
3125 /* HOLDS: context's lock */
3127 g_main_dispatch (GMainContext
*context
)
3129 GMainDispatch
*current
= get_dispatch ();
3132 for (i
= 0; i
< context
->pending_dispatches
->len
; i
++)
3134 GSource
*source
= context
->pending_dispatches
->pdata
[i
];
3136 context
->pending_dispatches
->pdata
[i
] = NULL
;
3139 source
->flags
&= ~G_SOURCE_READY
;
3141 if (!SOURCE_DESTROYED (source
))
3143 gboolean was_in_call
;
3144 gpointer user_data
= NULL
;
3145 GSourceFunc callback
= NULL
;
3146 GSourceCallbackFuncs
*cb_funcs
;
3148 gboolean need_destroy
;
3150 gboolean (*dispatch
) (GSource
*,
3153 GSource
*prev_source
;
3155 dispatch
= source
->source_funcs
->dispatch
;
3156 cb_funcs
= source
->callback_funcs
;
3157 cb_data
= source
->callback_data
;
3160 cb_funcs
->ref (cb_data
);
3162 if ((source
->flags
& G_SOURCE_CAN_RECURSE
) == 0)
3163 block_source (source
);
3165 was_in_call
= source
->flags
& G_HOOK_FLAG_IN_CALL
;
3166 source
->flags
|= G_HOOK_FLAG_IN_CALL
;
3169 cb_funcs
->get (cb_data
, source
, &callback
, &user_data
);
3171 UNLOCK_CONTEXT (context
);
3173 /* These operations are safe because 'current' is thread-local
3174 * and not modified from anywhere but this function.
3176 prev_source
= current
->source
;
3177 current
->source
= source
;
3180 TRACE (GLIB_MAIN_BEFORE_DISPATCH (g_source_get_name (source
), source
,
3181 dispatch
, callback
, user_data
));
3182 need_destroy
= !(* dispatch
) (source
, callback
, user_data
);
3183 TRACE (GLIB_MAIN_AFTER_DISPATCH (g_source_get_name (source
), source
,
3184 dispatch
, need_destroy
));
3186 current
->source
= prev_source
;
3190 cb_funcs
->unref (cb_data
);
3192 LOCK_CONTEXT (context
);
3195 source
->flags
&= ~G_HOOK_FLAG_IN_CALL
;
3197 if (SOURCE_BLOCKED (source
) && !SOURCE_DESTROYED (source
))
3198 unblock_source (source
);
3200 /* Note: this depends on the fact that we can't switch
3201 * sources from one main context to another
3203 if (need_destroy
&& !SOURCE_DESTROYED (source
))
3205 g_assert (source
->context
== context
);
3206 g_source_destroy_internal (source
, context
, TRUE
);
3210 SOURCE_UNREF (source
, context
);
3213 g_ptr_array_set_size (context
->pending_dispatches
, 0);
3217 * g_main_context_acquire:
3218 * @context: a #GMainContext
3220 * Tries to become the owner of the specified context.
3221 * If some other thread is the owner of the context,
3222 * returns %FALSE immediately. Ownership is properly
3223 * recursive: the owner can require ownership again
3224 * and will release ownership when g_main_context_release()
3225 * is called as many times as g_main_context_acquire().
3227 * You must be the owner of a context before you
3228 * can call g_main_context_prepare(), g_main_context_query(),
3229 * g_main_context_check(), g_main_context_dispatch().
3231 * Returns: %TRUE if the operation succeeded, and
3232 * this thread is now the owner of @context.
3235 g_main_context_acquire (GMainContext
*context
)
3237 gboolean result
= FALSE
;
3238 GThread
*self
= G_THREAD_SELF
;
3240 if (context
== NULL
)
3241 context
= g_main_context_default ();
3243 LOCK_CONTEXT (context
);
3245 if (!context
->owner
)
3247 context
->owner
= self
;
3248 g_assert (context
->owner_count
== 0);
3249 TRACE (GLIB_MAIN_CONTEXT_ACQUIRE (context
, TRUE
/* success */));
3252 if (context
->owner
== self
)
3254 context
->owner_count
++;
3259 TRACE (GLIB_MAIN_CONTEXT_ACQUIRE (context
, FALSE
/* failure */));
3262 UNLOCK_CONTEXT (context
);
3268 * g_main_context_release:
3269 * @context: a #GMainContext
3271 * Releases ownership of a context previously acquired by this thread
3272 * with g_main_context_acquire(). If the context was acquired multiple
3273 * times, the ownership will be released only when g_main_context_release()
3274 * is called as many times as it was acquired.
3277 g_main_context_release (GMainContext
*context
)
3279 if (context
== NULL
)
3280 context
= g_main_context_default ();
3282 LOCK_CONTEXT (context
);
3284 context
->owner_count
--;
3285 if (context
->owner_count
== 0)
3287 TRACE (GLIB_MAIN_CONTEXT_RELEASE (context
));
3289 context
->owner
= NULL
;
3291 if (context
->waiters
)
3293 GMainWaiter
*waiter
= context
->waiters
->data
;
3294 gboolean loop_internal_waiter
= (waiter
->mutex
== &context
->mutex
);
3295 context
->waiters
= g_slist_delete_link (context
->waiters
,
3297 if (!loop_internal_waiter
)
3298 g_mutex_lock (waiter
->mutex
);
3300 g_cond_signal (waiter
->cond
);
3302 if (!loop_internal_waiter
)
3303 g_mutex_unlock (waiter
->mutex
);
3307 UNLOCK_CONTEXT (context
);
3311 g_main_context_wait_internal (GMainContext
*context
,
3315 gboolean result
= FALSE
;
3316 GThread
*self
= G_THREAD_SELF
;
3317 gboolean loop_internal_waiter
;
3319 if (context
== NULL
)
3320 context
= g_main_context_default ();
3322 loop_internal_waiter
= (mutex
== &context
->mutex
);
3324 if (!loop_internal_waiter
)
3325 LOCK_CONTEXT (context
);
3327 if (context
->owner
&& context
->owner
!= self
)
3332 waiter
.mutex
= mutex
;
3334 context
->waiters
= g_slist_append (context
->waiters
, &waiter
);
3336 if (!loop_internal_waiter
)
3337 UNLOCK_CONTEXT (context
);
3338 g_cond_wait (cond
, mutex
);
3339 if (!loop_internal_waiter
)
3340 LOCK_CONTEXT (context
);
3342 context
->waiters
= g_slist_remove (context
->waiters
, &waiter
);
3345 if (!context
->owner
)
3347 context
->owner
= self
;
3348 g_assert (context
->owner_count
== 0);
3351 if (context
->owner
== self
)
3353 context
->owner_count
++;
3357 if (!loop_internal_waiter
)
3358 UNLOCK_CONTEXT (context
);
3364 * g_main_context_wait:
3365 * @context: a #GMainContext
3366 * @cond: a condition variable
3367 * @mutex: a mutex, currently held
3369 * Tries to become the owner of the specified context,
3370 * as with g_main_context_acquire(). But if another thread
3371 * is the owner, atomically drop @mutex and wait on @cond until
3372 * that owner releases ownership or until @cond is signaled, then
3373 * try again (once) to become the owner.
3375 * Returns: %TRUE if the operation succeeded, and
3376 * this thread is now the owner of @context.
3377 * Deprecated: 2.58: Use g_main_context_is_owner() and separate locking instead.
3380 g_main_context_wait (GMainContext
*context
,
3384 if (context
== NULL
)
3385 context
= g_main_context_default ();
3387 if (G_UNLIKELY (cond
!= &context
->cond
|| mutex
!= &context
->mutex
))
3389 static gboolean warned
;
3393 g_critical ("WARNING!! g_main_context_wait() will be removed in a future release. "
3394 "If you see this message, please file a bug immediately.");
3399 return g_main_context_wait_internal (context
, cond
, mutex
);
3403 * g_main_context_prepare:
3404 * @context: a #GMainContext
3405 * @priority: location to store priority of highest priority
3406 * source already ready.
3408 * Prepares to poll sources within a main loop. The resulting information
3409 * for polling is determined by calling g_main_context_query ().
3411 * You must have successfully acquired the context with
3412 * g_main_context_acquire() before you may call this function.
3414 * Returns: %TRUE if some source is ready to be dispatched
3418 g_main_context_prepare (GMainContext
*context
,
3423 gint current_priority
= G_MAXINT
;
3427 if (context
== NULL
)
3428 context
= g_main_context_default ();
3430 LOCK_CONTEXT (context
);
3432 context
->time_is_fresh
= FALSE
;
3434 if (context
->in_check_or_prepare
)
3436 g_warning ("g_main_context_prepare() called recursively from within a source's check() or "
3437 "prepare() member.");
3438 UNLOCK_CONTEXT (context
);
3442 TRACE (GLIB_MAIN_CONTEXT_BEFORE_PREPARE (context
));
3445 /* If recursing, finish up current dispatch, before starting over */
3446 if (context
->pending_dispatches
)
3449 g_main_dispatch (context
, ¤t_time
);
3451 UNLOCK_CONTEXT (context
);
3456 /* If recursing, clear list of pending dispatches */
3458 for (i
= 0; i
< context
->pending_dispatches
->len
; i
++)
3460 if (context
->pending_dispatches
->pdata
[i
])
3461 SOURCE_UNREF ((GSource
*)context
->pending_dispatches
->pdata
[i
], context
);
3463 g_ptr_array_set_size (context
->pending_dispatches
, 0);
3465 /* Prepare all sources */
3467 context
->timeout
= -1;
3469 g_source_iter_init (&iter
, context
, TRUE
);
3470 while (g_source_iter_next (&iter
, &source
))
3472 gint source_timeout
= -1;
3474 if (SOURCE_DESTROYED (source
) || SOURCE_BLOCKED (source
))
3476 if ((n_ready
> 0) && (source
->priority
> current_priority
))
3479 if (!(source
->flags
& G_SOURCE_READY
))
3482 gboolean (* prepare
) (GSource
*source
,
3485 prepare
= source
->source_funcs
->prepare
;
3489 context
->in_check_or_prepare
++;
3490 UNLOCK_CONTEXT (context
);
3492 result
= (* prepare
) (source
, &source_timeout
);
3493 TRACE (GLIB_MAIN_AFTER_PREPARE (source
, prepare
, source_timeout
));
3495 LOCK_CONTEXT (context
);
3496 context
->in_check_or_prepare
--;
3500 source_timeout
= -1;
3504 if (result
== FALSE
&& source
->priv
->ready_time
!= -1)
3506 if (!context
->time_is_fresh
)
3508 context
->time
= g_get_monotonic_time ();
3509 context
->time_is_fresh
= TRUE
;
3512 if (source
->priv
->ready_time
<= context
->time
)
3521 /* rounding down will lead to spinning, so always round up */
3522 timeout
= (source
->priv
->ready_time
- context
->time
+ 999) / 1000;
3524 if (source_timeout
< 0 || timeout
< source_timeout
)
3525 source_timeout
= timeout
;
3531 GSource
*ready_source
= source
;
3533 while (ready_source
)
3535 ready_source
->flags
|= G_SOURCE_READY
;
3536 ready_source
= ready_source
->priv
->parent_source
;
3541 if (source
->flags
& G_SOURCE_READY
)
3544 current_priority
= source
->priority
;
3545 context
->timeout
= 0;
3548 if (source_timeout
>= 0)
3550 if (context
->timeout
< 0)
3551 context
->timeout
= source_timeout
;
3553 context
->timeout
= MIN (context
->timeout
, source_timeout
);
3556 g_source_iter_clear (&iter
);
3558 TRACE (GLIB_MAIN_CONTEXT_AFTER_PREPARE (context
, current_priority
, n_ready
));
3560 UNLOCK_CONTEXT (context
);
3563 *priority
= current_priority
;
3565 return (n_ready
> 0);
3569 * g_main_context_query:
3570 * @context: a #GMainContext
3571 * @max_priority: maximum priority source to check
3572 * @timeout_: (out): location to store timeout to be used in polling
3573 * @fds: (out caller-allocates) (array length=n_fds): location to
3574 * store #GPollFD records that need to be polled.
3575 * @n_fds: (in): length of @fds.
3577 * Determines information necessary to poll this main loop.
3579 * You must have successfully acquired the context with
3580 * g_main_context_acquire() before you may call this function.
3582 * Returns: the number of records actually stored in @fds,
3583 * or, if more than @n_fds records need to be stored, the number
3584 * of records that need to be stored.
3587 g_main_context_query (GMainContext
*context
,
3594 GPollRec
*pollrec
, *lastpollrec
;
3597 LOCK_CONTEXT (context
);
3599 TRACE (GLIB_MAIN_CONTEXT_BEFORE_QUERY (context
, max_priority
));
3603 for (pollrec
= context
->poll_records
; pollrec
; pollrec
= pollrec
->next
)
3605 if (pollrec
->priority
> max_priority
)
3608 /* In direct contradiction to the Unix98 spec, IRIX runs into
3609 * difficulty if you pass in POLLERR, POLLHUP or POLLNVAL
3610 * flags in the events field of the pollfd while it should
3611 * just ignoring them. So we mask them out here.
3613 events
= pollrec
->fd
->events
& ~(G_IO_ERR
|G_IO_HUP
|G_IO_NVAL
);
3615 if (lastpollrec
&& pollrec
->fd
->fd
== lastpollrec
->fd
->fd
)
3617 if (n_poll
- 1 < n_fds
)
3618 fds
[n_poll
- 1].events
|= events
;
3624 fds
[n_poll
].fd
= pollrec
->fd
->fd
;
3625 fds
[n_poll
].events
= events
;
3626 fds
[n_poll
].revents
= 0;
3632 lastpollrec
= pollrec
;
3635 context
->poll_changed
= FALSE
;
3639 *timeout
= context
->timeout
;
3641 context
->time_is_fresh
= FALSE
;
3644 TRACE (GLIB_MAIN_CONTEXT_AFTER_QUERY (context
, context
->timeout
,
3647 UNLOCK_CONTEXT (context
);
3653 * g_main_context_check:
3654 * @context: a #GMainContext
3655 * @max_priority: the maximum numerical priority of sources to check
3656 * @fds: (array length=n_fds): array of #GPollFD's that was passed to
3657 * the last call to g_main_context_query()
3658 * @n_fds: return value of g_main_context_query()
3660 * Passes the results of polling back to the main loop.
3662 * You must have successfully acquired the context with
3663 * g_main_context_acquire() before you may call this function.
3665 * Returns: %TRUE if some sources are ready to be dispatched.
3668 g_main_context_check (GMainContext
*context
,
3679 LOCK_CONTEXT (context
);
3681 if (context
->in_check_or_prepare
)
3683 g_warning ("g_main_context_check() called recursively from within a source's check() or "
3684 "prepare() member.");
3685 UNLOCK_CONTEXT (context
);
3689 TRACE (GLIB_MAIN_CONTEXT_BEFORE_CHECK (context
, max_priority
, fds
, n_fds
));
3691 for (i
= 0; i
< n_fds
; i
++)
3693 if (fds
[i
].fd
== context
->wake_up_rec
.fd
)
3697 TRACE (GLIB_MAIN_CONTEXT_WAKEUP_ACKNOWLEDGE (context
));
3698 g_wakeup_acknowledge (context
->wakeup
);
3704 /* If the set of poll file descriptors changed, bail out
3705 * and let the main loop rerun
3707 if (context
->poll_changed
)
3709 TRACE (GLIB_MAIN_CONTEXT_AFTER_CHECK (context
, 0));
3711 UNLOCK_CONTEXT (context
);
3715 pollrec
= context
->poll_records
;
3717 while (pollrec
&& i
< n_fds
)
3719 while (pollrec
&& pollrec
->fd
->fd
== fds
[i
].fd
)
3721 if (pollrec
->priority
<= max_priority
)
3723 pollrec
->fd
->revents
=
3724 fds
[i
].revents
& (pollrec
->fd
->events
| G_IO_ERR
| G_IO_HUP
| G_IO_NVAL
);
3726 pollrec
= pollrec
->next
;
3732 g_source_iter_init (&iter
, context
, TRUE
);
3733 while (g_source_iter_next (&iter
, &source
))
3735 if (SOURCE_DESTROYED (source
) || SOURCE_BLOCKED (source
))
3737 if ((n_ready
> 0) && (source
->priority
> max_priority
))
3740 if (!(source
->flags
& G_SOURCE_READY
))
3743 gboolean (* check
) (GSource
*source
);
3745 check
= source
->source_funcs
->check
;
3749 /* If the check function is set, call it. */
3750 context
->in_check_or_prepare
++;
3751 UNLOCK_CONTEXT (context
);
3753 result
= (* check
) (source
);
3755 TRACE (GLIB_MAIN_AFTER_CHECK (source
, check
, result
));
3757 LOCK_CONTEXT (context
);
3758 context
->in_check_or_prepare
--;
3763 if (result
== FALSE
)
3767 /* If not already explicitly flagged ready by ->check()
3768 * (or if we have no check) then we can still be ready if
3769 * any of our fds poll as ready.
3771 for (tmp_list
= source
->priv
->fds
; tmp_list
; tmp_list
= tmp_list
->next
)
3773 GPollFD
*pollfd
= tmp_list
->data
;
3775 if (pollfd
->revents
)
3783 if (result
== FALSE
&& source
->priv
->ready_time
!= -1)
3785 if (!context
->time_is_fresh
)
3787 context
->time
= g_get_monotonic_time ();
3788 context
->time_is_fresh
= TRUE
;
3791 if (source
->priv
->ready_time
<= context
->time
)
3797 GSource
*ready_source
= source
;
3799 while (ready_source
)
3801 ready_source
->flags
|= G_SOURCE_READY
;
3802 ready_source
= ready_source
->priv
->parent_source
;
3807 if (source
->flags
& G_SOURCE_READY
)
3809 source
->ref_count
++;
3810 g_ptr_array_add (context
->pending_dispatches
, source
);
3814 /* never dispatch sources with less priority than the first
3815 * one we choose to dispatch
3817 max_priority
= source
->priority
;
3820 g_source_iter_clear (&iter
);
3822 TRACE (GLIB_MAIN_CONTEXT_AFTER_CHECK (context
, n_ready
));
3824 UNLOCK_CONTEXT (context
);
3830 * g_main_context_dispatch:
3831 * @context: a #GMainContext
3833 * Dispatches all pending sources.
3835 * You must have successfully acquired the context with
3836 * g_main_context_acquire() before you may call this function.
3839 g_main_context_dispatch (GMainContext
*context
)
3841 LOCK_CONTEXT (context
);
3843 TRACE (GLIB_MAIN_CONTEXT_BEFORE_DISPATCH (context
));
3845 if (context
->pending_dispatches
->len
> 0)
3847 g_main_dispatch (context
);
3850 TRACE (GLIB_MAIN_CONTEXT_AFTER_DISPATCH (context
));
3852 UNLOCK_CONTEXT (context
);
3855 /* HOLDS context lock */
3857 g_main_context_iterate (GMainContext
*context
,
3864 gboolean some_ready
;
3865 gint nfds
, allocated_nfds
;
3866 GPollFD
*fds
= NULL
;
3868 UNLOCK_CONTEXT (context
);
3870 if (!g_main_context_acquire (context
))
3872 gboolean got_ownership
;
3874 LOCK_CONTEXT (context
);
3879 got_ownership
= g_main_context_wait_internal (context
,
3887 LOCK_CONTEXT (context
);
3889 if (!context
->cached_poll_array
)
3891 context
->cached_poll_array_size
= context
->n_poll_records
;
3892 context
->cached_poll_array
= g_new (GPollFD
, context
->n_poll_records
);
3895 allocated_nfds
= context
->cached_poll_array_size
;
3896 fds
= context
->cached_poll_array
;
3898 UNLOCK_CONTEXT (context
);
3900 g_main_context_prepare (context
, &max_priority
);
3902 while ((nfds
= g_main_context_query (context
, max_priority
, &timeout
, fds
,
3903 allocated_nfds
)) > allocated_nfds
)
3905 LOCK_CONTEXT (context
);
3907 context
->cached_poll_array_size
= allocated_nfds
= nfds
;
3908 context
->cached_poll_array
= fds
= g_new (GPollFD
, nfds
);
3909 UNLOCK_CONTEXT (context
);
3915 g_main_context_poll (context
, timeout
, max_priority
, fds
, nfds
);
3917 some_ready
= g_main_context_check (context
, max_priority
, fds
, nfds
);
3920 g_main_context_dispatch (context
);
3922 g_main_context_release (context
);
3924 LOCK_CONTEXT (context
);
3930 * g_main_context_pending:
3931 * @context: (nullable): a #GMainContext (if %NULL, the default context will be used)
3933 * Checks if any sources have pending events for the given context.
3935 * Returns: %TRUE if events are pending.
3938 g_main_context_pending (GMainContext
*context
)
3943 context
= g_main_context_default();
3945 LOCK_CONTEXT (context
);
3946 retval
= g_main_context_iterate (context
, FALSE
, FALSE
, G_THREAD_SELF
);
3947 UNLOCK_CONTEXT (context
);
3953 * g_main_context_iteration:
3954 * @context: (nullable): a #GMainContext (if %NULL, the default context will be used)
3955 * @may_block: whether the call may block.
3957 * Runs a single iteration for the given main loop. This involves
3958 * checking to see if any event sources are ready to be processed,
3959 * then if no events sources are ready and @may_block is %TRUE, waiting
3960 * for a source to become ready, then dispatching the highest priority
3961 * events sources that are ready. Otherwise, if @may_block is %FALSE
3962 * sources are not waited to become ready, only those highest priority
3963 * events sources will be dispatched (if any), that are ready at this
3964 * given moment without further waiting.
3966 * Note that even when @may_block is %TRUE, it is still possible for
3967 * g_main_context_iteration() to return %FALSE, since the wait may
3968 * be interrupted for other reasons than an event source becoming ready.
3970 * Returns: %TRUE if events were dispatched.
3973 g_main_context_iteration (GMainContext
*context
, gboolean may_block
)
3978 context
= g_main_context_default();
3980 LOCK_CONTEXT (context
);
3981 retval
= g_main_context_iterate (context
, may_block
, TRUE
, G_THREAD_SELF
);
3982 UNLOCK_CONTEXT (context
);
3989 * @context: (nullable): a #GMainContext (if %NULL, the default context will be used).
3990 * @is_running: set to %TRUE to indicate that the loop is running. This
3991 * is not very important since calling g_main_loop_run() will set this to
3994 * Creates a new #GMainLoop structure.
3996 * Returns: a new #GMainLoop.
3999 g_main_loop_new (GMainContext
*context
,
4000 gboolean is_running
)
4005 context
= g_main_context_default();
4007 g_main_context_ref (context
);
4009 loop
= g_new0 (GMainLoop
, 1);
4010 loop
->context
= context
;
4011 loop
->is_running
= is_running
!= FALSE
;
4012 loop
->ref_count
= 1;
4014 TRACE (GLIB_MAIN_LOOP_NEW (loop
, context
));
4021 * @loop: a #GMainLoop
4023 * Increases the reference count on a #GMainLoop object by one.
4028 g_main_loop_ref (GMainLoop
*loop
)
4030 g_return_val_if_fail (loop
!= NULL
, NULL
);
4031 g_return_val_if_fail (g_atomic_int_get (&loop
->ref_count
) > 0, NULL
);
4033 g_atomic_int_inc (&loop
->ref_count
);
4039 * g_main_loop_unref:
4040 * @loop: a #GMainLoop
4042 * Decreases the reference count on a #GMainLoop object by one. If
4043 * the result is zero, free the loop and free all associated memory.
4046 g_main_loop_unref (GMainLoop
*loop
)
4048 g_return_if_fail (loop
!= NULL
);
4049 g_return_if_fail (g_atomic_int_get (&loop
->ref_count
) > 0);
4051 if (!g_atomic_int_dec_and_test (&loop
->ref_count
))
4054 g_main_context_unref (loop
->context
);
4060 * @loop: a #GMainLoop
4062 * Runs a main loop until g_main_loop_quit() is called on the loop.
4063 * If this is called for the thread of the loop's #GMainContext,
4064 * it will process events from the loop, otherwise it will
4068 g_main_loop_run (GMainLoop
*loop
)
4070 GThread
*self
= G_THREAD_SELF
;
4072 g_return_if_fail (loop
!= NULL
);
4073 g_return_if_fail (g_atomic_int_get (&loop
->ref_count
) > 0);
4075 if (!g_main_context_acquire (loop
->context
))
4077 gboolean got_ownership
= FALSE
;
4079 /* Another thread owns this context */
4080 LOCK_CONTEXT (loop
->context
);
4082 g_atomic_int_inc (&loop
->ref_count
);
4084 if (!loop
->is_running
)
4085 loop
->is_running
= TRUE
;
4087 while (loop
->is_running
&& !got_ownership
)
4088 got_ownership
= g_main_context_wait_internal (loop
->context
,
4089 &loop
->context
->cond
,
4090 &loop
->context
->mutex
);
4092 if (!loop
->is_running
)
4094 UNLOCK_CONTEXT (loop
->context
);
4096 g_main_context_release (loop
->context
);
4097 g_main_loop_unref (loop
);
4101 g_assert (got_ownership
);
4104 LOCK_CONTEXT (loop
->context
);
4106 if (loop
->context
->in_check_or_prepare
)
4108 g_warning ("g_main_loop_run(): called recursively from within a source's "
4109 "check() or prepare() member, iteration not possible.");
4113 g_atomic_int_inc (&loop
->ref_count
);
4114 loop
->is_running
= TRUE
;
4115 while (loop
->is_running
)
4116 g_main_context_iterate (loop
->context
, TRUE
, TRUE
, self
);
4118 UNLOCK_CONTEXT (loop
->context
);
4120 g_main_context_release (loop
->context
);
4122 g_main_loop_unref (loop
);
4127 * @loop: a #GMainLoop
4129 * Stops a #GMainLoop from running. Any calls to g_main_loop_run()
4130 * for the loop will return.
4132 * Note that sources that have already been dispatched when
4133 * g_main_loop_quit() is called will still be executed.
4136 g_main_loop_quit (GMainLoop
*loop
)
4138 g_return_if_fail (loop
!= NULL
);
4139 g_return_if_fail (g_atomic_int_get (&loop
->ref_count
) > 0);
4141 LOCK_CONTEXT (loop
->context
);
4142 loop
->is_running
= FALSE
;
4143 g_wakeup_signal (loop
->context
->wakeup
);
4145 g_cond_broadcast (&loop
->context
->cond
);
4147 UNLOCK_CONTEXT (loop
->context
);
4149 TRACE (GLIB_MAIN_LOOP_QUIT (loop
));
4153 * g_main_loop_is_running:
4154 * @loop: a #GMainLoop.
4156 * Checks to see if the main loop is currently being run via g_main_loop_run().
4158 * Returns: %TRUE if the mainloop is currently being run.
4161 g_main_loop_is_running (GMainLoop
*loop
)
4163 g_return_val_if_fail (loop
!= NULL
, FALSE
);
4164 g_return_val_if_fail (g_atomic_int_get (&loop
->ref_count
) > 0, FALSE
);
4166 return loop
->is_running
;
4170 * g_main_loop_get_context:
4171 * @loop: a #GMainLoop.
4173 * Returns the #GMainContext of @loop.
4175 * Returns: (transfer none): the #GMainContext of @loop
4178 g_main_loop_get_context (GMainLoop
*loop
)
4180 g_return_val_if_fail (loop
!= NULL
, NULL
);
4181 g_return_val_if_fail (g_atomic_int_get (&loop
->ref_count
) > 0, NULL
);
4183 return loop
->context
;
4186 /* HOLDS: context's lock */
4188 g_main_context_poll (GMainContext
*context
,
4194 #ifdef G_MAIN_POLL_DEBUG
4200 GPollFunc poll_func
;
4202 if (n_fds
|| timeout
!= 0)
4206 #ifdef G_MAIN_POLL_DEBUG
4208 if (_g_main_poll_debug
)
4210 g_print ("polling context=%p n=%d timeout=%d\n",
4211 context
, n_fds
, timeout
);
4212 poll_timer
= g_timer_new ();
4216 LOCK_CONTEXT (context
);
4218 poll_func
= context
->poll_func
;
4220 UNLOCK_CONTEXT (context
);
4221 ret
= (*poll_func
) (fds
, n_fds
, timeout
);
4223 if (ret
< 0 && errsv
!= EINTR
)
4226 g_warning ("poll(2) failed due to: %s.",
4227 g_strerror (errsv
));
4229 /* If g_poll () returns -1, it has already called g_warning() */
4233 #ifdef G_MAIN_POLL_DEBUG
4234 if (_g_main_poll_debug
)
4236 LOCK_CONTEXT (context
);
4238 g_print ("g_main_poll(%d) timeout: %d - elapsed %12.10f seconds",
4241 g_timer_elapsed (poll_timer
, NULL
));
4242 g_timer_destroy (poll_timer
);
4243 pollrec
= context
->poll_records
;
4245 while (pollrec
!= NULL
)
4250 if (fds
[i
].fd
== pollrec
->fd
->fd
&&
4251 pollrec
->fd
->events
&&
4254 g_print (" [" G_POLLFD_FORMAT
" :", fds
[i
].fd
);
4255 if (fds
[i
].revents
& G_IO_IN
)
4257 if (fds
[i
].revents
& G_IO_OUT
)
4259 if (fds
[i
].revents
& G_IO_PRI
)
4261 if (fds
[i
].revents
& G_IO_ERR
)
4263 if (fds
[i
].revents
& G_IO_HUP
)
4265 if (fds
[i
].revents
& G_IO_NVAL
)
4271 pollrec
= pollrec
->next
;
4275 UNLOCK_CONTEXT (context
);
4278 } /* if (n_fds || timeout != 0) */
4282 * g_main_context_add_poll:
4283 * @context: (nullable): a #GMainContext (or %NULL for the default context)
4284 * @fd: a #GPollFD structure holding information about a file
4285 * descriptor to watch.
4286 * @priority: the priority for this file descriptor which should be
4287 * the same as the priority used for g_source_attach() to ensure that the
4288 * file descriptor is polled whenever the results may be needed.
4290 * Adds a file descriptor to the set of file descriptors polled for
4291 * this context. This will very seldom be used directly. Instead
4292 * a typical event source will use g_source_add_unix_fd() instead.
4295 g_main_context_add_poll (GMainContext
*context
,
4300 context
= g_main_context_default ();
4302 g_return_if_fail (g_atomic_int_get (&context
->ref_count
) > 0);
4303 g_return_if_fail (fd
);
4305 LOCK_CONTEXT (context
);
4306 g_main_context_add_poll_unlocked (context
, priority
, fd
);
4307 UNLOCK_CONTEXT (context
);
4310 /* HOLDS: main_loop_lock */
4312 g_main_context_add_poll_unlocked (GMainContext
*context
,
4316 GPollRec
*prevrec
, *nextrec
;
4317 GPollRec
*newrec
= g_slice_new (GPollRec
);
4319 /* This file descriptor may be checked before we ever poll */
4322 newrec
->priority
= priority
;
4325 nextrec
= context
->poll_records
;
4328 if (nextrec
->fd
->fd
> fd
->fd
)
4331 nextrec
= nextrec
->next
;
4335 prevrec
->next
= newrec
;
4337 context
->poll_records
= newrec
;
4339 newrec
->prev
= prevrec
;
4340 newrec
->next
= nextrec
;
4343 nextrec
->prev
= newrec
;
4345 context
->n_poll_records
++;
4347 context
->poll_changed
= TRUE
;
4349 /* Now wake up the main loop if it is waiting in the poll() */
4350 g_wakeup_signal (context
->wakeup
);
4354 * g_main_context_remove_poll:
4355 * @context:a #GMainContext
4356 * @fd: a #GPollFD descriptor previously added with g_main_context_add_poll()
4358 * Removes file descriptor from the set of file descriptors to be
4359 * polled for a particular context.
4362 g_main_context_remove_poll (GMainContext
*context
,
4366 context
= g_main_context_default ();
4368 g_return_if_fail (g_atomic_int_get (&context
->ref_count
) > 0);
4369 g_return_if_fail (fd
);
4371 LOCK_CONTEXT (context
);
4372 g_main_context_remove_poll_unlocked (context
, fd
);
4373 UNLOCK_CONTEXT (context
);
4377 g_main_context_remove_poll_unlocked (GMainContext
*context
,
4380 GPollRec
*pollrec
, *prevrec
, *nextrec
;
4383 pollrec
= context
->poll_records
;
4387 nextrec
= pollrec
->next
;
4388 if (pollrec
->fd
== fd
)
4390 if (prevrec
!= NULL
)
4391 prevrec
->next
= nextrec
;
4393 context
->poll_records
= nextrec
;
4395 if (nextrec
!= NULL
)
4396 nextrec
->prev
= prevrec
;
4398 g_slice_free (GPollRec
, pollrec
);
4400 context
->n_poll_records
--;
4407 context
->poll_changed
= TRUE
;
4409 /* Now wake up the main loop if it is waiting in the poll() */
4410 g_wakeup_signal (context
->wakeup
);
4414 * g_source_get_current_time:
4415 * @source: a #GSource
4416 * @timeval: #GTimeVal structure in which to store current time.
4418 * This function ignores @source and is otherwise the same as
4419 * g_get_current_time().
4421 * Deprecated: 2.28: use g_source_get_time() instead
4424 g_source_get_current_time (GSource
*source
,
4427 g_get_current_time (timeval
);
4431 * g_source_get_time:
4432 * @source: a #GSource
4434 * Gets the time to be used when checking this source. The advantage of
4435 * calling this function over calling g_get_monotonic_time() directly is
4436 * that when checking multiple sources, GLib can cache a single value
4437 * instead of having to repeatedly get the system monotonic time.
4439 * The time here is the system monotonic time, if available, or some
4440 * other reasonable alternative otherwise. See g_get_monotonic_time().
4442 * Returns: the monotonic time in microseconds
4447 g_source_get_time (GSource
*source
)
4449 GMainContext
*context
;
4452 g_return_val_if_fail (source
->context
!= NULL
, 0);
4454 context
= source
->context
;
4456 LOCK_CONTEXT (context
);
4458 if (!context
->time_is_fresh
)
4460 context
->time
= g_get_monotonic_time ();
4461 context
->time_is_fresh
= TRUE
;
4464 result
= context
->time
;
4466 UNLOCK_CONTEXT (context
);
4472 * g_main_context_set_poll_func:
4473 * @context: a #GMainContext
4474 * @func: the function to call to poll all file descriptors
4476 * Sets the function to use to handle polling of file descriptors. It
4477 * will be used instead of the poll() system call
4478 * (or GLib's replacement function, which is used where
4479 * poll() isn't available).
4481 * This function could possibly be used to integrate the GLib event
4482 * loop with an external event loop.
4485 g_main_context_set_poll_func (GMainContext
*context
,
4489 context
= g_main_context_default ();
4491 g_return_if_fail (g_atomic_int_get (&context
->ref_count
) > 0);
4493 LOCK_CONTEXT (context
);
4496 context
->poll_func
= func
;
4498 context
->poll_func
= g_poll
;
4500 UNLOCK_CONTEXT (context
);
4504 * g_main_context_get_poll_func:
4505 * @context: a #GMainContext
4507 * Gets the poll function set by g_main_context_set_poll_func().
4509 * Returns: the poll function
4512 g_main_context_get_poll_func (GMainContext
*context
)
4517 context
= g_main_context_default ();
4519 g_return_val_if_fail (g_atomic_int_get (&context
->ref_count
) > 0, NULL
);
4521 LOCK_CONTEXT (context
);
4522 result
= context
->poll_func
;
4523 UNLOCK_CONTEXT (context
);
4529 * g_main_context_wakeup:
4530 * @context: a #GMainContext
4532 * If @context is currently blocking in g_main_context_iteration()
4533 * waiting for a source to become ready, cause it to stop blocking
4534 * and return. Otherwise, cause the next invocation of
4535 * g_main_context_iteration() to return without blocking.
4537 * This API is useful for low-level control over #GMainContext; for
4538 * example, integrating it with main loop implementations such as
4541 * Another related use for this function is when implementing a main
4542 * loop with a termination condition, computed from multiple threads:
4544 * |[<!-- language="C" -->
4545 * #define NUM_TASKS 10
4546 * static volatile gint tasks_remaining = NUM_TASKS;
4549 * while (g_atomic_int_get (&tasks_remaining) != 0)
4550 * g_main_context_iteration (NULL, TRUE);
4554 * |[<!-- language="C" -->
4557 * if (g_atomic_int_dec_and_test (&tasks_remaining))
4558 * g_main_context_wakeup (NULL);
4562 g_main_context_wakeup (GMainContext
*context
)
4565 context
= g_main_context_default ();
4567 g_return_if_fail (g_atomic_int_get (&context
->ref_count
) > 0);
4569 TRACE (GLIB_MAIN_CONTEXT_WAKEUP (context
));
4571 g_wakeup_signal (context
->wakeup
);
4575 * g_main_context_is_owner:
4576 * @context: a #GMainContext
4578 * Determines whether this thread holds the (recursive)
4579 * ownership of this #GMainContext. This is useful to
4580 * know before waiting on another thread that may be
4581 * blocking to get ownership of @context.
4583 * Returns: %TRUE if current thread is owner of @context.
4588 g_main_context_is_owner (GMainContext
*context
)
4593 context
= g_main_context_default ();
4595 LOCK_CONTEXT (context
);
4596 is_owner
= context
->owner
== G_THREAD_SELF
;
4597 UNLOCK_CONTEXT (context
);
4605 g_timeout_set_expiration (GTimeoutSource
*timeout_source
,
4606 gint64 current_time
)
4610 expiration
= current_time
+ (guint64
) timeout_source
->interval
* 1000;
4612 if (timeout_source
->seconds
)
4615 static gint timer_perturb
= -1;
4617 if (timer_perturb
== -1)
4620 * we want a per machine/session unique 'random' value; try the dbus
4621 * address first, that has a UUID in it. If there is no dbus, use the
4622 * hostname for hashing.
4624 const char *session_bus_address
= g_getenv ("DBUS_SESSION_BUS_ADDRESS");
4625 if (!session_bus_address
)
4626 session_bus_address
= g_getenv ("HOSTNAME");
4627 if (session_bus_address
)
4628 timer_perturb
= ABS ((gint
) g_str_hash (session_bus_address
)) % 1000000;
4633 /* We want the microseconds part of the timeout to land on the
4634 * 'timer_perturb' mark, but we need to make sure we don't try to
4635 * set the timeout in the past. We do this by ensuring that we
4636 * always only *increase* the expiration time by adding a full
4637 * second in the case that the microsecond portion decreases.
4639 expiration
-= timer_perturb
;
4641 remainder
= expiration
% 1000000;
4642 if (remainder
>= 1000000/4)
4643 expiration
+= 1000000;
4645 expiration
-= remainder
;
4646 expiration
+= timer_perturb
;
4649 g_source_set_ready_time ((GSource
*) timeout_source
, expiration
);
4653 g_timeout_dispatch (GSource
*source
,
4654 GSourceFunc callback
,
4657 GTimeoutSource
*timeout_source
= (GTimeoutSource
*)source
;
4662 g_warning ("Timeout source dispatched without callback. "
4663 "You must call g_source_set_callback().");
4667 again
= callback (user_data
);
4669 TRACE (GLIB_TIMEOUT_DISPATCH (source
, source
->context
, callback
, user_data
, again
));
4672 g_timeout_set_expiration (timeout_source
, g_source_get_time (source
));
4678 * g_timeout_source_new:
4679 * @interval: the timeout interval in milliseconds.
4681 * Creates a new timeout source.
4683 * The source will not initially be associated with any #GMainContext
4684 * and must be added to one with g_source_attach() before it will be
4687 * The interval given is in terms of monotonic time, not wall clock
4688 * time. See g_get_monotonic_time().
4690 * Returns: the newly-created timeout source
4693 g_timeout_source_new (guint interval
)
4695 GSource
*source
= g_source_new (&g_timeout_funcs
, sizeof (GTimeoutSource
));
4696 GTimeoutSource
*timeout_source
= (GTimeoutSource
*)source
;
4698 timeout_source
->interval
= interval
;
4699 g_timeout_set_expiration (timeout_source
, g_get_monotonic_time ());
4705 * g_timeout_source_new_seconds:
4706 * @interval: the timeout interval in seconds
4708 * Creates a new timeout source.
4710 * The source will not initially be associated with any #GMainContext
4711 * and must be added to one with g_source_attach() before it will be
4714 * The scheduling granularity/accuracy of this timeout source will be
4717 * The interval given is in terms of monotonic time, not wall clock time.
4718 * See g_get_monotonic_time().
4720 * Returns: the newly-created timeout source
4725 g_timeout_source_new_seconds (guint interval
)
4727 GSource
*source
= g_source_new (&g_timeout_funcs
, sizeof (GTimeoutSource
));
4728 GTimeoutSource
*timeout_source
= (GTimeoutSource
*)source
;
4730 timeout_source
->interval
= 1000 * interval
;
4731 timeout_source
->seconds
= TRUE
;
4733 g_timeout_set_expiration (timeout_source
, g_get_monotonic_time ());
4740 * g_timeout_add_full: (rename-to g_timeout_add)
4741 * @priority: the priority of the timeout source. Typically this will be in
4742 * the range between #G_PRIORITY_DEFAULT and #G_PRIORITY_HIGH.
4743 * @interval: the time between calls to the function, in milliseconds
4744 * (1/1000ths of a second)
4745 * @function: function to call
4746 * @data: data to pass to @function
4747 * @notify: (nullable): function to call when the timeout is removed, or %NULL
4749 * Sets a function to be called at regular intervals, with the given
4750 * priority. The function is called repeatedly until it returns
4751 * %FALSE, at which point the timeout is automatically destroyed and
4752 * the function will not be called again. The @notify function is
4753 * called when the timeout is destroyed. The first call to the
4754 * function will be at the end of the first @interval.
4756 * Note that timeout functions may be delayed, due to the processing of other
4757 * event sources. Thus they should not be relied on for precise timing.
4758 * After each call to the timeout function, the time of the next
4759 * timeout is recalculated based on the current time and the given interval
4760 * (it does not try to 'catch up' time lost in delays).
4762 * See [memory management of sources][mainloop-memory-management] for details
4763 * on how to handle the return value and memory management of @data.
4765 * This internally creates a main loop source using g_timeout_source_new()
4766 * and attaches it to the global #GMainContext using g_source_attach(), so
4767 * the callback will be invoked in whichever thread is running that main
4768 * context. You can do these steps manually if you need greater control or to
4769 * use a custom main context.
4771 * The interval given is in terms of monotonic time, not wall clock time.
4772 * See g_get_monotonic_time().
4774 * Returns: the ID (greater than 0) of the event source.
4777 g_timeout_add_full (gint priority
,
4779 GSourceFunc function
,
4781 GDestroyNotify notify
)
4786 g_return_val_if_fail (function
!= NULL
, 0);
4788 source
= g_timeout_source_new (interval
);
4790 if (priority
!= G_PRIORITY_DEFAULT
)
4791 g_source_set_priority (source
, priority
);
4793 g_source_set_callback (source
, function
, data
, notify
);
4794 id
= g_source_attach (source
, NULL
);
4796 TRACE (GLIB_TIMEOUT_ADD (source
, g_main_context_default (), id
, priority
, interval
, function
, data
));
4798 g_source_unref (source
);
4805 * @interval: the time between calls to the function, in milliseconds
4806 * (1/1000ths of a second)
4807 * @function: function to call
4808 * @data: data to pass to @function
4810 * Sets a function to be called at regular intervals, with the default
4811 * priority, #G_PRIORITY_DEFAULT. The function is called repeatedly
4812 * until it returns %FALSE, at which point the timeout is automatically
4813 * destroyed and the function will not be called again. The first call
4814 * to the function will be at the end of the first @interval.
4816 * Note that timeout functions may be delayed, due to the processing of other
4817 * event sources. Thus they should not be relied on for precise timing.
4818 * After each call to the timeout function, the time of the next
4819 * timeout is recalculated based on the current time and the given interval
4820 * (it does not try to 'catch up' time lost in delays).
4822 * See [memory management of sources][mainloop-memory-management] for details
4823 * on how to handle the return value and memory management of @data.
4825 * If you want to have a timer in the "seconds" range and do not care
4826 * about the exact time of the first call of the timer, use the
4827 * g_timeout_add_seconds() function; this function allows for more
4828 * optimizations and more efficient system power usage.
4830 * This internally creates a main loop source using g_timeout_source_new()
4831 * and attaches it to the global #GMainContext using g_source_attach(), so
4832 * the callback will be invoked in whichever thread is running that main
4833 * context. You can do these steps manually if you need greater control or to
4834 * use a custom main context.
4836 * The interval given is in terms of monotonic time, not wall clock
4837 * time. See g_get_monotonic_time().
4839 * Returns: the ID (greater than 0) of the event source.
4842 g_timeout_add (guint32 interval
,
4843 GSourceFunc function
,
4846 return g_timeout_add_full (G_PRIORITY_DEFAULT
,
4847 interval
, function
, data
, NULL
);
4851 * g_timeout_add_seconds_full: (rename-to g_timeout_add_seconds)
4852 * @priority: the priority of the timeout source. Typically this will be in
4853 * the range between #G_PRIORITY_DEFAULT and #G_PRIORITY_HIGH.
4854 * @interval: the time between calls to the function, in seconds
4855 * @function: function to call
4856 * @data: data to pass to @function
4857 * @notify: (nullable): function to call when the timeout is removed, or %NULL
4859 * Sets a function to be called at regular intervals, with @priority.
4860 * The function is called repeatedly until it returns %FALSE, at which
4861 * point the timeout is automatically destroyed and the function will
4862 * not be called again.
4864 * Unlike g_timeout_add(), this function operates at whole second granularity.
4865 * The initial starting point of the timer is determined by the implementation
4866 * and the implementation is expected to group multiple timers together so that
4867 * they fire all at the same time.
4868 * To allow this grouping, the @interval to the first timer is rounded
4869 * and can deviate up to one second from the specified interval.
4870 * Subsequent timer iterations will generally run at the specified interval.
4872 * Note that timeout functions may be delayed, due to the processing of other
4873 * event sources. Thus they should not be relied on for precise timing.
4874 * After each call to the timeout function, the time of the next
4875 * timeout is recalculated based on the current time and the given @interval
4877 * See [memory management of sources][mainloop-memory-management] for details
4878 * on how to handle the return value and memory management of @data.
4880 * If you want timing more precise than whole seconds, use g_timeout_add()
4883 * The grouping of timers to fire at the same time results in a more power
4884 * and CPU efficient behavior so if your timer is in multiples of seconds
4885 * and you don't require the first timer exactly one second from now, the
4886 * use of g_timeout_add_seconds() is preferred over g_timeout_add().
4888 * This internally creates a main loop source using
4889 * g_timeout_source_new_seconds() and attaches it to the main loop context
4890 * using g_source_attach(). You can do these steps manually if you need
4893 * The interval given is in terms of monotonic time, not wall clock
4894 * time. See g_get_monotonic_time().
4896 * Returns: the ID (greater than 0) of the event source.
4901 g_timeout_add_seconds_full (gint priority
,
4903 GSourceFunc function
,
4905 GDestroyNotify notify
)
4910 g_return_val_if_fail (function
!= NULL
, 0);
4912 source
= g_timeout_source_new_seconds (interval
);
4914 if (priority
!= G_PRIORITY_DEFAULT
)
4915 g_source_set_priority (source
, priority
);
4917 g_source_set_callback (source
, function
, data
, notify
);
4918 id
= g_source_attach (source
, NULL
);
4919 g_source_unref (source
);
4925 * g_timeout_add_seconds:
4926 * @interval: the time between calls to the function, in seconds
4927 * @function: function to call
4928 * @data: data to pass to @function
4930 * Sets a function to be called at regular intervals with the default
4931 * priority, #G_PRIORITY_DEFAULT. The function is called repeatedly until
4932 * it returns %FALSE, at which point the timeout is automatically destroyed
4933 * and the function will not be called again.
4935 * This internally creates a main loop source using
4936 * g_timeout_source_new_seconds() and attaches it to the main loop context
4937 * using g_source_attach(). You can do these steps manually if you need
4938 * greater control. Also see g_timeout_add_seconds_full().
4940 * Note that the first call of the timer may not be precise for timeouts
4941 * of one second. If you need finer precision and have such a timeout,
4942 * you may want to use g_timeout_add() instead.
4944 * See [memory management of sources][mainloop-memory-management] for details
4945 * on how to handle the return value and memory management of @data.
4947 * The interval given is in terms of monotonic time, not wall clock
4948 * time. See g_get_monotonic_time().
4950 * Returns: the ID (greater than 0) of the event source.
4955 g_timeout_add_seconds (guint interval
,
4956 GSourceFunc function
,
4959 g_return_val_if_fail (function
!= NULL
, 0);
4961 return g_timeout_add_seconds_full (G_PRIORITY_DEFAULT
, interval
, function
, data
, NULL
);
4964 /* Child watch functions */
4969 g_child_watch_prepare (GSource
*source
,
4977 g_child_watch_check (GSource
*source
)
4979 GChildWatchSource
*child_watch_source
;
4980 gboolean child_exited
;
4982 child_watch_source
= (GChildWatchSource
*) source
;
4984 child_exited
= child_watch_source
->poll
.revents
& G_IO_IN
;
4991 * Note: We do _not_ check for the special value of STILL_ACTIVE
4992 * since we know that the process has exited and doing so runs into
4993 * problems if the child process "happens to return STILL_ACTIVE(259)"
4994 * as Microsoft's Platform SDK puts it.
4996 if (!GetExitCodeProcess (child_watch_source
->pid
, &child_status
))
4998 gchar
*emsg
= g_win32_error_message (GetLastError ());
4999 g_warning (G_STRLOC
": GetExitCodeProcess() failed: %s", emsg
);
5002 child_watch_source
->child_status
= -1;
5005 child_watch_source
->child_status
= child_status
;
5008 return child_exited
;
5012 g_child_watch_finalize (GSource
*source
)
5016 #else /* G_OS_WIN32 */
5019 wake_source (GSource
*source
)
5021 GMainContext
*context
;
5023 /* This should be thread-safe:
5025 * - if the source is currently being added to a context, that
5026 * context will be woken up anyway
5028 * - if the source is currently being destroyed, we simply need not
5031 * - the memory for the source will remain valid until after the
5032 * source finalize function was called (which would remove the
5033 * source from the global list which we are currently holding the
5036 * - the GMainContext will either be NULL or point to a live
5039 * - the GMainContext will remain valid since we hold the
5040 * main_context_list lock
5042 * Since we are holding a lot of locks here, don't try to enter any
5043 * more GMainContext functions for fear of dealock -- just hit the
5044 * GWakeup and run. Even if that's safe now, it could easily become
5045 * unsafe with some very minor changes in the future, and signal
5046 * handling is not the most well-tested codepath.
5048 G_LOCK(main_context_list
);
5049 context
= source
->context
;
5051 g_wakeup_signal (context
->wakeup
);
5052 G_UNLOCK(main_context_list
);
5056 dispatch_unix_signals_unlocked (void)
5058 gboolean pending
[NSIG
];
5062 /* clear this first in case another one arrives while we're processing */
5063 any_unix_signal_pending
= FALSE
;
5065 /* We atomically test/clear the bit from the global array in case
5066 * other signals arrive while we are dispatching.
5068 * We then can safely use our own array below without worrying about
5071 for (i
= 0; i
< NSIG
; i
++)
5073 /* Be very careful with (the volatile) unix_signal_pending.
5075 * We must ensure that it's not possible that we clear it without
5076 * handling the signal. We therefore must ensure that our pending
5077 * array has a field set (ie: we will do something about the
5078 * signal) before we clear the item in unix_signal_pending.
5080 * Note specifically: we must check _our_ array.
5082 pending
[i
] = unix_signal_pending
[i
];
5084 unix_signal_pending
[i
] = FALSE
;
5087 /* handle GChildWatchSource instances */
5088 if (pending
[SIGCHLD
])
5090 /* The only way we can do this is to scan all of the children.
5092 * The docs promise that we will not reap children that we are not
5093 * explicitly watching, so that ties our hands from calling
5094 * waitpid(-1). We also can't use siginfo's si_pid field since if
5095 * multiple SIGCHLD arrive at the same time, one of them can be
5096 * dropped (since a given UNIX signal can only be pending once).
5098 for (node
= unix_child_watches
; node
; node
= node
->next
)
5100 GChildWatchSource
*source
= node
->data
;
5102 if (!source
->child_exited
)
5107 g_assert (source
->pid
> 0);
5109 pid
= waitpid (source
->pid
, &source
->child_status
, WNOHANG
);
5112 source
->child_exited
= TRUE
;
5113 wake_source ((GSource
*) source
);
5115 else if (pid
== -1 && errno
== ECHILD
)
5117 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.");
5118 source
->child_exited
= TRUE
;
5119 source
->child_status
= 0;
5120 wake_source ((GSource
*) source
);
5123 while (pid
== -1 && errno
== EINTR
);
5128 /* handle GUnixSignalWatchSource instances */
5129 for (node
= unix_signal_watches
; node
; node
= node
->next
)
5131 GUnixSignalWatchSource
*source
= node
->data
;
5133 if (!source
->pending
)
5135 if (pending
[source
->signum
])
5137 source
->pending
= TRUE
;
5139 wake_source ((GSource
*) source
);
5147 dispatch_unix_signals (void)
5149 G_LOCK(unix_signal_lock
);
5150 dispatch_unix_signals_unlocked ();
5151 G_UNLOCK(unix_signal_lock
);
5155 g_child_watch_prepare (GSource
*source
,
5158 GChildWatchSource
*child_watch_source
;
5160 child_watch_source
= (GChildWatchSource
*) source
;
5162 return child_watch_source
->child_exited
;
5166 g_child_watch_check (GSource
*source
)
5168 GChildWatchSource
*child_watch_source
;
5170 child_watch_source
= (GChildWatchSource
*) source
;
5172 return child_watch_source
->child_exited
;
5176 g_unix_signal_watch_prepare (GSource
*source
,
5179 GUnixSignalWatchSource
*unix_signal_source
;
5181 unix_signal_source
= (GUnixSignalWatchSource
*) source
;
5183 return unix_signal_source
->pending
;
5187 g_unix_signal_watch_check (GSource
*source
)
5189 GUnixSignalWatchSource
*unix_signal_source
;
5191 unix_signal_source
= (GUnixSignalWatchSource
*) source
;
5193 return unix_signal_source
->pending
;
5197 g_unix_signal_watch_dispatch (GSource
*source
,
5198 GSourceFunc callback
,
5201 GUnixSignalWatchSource
*unix_signal_source
;
5204 unix_signal_source
= (GUnixSignalWatchSource
*) source
;
5208 g_warning ("Unix signal source dispatched without callback. "
5209 "You must call g_source_set_callback().");
5213 again
= (callback
) (user_data
);
5215 unix_signal_source
->pending
= FALSE
;
5221 ref_unix_signal_handler_unlocked (int signum
)
5223 /* Ensure we have the worker context */
5224 g_get_worker_context ();
5225 unix_signal_refcount
[signum
]++;
5226 if (unix_signal_refcount
[signum
] == 1)
5228 struct sigaction action
;
5229 action
.sa_handler
= g_unix_signal_handler
;
5230 sigemptyset (&action
.sa_mask
);
5232 action
.sa_flags
= SA_RESTART
| SA_NOCLDSTOP
;
5234 action
.sa_flags
= SA_NOCLDSTOP
;
5236 sigaction (signum
, &action
, NULL
);
5241 unref_unix_signal_handler_unlocked (int signum
)
5243 unix_signal_refcount
[signum
]--;
5244 if (unix_signal_refcount
[signum
] == 0)
5246 struct sigaction action
;
5247 memset (&action
, 0, sizeof (action
));
5248 action
.sa_handler
= SIG_DFL
;
5249 sigemptyset (&action
.sa_mask
);
5250 sigaction (signum
, &action
, NULL
);
5254 /* Return a const string to avoid allocations. We lose precision in the case the
5255 * @signum is unrecognised, but that’ll do. */
5256 static const gchar
*
5257 signum_to_string (int signum
)
5259 /* See `man 0P signal.h` */
5262 return ("GUnixSignalSource: " #s);
5265 /* These signals are guaranteed to exist by POSIX. */
5272 /* Frustratingly, these are not, and hence for brevity the list is
5311 return "GUnixSignalSource: Unrecognized signal";
5317 _g_main_create_unix_signal_watch (int signum
)
5320 GUnixSignalWatchSource
*unix_signal_source
;
5322 source
= g_source_new (&g_unix_signal_funcs
, sizeof (GUnixSignalWatchSource
));
5323 unix_signal_source
= (GUnixSignalWatchSource
*) source
;
5325 unix_signal_source
->signum
= signum
;
5326 unix_signal_source
->pending
= FALSE
;
5328 /* Set a default name on the source, just in case the caller does not. */
5329 g_source_set_name (source
, signum_to_string (signum
));
5331 G_LOCK (unix_signal_lock
);
5332 ref_unix_signal_handler_unlocked (signum
);
5333 unix_signal_watches
= g_slist_prepend (unix_signal_watches
, unix_signal_source
);
5334 dispatch_unix_signals_unlocked ();
5335 G_UNLOCK (unix_signal_lock
);
5341 g_unix_signal_watch_finalize (GSource
*source
)
5343 GUnixSignalWatchSource
*unix_signal_source
;
5345 unix_signal_source
= (GUnixSignalWatchSource
*) source
;
5347 G_LOCK (unix_signal_lock
);
5348 unref_unix_signal_handler_unlocked (unix_signal_source
->signum
);
5349 unix_signal_watches
= g_slist_remove (unix_signal_watches
, source
);
5350 G_UNLOCK (unix_signal_lock
);
5354 g_child_watch_finalize (GSource
*source
)
5356 G_LOCK (unix_signal_lock
);
5357 unix_child_watches
= g_slist_remove (unix_child_watches
, source
);
5358 unref_unix_signal_handler_unlocked (SIGCHLD
);
5359 G_UNLOCK (unix_signal_lock
);
5362 #endif /* G_OS_WIN32 */
5365 g_child_watch_dispatch (GSource
*source
,
5366 GSourceFunc callback
,
5369 GChildWatchSource
*child_watch_source
;
5370 GChildWatchFunc child_watch_callback
= (GChildWatchFunc
) callback
;
5372 child_watch_source
= (GChildWatchSource
*) source
;
5376 g_warning ("Child watch source dispatched without callback. "
5377 "You must call g_source_set_callback().");
5381 (child_watch_callback
) (child_watch_source
->pid
, child_watch_source
->child_status
, user_data
);
5383 /* We never keep a child watch source around as the child is gone */
5390 g_unix_signal_handler (int signum
)
5392 gint saved_errno
= errno
;
5394 unix_signal_pending
[signum
] = TRUE
;
5395 any_unix_signal_pending
= TRUE
;
5397 g_wakeup_signal (glib_worker_context
->wakeup
);
5399 errno
= saved_errno
;
5402 #endif /* !G_OS_WIN32 */
5405 * g_child_watch_source_new:
5406 * @pid: process to watch. On POSIX the positive pid of a child process. On
5407 * Windows a handle for a process (which doesn't have to be a child).
5409 * Creates a new child_watch source.
5411 * The source will not initially be associated with any #GMainContext
5412 * and must be added to one with g_source_attach() before it will be
5415 * Note that child watch sources can only be used in conjunction with
5416 * `g_spawn...` when the %G_SPAWN_DO_NOT_REAP_CHILD flag is used.
5418 * Note that on platforms where #GPid must be explicitly closed
5419 * (see g_spawn_close_pid()) @pid must not be closed while the
5420 * source is still active. Typically, you will want to call
5421 * g_spawn_close_pid() in the callback function for the source.
5423 * On POSIX platforms, the following restrictions apply to this API
5424 * due to limitations in POSIX process interfaces:
5426 * * @pid must be a child of this process
5427 * * @pid must be positive
5428 * * the application must not call `waitpid` with a non-positive
5429 * first argument, for instance in another thread
5430 * * the application must not wait for @pid to exit by any other
5431 * mechanism, including `waitpid(pid, ...)` or a second child-watch
5432 * source for the same @pid
5433 * * the application must not ignore SIGCHILD
5435 * If any of those conditions are not met, this and related APIs will
5436 * not work correctly. This can often be diagnosed via a GLib warning
5437 * stating that `ECHILD` was received by `waitpid`.
5439 * Calling `waitpid` for specific processes other than @pid remains a
5440 * valid thing to do.
5442 * Returns: the newly-created child watch source
5447 g_child_watch_source_new (GPid pid
)
5450 GChildWatchSource
*child_watch_source
;
5453 g_return_val_if_fail (pid
> 0, NULL
);
5456 source
= g_source_new (&g_child_watch_funcs
, sizeof (GChildWatchSource
));
5457 child_watch_source
= (GChildWatchSource
*)source
;
5459 /* Set a default name on the source, just in case the caller does not. */
5460 g_source_set_name (source
, "GChildWatchSource");
5462 child_watch_source
->pid
= pid
;
5465 child_watch_source
->poll
.fd
= (gintptr
) pid
;
5466 child_watch_source
->poll
.events
= G_IO_IN
;
5468 g_source_add_poll (source
, &child_watch_source
->poll
);
5469 #else /* G_OS_WIN32 */
5470 G_LOCK (unix_signal_lock
);
5471 ref_unix_signal_handler_unlocked (SIGCHLD
);
5472 unix_child_watches
= g_slist_prepend (unix_child_watches
, child_watch_source
);
5473 if (waitpid (pid
, &child_watch_source
->child_status
, WNOHANG
) > 0)
5474 child_watch_source
->child_exited
= TRUE
;
5475 G_UNLOCK (unix_signal_lock
);
5476 #endif /* G_OS_WIN32 */
5482 * g_child_watch_add_full: (rename-to g_child_watch_add)
5483 * @priority: the priority of the idle source. Typically this will be in the
5484 * range between #G_PRIORITY_DEFAULT_IDLE and #G_PRIORITY_HIGH_IDLE.
5485 * @pid: process to watch. On POSIX the positive pid of a child process. On
5486 * Windows a handle for a process (which doesn't have to be a child).
5487 * @function: function to call
5488 * @data: data to pass to @function
5489 * @notify: (nullable): function to call when the idle is removed, or %NULL
5491 * Sets a function to be called when the child indicated by @pid
5492 * exits, at the priority @priority.
5494 * If you obtain @pid from g_spawn_async() or g_spawn_async_with_pipes()
5495 * you will need to pass #G_SPAWN_DO_NOT_REAP_CHILD as flag to
5496 * the spawn function for the child watching to work.
5498 * In many programs, you will want to call g_spawn_check_exit_status()
5499 * in the callback to determine whether or not the child exited
5502 * Also, note that on platforms where #GPid must be explicitly closed
5503 * (see g_spawn_close_pid()) @pid must not be closed while the source
5504 * is still active. Typically, you should invoke g_spawn_close_pid()
5505 * in the callback function for the source.
5507 * GLib supports only a single callback per process id.
5508 * On POSIX platforms, the same restrictions mentioned for
5509 * g_child_watch_source_new() apply to this function.
5511 * This internally creates a main loop source using
5512 * g_child_watch_source_new() and attaches it to the main loop context
5513 * using g_source_attach(). You can do these steps manually if you
5514 * need greater control.
5516 * Returns: the ID (greater than 0) of the event source.
5521 g_child_watch_add_full (gint priority
,
5523 GChildWatchFunc function
,
5525 GDestroyNotify notify
)
5530 g_return_val_if_fail (function
!= NULL
, 0);
5532 g_return_val_if_fail (pid
> 0, 0);
5535 source
= g_child_watch_source_new (pid
);
5537 if (priority
!= G_PRIORITY_DEFAULT
)
5538 g_source_set_priority (source
, priority
);
5540 g_source_set_callback (source
, (GSourceFunc
) function
, data
, notify
);
5541 id
= g_source_attach (source
, NULL
);
5542 g_source_unref (source
);
5548 * g_child_watch_add:
5549 * @pid: process id to watch. On POSIX the positive pid of a child
5550 * process. On Windows a handle for a process (which doesn't have to be
5552 * @function: function to call
5553 * @data: data to pass to @function
5555 * Sets a function to be called when the child indicated by @pid
5556 * exits, at a default priority, #G_PRIORITY_DEFAULT.
5558 * If you obtain @pid from g_spawn_async() or g_spawn_async_with_pipes()
5559 * you will need to pass #G_SPAWN_DO_NOT_REAP_CHILD as flag to
5560 * the spawn function for the child watching to work.
5562 * Note that on platforms where #GPid must be explicitly closed
5563 * (see g_spawn_close_pid()) @pid must not be closed while the
5564 * source is still active. Typically, you will want to call
5565 * g_spawn_close_pid() in the callback function for the source.
5567 * GLib supports only a single callback per process id.
5568 * On POSIX platforms, the same restrictions mentioned for
5569 * g_child_watch_source_new() apply to this function.
5571 * This internally creates a main loop source using
5572 * g_child_watch_source_new() and attaches it to the main loop context
5573 * using g_source_attach(). You can do these steps manually if you
5574 * need greater control.
5576 * Returns: the ID (greater than 0) of the event source.
5581 g_child_watch_add (GPid pid
,
5582 GChildWatchFunc function
,
5585 return g_child_watch_add_full (G_PRIORITY_DEFAULT
, pid
, function
, data
, NULL
);
5589 /* Idle functions */
5592 g_idle_prepare (GSource
*source
,
5601 g_idle_check (GSource
*source
)
5607 g_idle_dispatch (GSource
*source
,
5608 GSourceFunc callback
,
5615 g_warning ("Idle source dispatched without callback. "
5616 "You must call g_source_set_callback().");
5620 again
= callback (user_data
);
5622 TRACE (GLIB_IDLE_DISPATCH (source
, source
->context
, callback
, user_data
, again
));
5628 * g_idle_source_new:
5630 * Creates a new idle source.
5632 * The source will not initially be associated with any #GMainContext
5633 * and must be added to one with g_source_attach() before it will be
5634 * executed. Note that the default priority for idle sources is
5635 * %G_PRIORITY_DEFAULT_IDLE, as compared to other sources which
5636 * have a default priority of %G_PRIORITY_DEFAULT.
5638 * Returns: the newly-created idle source
5641 g_idle_source_new (void)
5645 source
= g_source_new (&g_idle_funcs
, sizeof (GSource
));
5646 g_source_set_priority (source
, G_PRIORITY_DEFAULT_IDLE
);
5648 /* Set a default name on the source, just in case the caller does not. */
5649 g_source_set_name (source
, "GIdleSource");
5655 * g_idle_add_full: (rename-to g_idle_add)
5656 * @priority: the priority of the idle source. Typically this will be in the
5657 * range between #G_PRIORITY_DEFAULT_IDLE and #G_PRIORITY_HIGH_IDLE.
5658 * @function: function to call
5659 * @data: data to pass to @function
5660 * @notify: (nullable): function to call when the idle is removed, or %NULL
5662 * Adds a function to be called whenever there are no higher priority
5663 * events pending. If the function returns %FALSE it is automatically
5664 * removed from the list of event sources and will not be called again.
5666 * See [memory management of sources][mainloop-memory-management] for details
5667 * on how to handle the return value and memory management of @data.
5669 * This internally creates a main loop source using g_idle_source_new()
5670 * and attaches it to the global #GMainContext using g_source_attach(), so
5671 * the callback will be invoked in whichever thread is running that main
5672 * context. You can do these steps manually if you need greater control or to
5673 * use a custom main context.
5675 * Returns: the ID (greater than 0) of the event source.
5678 g_idle_add_full (gint priority
,
5679 GSourceFunc function
,
5681 GDestroyNotify notify
)
5686 g_return_val_if_fail (function
!= NULL
, 0);
5688 source
= g_idle_source_new ();
5690 if (priority
!= G_PRIORITY_DEFAULT_IDLE
)
5691 g_source_set_priority (source
, priority
);
5693 g_source_set_callback (source
, function
, data
, notify
);
5694 id
= g_source_attach (source
, NULL
);
5696 TRACE (GLIB_IDLE_ADD (source
, g_main_context_default (), id
, priority
, function
, data
));
5698 g_source_unref (source
);
5705 * @function: function to call
5706 * @data: data to pass to @function.
5708 * Adds a function to be called whenever there are no higher priority
5709 * events pending to the default main loop. The function is given the
5710 * default idle priority, #G_PRIORITY_DEFAULT_IDLE. If the function
5711 * returns %FALSE it is automatically removed from the list of event
5712 * sources and will not be called again.
5714 * See [memory management of sources][mainloop-memory-management] for details
5715 * on how to handle the return value and memory management of @data.
5717 * This internally creates a main loop source using g_idle_source_new()
5718 * and attaches it to the global #GMainContext using g_source_attach(), so
5719 * the callback will be invoked in whichever thread is running that main
5720 * context. You can do these steps manually if you need greater control or to
5721 * use a custom main context.
5723 * Returns: the ID (greater than 0) of the event source.
5726 g_idle_add (GSourceFunc function
,
5729 return g_idle_add_full (G_PRIORITY_DEFAULT_IDLE
, function
, data
, NULL
);
5733 * g_idle_remove_by_data:
5734 * @data: the data for the idle source's callback.
5736 * Removes the idle function with the given data.
5738 * Returns: %TRUE if an idle source was found and removed.
5741 g_idle_remove_by_data (gpointer data
)
5743 return g_source_remove_by_funcs_user_data (&g_idle_funcs
, data
);
5747 * g_main_context_invoke:
5748 * @context: (nullable): a #GMainContext, or %NULL
5749 * @function: function to call
5750 * @data: data to pass to @function
5752 * Invokes a function in such a way that @context is owned during the
5753 * invocation of @function.
5755 * If @context is %NULL then the global default main context — as
5756 * returned by g_main_context_default() — is used.
5758 * If @context is owned by the current thread, @function is called
5759 * directly. Otherwise, if @context is the thread-default main context
5760 * of the current thread and g_main_context_acquire() succeeds, then
5761 * @function is called and g_main_context_release() is called
5764 * In any other case, an idle source is created to call @function and
5765 * that source is attached to @context (presumably to be run in another
5766 * thread). The idle source is attached with #G_PRIORITY_DEFAULT
5767 * priority. If you want a different priority, use
5768 * g_main_context_invoke_full().
5770 * Note that, as with normal idle functions, @function should probably
5771 * return %FALSE. If it returns %TRUE, it will be continuously run in a
5772 * loop (and may prevent this call from returning).
5777 g_main_context_invoke (GMainContext
*context
,
5778 GSourceFunc function
,
5781 g_main_context_invoke_full (context
,
5783 function
, data
, NULL
);
5787 * g_main_context_invoke_full:
5788 * @context: (nullable): a #GMainContext, or %NULL
5789 * @priority: the priority at which to run @function
5790 * @function: function to call
5791 * @data: data to pass to @function
5792 * @notify: (nullable): a function to call when @data is no longer in use, or %NULL.
5794 * Invokes a function in such a way that @context is owned during the
5795 * invocation of @function.
5797 * This function is the same as g_main_context_invoke() except that it
5798 * lets you specify the priority in case @function ends up being
5799 * scheduled as an idle and also lets you give a #GDestroyNotify for @data.
5801 * @notify should not assume that it is called from any particular
5802 * thread or with any particular context acquired.
5807 g_main_context_invoke_full (GMainContext
*context
,
5809 GSourceFunc function
,
5811 GDestroyNotify notify
)
5813 g_return_if_fail (function
!= NULL
);
5816 context
= g_main_context_default ();
5818 if (g_main_context_is_owner (context
))
5820 while (function (data
));
5827 GMainContext
*thread_default
;
5829 thread_default
= g_main_context_get_thread_default ();
5831 if (!thread_default
)
5832 thread_default
= g_main_context_default ();
5834 if (thread_default
== context
&& g_main_context_acquire (context
))
5836 while (function (data
));
5838 g_main_context_release (context
);
5847 source
= g_idle_source_new ();
5848 g_source_set_priority (source
, priority
);
5849 g_source_set_callback (source
, function
, data
, notify
);
5850 g_source_attach (source
, context
);
5851 g_source_unref (source
);
5857 glib_worker_main (gpointer data
)
5861 g_main_context_iteration (glib_worker_context
, TRUE
);
5864 if (any_unix_signal_pending
)
5865 dispatch_unix_signals ();
5869 return NULL
; /* worst GCC warning message ever... */
5873 g_get_worker_context (void)
5875 static gsize initialised
;
5877 if (g_once_init_enter (&initialised
))
5879 /* mask all signals in the worker thread */
5885 pthread_sigmask (SIG_SETMASK
, &all
, &prev_mask
);
5887 glib_worker_context
= g_main_context_new ();
5888 g_thread_new ("gmain", glib_worker_main
, NULL
);
5890 pthread_sigmask (SIG_SETMASK
, &prev_mask
, NULL
);
5892 g_once_init_leave (&initialised
, TRUE
);
5895 return glib_worker_context
;