1 /* GLIB - Library of useful routines for C programming
2 * Copyright (C) 1995-1997 Peter Mattis, Spencer Kimball and Josh MacDonald
4 * gmain.c: Main loop abstraction, timeouts, and idle functions
5 * Copyright 1998 Owen Taylor
7 * This library is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU Lesser General Public
9 * License as published by the Free Software Foundation; either
10 * version 2 of the License, or (at your option) any later version.
12 * This library is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 * Lesser General Public License for more details.
17 * You should have received a copy of the GNU Lesser General Public
18 * License along with this library; if not, 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
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
305 GDestroyNotify notify
;
310 GMainContext
*context
;
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 * Returns: the ID (greater than 0) for the source
1302 g_source_get_id (GSource
*source
)
1306 g_return_val_if_fail (source
!= NULL
, 0);
1307 g_return_val_if_fail (source
->context
!= NULL
, 0);
1309 LOCK_CONTEXT (source
->context
);
1310 result
= source
->source_id
;
1311 UNLOCK_CONTEXT (source
->context
);
1317 * g_source_get_context:
1318 * @source: a #GSource
1320 * Gets the #GMainContext with which the source is associated.
1322 * You can call this on a source that has been destroyed, provided
1323 * that the #GMainContext it was attached to still exists (in which
1324 * case it will return that #GMainContext). In particular, you can
1325 * always call this function on the source returned from
1326 * g_main_current_source(). But calling this function on a source
1327 * whose #GMainContext has been destroyed is an error.
1329 * Returns: (transfer none) (nullable): the #GMainContext with which the
1330 * source is associated, or %NULL if the context has not
1331 * yet been added to a source.
1334 g_source_get_context (GSource
*source
)
1336 g_return_val_if_fail (source
->context
!= NULL
|| !SOURCE_DESTROYED (source
), NULL
);
1338 return source
->context
;
1342 * g_source_add_poll:
1343 * @source:a #GSource
1344 * @fd: a #GPollFD structure holding information about a file
1345 * descriptor to watch.
1347 * Adds a file descriptor to the set of file descriptors polled for
1348 * this source. This is usually combined with g_source_new() to add an
1349 * event source. The event source's check function will typically test
1350 * the @revents field in the #GPollFD struct and return %TRUE if events need
1353 * This API is only intended to be used by implementations of #GSource.
1354 * Do not call this API on a #GSource that you did not create.
1356 * Using this API forces the linear scanning of event sources on each
1357 * main loop iteration. Newly-written event sources should try to use
1358 * g_source_add_unix_fd() instead of this API.
1361 g_source_add_poll (GSource
*source
,
1364 GMainContext
*context
;
1366 g_return_if_fail (source
!= NULL
);
1367 g_return_if_fail (fd
!= NULL
);
1368 g_return_if_fail (!SOURCE_DESTROYED (source
));
1370 context
= source
->context
;
1373 LOCK_CONTEXT (context
);
1375 source
->poll_fds
= g_slist_prepend (source
->poll_fds
, fd
);
1379 if (!SOURCE_BLOCKED (source
))
1380 g_main_context_add_poll_unlocked (context
, source
->priority
, fd
);
1381 UNLOCK_CONTEXT (context
);
1386 * g_source_remove_poll:
1387 * @source:a #GSource
1388 * @fd: a #GPollFD structure previously passed to g_source_add_poll().
1390 * Removes a file descriptor from the set of file descriptors polled for
1393 * This API is only intended to be used by implementations of #GSource.
1394 * Do not call this API on a #GSource that you did not create.
1397 g_source_remove_poll (GSource
*source
,
1400 GMainContext
*context
;
1402 g_return_if_fail (source
!= NULL
);
1403 g_return_if_fail (fd
!= NULL
);
1404 g_return_if_fail (!SOURCE_DESTROYED (source
));
1406 context
= source
->context
;
1409 LOCK_CONTEXT (context
);
1411 source
->poll_fds
= g_slist_remove (source
->poll_fds
, fd
);
1415 if (!SOURCE_BLOCKED (source
))
1416 g_main_context_remove_poll_unlocked (context
, fd
);
1417 UNLOCK_CONTEXT (context
);
1422 * g_source_add_child_source:
1423 * @source:a #GSource
1424 * @child_source: a second #GSource that @source should "poll"
1426 * Adds @child_source to @source as a "polled" source; when @source is
1427 * added to a #GMainContext, @child_source will be automatically added
1428 * with the same priority, when @child_source is triggered, it will
1429 * cause @source to dispatch (in addition to calling its own
1430 * callback), and when @source is destroyed, it will destroy
1431 * @child_source as well. (@source will also still be dispatched if
1432 * its own prepare/check functions indicate that it is ready.)
1434 * If you don't need @child_source to do anything on its own when it
1435 * triggers, you can call g_source_set_dummy_callback() on it to set a
1436 * callback that does nothing (except return %TRUE if appropriate).
1438 * @source will hold a reference on @child_source while @child_source
1439 * is attached to it.
1441 * This API is only intended to be used by implementations of #GSource.
1442 * Do not call this API on a #GSource that you did not create.
1447 g_source_add_child_source (GSource
*source
,
1448 GSource
*child_source
)
1450 GMainContext
*context
;
1452 g_return_if_fail (source
!= NULL
);
1453 g_return_if_fail (child_source
!= NULL
);
1454 g_return_if_fail (!SOURCE_DESTROYED (source
));
1455 g_return_if_fail (!SOURCE_DESTROYED (child_source
));
1456 g_return_if_fail (child_source
->context
== NULL
);
1457 g_return_if_fail (child_source
->priv
->parent_source
== NULL
);
1459 context
= source
->context
;
1462 LOCK_CONTEXT (context
);
1464 TRACE (GLIB_SOURCE_ADD_CHILD_SOURCE (source
, child_source
));
1466 source
->priv
->child_sources
= g_slist_prepend (source
->priv
->child_sources
,
1467 g_source_ref (child_source
));
1468 child_source
->priv
->parent_source
= source
;
1469 g_source_set_priority_unlocked (child_source
, NULL
, source
->priority
);
1470 if (SOURCE_BLOCKED (source
))
1471 block_source (child_source
);
1475 g_source_attach_unlocked (child_source
, context
, TRUE
);
1476 UNLOCK_CONTEXT (context
);
1481 g_child_source_remove_internal (GSource
*child_source
,
1482 GMainContext
*context
)
1484 GSource
*parent_source
= child_source
->priv
->parent_source
;
1486 parent_source
->priv
->child_sources
=
1487 g_slist_remove (parent_source
->priv
->child_sources
, child_source
);
1488 child_source
->priv
->parent_source
= NULL
;
1490 g_source_destroy_internal (child_source
, context
, TRUE
);
1491 g_source_unref_internal (child_source
, context
, TRUE
);
1495 * g_source_remove_child_source:
1496 * @source:a #GSource
1497 * @child_source: a #GSource previously passed to
1498 * g_source_add_child_source().
1500 * Detaches @child_source from @source and destroys it.
1502 * This API is only intended to be used by implementations of #GSource.
1503 * Do not call this API on a #GSource that you did not create.
1508 g_source_remove_child_source (GSource
*source
,
1509 GSource
*child_source
)
1511 GMainContext
*context
;
1513 g_return_if_fail (source
!= NULL
);
1514 g_return_if_fail (child_source
!= NULL
);
1515 g_return_if_fail (child_source
->priv
->parent_source
== source
);
1516 g_return_if_fail (!SOURCE_DESTROYED (source
));
1517 g_return_if_fail (!SOURCE_DESTROYED (child_source
));
1519 context
= source
->context
;
1522 LOCK_CONTEXT (context
);
1524 g_child_source_remove_internal (child_source
, context
);
1527 UNLOCK_CONTEXT (context
);
1531 g_source_callback_ref (gpointer cb_data
)
1533 GSourceCallback
*callback
= cb_data
;
1535 callback
->ref_count
++;
1539 g_source_callback_unref (gpointer cb_data
)
1541 GSourceCallback
*callback
= cb_data
;
1543 callback
->ref_count
--;
1544 if (callback
->ref_count
== 0)
1546 if (callback
->notify
)
1547 callback
->notify (callback
->data
);
1553 g_source_callback_get (gpointer cb_data
,
1558 GSourceCallback
*callback
= cb_data
;
1560 *func
= callback
->func
;
1561 *data
= callback
->data
;
1564 static GSourceCallbackFuncs g_source_callback_funcs
= {
1565 g_source_callback_ref
,
1566 g_source_callback_unref
,
1567 g_source_callback_get
,
1571 * g_source_set_callback_indirect:
1572 * @source: the source
1573 * @callback_data: pointer to callback data "object"
1574 * @callback_funcs: functions for reference counting @callback_data
1575 * and getting the callback and data
1577 * Sets the callback function storing the data as a refcounted callback
1578 * "object". This is used internally. Note that calling
1579 * g_source_set_callback_indirect() assumes
1580 * an initial reference count on @callback_data, and thus
1581 * @callback_funcs->unref will eventually be called once more
1582 * than @callback_funcs->ref.
1585 g_source_set_callback_indirect (GSource
*source
,
1586 gpointer callback_data
,
1587 GSourceCallbackFuncs
*callback_funcs
)
1589 GMainContext
*context
;
1590 gpointer old_cb_data
;
1591 GSourceCallbackFuncs
*old_cb_funcs
;
1593 g_return_if_fail (source
!= NULL
);
1594 g_return_if_fail (callback_funcs
!= NULL
|| callback_data
== NULL
);
1596 context
= source
->context
;
1599 LOCK_CONTEXT (context
);
1601 if (callback_funcs
!= &g_source_callback_funcs
)
1602 TRACE (GLIB_SOURCE_SET_CALLBACK_INDIRECT (source
, callback_data
,
1603 callback_funcs
->ref
,
1604 callback_funcs
->unref
,
1605 callback_funcs
->get
));
1607 old_cb_data
= source
->callback_data
;
1608 old_cb_funcs
= source
->callback_funcs
;
1610 source
->callback_data
= callback_data
;
1611 source
->callback_funcs
= callback_funcs
;
1614 UNLOCK_CONTEXT (context
);
1617 old_cb_funcs
->unref (old_cb_data
);
1621 * g_source_set_callback:
1622 * @source: the source
1623 * @func: a callback function
1624 * @data: the data to pass to callback function
1625 * @notify: (nullable): a function to call when @data is no longer in use, or %NULL.
1627 * Sets the callback function for a source. The callback for a source is
1628 * called from the source's dispatch function.
1630 * The exact type of @func depends on the type of source; ie. you
1631 * should not count on @func being called with @data as its first
1634 * See [memory management of sources][mainloop-memory-management] for details
1635 * on how to handle memory management of @data.
1637 * Typically, you won't use this function. Instead use functions specific
1638 * to the type of source you are using.
1641 g_source_set_callback (GSource
*source
,
1644 GDestroyNotify notify
)
1646 GSourceCallback
*new_callback
;
1648 g_return_if_fail (source
!= NULL
);
1650 TRACE (GLIB_SOURCE_SET_CALLBACK (source
, func
, data
, notify
));
1652 new_callback
= g_new (GSourceCallback
, 1);
1654 new_callback
->ref_count
= 1;
1655 new_callback
->func
= func
;
1656 new_callback
->data
= data
;
1657 new_callback
->notify
= notify
;
1659 g_source_set_callback_indirect (source
, new_callback
, &g_source_callback_funcs
);
1664 * g_source_set_funcs:
1665 * @source: a #GSource
1666 * @funcs: the new #GSourceFuncs
1668 * Sets the source functions (can be used to override
1669 * default implementations) of an unattached source.
1674 g_source_set_funcs (GSource
*source
,
1675 GSourceFuncs
*funcs
)
1677 g_return_if_fail (source
!= NULL
);
1678 g_return_if_fail (source
->context
== NULL
);
1679 g_return_if_fail (source
->ref_count
> 0);
1680 g_return_if_fail (funcs
!= NULL
);
1682 source
->source_funcs
= funcs
;
1686 g_source_set_priority_unlocked (GSource
*source
,
1687 GMainContext
*context
,
1692 g_return_if_fail (source
->priv
->parent_source
== NULL
||
1693 source
->priv
->parent_source
->priority
== priority
);
1695 TRACE (GLIB_SOURCE_SET_PRIORITY (source
, context
, priority
));
1699 /* Remove the source from the context's source and then
1700 * add it back after so it is sorted in the correct place
1702 source_remove_from_context (source
, source
->context
);
1705 source
->priority
= priority
;
1709 source_add_to_context (source
, source
->context
);
1711 if (!SOURCE_BLOCKED (source
))
1713 tmp_list
= source
->poll_fds
;
1716 g_main_context_remove_poll_unlocked (context
, tmp_list
->data
);
1717 g_main_context_add_poll_unlocked (context
, priority
, tmp_list
->data
);
1719 tmp_list
= tmp_list
->next
;
1722 for (tmp_list
= source
->priv
->fds
; tmp_list
; tmp_list
= tmp_list
->next
)
1724 g_main_context_remove_poll_unlocked (context
, tmp_list
->data
);
1725 g_main_context_add_poll_unlocked (context
, priority
, tmp_list
->data
);
1730 if (source
->priv
->child_sources
)
1732 tmp_list
= source
->priv
->child_sources
;
1735 g_source_set_priority_unlocked (tmp_list
->data
, context
, priority
);
1736 tmp_list
= tmp_list
->next
;
1742 * g_source_set_priority:
1743 * @source: a #GSource
1744 * @priority: the new priority.
1746 * Sets the priority of a source. While the main loop is being run, a
1747 * source will be dispatched if it is ready to be dispatched and no
1748 * sources at a higher (numerically smaller) priority are ready to be
1751 * A child source always has the same priority as its parent. It is not
1752 * permitted to change the priority of a source once it has been added
1753 * as a child of another source.
1756 g_source_set_priority (GSource
*source
,
1759 GMainContext
*context
;
1761 g_return_if_fail (source
!= NULL
);
1762 g_return_if_fail (source
->priv
->parent_source
== NULL
);
1764 context
= source
->context
;
1767 LOCK_CONTEXT (context
);
1768 g_source_set_priority_unlocked (source
, context
, priority
);
1770 UNLOCK_CONTEXT (source
->context
);
1774 * g_source_get_priority:
1775 * @source: a #GSource
1777 * Gets the priority of a source.
1779 * Returns: the priority of the source
1782 g_source_get_priority (GSource
*source
)
1784 g_return_val_if_fail (source
!= NULL
, 0);
1786 return source
->priority
;
1790 * g_source_set_ready_time:
1791 * @source: a #GSource
1792 * @ready_time: the monotonic time at which the source will be ready,
1793 * 0 for "immediately", -1 for "never"
1795 * Sets a #GSource to be dispatched when the given monotonic time is
1796 * reached (or passed). If the monotonic time is in the past (as it
1797 * always will be if @ready_time is 0) then the source will be
1798 * dispatched immediately.
1800 * If @ready_time is -1 then the source is never woken up on the basis
1801 * of the passage of time.
1803 * Dispatching the source does not reset the ready time. You should do
1804 * so yourself, from the source dispatch function.
1806 * Note that if you have a pair of sources where the ready time of one
1807 * suggests that it will be delivered first but the priority for the
1808 * other suggests that it would be delivered first, and the ready time
1809 * for both sources is reached during the same main context iteration
1810 * then the order of dispatch is undefined.
1812 * This API is only intended to be used by implementations of #GSource.
1813 * Do not call this API on a #GSource that you did not create.
1818 g_source_set_ready_time (GSource
*source
,
1821 GMainContext
*context
;
1823 g_return_if_fail (source
!= NULL
);
1824 g_return_if_fail (source
->ref_count
> 0);
1826 if (source
->priv
->ready_time
== ready_time
)
1829 context
= source
->context
;
1832 LOCK_CONTEXT (context
);
1834 source
->priv
->ready_time
= ready_time
;
1836 TRACE (GLIB_SOURCE_SET_READY_TIME (source
, ready_time
));
1840 /* Quite likely that we need to change the timeout on the poll */
1841 if (!SOURCE_BLOCKED (source
))
1842 if (context
->owner
&& context
->owner
!= G_THREAD_SELF
)
1843 g_wakeup_signal (context
->wakeup
);
1844 UNLOCK_CONTEXT (context
);
1849 * g_source_get_ready_time:
1850 * @source: a #GSource
1852 * Gets the "ready time" of @source, as set by
1853 * g_source_set_ready_time().
1855 * Any time before the current monotonic time (including 0) is an
1856 * indication that the source will fire immediately.
1858 * Returns: the monotonic ready time, -1 for "never"
1861 g_source_get_ready_time (GSource
*source
)
1863 g_return_val_if_fail (source
!= NULL
, -1);
1865 return source
->priv
->ready_time
;
1869 * g_source_set_can_recurse:
1870 * @source: a #GSource
1871 * @can_recurse: whether recursion is allowed for this source
1873 * Sets whether a source can be called recursively. If @can_recurse is
1874 * %TRUE, then while the source is being dispatched then this source
1875 * will be processed normally. Otherwise, all processing of this
1876 * source is blocked until the dispatch function returns.
1879 g_source_set_can_recurse (GSource
*source
,
1880 gboolean can_recurse
)
1882 GMainContext
*context
;
1884 g_return_if_fail (source
!= NULL
);
1886 context
= source
->context
;
1889 LOCK_CONTEXT (context
);
1892 source
->flags
|= G_SOURCE_CAN_RECURSE
;
1894 source
->flags
&= ~G_SOURCE_CAN_RECURSE
;
1897 UNLOCK_CONTEXT (context
);
1901 * g_source_get_can_recurse:
1902 * @source: a #GSource
1904 * Checks whether a source is allowed to be called recursively.
1905 * see g_source_set_can_recurse().
1907 * Returns: whether recursion is allowed.
1910 g_source_get_can_recurse (GSource
*source
)
1912 g_return_val_if_fail (source
!= NULL
, FALSE
);
1914 return (source
->flags
& G_SOURCE_CAN_RECURSE
) != 0;
1919 * g_source_set_name:
1920 * @source: a #GSource
1921 * @name: debug name for the source
1923 * Sets a name for the source, used in debugging and profiling.
1924 * The name defaults to #NULL.
1926 * The source name should describe in a human-readable way
1927 * what the source does. For example, "X11 event queue"
1928 * or "GTK+ repaint idle handler" or whatever it is.
1930 * It is permitted to call this function multiple times, but is not
1931 * recommended due to the potential performance impact. For example,
1932 * one could change the name in the "check" function of a #GSourceFuncs
1933 * to include details like the event type in the source name.
1935 * Use caution if changing the name while another thread may be
1936 * accessing it with g_source_get_name(); that function does not copy
1937 * the value, and changing the value will free it while the other thread
1938 * may be attempting to use it.
1943 g_source_set_name (GSource
*source
,
1946 GMainContext
*context
;
1948 g_return_if_fail (source
!= NULL
);
1950 context
= source
->context
;
1953 LOCK_CONTEXT (context
);
1955 TRACE (GLIB_SOURCE_SET_NAME (source
, name
));
1957 /* setting back to NULL is allowed, just because it's
1958 * weird if get_name can return NULL but you can't
1962 g_free (source
->name
);
1963 source
->name
= g_strdup (name
);
1966 UNLOCK_CONTEXT (context
);
1970 * g_source_get_name:
1971 * @source: a #GSource
1973 * Gets a name for the source, used in debugging and profiling. The
1974 * name may be #NULL if it has never been set with g_source_set_name().
1976 * Returns: the name of the source
1981 g_source_get_name (GSource
*source
)
1983 g_return_val_if_fail (source
!= NULL
, NULL
);
1985 return source
->name
;
1989 * g_source_set_name_by_id:
1990 * @tag: a #GSource ID
1991 * @name: debug name for the source
1993 * Sets the name of a source using its ID.
1995 * This is a convenience utility to set source names from the return
1996 * value of g_idle_add(), g_timeout_add(), etc.
1998 * It is a programmer error to attempt to set the name of a non-existent
2001 * More specifically: source IDs can be reissued after a source has been
2002 * destroyed and therefore it is never valid to use this function with a
2003 * source ID which may have already been removed. An example is when
2004 * scheduling an idle to run in another thread with g_idle_add(): the
2005 * idle may already have run and been removed by the time this function
2006 * is called on its (now invalid) source ID. This source ID may have
2007 * been reissued, leading to the operation being performed against the
2013 g_source_set_name_by_id (guint tag
,
2018 g_return_if_fail (tag
> 0);
2020 source
= g_main_context_find_source_by_id (NULL
, tag
);
2024 g_source_set_name (source
, name
);
2030 * @source: a #GSource
2032 * Increases the reference count on a source by one.
2037 g_source_ref (GSource
*source
)
2039 GMainContext
*context
;
2041 g_return_val_if_fail (source
!= NULL
, NULL
);
2043 context
= source
->context
;
2046 LOCK_CONTEXT (context
);
2048 source
->ref_count
++;
2051 UNLOCK_CONTEXT (context
);
2056 /* g_source_unref() but possible to call within context lock
2059 g_source_unref_internal (GSource
*source
,
2060 GMainContext
*context
,
2063 gpointer old_cb_data
= NULL
;
2064 GSourceCallbackFuncs
*old_cb_funcs
= NULL
;
2066 g_return_if_fail (source
!= NULL
);
2068 if (!have_lock
&& context
)
2069 LOCK_CONTEXT (context
);
2071 source
->ref_count
--;
2072 if (source
->ref_count
== 0)
2074 TRACE (GLIB_SOURCE_BEFORE_FREE (source
, context
,
2075 source
->source_funcs
->finalize
));
2077 old_cb_data
= source
->callback_data
;
2078 old_cb_funcs
= source
->callback_funcs
;
2080 source
->callback_data
= NULL
;
2081 source
->callback_funcs
= NULL
;
2085 if (!SOURCE_DESTROYED (source
))
2086 g_warning (G_STRLOC
": ref_count == 0, but source was still attached to a context!");
2087 source_remove_from_context (source
, context
);
2089 g_hash_table_remove (context
->sources
, GUINT_TO_POINTER (source
->source_id
));
2092 if (source
->source_funcs
->finalize
)
2095 UNLOCK_CONTEXT (context
);
2096 source
->source_funcs
->finalize (source
);
2098 LOCK_CONTEXT (context
);
2101 g_free (source
->name
);
2102 source
->name
= NULL
;
2104 g_slist_free (source
->poll_fds
);
2105 source
->poll_fds
= NULL
;
2107 g_slist_free_full (source
->priv
->fds
, g_free
);
2109 while (source
->priv
->child_sources
)
2111 GSource
*child_source
= source
->priv
->child_sources
->data
;
2113 source
->priv
->child_sources
=
2114 g_slist_remove (source
->priv
->child_sources
, child_source
);
2115 child_source
->priv
->parent_source
= NULL
;
2117 g_source_unref_internal (child_source
, context
, have_lock
);
2120 g_slice_free (GSourcePrivate
, source
->priv
);
2121 source
->priv
= NULL
;
2126 if (!have_lock
&& context
)
2127 UNLOCK_CONTEXT (context
);
2132 UNLOCK_CONTEXT (context
);
2134 old_cb_funcs
->unref (old_cb_data
);
2137 LOCK_CONTEXT (context
);
2143 * @source: a #GSource
2145 * Decreases the reference count of a source by one. If the
2146 * resulting reference count is zero the source and associated
2147 * memory will be destroyed.
2150 g_source_unref (GSource
*source
)
2152 g_return_if_fail (source
!= NULL
);
2154 g_source_unref_internal (source
, source
->context
, FALSE
);
2158 * g_main_context_find_source_by_id:
2159 * @context: (nullable): a #GMainContext (if %NULL, the default context will be used)
2160 * @source_id: the source ID, as returned by g_source_get_id().
2162 * Finds a #GSource given a pair of context and ID.
2164 * It is a programmer error to attempt to lookup a non-existent source.
2166 * More specifically: source IDs can be reissued after a source has been
2167 * destroyed and therefore it is never valid to use this function with a
2168 * source ID which may have already been removed. An example is when
2169 * scheduling an idle to run in another thread with g_idle_add(): the
2170 * idle may already have run and been removed by the time this function
2171 * is called on its (now invalid) source ID. This source ID may have
2172 * been reissued, leading to the operation being performed against the
2175 * Returns: (transfer none): the #GSource
2178 g_main_context_find_source_by_id (GMainContext
*context
,
2183 g_return_val_if_fail (source_id
> 0, NULL
);
2185 if (context
== NULL
)
2186 context
= g_main_context_default ();
2188 LOCK_CONTEXT (context
);
2189 source
= g_hash_table_lookup (context
->sources
, GUINT_TO_POINTER (source_id
));
2190 UNLOCK_CONTEXT (context
);
2192 if (source
&& SOURCE_DESTROYED (source
))
2199 * g_main_context_find_source_by_funcs_user_data:
2200 * @context: (nullable): a #GMainContext (if %NULL, the default context will be used).
2201 * @funcs: the @source_funcs passed to g_source_new().
2202 * @user_data: the user data from the callback.
2204 * Finds a source with the given source functions and user data. If
2205 * multiple sources exist with the same source function and user data,
2206 * the first one found will be returned.
2208 * Returns: (transfer none): the source, if one was found, otherwise %NULL
2211 g_main_context_find_source_by_funcs_user_data (GMainContext
*context
,
2212 GSourceFuncs
*funcs
,
2218 g_return_val_if_fail (funcs
!= NULL
, NULL
);
2220 if (context
== NULL
)
2221 context
= g_main_context_default ();
2223 LOCK_CONTEXT (context
);
2225 g_source_iter_init (&iter
, context
, FALSE
);
2226 while (g_source_iter_next (&iter
, &source
))
2228 if (!SOURCE_DESTROYED (source
) &&
2229 source
->source_funcs
== funcs
&&
2230 source
->callback_funcs
)
2232 GSourceFunc callback
;
2233 gpointer callback_data
;
2235 source
->callback_funcs
->get (source
->callback_data
, source
, &callback
, &callback_data
);
2237 if (callback_data
== user_data
)
2241 g_source_iter_clear (&iter
);
2243 UNLOCK_CONTEXT (context
);
2249 * g_main_context_find_source_by_user_data:
2250 * @context: a #GMainContext
2251 * @user_data: the user_data for the callback.
2253 * Finds a source with the given user data for the callback. If
2254 * multiple sources exist with the same user data, the first
2255 * one found will be returned.
2257 * Returns: (transfer none): the source, if one was found, otherwise %NULL
2260 g_main_context_find_source_by_user_data (GMainContext
*context
,
2266 if (context
== NULL
)
2267 context
= g_main_context_default ();
2269 LOCK_CONTEXT (context
);
2271 g_source_iter_init (&iter
, context
, FALSE
);
2272 while (g_source_iter_next (&iter
, &source
))
2274 if (!SOURCE_DESTROYED (source
) &&
2275 source
->callback_funcs
)
2277 GSourceFunc callback
;
2278 gpointer callback_data
= NULL
;
2280 source
->callback_funcs
->get (source
->callback_data
, source
, &callback
, &callback_data
);
2282 if (callback_data
== user_data
)
2286 g_source_iter_clear (&iter
);
2288 UNLOCK_CONTEXT (context
);
2295 * @tag: the ID of the source to remove.
2297 * Removes the source with the given id from the default main context.
2299 * The id of a #GSource is given by g_source_get_id(), or will be
2300 * returned by the functions g_source_attach(), g_idle_add(),
2301 * g_idle_add_full(), g_timeout_add(), g_timeout_add_full(),
2302 * g_child_watch_add(), g_child_watch_add_full(), g_io_add_watch(), and
2303 * g_io_add_watch_full().
2305 * See also g_source_destroy(). You must use g_source_destroy() for sources
2306 * added to a non-default main context.
2308 * It is a programmer error to attempt to remove a non-existent source.
2310 * More specifically: source IDs can be reissued after a source has been
2311 * destroyed and therefore it is never valid to use this function with a
2312 * source ID which may have already been removed. An example is when
2313 * scheduling an idle to run in another thread with g_idle_add(): the
2314 * idle may already have run and been removed by the time this function
2315 * is called on its (now invalid) source ID. This source ID may have
2316 * been reissued, leading to the operation being performed against the
2319 * Returns: For historical reasons, this function always returns %TRUE
2322 g_source_remove (guint tag
)
2326 g_return_val_if_fail (tag
> 0, FALSE
);
2328 source
= g_main_context_find_source_by_id (NULL
, tag
);
2330 g_source_destroy (source
);
2332 g_critical ("Source ID %u was not found when attempting to remove it", tag
);
2334 return source
!= NULL
;
2338 * g_source_remove_by_user_data:
2339 * @user_data: the user_data for the callback.
2341 * Removes a source from the default main loop context given the user
2342 * data for the callback. If multiple sources exist with the same user
2343 * data, only one will be destroyed.
2345 * Returns: %TRUE if a source was found and removed.
2348 g_source_remove_by_user_data (gpointer user_data
)
2352 source
= g_main_context_find_source_by_user_data (NULL
, user_data
);
2355 g_source_destroy (source
);
2363 * g_source_remove_by_funcs_user_data:
2364 * @funcs: The @source_funcs passed to g_source_new()
2365 * @user_data: the user data for the callback
2367 * Removes a source from the default main loop context given the
2368 * source functions and user data. If multiple sources exist with the
2369 * same source functions and user data, only one will be destroyed.
2371 * Returns: %TRUE if a source was found and removed.
2374 g_source_remove_by_funcs_user_data (GSourceFuncs
*funcs
,
2379 g_return_val_if_fail (funcs
!= NULL
, FALSE
);
2381 source
= g_main_context_find_source_by_funcs_user_data (NULL
, funcs
, user_data
);
2384 g_source_destroy (source
);
2393 * g_source_add_unix_fd:
2394 * @source: a #GSource
2395 * @fd: the fd to monitor
2396 * @events: an event mask
2398 * Monitors @fd for the IO events in @events.
2400 * The tag returned by this function can be used to remove or modify the
2401 * monitoring of the fd using g_source_remove_unix_fd() or
2402 * g_source_modify_unix_fd().
2404 * It is not necessary to remove the fd before destroying the source; it
2405 * will be cleaned up automatically.
2407 * This API is only intended to be used by implementations of #GSource.
2408 * Do not call this API on a #GSource that you did not create.
2410 * As the name suggests, this function is not available on Windows.
2412 * Returns: (not nullable): an opaque tag
2417 g_source_add_unix_fd (GSource
*source
,
2419 GIOCondition events
)
2421 GMainContext
*context
;
2424 g_return_val_if_fail (source
!= NULL
, NULL
);
2425 g_return_val_if_fail (!SOURCE_DESTROYED (source
), NULL
);
2427 poll_fd
= g_new (GPollFD
, 1);
2429 poll_fd
->events
= events
;
2430 poll_fd
->revents
= 0;
2432 context
= source
->context
;
2435 LOCK_CONTEXT (context
);
2437 source
->priv
->fds
= g_slist_prepend (source
->priv
->fds
, poll_fd
);
2441 if (!SOURCE_BLOCKED (source
))
2442 g_main_context_add_poll_unlocked (context
, source
->priority
, poll_fd
);
2443 UNLOCK_CONTEXT (context
);
2450 * g_source_modify_unix_fd:
2451 * @source: a #GSource
2452 * @tag: (not nullable): the tag from g_source_add_unix_fd()
2453 * @new_events: the new event mask to watch
2455 * Updates the event mask to watch for the fd identified by @tag.
2457 * @tag is the tag returned from g_source_add_unix_fd().
2459 * If you want to remove a fd, don't set its event mask to zero.
2460 * Instead, call g_source_remove_unix_fd().
2462 * This API is only intended to be used by implementations of #GSource.
2463 * Do not call this API on a #GSource that you did not create.
2465 * As the name suggests, this function is not available on Windows.
2470 g_source_modify_unix_fd (GSource
*source
,
2472 GIOCondition new_events
)
2474 GMainContext
*context
;
2477 g_return_if_fail (source
!= NULL
);
2478 g_return_if_fail (g_slist_find (source
->priv
->fds
, tag
));
2480 context
= source
->context
;
2483 poll_fd
->events
= new_events
;
2486 g_main_context_wakeup (context
);
2490 * g_source_remove_unix_fd:
2491 * @source: a #GSource
2492 * @tag: (not nullable): the tag from g_source_add_unix_fd()
2494 * Reverses the effect of a previous call to g_source_add_unix_fd().
2496 * You only need to call this if you want to remove an fd from being
2497 * watched while keeping the same source around. In the normal case you
2498 * will just want to destroy the source.
2500 * This API is only intended to be used by implementations of #GSource.
2501 * Do not call this API on a #GSource that you did not create.
2503 * As the name suggests, this function is not available on Windows.
2508 g_source_remove_unix_fd (GSource
*source
,
2511 GMainContext
*context
;
2514 g_return_if_fail (source
!= NULL
);
2515 g_return_if_fail (g_slist_find (source
->priv
->fds
, tag
));
2517 context
= source
->context
;
2521 LOCK_CONTEXT (context
);
2523 source
->priv
->fds
= g_slist_remove (source
->priv
->fds
, poll_fd
);
2527 if (!SOURCE_BLOCKED (source
))
2528 g_main_context_remove_poll_unlocked (context
, poll_fd
);
2530 UNLOCK_CONTEXT (context
);
2537 * g_source_query_unix_fd:
2538 * @source: a #GSource
2539 * @tag: (not nullable): the tag from g_source_add_unix_fd()
2541 * Queries the events reported for the fd corresponding to @tag on
2542 * @source during the last poll.
2544 * The return value of this function is only defined when the function
2545 * is called from the check or dispatch functions for @source.
2547 * This API is only intended to be used by implementations of #GSource.
2548 * Do not call this API on a #GSource that you did not create.
2550 * As the name suggests, this function is not available on Windows.
2552 * Returns: the conditions reported on the fd
2557 g_source_query_unix_fd (GSource
*source
,
2562 g_return_val_if_fail (source
!= NULL
, 0);
2563 g_return_val_if_fail (g_slist_find (source
->priv
->fds
, tag
), 0);
2567 return poll_fd
->revents
;
2569 #endif /* G_OS_UNIX */
2572 * g_get_current_time:
2573 * @result: #GTimeVal structure in which to store current time.
2575 * Equivalent to the UNIX gettimeofday() function, but portable.
2577 * You may find g_get_real_time() to be more convenient.
2580 g_get_current_time (GTimeVal
*result
)
2585 g_return_if_fail (result
!= NULL
);
2587 /*this is required on alpha, there the timeval structs are int's
2588 not longs and a cast only would fail horribly*/
2589 gettimeofday (&r
, NULL
);
2590 result
->tv_sec
= r
.tv_sec
;
2591 result
->tv_usec
= r
.tv_usec
;
2596 g_return_if_fail (result
!= NULL
);
2598 GetSystemTimeAsFileTime (&ft
);
2599 memmove (&time64
, &ft
, sizeof (FILETIME
));
2601 /* Convert from 100s of nanoseconds since 1601-01-01
2602 * to Unix epoch. Yes, this is Y2038 unsafe.
2604 time64
-= G_GINT64_CONSTANT (116444736000000000);
2607 result
->tv_sec
= time64
/ 1000000;
2608 result
->tv_usec
= time64
% 1000000;
2615 * Queries the system wall-clock time.
2617 * This call is functionally equivalent to g_get_current_time() except
2618 * that the return value is often more convenient than dealing with a
2621 * You should only use this call if you are actually interested in the real
2622 * wall-clock time. g_get_monotonic_time() is probably more useful for
2623 * measuring intervals.
2625 * Returns: the number of microseconds since January 1, 1970 UTC.
2630 g_get_real_time (void)
2634 g_get_current_time (&tv
);
2636 return (((gint64
) tv
.tv_sec
) * 1000000) + tv
.tv_usec
;
2640 * g_get_monotonic_time:
2642 * Queries the system monotonic time.
2644 * The monotonic clock will always increase and doesn't suffer
2645 * discontinuities when the user (or NTP) changes the system time. It
2646 * may or may not continue to tick during times where the machine is
2649 * We try to use the clock that corresponds as closely as possible to
2650 * the passage of time as measured by system calls such as poll() but it
2651 * may not always be possible to do this.
2653 * Returns: the monotonic time, in microseconds
2657 #if defined (G_OS_WIN32)
2658 static ULONGLONG (*g_GetTickCount64
) (void) = NULL
;
2659 static guint32 g_win32_tick_epoch
= 0;
2662 g_clock_win32_init (void)
2666 g_GetTickCount64
= NULL
;
2667 kernel32
= GetModuleHandle ("KERNEL32.DLL");
2668 if (kernel32
!= NULL
)
2669 g_GetTickCount64
= (void *) GetProcAddress (kernel32
, "GetTickCount64");
2670 g_win32_tick_epoch
= ((guint32
)GetTickCount()) >> 31;
2674 g_get_monotonic_time (void)
2679 /* There are four sources for the monotonic time on Windows:
2681 * Three are based on a (1 msec accuracy, but only read periodically) clock chip:
2682 * - GetTickCount (GTC)
2683 * 32bit msec counter, updated each ~15msec, wraps in ~50 days
2684 * - GetTickCount64 (GTC64)
2685 * Same as GetTickCount, but extended to 64bit, so no wrap
2686 * Only available in Vista or later
2687 * - timeGetTime (TGT)
2688 * similar to GetTickCount by default: 15msec, 50 day wrap.
2689 * available in winmm.dll (thus known as the multimedia timers)
2690 * However apps can raise the system timer clock frequency using timeBeginPeriod()
2691 * increasing the accuracy up to 1 msec, at a cost in general system performance
2694 * One is based on high precision clocks:
2695 * - QueryPrecisionCounter (QPC)
2696 * This has much higher accuracy, but is not guaranteed monotonic, and
2697 * has lots of complications like clock jumps and different times on different
2698 * CPUs. It also has lower long term accuracy (i.e. it will drift compared to
2699 * the low precision clocks.
2701 * Additionally, the precision available in the timer-based wakeup such as
2702 * MsgWaitForMultipleObjectsEx (which is what the mainloop is based on) is based
2703 * on the TGT resolution, so by default it is ~15msec, but can be increased by apps.
2705 * The QPC timer has too many issues to be used as is. The only way it could be used
2706 * is to use it to interpolate the lower precision clocks. Firefox does something like
2708 * https://bugzilla.mozilla.org/show_bug.cgi?id=363258
2710 * However this seems quite complicated, so we're not doing this right now.
2712 * The approach we take instead is to use the TGT timer, extending it to 64bit
2713 * either by using the GTC64 value, or if that is not available, a process local
2714 * time epoch that we increment when we detect a timer wrap (assumes that we read
2715 * the time at least once every 50 days).
2718 * - We have a globally consistent monotonic clock on Vista and later
2719 * - We have a locally monotonic clock on XP
2720 * - Apps that need higher precision in timeouts and clock reads can call
2721 * timeBeginPeriod() to increase it as much as they want
2724 if (g_GetTickCount64
!= NULL
)
2726 guint32 ticks_as_32bit
;
2728 ticks
= g_GetTickCount64 ();
2729 ticks32
= timeGetTime();
2731 /* GTC64 and TGT are sampled at different times, however they
2732 * have the same base and source (msecs since system boot).
2733 * They can differ by as much as -16 to +16 msecs.
2734 * We can't just inject the low bits into the 64bit counter
2735 * as one of the counters can have wrapped in 32bit space and
2736 * the other not. Instead we calculate the signed difference
2737 * in 32bit space and apply that difference to the 64bit counter.
2739 ticks_as_32bit
= (guint32
)ticks
;
2741 /* We could do some 2's complement hack, but we play it safe */
2742 if (ticks32
- ticks_as_32bit
<= G_MAXINT32
)
2743 ticks
+= ticks32
- ticks_as_32bit
;
2745 ticks
-= ticks_as_32bit
- ticks32
;
2751 epoch
= g_atomic_int_get (&g_win32_tick_epoch
);
2753 /* Must read ticks after the epoch. Then we're guaranteed
2754 * that the ticks value we read is higher or equal to any
2755 * previous ones that lead to the writing of the epoch.
2757 ticks32
= timeGetTime();
2759 /* We store the MSB of the current time as the LSB
2760 * of the epoch. Comparing these bits lets us detect when
2761 * the 32bit counter has wrapped so we can increase the
2764 * This will work as long as this function is called at
2765 * least once every ~24 days, which is half the wrap time
2766 * of a 32bit msec counter. I think this is pretty likely.
2768 * Note that g_win32_tick_epoch is a process local state,
2769 * so the monotonic clock will not be the same between
2772 if ((ticks32
>> 31) != (epoch
& 1))
2775 g_atomic_int_set (&g_win32_tick_epoch
, epoch
);
2779 ticks
= (guint64
)ticks32
| ((guint64
)epoch
) << 31;
2782 return ticks
* 1000;
2784 #elif defined(HAVE_MACH_MACH_TIME_H) /* Mac OS */
2786 g_get_monotonic_time (void)
2788 static mach_timebase_info_data_t timebase_info
;
2790 if (timebase_info
.denom
== 0)
2792 /* This is a fraction that we must use to scale
2793 * mach_absolute_time() by in order to reach nanoseconds.
2795 * We've only ever observed this to be 1/1, but maybe it could be
2796 * 1000/1 if mach time is microseconds already, or 1/1000 if
2797 * picoseconds. Try to deal nicely with that.
2799 mach_timebase_info (&timebase_info
);
2801 /* We actually want microseconds... */
2802 if (timebase_info
.numer
% 1000 == 0)
2803 timebase_info
.numer
/= 1000;
2805 timebase_info
.denom
*= 1000;
2807 /* We want to make the numer 1 to avoid having to multiply... */
2808 if (timebase_info
.denom
% timebase_info
.numer
== 0)
2810 timebase_info
.denom
/= timebase_info
.numer
;
2811 timebase_info
.numer
= 1;
2815 /* We could just multiply by timebase_info.numer below, but why
2816 * bother for a case that may never actually exist...
2818 * Plus -- performing the multiplication would risk integer
2819 * overflow. If we ever actually end up in this situation, we
2820 * should more carefully evaluate the correct course of action.
2822 mach_timebase_info (&timebase_info
); /* Get a fresh copy for a better message */
2823 g_error ("Got weird mach timebase info of %d/%d. Please file a bug against GLib.",
2824 timebase_info
.numer
, timebase_info
.denom
);
2828 return mach_absolute_time () / timebase_info
.denom
;
2832 g_get_monotonic_time (void)
2837 result
= clock_gettime (CLOCK_MONOTONIC
, &ts
);
2839 if G_UNLIKELY (result
!= 0)
2840 g_error ("GLib requires working CLOCK_MONOTONIC");
2842 return (((gint64
) ts
.tv_sec
) * 1000000) + (ts
.tv_nsec
/ 1000);
2847 g_main_dispatch_free (gpointer dispatch
)
2849 g_slice_free (GMainDispatch
, dispatch
);
2852 /* Running the main loop */
2854 static GMainDispatch
*
2857 static GPrivate depth_private
= G_PRIVATE_INIT (g_main_dispatch_free
);
2858 GMainDispatch
*dispatch
;
2860 dispatch
= g_private_get (&depth_private
);
2864 dispatch
= g_slice_new0 (GMainDispatch
);
2865 g_private_set (&depth_private
, dispatch
);
2874 * Returns the depth of the stack of calls to
2875 * g_main_context_dispatch() on any #GMainContext in the current thread.
2876 * That is, when called from the toplevel, it gives 0. When
2877 * called from within a callback from g_main_context_iteration()
2878 * (or g_main_loop_run(), etc.) it returns 1. When called from within
2879 * a callback to a recursive call to g_main_context_iteration(),
2880 * it returns 2. And so forth.
2882 * This function is useful in a situation like the following:
2883 * Imagine an extremely simple "garbage collected" system.
2885 * |[<!-- language="C" -->
2886 * static GList *free_list;
2889 * allocate_memory (gsize size)
2891 * gpointer result = g_malloc (size);
2892 * free_list = g_list_prepend (free_list, result);
2897 * free_allocated_memory (void)
2900 * for (l = free_list; l; l = l->next);
2902 * g_list_free (free_list);
2910 * g_main_context_iteration (NULL, TRUE);
2911 * free_allocated_memory();
2915 * This works from an application, however, if you want to do the same
2916 * thing from a library, it gets more difficult, since you no longer
2917 * control the main loop. You might think you can simply use an idle
2918 * function to make the call to free_allocated_memory(), but that
2919 * doesn't work, since the idle function could be called from a
2920 * recursive callback. This can be fixed by using g_main_depth()
2922 * |[<!-- language="C" -->
2924 * allocate_memory (gsize size)
2926 * FreeListBlock *block = g_new (FreeListBlock, 1);
2927 * block->mem = g_malloc (size);
2928 * block->depth = g_main_depth ();
2929 * free_list = g_list_prepend (free_list, block);
2930 * return block->mem;
2934 * free_allocated_memory (void)
2938 * int depth = g_main_depth ();
2939 * for (l = free_list; l; );
2941 * GList *next = l->next;
2942 * FreeListBlock *block = l->data;
2943 * if (block->depth > depth)
2945 * g_free (block->mem);
2947 * free_list = g_list_delete_link (free_list, l);
2955 * There is a temptation to use g_main_depth() to solve
2956 * problems with reentrancy. For instance, while waiting for data
2957 * to be received from the network in response to a menu item,
2958 * the menu item might be selected again. It might seem that
2959 * one could make the menu item's callback return immediately
2960 * and do nothing if g_main_depth() returns a value greater than 1.
2961 * However, this should be avoided since the user then sees selecting
2962 * the menu item do nothing. Furthermore, you'll find yourself adding
2963 * these checks all over your code, since there are doubtless many,
2964 * many things that the user could do. Instead, you can use the
2965 * following techniques:
2967 * 1. Use gtk_widget_set_sensitive() or modal dialogs to prevent
2968 * the user from interacting with elements while the main
2969 * loop is recursing.
2971 * 2. Avoid main loop recursion in situations where you can't handle
2972 * arbitrary callbacks. Instead, structure your code so that you
2973 * simply return to the main loop and then get called again when
2974 * there is more work to do.
2976 * Returns: The main loop recursion level in the current thread
2981 GMainDispatch
*dispatch
= get_dispatch ();
2982 return dispatch
->depth
;
2986 * g_main_current_source:
2988 * Returns the currently firing source for this thread.
2990 * Returns: (transfer none): The currently firing source or %NULL.
2995 g_main_current_source (void)
2997 GMainDispatch
*dispatch
= get_dispatch ();
2998 return dispatch
->source
;
3002 * g_source_is_destroyed:
3003 * @source: a #GSource
3005 * Returns whether @source has been destroyed.
3007 * This is important when you operate upon your objects
3008 * from within idle handlers, but may have freed the object
3009 * before the dispatch of your idle handler.
3011 * |[<!-- language="C" -->
3013 * idle_callback (gpointer data)
3015 * SomeWidget *self = data;
3017 * GDK_THREADS_ENTER ();
3018 * // do stuff with self
3019 * self->idle_id = 0;
3020 * GDK_THREADS_LEAVE ();
3022 * return G_SOURCE_REMOVE;
3026 * some_widget_do_stuff_later (SomeWidget *self)
3028 * self->idle_id = g_idle_add (idle_callback, self);
3032 * some_widget_finalize (GObject *object)
3034 * SomeWidget *self = SOME_WIDGET (object);
3036 * if (self->idle_id)
3037 * g_source_remove (self->idle_id);
3039 * G_OBJECT_CLASS (parent_class)->finalize (object);
3043 * This will fail in a multi-threaded application if the
3044 * widget is destroyed before the idle handler fires due
3045 * to the use after free in the callback. A solution, to
3046 * this particular problem, is to check to if the source
3047 * has already been destroy within the callback.
3049 * |[<!-- language="C" -->
3051 * idle_callback (gpointer data)
3053 * SomeWidget *self = data;
3055 * GDK_THREADS_ENTER ();
3056 * if (!g_source_is_destroyed (g_main_current_source ()))
3058 * // do stuff with self
3060 * GDK_THREADS_LEAVE ();
3066 * Returns: %TRUE if the source has been destroyed
3071 g_source_is_destroyed (GSource
*source
)
3073 return SOURCE_DESTROYED (source
);
3076 /* Temporarily remove all this source's file descriptors from the
3077 * poll(), so that if data comes available for one of the file descriptors
3078 * we don't continually spin in the poll()
3080 /* HOLDS: source->context's lock */
3082 block_source (GSource
*source
)
3086 g_return_if_fail (!SOURCE_BLOCKED (source
));
3088 source
->flags
|= G_SOURCE_BLOCKED
;
3090 if (source
->context
)
3092 tmp_list
= source
->poll_fds
;
3095 g_main_context_remove_poll_unlocked (source
->context
, tmp_list
->data
);
3096 tmp_list
= tmp_list
->next
;
3099 for (tmp_list
= source
->priv
->fds
; tmp_list
; tmp_list
= tmp_list
->next
)
3100 g_main_context_remove_poll_unlocked (source
->context
, tmp_list
->data
);
3103 if (source
->priv
&& source
->priv
->child_sources
)
3105 tmp_list
= source
->priv
->child_sources
;
3108 block_source (tmp_list
->data
);
3109 tmp_list
= tmp_list
->next
;
3114 /* HOLDS: source->context's lock */
3116 unblock_source (GSource
*source
)
3120 g_return_if_fail (SOURCE_BLOCKED (source
)); /* Source already unblocked */
3121 g_return_if_fail (!SOURCE_DESTROYED (source
));
3123 source
->flags
&= ~G_SOURCE_BLOCKED
;
3125 tmp_list
= source
->poll_fds
;
3128 g_main_context_add_poll_unlocked (source
->context
, source
->priority
, tmp_list
->data
);
3129 tmp_list
= tmp_list
->next
;
3132 for (tmp_list
= source
->priv
->fds
; tmp_list
; tmp_list
= tmp_list
->next
)
3133 g_main_context_add_poll_unlocked (source
->context
, source
->priority
, tmp_list
->data
);
3135 if (source
->priv
&& source
->priv
->child_sources
)
3137 tmp_list
= source
->priv
->child_sources
;
3140 unblock_source (tmp_list
->data
);
3141 tmp_list
= tmp_list
->next
;
3146 /* HOLDS: context's lock */
3148 g_main_dispatch (GMainContext
*context
)
3150 GMainDispatch
*current
= get_dispatch ();
3153 for (i
= 0; i
< context
->pending_dispatches
->len
; i
++)
3155 GSource
*source
= context
->pending_dispatches
->pdata
[i
];
3157 context
->pending_dispatches
->pdata
[i
] = NULL
;
3160 source
->flags
&= ~G_SOURCE_READY
;
3162 if (!SOURCE_DESTROYED (source
))
3164 gboolean was_in_call
;
3165 gpointer user_data
= NULL
;
3166 GSourceFunc callback
= NULL
;
3167 GSourceCallbackFuncs
*cb_funcs
;
3169 gboolean need_destroy
;
3171 gboolean (*dispatch
) (GSource
*,
3174 GSource
*prev_source
;
3176 dispatch
= source
->source_funcs
->dispatch
;
3177 cb_funcs
= source
->callback_funcs
;
3178 cb_data
= source
->callback_data
;
3181 cb_funcs
->ref (cb_data
);
3183 if ((source
->flags
& G_SOURCE_CAN_RECURSE
) == 0)
3184 block_source (source
);
3186 was_in_call
= source
->flags
& G_HOOK_FLAG_IN_CALL
;
3187 source
->flags
|= G_HOOK_FLAG_IN_CALL
;
3190 cb_funcs
->get (cb_data
, source
, &callback
, &user_data
);
3192 UNLOCK_CONTEXT (context
);
3194 /* These operations are safe because 'current' is thread-local
3195 * and not modified from anywhere but this function.
3197 prev_source
= current
->source
;
3198 current
->source
= source
;
3201 TRACE (GLIB_MAIN_BEFORE_DISPATCH (g_source_get_name (source
), source
,
3202 dispatch
, callback
, user_data
));
3203 need_destroy
= !(* dispatch
) (source
, callback
, user_data
);
3204 TRACE (GLIB_MAIN_AFTER_DISPATCH (g_source_get_name (source
), source
,
3205 dispatch
, need_destroy
));
3207 current
->source
= prev_source
;
3211 cb_funcs
->unref (cb_data
);
3213 LOCK_CONTEXT (context
);
3216 source
->flags
&= ~G_HOOK_FLAG_IN_CALL
;
3218 if (SOURCE_BLOCKED (source
) && !SOURCE_DESTROYED (source
))
3219 unblock_source (source
);
3221 /* Note: this depends on the fact that we can't switch
3222 * sources from one main context to another
3224 if (need_destroy
&& !SOURCE_DESTROYED (source
))
3226 g_assert (source
->context
== context
);
3227 g_source_destroy_internal (source
, context
, TRUE
);
3231 SOURCE_UNREF (source
, context
);
3234 g_ptr_array_set_size (context
->pending_dispatches
, 0);
3238 * g_main_context_acquire:
3239 * @context: a #GMainContext
3241 * Tries to become the owner of the specified context.
3242 * If some other thread is the owner of the context,
3243 * returns %FALSE immediately. Ownership is properly
3244 * recursive: the owner can require ownership again
3245 * and will release ownership when g_main_context_release()
3246 * is called as many times as g_main_context_acquire().
3248 * You must be the owner of a context before you
3249 * can call g_main_context_prepare(), g_main_context_query(),
3250 * g_main_context_check(), g_main_context_dispatch().
3252 * Returns: %TRUE if the operation succeeded, and
3253 * this thread is now the owner of @context.
3256 g_main_context_acquire (GMainContext
*context
)
3258 gboolean result
= FALSE
;
3259 GThread
*self
= G_THREAD_SELF
;
3261 if (context
== NULL
)
3262 context
= g_main_context_default ();
3264 LOCK_CONTEXT (context
);
3266 if (!context
->owner
)
3268 context
->owner
= self
;
3269 g_assert (context
->owner_count
== 0);
3270 TRACE (GLIB_MAIN_CONTEXT_ACQUIRE (context
, TRUE
/* success */));
3273 if (context
->owner
== self
)
3275 context
->owner_count
++;
3280 TRACE (GLIB_MAIN_CONTEXT_ACQUIRE (context
, FALSE
/* failure */));
3283 UNLOCK_CONTEXT (context
);
3289 * g_main_context_release:
3290 * @context: a #GMainContext
3292 * Releases ownership of a context previously acquired by this thread
3293 * with g_main_context_acquire(). If the context was acquired multiple
3294 * times, the ownership will be released only when g_main_context_release()
3295 * is called as many times as it was acquired.
3298 g_main_context_release (GMainContext
*context
)
3300 if (context
== NULL
)
3301 context
= g_main_context_default ();
3303 LOCK_CONTEXT (context
);
3305 context
->owner_count
--;
3306 if (context
->owner_count
== 0)
3308 TRACE (GLIB_MAIN_CONTEXT_RELEASE (context
));
3310 context
->owner
= NULL
;
3312 if (context
->waiters
)
3314 GMainWaiter
*waiter
= context
->waiters
->data
;
3315 gboolean loop_internal_waiter
= (waiter
->mutex
== &context
->mutex
);
3316 context
->waiters
= g_slist_delete_link (context
->waiters
,
3318 if (!loop_internal_waiter
)
3319 g_mutex_lock (waiter
->mutex
);
3321 g_cond_signal (waiter
->cond
);
3323 if (!loop_internal_waiter
)
3324 g_mutex_unlock (waiter
->mutex
);
3328 UNLOCK_CONTEXT (context
);
3332 * g_main_context_wait:
3333 * @context: a #GMainContext
3334 * @cond: a condition variable
3335 * @mutex: a mutex, currently held
3337 * Tries to become the owner of the specified context,
3338 * as with g_main_context_acquire(). But if another thread
3339 * is the owner, atomically drop @mutex and wait on @cond until
3340 * that owner releases ownership or until @cond is signaled, then
3341 * try again (once) to become the owner.
3343 * Returns: %TRUE if the operation succeeded, and
3344 * this thread is now the owner of @context.
3347 g_main_context_wait (GMainContext
*context
,
3351 gboolean result
= FALSE
;
3352 GThread
*self
= G_THREAD_SELF
;
3353 gboolean loop_internal_waiter
;
3355 if (context
== NULL
)
3356 context
= g_main_context_default ();
3358 if G_UNLIKELY (cond
!= &context
->cond
|| mutex
!= &context
->mutex
)
3360 static gboolean warned
;
3364 g_critical ("WARNING!! g_main_context_wait() will be removed in a future release. "
3365 "If you see this message, please file a bug immediately.");
3370 loop_internal_waiter
= (mutex
== &context
->mutex
);
3372 if (!loop_internal_waiter
)
3373 LOCK_CONTEXT (context
);
3375 if (context
->owner
&& context
->owner
!= self
)
3380 waiter
.mutex
= mutex
;
3382 context
->waiters
= g_slist_append (context
->waiters
, &waiter
);
3384 if (!loop_internal_waiter
)
3385 UNLOCK_CONTEXT (context
);
3386 g_cond_wait (cond
, mutex
);
3387 if (!loop_internal_waiter
)
3388 LOCK_CONTEXT (context
);
3390 context
->waiters
= g_slist_remove (context
->waiters
, &waiter
);
3393 if (!context
->owner
)
3395 context
->owner
= self
;
3396 g_assert (context
->owner_count
== 0);
3399 if (context
->owner
== self
)
3401 context
->owner_count
++;
3405 if (!loop_internal_waiter
)
3406 UNLOCK_CONTEXT (context
);
3412 * g_main_context_prepare:
3413 * @context: a #GMainContext
3414 * @priority: location to store priority of highest priority
3415 * source already ready.
3417 * Prepares to poll sources within a main loop. The resulting information
3418 * for polling is determined by calling g_main_context_query ().
3420 * You must have successfully acquired the context with
3421 * g_main_context_acquire() before you may call this function.
3423 * Returns: %TRUE if some source is ready to be dispatched
3427 g_main_context_prepare (GMainContext
*context
,
3432 gint current_priority
= G_MAXINT
;
3436 if (context
== NULL
)
3437 context
= g_main_context_default ();
3439 LOCK_CONTEXT (context
);
3441 context
->time_is_fresh
= FALSE
;
3443 if (context
->in_check_or_prepare
)
3445 g_warning ("g_main_context_prepare() called recursively from within a source's check() or "
3446 "prepare() member.");
3447 UNLOCK_CONTEXT (context
);
3451 TRACE (GLIB_MAIN_CONTEXT_BEFORE_PREPARE (context
));
3454 /* If recursing, finish up current dispatch, before starting over */
3455 if (context
->pending_dispatches
)
3458 g_main_dispatch (context
, ¤t_time
);
3460 UNLOCK_CONTEXT (context
);
3465 /* If recursing, clear list of pending dispatches */
3467 for (i
= 0; i
< context
->pending_dispatches
->len
; i
++)
3469 if (context
->pending_dispatches
->pdata
[i
])
3470 SOURCE_UNREF ((GSource
*)context
->pending_dispatches
->pdata
[i
], context
);
3472 g_ptr_array_set_size (context
->pending_dispatches
, 0);
3474 /* Prepare all sources */
3476 context
->timeout
= -1;
3478 g_source_iter_init (&iter
, context
, TRUE
);
3479 while (g_source_iter_next (&iter
, &source
))
3481 gint source_timeout
= -1;
3483 if (SOURCE_DESTROYED (source
) || SOURCE_BLOCKED (source
))
3485 if ((n_ready
> 0) && (source
->priority
> current_priority
))
3488 if (!(source
->flags
& G_SOURCE_READY
))
3491 gboolean (* prepare
) (GSource
*source
,
3494 prepare
= source
->source_funcs
->prepare
;
3498 context
->in_check_or_prepare
++;
3499 UNLOCK_CONTEXT (context
);
3501 result
= (* prepare
) (source
, &source_timeout
);
3502 TRACE (GLIB_MAIN_AFTER_PREPARE (source
, prepare
, source_timeout
));
3504 LOCK_CONTEXT (context
);
3505 context
->in_check_or_prepare
--;
3509 source_timeout
= -1;
3513 if (result
== FALSE
&& source
->priv
->ready_time
!= -1)
3515 if (!context
->time_is_fresh
)
3517 context
->time
= g_get_monotonic_time ();
3518 context
->time_is_fresh
= TRUE
;
3521 if (source
->priv
->ready_time
<= context
->time
)
3530 /* rounding down will lead to spinning, so always round up */
3531 timeout
= (source
->priv
->ready_time
- context
->time
+ 999) / 1000;
3533 if (source_timeout
< 0 || timeout
< source_timeout
)
3534 source_timeout
= timeout
;
3540 GSource
*ready_source
= source
;
3542 while (ready_source
)
3544 ready_source
->flags
|= G_SOURCE_READY
;
3545 ready_source
= ready_source
->priv
->parent_source
;
3550 if (source
->flags
& G_SOURCE_READY
)
3553 current_priority
= source
->priority
;
3554 context
->timeout
= 0;
3557 if (source_timeout
>= 0)
3559 if (context
->timeout
< 0)
3560 context
->timeout
= source_timeout
;
3562 context
->timeout
= MIN (context
->timeout
, source_timeout
);
3565 g_source_iter_clear (&iter
);
3567 TRACE (GLIB_MAIN_CONTEXT_AFTER_PREPARE (context
, current_priority
, n_ready
));
3569 UNLOCK_CONTEXT (context
);
3572 *priority
= current_priority
;
3574 return (n_ready
> 0);
3578 * g_main_context_query:
3579 * @context: a #GMainContext
3580 * @max_priority: maximum priority source to check
3581 * @timeout_: (out): location to store timeout to be used in polling
3582 * @fds: (out caller-allocates) (array length=n_fds): location to
3583 * store #GPollFD records that need to be polled.
3584 * @n_fds: (in): length of @fds.
3586 * Determines information necessary to poll this main loop.
3588 * You must have successfully acquired the context with
3589 * g_main_context_acquire() before you may call this function.
3591 * Returns: the number of records actually stored in @fds,
3592 * or, if more than @n_fds records need to be stored, the number
3593 * of records that need to be stored.
3596 g_main_context_query (GMainContext
*context
,
3603 GPollRec
*pollrec
, *lastpollrec
;
3606 LOCK_CONTEXT (context
);
3608 TRACE (GLIB_MAIN_CONTEXT_BEFORE_QUERY (context
, max_priority
));
3612 for (pollrec
= context
->poll_records
; pollrec
; pollrec
= pollrec
->next
)
3614 if (pollrec
->priority
> max_priority
)
3617 /* In direct contradiction to the Unix98 spec, IRIX runs into
3618 * difficulty if you pass in POLLERR, POLLHUP or POLLNVAL
3619 * flags in the events field of the pollfd while it should
3620 * just ignoring them. So we mask them out here.
3622 events
= pollrec
->fd
->events
& ~(G_IO_ERR
|G_IO_HUP
|G_IO_NVAL
);
3624 if (lastpollrec
&& pollrec
->fd
->fd
== lastpollrec
->fd
->fd
)
3626 if (n_poll
- 1 < n_fds
)
3627 fds
[n_poll
- 1].events
|= events
;
3633 fds
[n_poll
].fd
= pollrec
->fd
->fd
;
3634 fds
[n_poll
].events
= events
;
3635 fds
[n_poll
].revents
= 0;
3641 lastpollrec
= pollrec
;
3644 context
->poll_changed
= FALSE
;
3648 *timeout
= context
->timeout
;
3650 context
->time_is_fresh
= FALSE
;
3653 TRACE (GLIB_MAIN_CONTEXT_AFTER_QUERY (context
, context
->timeout
,
3656 UNLOCK_CONTEXT (context
);
3662 * g_main_context_check:
3663 * @context: a #GMainContext
3664 * @max_priority: the maximum numerical priority of sources to check
3665 * @fds: (array length=n_fds): array of #GPollFD's that was passed to
3666 * the last call to g_main_context_query()
3667 * @n_fds: return value of g_main_context_query()
3669 * Passes the results of polling back to the main loop.
3671 * You must have successfully acquired the context with
3672 * g_main_context_acquire() before you may call this function.
3674 * Returns: %TRUE if some sources are ready to be dispatched.
3677 g_main_context_check (GMainContext
*context
,
3688 LOCK_CONTEXT (context
);
3690 if (context
->in_check_or_prepare
)
3692 g_warning ("g_main_context_check() called recursively from within a source's check() or "
3693 "prepare() member.");
3694 UNLOCK_CONTEXT (context
);
3698 TRACE (GLIB_MAIN_CONTEXT_BEFORE_CHECK (context
, max_priority
, fds
, n_fds
));
3700 for (i
= 0; i
< n_fds
; i
++)
3702 if (fds
[i
].fd
== context
->wake_up_rec
.fd
)
3706 TRACE (GLIB_MAIN_CONTEXT_WAKEUP_ACKNOWLEDGE (context
));
3707 g_wakeup_acknowledge (context
->wakeup
);
3713 /* If the set of poll file descriptors changed, bail out
3714 * and let the main loop rerun
3716 if (context
->poll_changed
)
3718 TRACE (GLIB_MAIN_CONTEXT_AFTER_CHECK (context
, 0));
3720 UNLOCK_CONTEXT (context
);
3724 pollrec
= context
->poll_records
;
3726 while (pollrec
&& i
< n_fds
)
3728 while (pollrec
&& pollrec
->fd
->fd
== fds
[i
].fd
)
3730 if (pollrec
->priority
<= max_priority
)
3732 pollrec
->fd
->revents
=
3733 fds
[i
].revents
& (pollrec
->fd
->events
| G_IO_ERR
| G_IO_HUP
| G_IO_NVAL
);
3735 pollrec
= pollrec
->next
;
3741 g_source_iter_init (&iter
, context
, TRUE
);
3742 while (g_source_iter_next (&iter
, &source
))
3744 if (SOURCE_DESTROYED (source
) || SOURCE_BLOCKED (source
))
3746 if ((n_ready
> 0) && (source
->priority
> max_priority
))
3749 if (!(source
->flags
& G_SOURCE_READY
))
3752 gboolean (* check
) (GSource
*source
);
3754 check
= source
->source_funcs
->check
;
3758 /* If the check function is set, call it. */
3759 context
->in_check_or_prepare
++;
3760 UNLOCK_CONTEXT (context
);
3762 result
= (* check
) (source
);
3764 TRACE (GLIB_MAIN_AFTER_CHECK (source
, check
, result
));
3766 LOCK_CONTEXT (context
);
3767 context
->in_check_or_prepare
--;
3772 if (result
== FALSE
)
3776 /* If not already explicitly flagged ready by ->check()
3777 * (or if we have no check) then we can still be ready if
3778 * any of our fds poll as ready.
3780 for (tmp_list
= source
->priv
->fds
; tmp_list
; tmp_list
= tmp_list
->next
)
3782 GPollFD
*pollfd
= tmp_list
->data
;
3784 if (pollfd
->revents
)
3792 if (result
== FALSE
&& source
->priv
->ready_time
!= -1)
3794 if (!context
->time_is_fresh
)
3796 context
->time
= g_get_monotonic_time ();
3797 context
->time_is_fresh
= TRUE
;
3800 if (source
->priv
->ready_time
<= context
->time
)
3806 GSource
*ready_source
= source
;
3808 while (ready_source
)
3810 ready_source
->flags
|= G_SOURCE_READY
;
3811 ready_source
= ready_source
->priv
->parent_source
;
3816 if (source
->flags
& G_SOURCE_READY
)
3818 source
->ref_count
++;
3819 g_ptr_array_add (context
->pending_dispatches
, source
);
3823 /* never dispatch sources with less priority than the first
3824 * one we choose to dispatch
3826 max_priority
= source
->priority
;
3829 g_source_iter_clear (&iter
);
3831 TRACE (GLIB_MAIN_CONTEXT_AFTER_CHECK (context
, n_ready
));
3833 UNLOCK_CONTEXT (context
);
3839 * g_main_context_dispatch:
3840 * @context: a #GMainContext
3842 * Dispatches all pending sources.
3844 * You must have successfully acquired the context with
3845 * g_main_context_acquire() before you may call this function.
3848 g_main_context_dispatch (GMainContext
*context
)
3850 LOCK_CONTEXT (context
);
3852 TRACE (GLIB_MAIN_CONTEXT_BEFORE_DISPATCH (context
));
3854 if (context
->pending_dispatches
->len
> 0)
3856 g_main_dispatch (context
);
3859 TRACE (GLIB_MAIN_CONTEXT_AFTER_DISPATCH (context
));
3861 UNLOCK_CONTEXT (context
);
3864 /* HOLDS context lock */
3866 g_main_context_iterate (GMainContext
*context
,
3873 gboolean some_ready
;
3874 gint nfds
, allocated_nfds
;
3875 GPollFD
*fds
= NULL
;
3877 UNLOCK_CONTEXT (context
);
3879 if (!g_main_context_acquire (context
))
3881 gboolean got_ownership
;
3883 LOCK_CONTEXT (context
);
3888 got_ownership
= g_main_context_wait (context
,
3896 LOCK_CONTEXT (context
);
3898 if (!context
->cached_poll_array
)
3900 context
->cached_poll_array_size
= context
->n_poll_records
;
3901 context
->cached_poll_array
= g_new (GPollFD
, context
->n_poll_records
);
3904 allocated_nfds
= context
->cached_poll_array_size
;
3905 fds
= context
->cached_poll_array
;
3907 UNLOCK_CONTEXT (context
);
3909 g_main_context_prepare (context
, &max_priority
);
3911 while ((nfds
= g_main_context_query (context
, max_priority
, &timeout
, fds
,
3912 allocated_nfds
)) > allocated_nfds
)
3914 LOCK_CONTEXT (context
);
3916 context
->cached_poll_array_size
= allocated_nfds
= nfds
;
3917 context
->cached_poll_array
= fds
= g_new (GPollFD
, nfds
);
3918 UNLOCK_CONTEXT (context
);
3924 g_main_context_poll (context
, timeout
, max_priority
, fds
, nfds
);
3926 some_ready
= g_main_context_check (context
, max_priority
, fds
, nfds
);
3929 g_main_context_dispatch (context
);
3931 g_main_context_release (context
);
3933 LOCK_CONTEXT (context
);
3939 * g_main_context_pending:
3940 * @context: (nullable): a #GMainContext (if %NULL, the default context will be used)
3942 * Checks if any sources have pending events for the given context.
3944 * Returns: %TRUE if events are pending.
3947 g_main_context_pending (GMainContext
*context
)
3952 context
= g_main_context_default();
3954 LOCK_CONTEXT (context
);
3955 retval
= g_main_context_iterate (context
, FALSE
, FALSE
, G_THREAD_SELF
);
3956 UNLOCK_CONTEXT (context
);
3962 * g_main_context_iteration:
3963 * @context: (nullable): a #GMainContext (if %NULL, the default context will be used)
3964 * @may_block: whether the call may block.
3966 * Runs a single iteration for the given main loop. This involves
3967 * checking to see if any event sources are ready to be processed,
3968 * then if no events sources are ready and @may_block is %TRUE, waiting
3969 * for a source to become ready, then dispatching the highest priority
3970 * events sources that are ready. Otherwise, if @may_block is %FALSE
3971 * sources are not waited to become ready, only those highest priority
3972 * events sources will be dispatched (if any), that are ready at this
3973 * given moment without further waiting.
3975 * Note that even when @may_block is %TRUE, it is still possible for
3976 * g_main_context_iteration() to return %FALSE, since the wait may
3977 * be interrupted for other reasons than an event source becoming ready.
3979 * Returns: %TRUE if events were dispatched.
3982 g_main_context_iteration (GMainContext
*context
, gboolean may_block
)
3987 context
= g_main_context_default();
3989 LOCK_CONTEXT (context
);
3990 retval
= g_main_context_iterate (context
, may_block
, TRUE
, G_THREAD_SELF
);
3991 UNLOCK_CONTEXT (context
);
3998 * @context: (nullable): a #GMainContext (if %NULL, the default context will be used).
3999 * @is_running: set to %TRUE to indicate that the loop is running. This
4000 * is not very important since calling g_main_loop_run() will set this to
4003 * Creates a new #GMainLoop structure.
4005 * Returns: a new #GMainLoop.
4008 g_main_loop_new (GMainContext
*context
,
4009 gboolean is_running
)
4014 context
= g_main_context_default();
4016 g_main_context_ref (context
);
4018 loop
= g_new0 (GMainLoop
, 1);
4019 loop
->context
= context
;
4020 loop
->is_running
= is_running
!= FALSE
;
4021 loop
->ref_count
= 1;
4023 TRACE (GLIB_MAIN_LOOP_NEW (loop
, context
));
4030 * @loop: a #GMainLoop
4032 * Increases the reference count on a #GMainLoop object by one.
4037 g_main_loop_ref (GMainLoop
*loop
)
4039 g_return_val_if_fail (loop
!= NULL
, NULL
);
4040 g_return_val_if_fail (g_atomic_int_get (&loop
->ref_count
) > 0, NULL
);
4042 g_atomic_int_inc (&loop
->ref_count
);
4048 * g_main_loop_unref:
4049 * @loop: a #GMainLoop
4051 * Decreases the reference count on a #GMainLoop object by one. If
4052 * the result is zero, free the loop and free all associated memory.
4055 g_main_loop_unref (GMainLoop
*loop
)
4057 g_return_if_fail (loop
!= NULL
);
4058 g_return_if_fail (g_atomic_int_get (&loop
->ref_count
) > 0);
4060 if (!g_atomic_int_dec_and_test (&loop
->ref_count
))
4063 g_main_context_unref (loop
->context
);
4069 * @loop: a #GMainLoop
4071 * Runs a main loop until g_main_loop_quit() is called on the loop.
4072 * If this is called for the thread of the loop's #GMainContext,
4073 * it will process events from the loop, otherwise it will
4077 g_main_loop_run (GMainLoop
*loop
)
4079 GThread
*self
= G_THREAD_SELF
;
4081 g_return_if_fail (loop
!= NULL
);
4082 g_return_if_fail (g_atomic_int_get (&loop
->ref_count
) > 0);
4084 if (!g_main_context_acquire (loop
->context
))
4086 gboolean got_ownership
= FALSE
;
4088 /* Another thread owns this context */
4089 LOCK_CONTEXT (loop
->context
);
4091 g_atomic_int_inc (&loop
->ref_count
);
4093 if (!loop
->is_running
)
4094 loop
->is_running
= TRUE
;
4096 while (loop
->is_running
&& !got_ownership
)
4097 got_ownership
= g_main_context_wait (loop
->context
,
4098 &loop
->context
->cond
,
4099 &loop
->context
->mutex
);
4101 if (!loop
->is_running
)
4103 UNLOCK_CONTEXT (loop
->context
);
4105 g_main_context_release (loop
->context
);
4106 g_main_loop_unref (loop
);
4110 g_assert (got_ownership
);
4113 LOCK_CONTEXT (loop
->context
);
4115 if (loop
->context
->in_check_or_prepare
)
4117 g_warning ("g_main_loop_run(): called recursively from within a source's "
4118 "check() or prepare() member, iteration not possible.");
4122 g_atomic_int_inc (&loop
->ref_count
);
4123 loop
->is_running
= TRUE
;
4124 while (loop
->is_running
)
4125 g_main_context_iterate (loop
->context
, TRUE
, TRUE
, self
);
4127 UNLOCK_CONTEXT (loop
->context
);
4129 g_main_context_release (loop
->context
);
4131 g_main_loop_unref (loop
);
4136 * @loop: a #GMainLoop
4138 * Stops a #GMainLoop from running. Any calls to g_main_loop_run()
4139 * for the loop will return.
4141 * Note that sources that have already been dispatched when
4142 * g_main_loop_quit() is called will still be executed.
4145 g_main_loop_quit (GMainLoop
*loop
)
4147 g_return_if_fail (loop
!= NULL
);
4148 g_return_if_fail (g_atomic_int_get (&loop
->ref_count
) > 0);
4150 LOCK_CONTEXT (loop
->context
);
4151 loop
->is_running
= FALSE
;
4152 g_wakeup_signal (loop
->context
->wakeup
);
4154 g_cond_broadcast (&loop
->context
->cond
);
4156 UNLOCK_CONTEXT (loop
->context
);
4158 TRACE (GLIB_MAIN_LOOP_QUIT (loop
));
4162 * g_main_loop_is_running:
4163 * @loop: a #GMainLoop.
4165 * Checks to see if the main loop is currently being run via g_main_loop_run().
4167 * Returns: %TRUE if the mainloop is currently being run.
4170 g_main_loop_is_running (GMainLoop
*loop
)
4172 g_return_val_if_fail (loop
!= NULL
, FALSE
);
4173 g_return_val_if_fail (g_atomic_int_get (&loop
->ref_count
) > 0, FALSE
);
4175 return loop
->is_running
;
4179 * g_main_loop_get_context:
4180 * @loop: a #GMainLoop.
4182 * Returns the #GMainContext of @loop.
4184 * Returns: (transfer none): the #GMainContext of @loop
4187 g_main_loop_get_context (GMainLoop
*loop
)
4189 g_return_val_if_fail (loop
!= NULL
, NULL
);
4190 g_return_val_if_fail (g_atomic_int_get (&loop
->ref_count
) > 0, NULL
);
4192 return loop
->context
;
4195 /* HOLDS: context's lock */
4197 g_main_context_poll (GMainContext
*context
,
4203 #ifdef G_MAIN_POLL_DEBUG
4209 GPollFunc poll_func
;
4211 if (n_fds
|| timeout
!= 0)
4213 #ifdef G_MAIN_POLL_DEBUG
4215 if (_g_main_poll_debug
)
4217 g_print ("polling context=%p n=%d timeout=%d\n",
4218 context
, n_fds
, timeout
);
4219 poll_timer
= g_timer_new ();
4223 LOCK_CONTEXT (context
);
4225 poll_func
= context
->poll_func
;
4227 UNLOCK_CONTEXT (context
);
4228 if ((*poll_func
) (fds
, n_fds
, timeout
) < 0 && errno
!= EINTR
)
4231 g_warning ("poll(2) failed due to: %s.",
4232 g_strerror (errno
));
4234 /* If g_poll () returns -1, it has already called g_warning() */
4238 #ifdef G_MAIN_POLL_DEBUG
4239 if (_g_main_poll_debug
)
4241 LOCK_CONTEXT (context
);
4243 g_print ("g_main_poll(%d) timeout: %d - elapsed %12.10f seconds",
4246 g_timer_elapsed (poll_timer
, NULL
));
4247 g_timer_destroy (poll_timer
);
4248 pollrec
= context
->poll_records
;
4250 while (pollrec
!= NULL
)
4255 if (fds
[i
].fd
== pollrec
->fd
->fd
&&
4256 pollrec
->fd
->events
&&
4259 g_print (" [" G_POLLFD_FORMAT
" :", fds
[i
].fd
);
4260 if (fds
[i
].revents
& G_IO_IN
)
4262 if (fds
[i
].revents
& G_IO_OUT
)
4264 if (fds
[i
].revents
& G_IO_PRI
)
4266 if (fds
[i
].revents
& G_IO_ERR
)
4268 if (fds
[i
].revents
& G_IO_HUP
)
4270 if (fds
[i
].revents
& G_IO_NVAL
)
4276 pollrec
= pollrec
->next
;
4280 UNLOCK_CONTEXT (context
);
4283 } /* if (n_fds || timeout != 0) */
4287 * g_main_context_add_poll:
4288 * @context: (nullable): a #GMainContext (or %NULL for the default context)
4289 * @fd: a #GPollFD structure holding information about a file
4290 * descriptor to watch.
4291 * @priority: the priority for this file descriptor which should be
4292 * the same as the priority used for g_source_attach() to ensure that the
4293 * file descriptor is polled whenever the results may be needed.
4295 * Adds a file descriptor to the set of file descriptors polled for
4296 * this context. This will very seldom be used directly. Instead
4297 * a typical event source will use g_source_add_unix_fd() instead.
4300 g_main_context_add_poll (GMainContext
*context
,
4305 context
= g_main_context_default ();
4307 g_return_if_fail (g_atomic_int_get (&context
->ref_count
) > 0);
4308 g_return_if_fail (fd
);
4310 LOCK_CONTEXT (context
);
4311 g_main_context_add_poll_unlocked (context
, priority
, fd
);
4312 UNLOCK_CONTEXT (context
);
4315 /* HOLDS: main_loop_lock */
4317 g_main_context_add_poll_unlocked (GMainContext
*context
,
4321 GPollRec
*prevrec
, *nextrec
;
4322 GPollRec
*newrec
= g_slice_new (GPollRec
);
4324 /* This file descriptor may be checked before we ever poll */
4327 newrec
->priority
= priority
;
4330 nextrec
= context
->poll_records
;
4333 if (nextrec
->fd
->fd
> fd
->fd
)
4336 nextrec
= nextrec
->next
;
4340 prevrec
->next
= newrec
;
4342 context
->poll_records
= newrec
;
4344 newrec
->prev
= prevrec
;
4345 newrec
->next
= nextrec
;
4348 nextrec
->prev
= newrec
;
4350 context
->n_poll_records
++;
4352 context
->poll_changed
= TRUE
;
4354 /* Now wake up the main loop if it is waiting in the poll() */
4355 if (context
->owner
&& context
->owner
!= G_THREAD_SELF
)
4356 g_wakeup_signal (context
->wakeup
);
4360 * g_main_context_remove_poll:
4361 * @context:a #GMainContext
4362 * @fd: a #GPollFD descriptor previously added with g_main_context_add_poll()
4364 * Removes file descriptor from the set of file descriptors to be
4365 * polled for a particular context.
4368 g_main_context_remove_poll (GMainContext
*context
,
4372 context
= g_main_context_default ();
4374 g_return_if_fail (g_atomic_int_get (&context
->ref_count
) > 0);
4375 g_return_if_fail (fd
);
4377 LOCK_CONTEXT (context
);
4378 g_main_context_remove_poll_unlocked (context
, fd
);
4379 UNLOCK_CONTEXT (context
);
4383 g_main_context_remove_poll_unlocked (GMainContext
*context
,
4386 GPollRec
*pollrec
, *prevrec
, *nextrec
;
4389 pollrec
= context
->poll_records
;
4393 nextrec
= pollrec
->next
;
4394 if (pollrec
->fd
== fd
)
4396 if (prevrec
!= NULL
)
4397 prevrec
->next
= nextrec
;
4399 context
->poll_records
= nextrec
;
4401 if (nextrec
!= NULL
)
4402 nextrec
->prev
= prevrec
;
4404 g_slice_free (GPollRec
, pollrec
);
4406 context
->n_poll_records
--;
4413 context
->poll_changed
= TRUE
;
4415 /* Now wake up the main loop if it is waiting in the poll() */
4416 if (context
->owner
&& context
->owner
!= G_THREAD_SELF
)
4417 g_wakeup_signal (context
->wakeup
);
4421 * g_source_get_current_time:
4422 * @source: a #GSource
4423 * @timeval: #GTimeVal structure in which to store current time.
4425 * This function ignores @source and is otherwise the same as
4426 * g_get_current_time().
4428 * Deprecated: 2.28: use g_source_get_time() instead
4431 g_source_get_current_time (GSource
*source
,
4434 g_get_current_time (timeval
);
4438 * g_source_get_time:
4439 * @source: a #GSource
4441 * Gets the time to be used when checking this source. The advantage of
4442 * calling this function over calling g_get_monotonic_time() directly is
4443 * that when checking multiple sources, GLib can cache a single value
4444 * instead of having to repeatedly get the system monotonic time.
4446 * The time here is the system monotonic time, if available, or some
4447 * other reasonable alternative otherwise. See g_get_monotonic_time().
4449 * Returns: the monotonic time in microseconds
4454 g_source_get_time (GSource
*source
)
4456 GMainContext
*context
;
4459 g_return_val_if_fail (source
->context
!= NULL
, 0);
4461 context
= source
->context
;
4463 LOCK_CONTEXT (context
);
4465 if (!context
->time_is_fresh
)
4467 context
->time
= g_get_monotonic_time ();
4468 context
->time_is_fresh
= TRUE
;
4471 result
= context
->time
;
4473 UNLOCK_CONTEXT (context
);
4479 * g_main_context_set_poll_func:
4480 * @context: a #GMainContext
4481 * @func: the function to call to poll all file descriptors
4483 * Sets the function to use to handle polling of file descriptors. It
4484 * will be used instead of the poll() system call
4485 * (or GLib's replacement function, which is used where
4486 * poll() isn't available).
4488 * This function could possibly be used to integrate the GLib event
4489 * loop with an external event loop.
4492 g_main_context_set_poll_func (GMainContext
*context
,
4496 context
= g_main_context_default ();
4498 g_return_if_fail (g_atomic_int_get (&context
->ref_count
) > 0);
4500 LOCK_CONTEXT (context
);
4503 context
->poll_func
= func
;
4505 context
->poll_func
= g_poll
;
4507 UNLOCK_CONTEXT (context
);
4511 * g_main_context_get_poll_func:
4512 * @context: a #GMainContext
4514 * Gets the poll function set by g_main_context_set_poll_func().
4516 * Returns: the poll function
4519 g_main_context_get_poll_func (GMainContext
*context
)
4524 context
= g_main_context_default ();
4526 g_return_val_if_fail (g_atomic_int_get (&context
->ref_count
) > 0, NULL
);
4528 LOCK_CONTEXT (context
);
4529 result
= context
->poll_func
;
4530 UNLOCK_CONTEXT (context
);
4536 * g_main_context_wakeup:
4537 * @context: a #GMainContext
4539 * If @context is currently blocking in g_main_context_iteration()
4540 * waiting for a source to become ready, cause it to stop blocking
4541 * and return. Otherwise, cause the next invocation of
4542 * g_main_context_iteration() to return without blocking.
4544 * This API is useful for low-level control over #GMainContext; for
4545 * example, integrating it with main loop implementations such as
4548 * Another related use for this function is when implementing a main
4549 * loop with a termination condition, computed from multiple threads:
4551 * |[<!-- language="C" -->
4552 * #define NUM_TASKS 10
4553 * static volatile gint tasks_remaining = NUM_TASKS;
4556 * while (g_atomic_int_get (&tasks_remaining) != 0)
4557 * g_main_context_iteration (NULL, TRUE);
4561 * |[<!-- language="C" -->
4564 * if (g_atomic_int_dec_and_test (&tasks_remaining))
4565 * g_main_context_wakeup (NULL);
4569 g_main_context_wakeup (GMainContext
*context
)
4572 context
= g_main_context_default ();
4574 g_return_if_fail (g_atomic_int_get (&context
->ref_count
) > 0);
4576 TRACE (GLIB_MAIN_CONTEXT_WAKEUP (context
));
4578 g_wakeup_signal (context
->wakeup
);
4582 * g_main_context_is_owner:
4583 * @context: a #GMainContext
4585 * Determines whether this thread holds the (recursive)
4586 * ownership of this #GMainContext. This is useful to
4587 * know before waiting on another thread that may be
4588 * blocking to get ownership of @context.
4590 * Returns: %TRUE if current thread is owner of @context.
4595 g_main_context_is_owner (GMainContext
*context
)
4600 context
= g_main_context_default ();
4602 LOCK_CONTEXT (context
);
4603 is_owner
= context
->owner
== G_THREAD_SELF
;
4604 UNLOCK_CONTEXT (context
);
4612 g_timeout_set_expiration (GTimeoutSource
*timeout_source
,
4613 gint64 current_time
)
4617 expiration
= current_time
+ (guint64
) timeout_source
->interval
* 1000;
4619 if (timeout_source
->seconds
)
4622 static gint timer_perturb
= -1;
4624 if (timer_perturb
== -1)
4627 * we want a per machine/session unique 'random' value; try the dbus
4628 * address first, that has a UUID in it. If there is no dbus, use the
4629 * hostname for hashing.
4631 const char *session_bus_address
= g_getenv ("DBUS_SESSION_BUS_ADDRESS");
4632 if (!session_bus_address
)
4633 session_bus_address
= g_getenv ("HOSTNAME");
4634 if (session_bus_address
)
4635 timer_perturb
= ABS ((gint
) g_str_hash (session_bus_address
)) % 1000000;
4640 /* We want the microseconds part of the timeout to land on the
4641 * 'timer_perturb' mark, but we need to make sure we don't try to
4642 * set the timeout in the past. We do this by ensuring that we
4643 * always only *increase* the expiration time by adding a full
4644 * second in the case that the microsecond portion decreases.
4646 expiration
-= timer_perturb
;
4648 remainder
= expiration
% 1000000;
4649 if (remainder
>= 1000000/4)
4650 expiration
+= 1000000;
4652 expiration
-= remainder
;
4653 expiration
+= timer_perturb
;
4656 g_source_set_ready_time ((GSource
*) timeout_source
, expiration
);
4660 g_timeout_dispatch (GSource
*source
,
4661 GSourceFunc callback
,
4664 GTimeoutSource
*timeout_source
= (GTimeoutSource
*)source
;
4669 g_warning ("Timeout source dispatched without callback\n"
4670 "You must call g_source_set_callback().");
4674 again
= callback (user_data
);
4676 TRACE (GLIB_TIMEOUT_DISPATCH (source
, source
->context
, callback
, user_data
, again
));
4679 g_timeout_set_expiration (timeout_source
, g_source_get_time (source
));
4685 * g_timeout_source_new:
4686 * @interval: the timeout interval in milliseconds.
4688 * Creates a new timeout source.
4690 * The source will not initially be associated with any #GMainContext
4691 * and must be added to one with g_source_attach() before it will be
4694 * The interval given is in terms of monotonic time, not wall clock
4695 * time. See g_get_monotonic_time().
4697 * Returns: the newly-created timeout source
4700 g_timeout_source_new (guint interval
)
4702 GSource
*source
= g_source_new (&g_timeout_funcs
, sizeof (GTimeoutSource
));
4703 GTimeoutSource
*timeout_source
= (GTimeoutSource
*)source
;
4705 timeout_source
->interval
= interval
;
4706 g_timeout_set_expiration (timeout_source
, g_get_monotonic_time ());
4712 * g_timeout_source_new_seconds:
4713 * @interval: the timeout interval in seconds
4715 * Creates a new timeout source.
4717 * The source will not initially be associated with any #GMainContext
4718 * and must be added to one with g_source_attach() before it will be
4721 * The scheduling granularity/accuracy of this timeout source will be
4724 * The interval given in terms of monotonic time, not wall clock time.
4725 * See g_get_monotonic_time().
4727 * Returns: the newly-created timeout source
4732 g_timeout_source_new_seconds (guint interval
)
4734 GSource
*source
= g_source_new (&g_timeout_funcs
, sizeof (GTimeoutSource
));
4735 GTimeoutSource
*timeout_source
= (GTimeoutSource
*)source
;
4737 timeout_source
->interval
= 1000 * interval
;
4738 timeout_source
->seconds
= TRUE
;
4740 g_timeout_set_expiration (timeout_source
, g_get_monotonic_time ());
4747 * g_timeout_add_full: (rename-to g_timeout_add)
4748 * @priority: the priority of the timeout source. Typically this will be in
4749 * the range between #G_PRIORITY_DEFAULT and #G_PRIORITY_HIGH.
4750 * @interval: the time between calls to the function, in milliseconds
4751 * (1/1000ths of a second)
4752 * @function: function to call
4753 * @data: data to pass to @function
4754 * @notify: (nullable): function to call when the timeout is removed, or %NULL
4756 * Sets a function to be called at regular intervals, with the given
4757 * priority. The function is called repeatedly until it returns
4758 * %FALSE, at which point the timeout is automatically destroyed and
4759 * the function will not be called again. The @notify function is
4760 * called when the timeout is destroyed. The first call to the
4761 * function will be at the end of the first @interval.
4763 * Note that timeout functions may be delayed, due to the processing of other
4764 * event sources. Thus they should not be relied on for precise timing.
4765 * After each call to the timeout function, the time of the next
4766 * timeout is recalculated based on the current time and the given interval
4767 * (it does not try to 'catch up' time lost in delays).
4769 * See [memory management of sources][mainloop-memory-management] for details
4770 * on how to handle the return value and memory management of @data.
4772 * This internally creates a main loop source using g_timeout_source_new()
4773 * and attaches it to the global #GMainContext using g_source_attach(), so
4774 * the callback will be invoked in whichever thread is running that main
4775 * context. You can do these steps manually if you need greater control or to
4776 * use a custom main context.
4778 * The interval given in terms of monotonic time, not wall clock time.
4779 * See g_get_monotonic_time().
4781 * Returns: the ID (greater than 0) of the event source.
4784 g_timeout_add_full (gint priority
,
4786 GSourceFunc function
,
4788 GDestroyNotify notify
)
4793 g_return_val_if_fail (function
!= NULL
, 0);
4795 source
= g_timeout_source_new (interval
);
4797 if (priority
!= G_PRIORITY_DEFAULT
)
4798 g_source_set_priority (source
, priority
);
4800 g_source_set_callback (source
, function
, data
, notify
);
4801 id
= g_source_attach (source
, NULL
);
4803 TRACE (GLIB_TIMEOUT_ADD (source
, g_main_context_default (), id
, priority
, interval
, function
, data
));
4805 g_source_unref (source
);
4812 * @interval: the time between calls to the function, in milliseconds
4813 * (1/1000ths of a second)
4814 * @function: function to call
4815 * @data: data to pass to @function
4817 * Sets a function to be called at regular intervals, with the default
4818 * priority, #G_PRIORITY_DEFAULT. The function is called repeatedly
4819 * until it returns %FALSE, at which point the timeout is automatically
4820 * destroyed and the function will not be called again. The first call
4821 * to the function will be at the end of the first @interval.
4823 * Note that timeout functions may be delayed, due to the processing of other
4824 * event sources. Thus they should not be relied on for precise timing.
4825 * After each call to the timeout function, the time of the next
4826 * timeout is recalculated based on the current time and the given interval
4827 * (it does not try to 'catch up' time lost in delays).
4829 * See [memory management of sources][mainloop-memory-management] for details
4830 * on how to handle the return value and memory management of @data.
4832 * If you want to have a timer in the "seconds" range and do not care
4833 * about the exact time of the first call of the timer, use the
4834 * g_timeout_add_seconds() function; this function allows for more
4835 * optimizations and more efficient system power usage.
4837 * This internally creates a main loop source using g_timeout_source_new()
4838 * and attaches it to the global #GMainContext using g_source_attach(), so
4839 * the callback will be invoked in whichever thread is running that main
4840 * context. You can do these steps manually if you need greater control or to
4841 * use a custom main context.
4843 * The interval given is in terms of monotonic time, not wall clock
4844 * time. See g_get_monotonic_time().
4846 * Returns: the ID (greater than 0) of the event source.
4849 g_timeout_add (guint32 interval
,
4850 GSourceFunc function
,
4853 return g_timeout_add_full (G_PRIORITY_DEFAULT
,
4854 interval
, function
, data
, NULL
);
4858 * g_timeout_add_seconds_full: (rename-to g_timeout_add_seconds)
4859 * @priority: the priority of the timeout source. Typically this will be in
4860 * the range between #G_PRIORITY_DEFAULT and #G_PRIORITY_HIGH.
4861 * @interval: the time between calls to the function, in seconds
4862 * @function: function to call
4863 * @data: data to pass to @function
4864 * @notify: (nullable): function to call when the timeout is removed, or %NULL
4866 * Sets a function to be called at regular intervals, with @priority.
4867 * The function is called repeatedly until it returns %FALSE, at which
4868 * point the timeout is automatically destroyed and the function will
4869 * not be called again.
4871 * Unlike g_timeout_add(), this function operates at whole second granularity.
4872 * The initial starting point of the timer is determined by the implementation
4873 * and the implementation is expected to group multiple timers together so that
4874 * they fire all at the same time.
4875 * To allow this grouping, the @interval to the first timer is rounded
4876 * and can deviate up to one second from the specified interval.
4877 * Subsequent timer iterations will generally run at the specified interval.
4879 * Note that timeout functions may be delayed, due to the processing of other
4880 * event sources. Thus they should not be relied on for precise timing.
4881 * After each call to the timeout function, the time of the next
4882 * timeout is recalculated based on the current time and the given @interval
4884 * See [memory management of sources][mainloop-memory-management] for details
4885 * on how to handle the return value and memory management of @data.
4887 * If you want timing more precise than whole seconds, use g_timeout_add()
4890 * The grouping of timers to fire at the same time results in a more power
4891 * and CPU efficient behavior so if your timer is in multiples of seconds
4892 * and you don't require the first timer exactly one second from now, the
4893 * use of g_timeout_add_seconds() is preferred over g_timeout_add().
4895 * This internally creates a main loop source using
4896 * g_timeout_source_new_seconds() and attaches it to the main loop context
4897 * using g_source_attach(). You can do these steps manually if you need
4900 * The interval given is in terms of monotonic time, not wall clock
4901 * time. See g_get_monotonic_time().
4903 * Returns: the ID (greater than 0) of the event source.
4908 g_timeout_add_seconds_full (gint priority
,
4910 GSourceFunc function
,
4912 GDestroyNotify notify
)
4917 g_return_val_if_fail (function
!= NULL
, 0);
4919 source
= g_timeout_source_new_seconds (interval
);
4921 if (priority
!= G_PRIORITY_DEFAULT
)
4922 g_source_set_priority (source
, priority
);
4924 g_source_set_callback (source
, function
, data
, notify
);
4925 id
= g_source_attach (source
, NULL
);
4926 g_source_unref (source
);
4932 * g_timeout_add_seconds:
4933 * @interval: the time between calls to the function, in seconds
4934 * @function: function to call
4935 * @data: data to pass to @function
4937 * Sets a function to be called at regular intervals with the default
4938 * priority, #G_PRIORITY_DEFAULT. The function is called repeatedly until
4939 * it returns %FALSE, at which point the timeout is automatically destroyed
4940 * and the function will not be called again.
4942 * This internally creates a main loop source using
4943 * g_timeout_source_new_seconds() and attaches it to the main loop context
4944 * using g_source_attach(). You can do these steps manually if you need
4945 * greater control. Also see g_timeout_add_seconds_full().
4947 * Note that the first call of the timer may not be precise for timeouts
4948 * of one second. If you need finer precision and have such a timeout,
4949 * you may want to use g_timeout_add() instead.
4951 * See [memory management of sources][mainloop-memory-management] for details
4952 * on how to handle the return value and memory management of @data.
4954 * The interval given is in terms of monotonic time, not wall clock
4955 * time. See g_get_monotonic_time().
4957 * Returns: the ID (greater than 0) of the event source.
4962 g_timeout_add_seconds (guint interval
,
4963 GSourceFunc function
,
4966 g_return_val_if_fail (function
!= NULL
, 0);
4968 return g_timeout_add_seconds_full (G_PRIORITY_DEFAULT
, interval
, function
, data
, NULL
);
4971 /* Child watch functions */
4976 g_child_watch_prepare (GSource
*source
,
4984 g_child_watch_check (GSource
*source
)
4986 GChildWatchSource
*child_watch_source
;
4987 gboolean child_exited
;
4989 child_watch_source
= (GChildWatchSource
*) source
;
4991 child_exited
= child_watch_source
->poll
.revents
& G_IO_IN
;
4998 * Note: We do _not_ check for the special value of STILL_ACTIVE
4999 * since we know that the process has exited and doing so runs into
5000 * problems if the child process "happens to return STILL_ACTIVE(259)"
5001 * as Microsoft's Platform SDK puts it.
5003 if (!GetExitCodeProcess (child_watch_source
->pid
, &child_status
))
5005 gchar
*emsg
= g_win32_error_message (GetLastError ());
5006 g_warning (G_STRLOC
": GetExitCodeProcess() failed: %s", emsg
);
5009 child_watch_source
->child_status
= -1;
5012 child_watch_source
->child_status
= child_status
;
5015 return child_exited
;
5019 g_child_watch_finalize (GSource
*source
)
5023 #else /* G_OS_WIN32 */
5026 wake_source (GSource
*source
)
5028 GMainContext
*context
;
5030 /* This should be thread-safe:
5032 * - if the source is currently being added to a context, that
5033 * context will be woken up anyway
5035 * - if the source is currently being destroyed, we simply need not
5038 * - the memory for the source will remain valid until after the
5039 * source finalize function was called (which would remove the
5040 * source from the global list which we are currently holding the
5043 * - the GMainContext will either be NULL or point to a live
5046 * - the GMainContext will remain valid since we hold the
5047 * main_context_list lock
5049 * Since we are holding a lot of locks here, don't try to enter any
5050 * more GMainContext functions for fear of dealock -- just hit the
5051 * GWakeup and run. Even if that's safe now, it could easily become
5052 * unsafe with some very minor changes in the future, and signal
5053 * handling is not the most well-tested codepath.
5055 G_LOCK(main_context_list
);
5056 context
= source
->context
;
5058 g_wakeup_signal (context
->wakeup
);
5059 G_UNLOCK(main_context_list
);
5063 dispatch_unix_signals_unlocked (void)
5065 gboolean pending
[NSIG
];
5069 /* clear this first incase another one arrives while we're processing */
5070 any_unix_signal_pending
= FALSE
;
5072 /* We atomically test/clear the bit from the global array in case
5073 * other signals arrive while we are dispatching.
5075 * We then can safely use our own array below without worrying about
5078 for (i
= 0; i
< NSIG
; i
++)
5080 /* Be very careful with (the volatile) unix_signal_pending.
5082 * We must ensure that it's not possible that we clear it without
5083 * handling the signal. We therefore must ensure that our pending
5084 * array has a field set (ie: we will do something about the
5085 * signal) before we clear the item in unix_signal_pending.
5087 * Note specifically: we must check _our_ array.
5089 pending
[i
] = unix_signal_pending
[i
];
5091 unix_signal_pending
[i
] = FALSE
;
5094 /* handle GChildWatchSource instances */
5095 if (pending
[SIGCHLD
])
5097 /* The only way we can do this is to scan all of the children.
5099 * The docs promise that we will not reap children that we are not
5100 * explicitly watching, so that ties our hands from calling
5101 * waitpid(-1). We also can't use siginfo's si_pid field since if
5102 * multiple SIGCHLD arrive at the same time, one of them can be
5103 * dropped (since a given UNIX signal can only be pending once).
5105 for (node
= unix_child_watches
; node
; node
= node
->next
)
5107 GChildWatchSource
*source
= node
->data
;
5109 if (!source
->child_exited
)
5114 g_assert (source
->pid
> 0);
5116 pid
= waitpid (source
->pid
, &source
->child_status
, WNOHANG
);
5119 source
->child_exited
= TRUE
;
5120 wake_source ((GSource
*) source
);
5122 else if (pid
== -1 && errno
== ECHILD
)
5124 g_warning ("GChildWatchSource: Exit status of a child process was requested but ECHILD was received by waitpid(). Most likely the process is ignoring SIGCHLD, or some other thread is invoking waitpid() with a nonpositive first argument; either behavior can break applications that use g_child_watch_add()/g_spawn_sync() either directly or indirectly.");
5125 source
->child_exited
= TRUE
;
5126 source
->child_status
= 0;
5127 wake_source ((GSource
*) source
);
5130 while (pid
== -1 && errno
== EINTR
);
5135 /* handle GUnixSignalWatchSource instances */
5136 for (node
= unix_signal_watches
; node
; node
= node
->next
)
5138 GUnixSignalWatchSource
*source
= node
->data
;
5140 if (!source
->pending
)
5142 if (pending
[source
->signum
])
5144 source
->pending
= TRUE
;
5146 wake_source ((GSource
*) source
);
5154 dispatch_unix_signals (void)
5156 G_LOCK(unix_signal_lock
);
5157 dispatch_unix_signals_unlocked ();
5158 G_UNLOCK(unix_signal_lock
);
5162 g_child_watch_prepare (GSource
*source
,
5165 GChildWatchSource
*child_watch_source
;
5167 child_watch_source
= (GChildWatchSource
*) source
;
5169 return child_watch_source
->child_exited
;
5173 g_child_watch_check (GSource
*source
)
5175 GChildWatchSource
*child_watch_source
;
5177 child_watch_source
= (GChildWatchSource
*) source
;
5179 return child_watch_source
->child_exited
;
5183 g_unix_signal_watch_prepare (GSource
*source
,
5186 GUnixSignalWatchSource
*unix_signal_source
;
5188 unix_signal_source
= (GUnixSignalWatchSource
*) source
;
5190 return unix_signal_source
->pending
;
5194 g_unix_signal_watch_check (GSource
*source
)
5196 GUnixSignalWatchSource
*unix_signal_source
;
5198 unix_signal_source
= (GUnixSignalWatchSource
*) source
;
5200 return unix_signal_source
->pending
;
5204 g_unix_signal_watch_dispatch (GSource
*source
,
5205 GSourceFunc callback
,
5208 GUnixSignalWatchSource
*unix_signal_source
;
5211 unix_signal_source
= (GUnixSignalWatchSource
*) source
;
5215 g_warning ("Unix signal source dispatched without callback\n"
5216 "You must call g_source_set_callback().");
5220 again
= (callback
) (user_data
);
5222 unix_signal_source
->pending
= FALSE
;
5228 ref_unix_signal_handler_unlocked (int signum
)
5230 /* Ensure we have the worker context */
5231 g_get_worker_context ();
5232 unix_signal_refcount
[signum
]++;
5233 if (unix_signal_refcount
[signum
] == 1)
5235 struct sigaction action
;
5236 action
.sa_handler
= g_unix_signal_handler
;
5237 sigemptyset (&action
.sa_mask
);
5239 action
.sa_flags
= SA_RESTART
| SA_NOCLDSTOP
;
5241 action
.sa_flags
= SA_NOCLDSTOP
;
5243 sigaction (signum
, &action
, NULL
);
5248 unref_unix_signal_handler_unlocked (int signum
)
5250 unix_signal_refcount
[signum
]--;
5251 if (unix_signal_refcount
[signum
] == 0)
5253 struct sigaction action
;
5254 memset (&action
, 0, sizeof (action
));
5255 action
.sa_handler
= SIG_DFL
;
5256 sigemptyset (&action
.sa_mask
);
5257 sigaction (signum
, &action
, NULL
);
5262 _g_main_create_unix_signal_watch (int signum
)
5265 GUnixSignalWatchSource
*unix_signal_source
;
5267 source
= g_source_new (&g_unix_signal_funcs
, sizeof (GUnixSignalWatchSource
));
5268 unix_signal_source
= (GUnixSignalWatchSource
*) source
;
5270 unix_signal_source
->signum
= signum
;
5271 unix_signal_source
->pending
= FALSE
;
5273 G_LOCK (unix_signal_lock
);
5274 ref_unix_signal_handler_unlocked (signum
);
5275 unix_signal_watches
= g_slist_prepend (unix_signal_watches
, unix_signal_source
);
5276 dispatch_unix_signals_unlocked ();
5277 G_UNLOCK (unix_signal_lock
);
5283 g_unix_signal_watch_finalize (GSource
*source
)
5285 GUnixSignalWatchSource
*unix_signal_source
;
5287 unix_signal_source
= (GUnixSignalWatchSource
*) source
;
5289 G_LOCK (unix_signal_lock
);
5290 unref_unix_signal_handler_unlocked (unix_signal_source
->signum
);
5291 unix_signal_watches
= g_slist_remove (unix_signal_watches
, source
);
5292 G_UNLOCK (unix_signal_lock
);
5296 g_child_watch_finalize (GSource
*source
)
5298 G_LOCK (unix_signal_lock
);
5299 unix_child_watches
= g_slist_remove (unix_child_watches
, source
);
5300 unref_unix_signal_handler_unlocked (SIGCHLD
);
5301 G_UNLOCK (unix_signal_lock
);
5304 #endif /* G_OS_WIN32 */
5307 g_child_watch_dispatch (GSource
*source
,
5308 GSourceFunc callback
,
5311 GChildWatchSource
*child_watch_source
;
5312 GChildWatchFunc child_watch_callback
= (GChildWatchFunc
) callback
;
5314 child_watch_source
= (GChildWatchSource
*) source
;
5318 g_warning ("Child watch source dispatched without callback\n"
5319 "You must call g_source_set_callback().");
5323 (child_watch_callback
) (child_watch_source
->pid
, child_watch_source
->child_status
, user_data
);
5325 /* We never keep a child watch source around as the child is gone */
5332 g_unix_signal_handler (int signum
)
5334 gint saved_errno
= errno
;
5336 unix_signal_pending
[signum
] = TRUE
;
5337 any_unix_signal_pending
= TRUE
;
5339 g_wakeup_signal (glib_worker_context
->wakeup
);
5341 errno
= saved_errno
;
5344 #endif /* !G_OS_WIN32 */
5347 * g_child_watch_source_new:
5348 * @pid: process to watch. On POSIX the positive pid of a child process. On
5349 * Windows a handle for a process (which doesn't have to be a child).
5351 * Creates a new child_watch source.
5353 * The source will not initially be associated with any #GMainContext
5354 * and must be added to one with g_source_attach() before it will be
5357 * Note that child watch sources can only be used in conjunction with
5358 * `g_spawn...` when the %G_SPAWN_DO_NOT_REAP_CHILD flag is used.
5360 * Note that on platforms where #GPid must be explicitly closed
5361 * (see g_spawn_close_pid()) @pid must not be closed while the
5362 * source is still active. Typically, you will want to call
5363 * g_spawn_close_pid() in the callback function for the source.
5365 * Note further that using g_child_watch_source_new() is not
5366 * compatible with calling `waitpid` with a nonpositive first
5367 * argument in the application. Calling waitpid() for individual
5368 * pids will still work fine.
5370 * Similarly, on POSIX platforms, the @pid passed to this function must
5371 * be greater than 0 (i.e. this function must wait for a specific child,
5372 * and cannot wait for one of many children by using a nonpositive argument).
5374 * Returns: the newly-created child watch source
5379 g_child_watch_source_new (GPid pid
)
5382 GChildWatchSource
*child_watch_source
;
5385 g_return_val_if_fail (pid
> 0, NULL
);
5388 source
= g_source_new (&g_child_watch_funcs
, sizeof (GChildWatchSource
));
5389 child_watch_source
= (GChildWatchSource
*)source
;
5391 child_watch_source
->pid
= pid
;
5394 child_watch_source
->poll
.fd
= (gintptr
) pid
;
5395 child_watch_source
->poll
.events
= G_IO_IN
;
5397 g_source_add_poll (source
, &child_watch_source
->poll
);
5398 #else /* G_OS_WIN32 */
5399 G_LOCK (unix_signal_lock
);
5400 ref_unix_signal_handler_unlocked (SIGCHLD
);
5401 unix_child_watches
= g_slist_prepend (unix_child_watches
, child_watch_source
);
5402 if (waitpid (pid
, &child_watch_source
->child_status
, WNOHANG
) > 0)
5403 child_watch_source
->child_exited
= TRUE
;
5404 G_UNLOCK (unix_signal_lock
);
5405 #endif /* G_OS_WIN32 */
5411 * g_child_watch_add_full: (rename-to g_child_watch_add)
5412 * @priority: the priority of the idle source. Typically this will be in the
5413 * range between #G_PRIORITY_DEFAULT_IDLE and #G_PRIORITY_HIGH_IDLE.
5414 * @pid: process to watch. On POSIX the positive pid of a child process. On
5415 * Windows a handle for a process (which doesn't have to be a child).
5416 * @function: function to call
5417 * @data: data to pass to @function
5418 * @notify: (nullable): function to call when the idle is removed, or %NULL
5420 * Sets a function to be called when the child indicated by @pid
5421 * exits, at the priority @priority.
5423 * If you obtain @pid from g_spawn_async() or g_spawn_async_with_pipes()
5424 * you will need to pass #G_SPAWN_DO_NOT_REAP_CHILD as flag to
5425 * the spawn function for the child watching to work.
5427 * In many programs, you will want to call g_spawn_check_exit_status()
5428 * in the callback to determine whether or not the child exited
5431 * Also, note that on platforms where #GPid must be explicitly closed
5432 * (see g_spawn_close_pid()) @pid must not be closed while the source
5433 * is still active. Typically, you should invoke g_spawn_close_pid()
5434 * in the callback function for the source.
5436 * GLib supports only a single callback per process id.
5438 * This internally creates a main loop source using
5439 * g_child_watch_source_new() and attaches it to the main loop context
5440 * using g_source_attach(). You can do these steps manually if you
5441 * need greater control.
5443 * Returns: the ID (greater than 0) of the event source.
5448 g_child_watch_add_full (gint priority
,
5450 GChildWatchFunc function
,
5452 GDestroyNotify notify
)
5457 g_return_val_if_fail (function
!= NULL
, 0);
5459 g_return_val_if_fail (pid
> 0, 0);
5462 source
= g_child_watch_source_new (pid
);
5464 if (priority
!= G_PRIORITY_DEFAULT
)
5465 g_source_set_priority (source
, priority
);
5467 g_source_set_callback (source
, (GSourceFunc
) function
, data
, notify
);
5468 id
= g_source_attach (source
, NULL
);
5469 g_source_unref (source
);
5475 * g_child_watch_add:
5476 * @pid: process id to watch. On POSIX the positive pid of a child
5477 * process. On Windows a handle for a process (which doesn't have to be
5479 * @function: function to call
5480 * @data: data to pass to @function
5482 * Sets a function to be called when the child indicated by @pid
5483 * exits, at a default priority, #G_PRIORITY_DEFAULT.
5485 * If you obtain @pid from g_spawn_async() or g_spawn_async_with_pipes()
5486 * you will need to pass #G_SPAWN_DO_NOT_REAP_CHILD as flag to
5487 * the spawn function for the child watching to work.
5489 * Note that on platforms where #GPid must be explicitly closed
5490 * (see g_spawn_close_pid()) @pid must not be closed while the
5491 * source is still active. Typically, you will want to call
5492 * g_spawn_close_pid() in the callback function for the source.
5494 * GLib supports only a single callback per process id.
5496 * This internally creates a main loop source using
5497 * g_child_watch_source_new() and attaches it to the main loop context
5498 * using g_source_attach(). You can do these steps manually if you
5499 * need greater control.
5501 * Returns: the ID (greater than 0) of the event source.
5506 g_child_watch_add (GPid pid
,
5507 GChildWatchFunc function
,
5510 return g_child_watch_add_full (G_PRIORITY_DEFAULT
, pid
, function
, data
, NULL
);
5514 /* Idle functions */
5517 g_idle_prepare (GSource
*source
,
5526 g_idle_check (GSource
*source
)
5532 g_idle_dispatch (GSource
*source
,
5533 GSourceFunc callback
,
5540 g_warning ("Idle source dispatched without callback\n"
5541 "You must call g_source_set_callback().");
5545 again
= callback (user_data
);
5547 TRACE (GLIB_IDLE_DISPATCH (source
, source
->context
, callback
, user_data
, again
));
5553 * g_idle_source_new:
5555 * Creates a new idle source.
5557 * The source will not initially be associated with any #GMainContext
5558 * and must be added to one with g_source_attach() before it will be
5559 * executed. Note that the default priority for idle sources is
5560 * %G_PRIORITY_DEFAULT_IDLE, as compared to other sources which
5561 * have a default priority of %G_PRIORITY_DEFAULT.
5563 * Returns: the newly-created idle source
5566 g_idle_source_new (void)
5570 source
= g_source_new (&g_idle_funcs
, sizeof (GSource
));
5571 g_source_set_priority (source
, G_PRIORITY_DEFAULT_IDLE
);
5577 * g_idle_add_full: (rename-to g_idle_add)
5578 * @priority: the priority of the idle source. Typically this will be in the
5579 * range between #G_PRIORITY_DEFAULT_IDLE and #G_PRIORITY_HIGH_IDLE.
5580 * @function: function to call
5581 * @data: data to pass to @function
5582 * @notify: (nullable): function to call when the idle is removed, or %NULL
5584 * Adds a function to be called whenever there are no higher priority
5585 * events pending. If the function returns %FALSE it is automatically
5586 * removed from the list of event sources and will not be called again.
5588 * See [memory management of sources][mainloop-memory-management] for details
5589 * on how to handle the return value and memory management of @data.
5591 * This internally creates a main loop source using g_idle_source_new()
5592 * and attaches it to the global #GMainContext using g_source_attach(), so
5593 * the callback will be invoked in whichever thread is running that main
5594 * context. You can do these steps manually if you need greater control or to
5595 * use a custom main context.
5597 * Returns: the ID (greater than 0) of the event source.
5600 g_idle_add_full (gint priority
,
5601 GSourceFunc function
,
5603 GDestroyNotify notify
)
5608 g_return_val_if_fail (function
!= NULL
, 0);
5610 source
= g_idle_source_new ();
5612 if (priority
!= G_PRIORITY_DEFAULT_IDLE
)
5613 g_source_set_priority (source
, priority
);
5615 g_source_set_callback (source
, function
, data
, notify
);
5616 id
= g_source_attach (source
, NULL
);
5618 TRACE (GLIB_IDLE_ADD (source
, g_main_context_default (), id
, priority
, function
, data
));
5620 g_source_unref (source
);
5627 * @function: function to call
5628 * @data: data to pass to @function.
5630 * Adds a function to be called whenever there are no higher priority
5631 * events pending to the default main loop. The function is given the
5632 * default idle priority, #G_PRIORITY_DEFAULT_IDLE. If the function
5633 * returns %FALSE it is automatically removed from the list of event
5634 * sources and will not be called again.
5636 * See [memory management of sources][mainloop-memory-management] for details
5637 * on how to handle the return value and memory management of @data.
5639 * This internally creates a main loop source using g_idle_source_new()
5640 * and attaches it to the global #GMainContext using g_source_attach(), so
5641 * the callback will be invoked in whichever thread is running that main
5642 * context. You can do these steps manually if you need greater control or to
5643 * use a custom main context.
5645 * Returns: the ID (greater than 0) of the event source.
5648 g_idle_add (GSourceFunc function
,
5651 return g_idle_add_full (G_PRIORITY_DEFAULT_IDLE
, function
, data
, NULL
);
5655 * g_idle_remove_by_data:
5656 * @data: the data for the idle source's callback.
5658 * Removes the idle function with the given data.
5660 * Returns: %TRUE if an idle source was found and removed.
5663 g_idle_remove_by_data (gpointer data
)
5665 return g_source_remove_by_funcs_user_data (&g_idle_funcs
, data
);
5669 * g_main_context_invoke:
5670 * @context: (nullable): a #GMainContext, or %NULL
5671 * @function: function to call
5672 * @data: data to pass to @function
5674 * Invokes a function in such a way that @context is owned during the
5675 * invocation of @function.
5677 * If @context is %NULL then the global default main context — as
5678 * returned by g_main_context_default() — is used.
5680 * If @context is owned by the current thread, @function is called
5681 * directly. Otherwise, if @context is the thread-default main context
5682 * of the current thread and g_main_context_acquire() succeeds, then
5683 * @function is called and g_main_context_release() is called
5686 * In any other case, an idle source is created to call @function and
5687 * that source is attached to @context (presumably to be run in another
5688 * thread). The idle source is attached with #G_PRIORITY_DEFAULT
5689 * priority. If you want a different priority, use
5690 * g_main_context_invoke_full().
5692 * Note that, as with normal idle functions, @function should probably
5693 * return %FALSE. If it returns %TRUE, it will be continuously run in a
5694 * loop (and may prevent this call from returning).
5699 g_main_context_invoke (GMainContext
*context
,
5700 GSourceFunc function
,
5703 g_main_context_invoke_full (context
,
5705 function
, data
, NULL
);
5709 * g_main_context_invoke_full:
5710 * @context: (nullable): a #GMainContext, or %NULL
5711 * @priority: the priority at which to run @function
5712 * @function: function to call
5713 * @data: data to pass to @function
5714 * @notify: (nullable): a function to call when @data is no longer in use, or %NULL.
5716 * Invokes a function in such a way that @context is owned during the
5717 * invocation of @function.
5719 * This function is the same as g_main_context_invoke() except that it
5720 * lets you specify the priority incase @function ends up being
5721 * scheduled as an idle and also lets you give a #GDestroyNotify for @data.
5723 * @notify should not assume that it is called from any particular
5724 * thread or with any particular context acquired.
5729 g_main_context_invoke_full (GMainContext
*context
,
5731 GSourceFunc function
,
5733 GDestroyNotify notify
)
5735 g_return_if_fail (function
!= NULL
);
5738 context
= g_main_context_default ();
5740 if (g_main_context_is_owner (context
))
5742 while (function (data
));
5749 GMainContext
*thread_default
;
5751 thread_default
= g_main_context_get_thread_default ();
5753 if (!thread_default
)
5754 thread_default
= g_main_context_default ();
5756 if (thread_default
== context
&& g_main_context_acquire (context
))
5758 while (function (data
));
5760 g_main_context_release (context
);
5769 source
= g_idle_source_new ();
5770 g_source_set_priority (source
, priority
);
5771 g_source_set_callback (source
, function
, data
, notify
);
5772 g_source_attach (source
, context
);
5773 g_source_unref (source
);
5779 glib_worker_main (gpointer data
)
5783 g_main_context_iteration (glib_worker_context
, TRUE
);
5786 if (any_unix_signal_pending
)
5787 dispatch_unix_signals ();
5791 return NULL
; /* worst GCC warning message ever... */
5795 g_get_worker_context (void)
5797 static gsize initialised
;
5799 if (g_once_init_enter (&initialised
))
5801 /* mask all signals in the worker thread */
5807 pthread_sigmask (SIG_SETMASK
, &all
, &prev_mask
);
5809 glib_worker_context
= g_main_context_new ();
5810 g_thread_new ("gmain", glib_worker_main
, NULL
);
5812 pthread_sigmask (SIG_SETMASK
, &prev_mask
, NULL
);
5814 g_once_init_leave (&initialised
, TRUE
);
5817 return glib_worker_context
;