1 /* GLIB - Library of useful routines for C programming
2 * Copyright (C) 1995-1997 Peter Mattis, Spencer Kimball and Josh MacDonald
4 * gmain.c: Main loop abstraction, timeouts, and idle functions
5 * Copyright 1998 Owen Taylor
7 * This library is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU Lesser General Public
9 * License as published by the Free Software Foundation; either
10 * version 2.1 of the License, or (at your option) any later version.
12 * This library is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 * Lesser General Public License for more details.
17 * You should have received a copy of the GNU Lesser General Public
18 * License along with this library; if not, see <http://www.gnu.org/licenses/>.
22 * Modified by the GLib Team and others 1997-2000. See the AUTHORS
23 * file for a list of people on the GLib Team. See the ChangeLog
24 * files for a list of changes. These files are distributed with
25 * GLib at ftp://ftp.gtk.org/pub/gtk/.
33 #include "glibconfig.h"
34 #include "glib_trace.h"
36 /* Uncomment the next line (and the corresponding line in gpoll.c) to
37 * enable debugging printouts if the environment variable
38 * G_MAIN_POLL_DEBUG is set to some value.
40 /* #define G_MAIN_POLL_DEBUG */
43 /* Always enable debugging printout on Windows, as it is more often
46 #define G_MAIN_POLL_DEBUG
50 #include "glib-unix.h"
53 #include <sys/eventfd.h>
58 #include <sys/types.h>
61 #ifdef HAVE_SYS_TIME_H
63 #endif /* HAVE_SYS_TIME_H */
66 #endif /* G_OS_UNIX */
73 #endif /* G_OS_WIN32 */
75 #ifdef HAVE_MACH_MACH_TIME_H
76 #include <mach/mach_time.h>
79 #include "glib_trace.h"
84 #include "giochannel.h"
88 #include "gstrfuncs.h"
89 #include "gtestutils.h"
95 #ifdef G_MAIN_POLL_DEBUG
100 #include "gmain-internal.h"
101 #include "glib-init.h"
102 #include "glib-private.h"
106 * @title: The Main Event Loop
107 * @short_description: manages all available sources of events
109 * The main event loop manages all the available sources of events for
110 * GLib and GTK+ applications. These events can come from any number of
111 * different types of sources such as file descriptors (plain files,
112 * pipes or sockets) and timeouts. New types of event sources can also
113 * be added using g_source_attach().
115 * To allow multiple independent sets of sources to be handled in
116 * different threads, each source is associated with a #GMainContext.
117 * A GMainContext can only be running in a single thread, but
118 * sources can be added to it and removed from it from other threads.
120 * Each event source is assigned a priority. The default priority,
121 * #G_PRIORITY_DEFAULT, is 0. Values less than 0 denote higher priorities.
122 * Values greater than 0 denote lower priorities. Events from high priority
123 * sources are always processed before events from lower priority sources.
125 * Idle functions can also be added, and assigned a priority. These will
126 * be run whenever no events with a higher priority are ready to be processed.
128 * The #GMainLoop data type represents a main event loop. A GMainLoop is
129 * created with g_main_loop_new(). After adding the initial event sources,
130 * g_main_loop_run() is called. This continuously checks for new events from
131 * each of the event sources and dispatches them. Finally, the processing of
132 * an event from one of the sources leads to a call to g_main_loop_quit() to
133 * exit the main loop, and g_main_loop_run() returns.
135 * It is possible to create new instances of #GMainLoop recursively.
136 * This is often used in GTK+ applications when showing modal dialog
137 * boxes. Note that event sources are associated with a particular
138 * #GMainContext, and will be checked and dispatched for all main
139 * loops associated with that GMainContext.
141 * GTK+ contains wrappers of some of these functions, e.g. gtk_main(),
142 * gtk_main_quit() and gtk_events_pending().
144 * ## Creating new source types
146 * One of the unusual features of the #GMainLoop functionality
147 * is that new types of event source can be created and used in
148 * addition to the builtin type of event source. A new event source
149 * type is used for handling GDK events. A new source type is created
150 * by "deriving" from the #GSource structure. The derived type of
151 * source is represented by a structure that has the #GSource structure
152 * as a first element, and other elements specific to the new source
153 * type. To create an instance of the new source type, call
154 * g_source_new() passing in the size of the derived structure and
155 * a table of functions. These #GSourceFuncs determine the behavior of
156 * the new source type.
158 * New source types basically interact with the main context
159 * in two ways. Their prepare function in #GSourceFuncs can set a timeout
160 * to determine the maximum amount of time that the main loop will sleep
161 * before checking the source again. In addition, or as well, the source
162 * can add file descriptors to the set that the main context checks using
163 * g_source_add_poll().
165 * ## Customizing the main loop iteration
167 * Single iterations of a #GMainContext can be run with
168 * g_main_context_iteration(). In some cases, more detailed control
169 * of exactly how the details of the main loop work is desired, for
170 * instance, when integrating the #GMainLoop with an external main loop.
171 * In such cases, you can call the component functions of
172 * g_main_context_iteration() directly. These functions are
173 * g_main_context_prepare(), g_main_context_query(),
174 * g_main_context_check() and g_main_context_dispatch().
176 * ## State of a Main Context # {#mainloop-states}
178 * The operation of these functions can best be seen in terms
179 * of a state diagram, as shown in this image.
181 * ![](mainloop-states.gif)
183 * On UNIX, the GLib mainloop is incompatible with fork(). Any program
184 * using the mainloop must either exec() or exit() from the child
185 * without returning to the mainloop.
187 * ## Memory management of sources # {#mainloop-memory-management}
189 * There are two options for memory management of the user data passed to a
190 * #GSource to be passed to its callback on invocation. This data is provided
191 * in calls to g_timeout_add(), g_timeout_add_full(), g_idle_add(), etc. and
192 * more generally, using g_source_set_callback(). This data is typically an
193 * object which ‘owns’ the timeout or idle callback, such as a widget or a
194 * network protocol implementation. In many cases, it is an error for the
195 * callback to be invoked after this owning object has been destroyed, as that
196 * results in use of freed memory.
198 * The first, and preferred, option is to store the source ID returned by
199 * functions such as g_timeout_add() or g_source_attach(), and explicitly
200 * remove that source from the main context using g_source_remove() when the
201 * owning object is finalized. This ensures that the callback can only be
202 * invoked while the object is still alive.
204 * The second option is to hold a strong reference to the object in the
205 * callback, and to release it in the callback’s #GDestroyNotify. This ensures
206 * that the object is kept alive until after the source is finalized, which is
207 * guaranteed to be after it is invoked for the final time. The #GDestroyNotify
208 * is another callback passed to the ‘full’ variants of #GSource functions (for
209 * example, g_timeout_add_full()). It is called when the source is finalized,
210 * and is designed for releasing references like this.
212 * One important caveat of this second approach is that it will keep the object
213 * alive indefinitely if the main loop is stopped before the #GSource is
214 * invoked, which may be undesirable.
219 typedef struct _GTimeoutSource GTimeoutSource
;
220 typedef struct _GChildWatchSource GChildWatchSource
;
221 typedef struct _GUnixSignalWatchSource GUnixSignalWatchSource
;
222 typedef struct _GPollRec GPollRec
;
223 typedef struct _GSourceCallback GSourceCallback
;
227 G_SOURCE_READY
= 1 << G_HOOK_FLAG_USER_SHIFT
,
228 G_SOURCE_CAN_RECURSE
= 1 << (G_HOOK_FLAG_USER_SHIFT
+ 1),
229 G_SOURCE_BLOCKED
= 1 << (G_HOOK_FLAG_USER_SHIFT
+ 2)
232 typedef struct _GSourceList GSourceList
;
236 GSource
*head
, *tail
;
240 typedef struct _GMainWaiter GMainWaiter
;
248 typedef struct _GMainDispatch GMainDispatch
;
250 struct _GMainDispatch
256 #ifdef G_MAIN_POLL_DEBUG
257 gboolean _g_main_poll_debug
= FALSE
;
262 /* The following lock is used for both the list of sources
263 * and the list of poll records
271 volatile gint ref_count
;
273 GHashTable
*sources
; /* guint -> GSource */
275 GPtrArray
*pending_dispatches
;
276 gint timeout
; /* Timeout for current iteration */
280 gboolean in_check_or_prepare
;
281 gboolean need_wakeup
;
283 GPollRec
*poll_records
;
284 guint n_poll_records
;
285 GPollFD
*cached_poll_array
;
286 guint cached_poll_array_size
;
292 /* Flag indicating whether the set of fd's changed during a poll */
293 gboolean poll_changed
;
298 gboolean time_is_fresh
;
301 struct _GSourceCallback
303 volatile gint ref_count
;
306 GDestroyNotify notify
;
311 GMainContext
*context
;
313 volatile gint ref_count
;
316 struct _GTimeoutSource
323 struct _GChildWatchSource
330 #else /* G_OS_WIN32 */
331 gboolean child_exited
;
332 #endif /* G_OS_WIN32 */
335 struct _GUnixSignalWatchSource
350 struct _GSourcePrivate
352 GSList
*child_sources
;
353 GSource
*parent_source
;
357 /* This is currently only used on UNIX, but we always declare it (and
358 * let it remain empty on Windows) to avoid #ifdef all over the place.
363 typedef struct _GSourceIter
365 GMainContext
*context
;
371 #define LOCK_CONTEXT(context) g_mutex_lock (&context->mutex)
372 #define UNLOCK_CONTEXT(context) g_mutex_unlock (&context->mutex)
373 #define G_THREAD_SELF g_thread_self ()
375 #define SOURCE_DESTROYED(source) (((source)->flags & G_HOOK_FLAG_ACTIVE) == 0)
376 #define SOURCE_BLOCKED(source) (((source)->flags & G_SOURCE_BLOCKED) != 0)
378 #define SOURCE_UNREF(source, context) \
380 if ((source)->ref_count > 1) \
381 (source)->ref_count--; \
383 g_source_unref_internal ((source), (context), TRUE); \
387 /* Forward declarations */
389 static void g_source_unref_internal (GSource
*source
,
390 GMainContext
*context
,
392 static void g_source_destroy_internal (GSource
*source
,
393 GMainContext
*context
,
395 static void g_source_set_priority_unlocked (GSource
*source
,
396 GMainContext
*context
,
398 static void g_child_source_remove_internal (GSource
*child_source
,
399 GMainContext
*context
);
401 static void g_main_context_poll (GMainContext
*context
,
406 static void g_main_context_add_poll_unlocked (GMainContext
*context
,
409 static void g_main_context_remove_poll_unlocked (GMainContext
*context
,
412 static void g_source_iter_init (GSourceIter
*iter
,
413 GMainContext
*context
,
414 gboolean may_modify
);
415 static gboolean
g_source_iter_next (GSourceIter
*iter
,
417 static void g_source_iter_clear (GSourceIter
*iter
);
419 static gboolean
g_timeout_dispatch (GSource
*source
,
420 GSourceFunc callback
,
422 static gboolean
g_child_watch_prepare (GSource
*source
,
424 static gboolean
g_child_watch_check (GSource
*source
);
425 static gboolean
g_child_watch_dispatch (GSource
*source
,
426 GSourceFunc callback
,
428 static void g_child_watch_finalize (GSource
*source
);
430 static void g_unix_signal_handler (int signum
);
431 static gboolean
g_unix_signal_watch_prepare (GSource
*source
,
433 static gboolean
g_unix_signal_watch_check (GSource
*source
);
434 static gboolean
g_unix_signal_watch_dispatch (GSource
*source
,
435 GSourceFunc callback
,
437 static void g_unix_signal_watch_finalize (GSource
*source
);
439 static gboolean
g_idle_prepare (GSource
*source
,
441 static gboolean
g_idle_check (GSource
*source
);
442 static gboolean
g_idle_dispatch (GSource
*source
,
443 GSourceFunc callback
,
446 static void block_source (GSource
*source
);
448 static GMainContext
*glib_worker_context
;
450 G_LOCK_DEFINE_STATIC (main_loop
);
451 static GMainContext
*default_main_context
;
456 /* UNIX signals work by marking one of these variables then waking the
457 * worker context to check on them and dispatch accordingly.
459 #ifdef HAVE_SIG_ATOMIC_T
460 static volatile sig_atomic_t unix_signal_pending
[NSIG
];
461 static volatile sig_atomic_t any_unix_signal_pending
;
463 static volatile int unix_signal_pending
[NSIG
];
464 static volatile int any_unix_signal_pending
;
466 static volatile guint unix_signal_refcount
[NSIG
];
468 /* Guards all the data below */
469 G_LOCK_DEFINE_STATIC (unix_signal_lock
);
470 static GSList
*unix_signal_watches
;
471 static GSList
*unix_child_watches
;
473 GSourceFuncs g_unix_signal_funcs
=
475 g_unix_signal_watch_prepare
,
476 g_unix_signal_watch_check
,
477 g_unix_signal_watch_dispatch
,
478 g_unix_signal_watch_finalize
480 #endif /* !G_OS_WIN32 */
481 G_LOCK_DEFINE_STATIC (main_context_list
);
482 static GSList
*main_context_list
= NULL
;
484 GSourceFuncs g_timeout_funcs
=
492 GSourceFuncs g_child_watch_funcs
=
494 g_child_watch_prepare
,
496 g_child_watch_dispatch
,
497 g_child_watch_finalize
500 GSourceFuncs g_idle_funcs
=
509 * g_main_context_ref:
510 * @context: a #GMainContext
512 * Increases the reference count on a #GMainContext object by one.
514 * Returns: the @context that was passed in (since 2.6)
517 g_main_context_ref (GMainContext
*context
)
519 g_return_val_if_fail (context
!= NULL
, NULL
);
520 g_return_val_if_fail (g_atomic_int_get (&context
->ref_count
) > 0, NULL
);
522 g_atomic_int_inc (&context
->ref_count
);
528 poll_rec_list_free (GMainContext
*context
,
531 g_slice_free_chain (GPollRec
, list
, next
);
535 * g_main_context_unref:
536 * @context: a #GMainContext
538 * Decreases the reference count on a #GMainContext object by one. If
539 * the result is zero, free the context and free all associated memory.
542 g_main_context_unref (GMainContext
*context
)
550 g_return_if_fail (context
!= NULL
);
551 g_return_if_fail (g_atomic_int_get (&context
->ref_count
) > 0);
553 if (!g_atomic_int_dec_and_test (&context
->ref_count
))
556 G_LOCK (main_context_list
);
557 main_context_list
= g_slist_remove (main_context_list
, context
);
558 G_UNLOCK (main_context_list
);
560 /* Free pending dispatches */
561 for (i
= 0; i
< context
->pending_dispatches
->len
; i
++)
562 g_source_unref_internal (context
->pending_dispatches
->pdata
[i
], context
, FALSE
);
564 /* g_source_iter_next() assumes the context is locked. */
565 LOCK_CONTEXT (context
);
566 g_source_iter_init (&iter
, context
, TRUE
);
567 while (g_source_iter_next (&iter
, &source
))
569 source
->context
= NULL
;
570 g_source_destroy_internal (source
, context
, TRUE
);
572 UNLOCK_CONTEXT (context
);
574 for (sl_iter
= context
->source_lists
; sl_iter
; sl_iter
= sl_iter
->next
)
576 list
= sl_iter
->data
;
577 g_slice_free (GSourceList
, list
);
579 g_list_free (context
->source_lists
);
581 g_hash_table_destroy (context
->sources
);
583 g_mutex_clear (&context
->mutex
);
585 g_ptr_array_free (context
->pending_dispatches
, TRUE
);
586 g_free (context
->cached_poll_array
);
588 poll_rec_list_free (context
, context
->poll_records
);
590 g_wakeup_free (context
->wakeup
);
591 g_cond_clear (&context
->cond
);
596 /* Helper function used by mainloop/overflow test.
599 g_main_context_new_with_next_id (guint next_id
)
601 GMainContext
*ret
= g_main_context_new ();
603 ret
->next_id
= next_id
;
609 * g_main_context_new:
611 * Creates a new #GMainContext structure.
613 * Returns: the new #GMainContext
616 g_main_context_new (void)
618 static gsize initialised
;
619 GMainContext
*context
;
621 if (g_once_init_enter (&initialised
))
623 #ifdef G_MAIN_POLL_DEBUG
624 if (getenv ("G_MAIN_POLL_DEBUG") != NULL
)
625 _g_main_poll_debug
= TRUE
;
628 g_once_init_leave (&initialised
, TRUE
);
631 context
= g_new0 (GMainContext
, 1);
633 TRACE (GLIB_MAIN_CONTEXT_NEW (context
));
635 g_mutex_init (&context
->mutex
);
636 g_cond_init (&context
->cond
);
638 context
->sources
= g_hash_table_new (NULL
, NULL
);
639 context
->owner
= NULL
;
640 context
->waiters
= NULL
;
642 context
->ref_count
= 1;
644 context
->next_id
= 1;
646 context
->source_lists
= NULL
;
648 context
->poll_func
= g_poll
;
650 context
->cached_poll_array
= NULL
;
651 context
->cached_poll_array_size
= 0;
653 context
->pending_dispatches
= g_ptr_array_new ();
655 context
->need_wakeup
= FALSE
;
656 context
->time_is_fresh
= FALSE
;
658 context
->wakeup
= g_wakeup_new ();
659 g_wakeup_get_pollfd (context
->wakeup
, &context
->wake_up_rec
);
660 g_main_context_add_poll_unlocked (context
, 0, &context
->wake_up_rec
);
662 G_LOCK (main_context_list
);
663 main_context_list
= g_slist_append (main_context_list
, context
);
665 #ifdef G_MAIN_POLL_DEBUG
666 if (_g_main_poll_debug
)
667 g_print ("created context=%p\n", context
);
670 G_UNLOCK (main_context_list
);
676 * g_main_context_default:
678 * Returns the global default main context. This is the main context
679 * used for main loop functions when a main loop is not explicitly
680 * specified, and corresponds to the "main" main loop. See also
681 * g_main_context_get_thread_default().
683 * Returns: (transfer none): the global default main context.
686 g_main_context_default (void)
692 if (!default_main_context
)
694 default_main_context
= g_main_context_new ();
696 TRACE (GLIB_MAIN_CONTEXT_DEFAULT (default_main_context
));
698 #ifdef G_MAIN_POLL_DEBUG
699 if (_g_main_poll_debug
)
700 g_print ("default context=%p\n", default_main_context
);
704 G_UNLOCK (main_loop
);
706 return default_main_context
;
710 free_context (gpointer data
)
712 GMainContext
*context
= data
;
714 TRACE (GLIB_MAIN_CONTEXT_FREE (context
));
716 g_main_context_release (context
);
718 g_main_context_unref (context
);
722 free_context_stack (gpointer data
)
724 g_queue_free_full((GQueue
*) data
, (GDestroyNotify
) free_context
);
727 static GPrivate thread_context_stack
= G_PRIVATE_INIT (free_context_stack
);
730 * g_main_context_push_thread_default:
731 * @context: (nullable): a #GMainContext, or %NULL for the global default context
733 * Acquires @context and sets it as the thread-default context for the
734 * current thread. This will cause certain asynchronous operations
735 * (such as most [gio][gio]-based I/O) which are
736 * started in this thread to run under @context and deliver their
737 * results to its main loop, rather than running under the global
738 * default context in the main thread. Note that calling this function
739 * changes the context returned by g_main_context_get_thread_default(),
740 * not the one returned by g_main_context_default(), so it does not affect
741 * the context used by functions like g_idle_add().
743 * Normally you would call this function shortly after creating a new
744 * thread, passing it a #GMainContext which will be run by a
745 * #GMainLoop in that thread, to set a new default context for all
746 * async operations in that thread. In this case you may not need to
747 * ever call g_main_context_pop_thread_default(), assuming you want the
748 * new #GMainContext to be the default for the whole lifecycle of the
751 * If you don't have control over how the new thread was created (e.g.
752 * in the new thread isn't newly created, or if the thread life
753 * cycle is managed by a #GThreadPool), it is always suggested to wrap
754 * the logic that needs to use the new #GMainContext inside a
755 * g_main_context_push_thread_default() / g_main_context_pop_thread_default()
756 * pair, otherwise threads that are re-used will end up never explicitly
757 * releasing the #GMainContext reference they hold.
759 * In some cases you may want to schedule a single operation in a
760 * non-default context, or temporarily use a non-default context in
761 * the main thread. In that case, you can wrap the call to the
762 * asynchronous operation inside a
763 * g_main_context_push_thread_default() /
764 * g_main_context_pop_thread_default() pair, but it is up to you to
765 * ensure that no other asynchronous operations accidentally get
766 * started while the non-default context is active.
768 * Beware that libraries that predate this function may not correctly
769 * handle being used from a thread with a thread-default context. Eg,
770 * see g_file_supports_thread_contexts().
775 g_main_context_push_thread_default (GMainContext
*context
)
778 gboolean acquired_context
;
780 acquired_context
= g_main_context_acquire (context
);
781 g_return_if_fail (acquired_context
);
783 if (context
== g_main_context_default ())
786 g_main_context_ref (context
);
788 stack
= g_private_get (&thread_context_stack
);
791 stack
= g_queue_new ();
792 g_private_set (&thread_context_stack
, stack
);
795 g_queue_push_head (stack
, context
);
797 TRACE (GLIB_MAIN_CONTEXT_PUSH_THREAD_DEFAULT (context
));
801 * g_main_context_pop_thread_default:
802 * @context: (nullable): a #GMainContext object, or %NULL
804 * Pops @context off the thread-default context stack (verifying that
805 * it was on the top of the stack).
810 g_main_context_pop_thread_default (GMainContext
*context
)
814 if (context
== g_main_context_default ())
817 stack
= g_private_get (&thread_context_stack
);
819 g_return_if_fail (stack
!= NULL
);
820 g_return_if_fail (g_queue_peek_head (stack
) == context
);
822 TRACE (GLIB_MAIN_CONTEXT_POP_THREAD_DEFAULT (context
));
824 g_queue_pop_head (stack
);
826 g_main_context_release (context
);
828 g_main_context_unref (context
);
832 * g_main_context_get_thread_default:
834 * Gets the thread-default #GMainContext for this thread. Asynchronous
835 * operations that want to be able to be run in contexts other than
836 * the default one should call this method or
837 * g_main_context_ref_thread_default() to get a #GMainContext to add
838 * their #GSources to. (Note that even in single-threaded
839 * programs applications may sometimes want to temporarily push a
840 * non-default context, so it is not safe to assume that this will
841 * always return %NULL if you are running in the default thread.)
843 * If you need to hold a reference on the context, use
844 * g_main_context_ref_thread_default() instead.
846 * Returns: (transfer none): the thread-default #GMainContext, or
847 * %NULL if the thread-default context is the global default context.
852 g_main_context_get_thread_default (void)
856 stack
= g_private_get (&thread_context_stack
);
858 return g_queue_peek_head (stack
);
864 * g_main_context_ref_thread_default:
866 * Gets the thread-default #GMainContext for this thread, as with
867 * g_main_context_get_thread_default(), but also adds a reference to
868 * it with g_main_context_ref(). In addition, unlike
869 * g_main_context_get_thread_default(), if the thread-default context
870 * is the global default context, this will return that #GMainContext
871 * (with a ref added to it) rather than returning %NULL.
873 * Returns: (transfer full): the thread-default #GMainContext. Unref
874 * with g_main_context_unref() when you are done with it.
879 g_main_context_ref_thread_default (void)
881 GMainContext
*context
;
883 context
= g_main_context_get_thread_default ();
885 context
= g_main_context_default ();
886 return g_main_context_ref (context
);
889 /* Hooks for adding to the main loop */
893 * @source_funcs: structure containing functions that implement
894 * the sources behavior.
895 * @struct_size: size of the #GSource structure to create.
897 * Creates a new #GSource structure. The size is specified to
898 * allow creating structures derived from #GSource that contain
899 * additional data. The size passed in must be at least
900 * `sizeof (GSource)`.
902 * The source will not initially be associated with any #GMainContext
903 * and must be added to one with g_source_attach() before it will be
906 * Returns: the newly-created #GSource.
909 g_source_new (GSourceFuncs
*source_funcs
,
914 g_return_val_if_fail (source_funcs
!= NULL
, NULL
);
915 g_return_val_if_fail (struct_size
>= sizeof (GSource
), NULL
);
917 source
= (GSource
*) g_malloc0 (struct_size
);
918 source
->priv
= g_slice_new0 (GSourcePrivate
);
919 source
->source_funcs
= source_funcs
;
920 source
->ref_count
= 1;
922 source
->priority
= G_PRIORITY_DEFAULT
;
924 source
->flags
= G_HOOK_FLAG_ACTIVE
;
926 source
->priv
->ready_time
= -1;
928 /* NULL/0 initialization for all other fields */
930 TRACE (GLIB_SOURCE_NEW (source
, source_funcs
->prepare
, source_funcs
->check
,
931 source_funcs
->dispatch
, source_funcs
->finalize
,
937 /* Holds context's lock */
939 g_source_iter_init (GSourceIter
*iter
,
940 GMainContext
*context
,
943 iter
->context
= context
;
944 iter
->current_list
= NULL
;
946 iter
->may_modify
= may_modify
;
949 /* Holds context's lock */
951 g_source_iter_next (GSourceIter
*iter
, GSource
**source
)
953 GSource
*next_source
;
956 next_source
= iter
->source
->next
;
962 if (iter
->current_list
)
963 iter
->current_list
= iter
->current_list
->next
;
965 iter
->current_list
= iter
->context
->source_lists
;
967 if (iter
->current_list
)
969 GSourceList
*source_list
= iter
->current_list
->data
;
971 next_source
= source_list
->head
;
975 /* Note: unreffing iter->source could potentially cause its
976 * GSourceList to be removed from source_lists (if iter->source is
977 * the only source in its list, and it is destroyed), so we have to
978 * keep it reffed until after we advance iter->current_list, above.
981 if (iter
->source
&& iter
->may_modify
)
982 SOURCE_UNREF (iter
->source
, iter
->context
);
983 iter
->source
= next_source
;
984 if (iter
->source
&& iter
->may_modify
)
985 iter
->source
->ref_count
++;
987 *source
= iter
->source
;
988 return *source
!= NULL
;
991 /* Holds context's lock. Only necessary to call if you broke out of
992 * the g_source_iter_next() loop early.
995 g_source_iter_clear (GSourceIter
*iter
)
997 if (iter
->source
&& iter
->may_modify
)
999 SOURCE_UNREF (iter
->source
, iter
->context
);
1000 iter
->source
= NULL
;
1004 /* Holds context's lock
1006 static GSourceList
*
1007 find_source_list_for_priority (GMainContext
*context
,
1012 GSourceList
*source_list
;
1015 for (iter
= context
->source_lists
; iter
!= NULL
; last
= iter
, iter
= iter
->next
)
1017 source_list
= iter
->data
;
1019 if (source_list
->priority
== priority
)
1022 if (source_list
->priority
> priority
)
1027 source_list
= g_slice_new0 (GSourceList
);
1028 source_list
->priority
= priority
;
1029 context
->source_lists
= g_list_insert_before (context
->source_lists
,
1039 source_list
= g_slice_new0 (GSourceList
);
1040 source_list
->priority
= priority
;
1043 context
->source_lists
= g_list_append (NULL
, source_list
);
1046 /* This just appends source_list to the end of
1047 * context->source_lists without having to walk the list again.
1049 last
= g_list_append (last
, source_list
);
1054 /* Holds context's lock
1057 source_add_to_context (GSource
*source
,
1058 GMainContext
*context
)
1060 GSourceList
*source_list
;
1061 GSource
*prev
, *next
;
1063 source_list
= find_source_list_for_priority (context
, source
->priority
, TRUE
);
1065 if (source
->priv
->parent_source
)
1067 g_assert (source_list
->head
!= NULL
);
1069 /* Put the source immediately before its parent */
1070 prev
= source
->priv
->parent_source
->prev
;
1071 next
= source
->priv
->parent_source
;
1075 prev
= source_list
->tail
;
1079 source
->next
= next
;
1081 next
->prev
= source
;
1083 source_list
->tail
= source
;
1085 source
->prev
= prev
;
1087 prev
->next
= source
;
1089 source_list
->head
= source
;
1092 /* Holds context's lock
1095 source_remove_from_context (GSource
*source
,
1096 GMainContext
*context
)
1098 GSourceList
*source_list
;
1100 source_list
= find_source_list_for_priority (context
, source
->priority
, FALSE
);
1101 g_return_if_fail (source_list
!= NULL
);
1104 source
->prev
->next
= source
->next
;
1106 source_list
->head
= source
->next
;
1109 source
->next
->prev
= source
->prev
;
1111 source_list
->tail
= source
->prev
;
1113 source
->prev
= NULL
;
1114 source
->next
= NULL
;
1116 if (source_list
->head
== NULL
)
1118 context
->source_lists
= g_list_remove (context
->source_lists
, source_list
);
1119 g_slice_free (GSourceList
, source_list
);
1123 /* See https://bugzilla.gnome.org/show_bug.cgi?id=761102 for
1124 * the introduction of this.
1126 * The main optimization is to avoid waking up the main
1127 * context if a change is made by the current owner.
1130 conditional_wakeup (GMainContext
*context
)
1132 /* This flag is set if at the start of prepare() we have no other ready
1133 * sources, and hence would wait in poll(). In that case, any other threads
1134 * attaching sources will need to signal a wakeup.
1136 if (context
->need_wakeup
)
1137 g_wakeup_signal (context
->wakeup
);
1141 g_source_attach_unlocked (GSource
*source
,
1142 GMainContext
*context
,
1148 /* The counter may have wrapped, so we must ensure that we do not
1149 * reuse the source id of an existing source.
1152 id
= context
->next_id
++;
1153 while (id
== 0 || g_hash_table_contains (context
->sources
, GUINT_TO_POINTER (id
)));
1155 source
->context
= context
;
1156 source
->source_id
= id
;
1157 source
->ref_count
++;
1159 g_hash_table_insert (context
->sources
, GUINT_TO_POINTER (id
), source
);
1161 source_add_to_context (source
, context
);
1163 if (!SOURCE_BLOCKED (source
))
1165 tmp_list
= source
->poll_fds
;
1168 g_main_context_add_poll_unlocked (context
, source
->priority
, tmp_list
->data
);
1169 tmp_list
= tmp_list
->next
;
1172 for (tmp_list
= source
->priv
->fds
; tmp_list
; tmp_list
= tmp_list
->next
)
1173 g_main_context_add_poll_unlocked (context
, source
->priority
, tmp_list
->data
);
1176 tmp_list
= source
->priv
->child_sources
;
1179 g_source_attach_unlocked (tmp_list
->data
, context
, FALSE
);
1180 tmp_list
= tmp_list
->next
;
1183 /* If another thread has acquired the context, wake it up since it
1184 * might be in poll() right now.
1187 conditional_wakeup (context
);
1189 return source
->source_id
;
1194 * @source: a #GSource
1195 * @context: (nullable): a #GMainContext (if %NULL, the default context will be used)
1197 * Adds a #GSource to a @context so that it will be executed within
1198 * that context. Remove it by calling g_source_destroy().
1200 * Returns: the ID (greater than 0) for the source within the
1204 g_source_attach (GSource
*source
,
1205 GMainContext
*context
)
1209 g_return_val_if_fail (source
->context
== NULL
, 0);
1210 g_return_val_if_fail (!SOURCE_DESTROYED (source
), 0);
1213 context
= g_main_context_default ();
1215 LOCK_CONTEXT (context
);
1217 result
= g_source_attach_unlocked (source
, context
, TRUE
);
1219 TRACE (GLIB_MAIN_SOURCE_ATTACH (g_source_get_name (source
), source
, context
,
1222 UNLOCK_CONTEXT (context
);
1228 g_source_destroy_internal (GSource
*source
,
1229 GMainContext
*context
,
1232 TRACE (GLIB_MAIN_SOURCE_DESTROY (g_source_get_name (source
), source
,
1236 LOCK_CONTEXT (context
);
1238 if (!SOURCE_DESTROYED (source
))
1241 gpointer old_cb_data
;
1242 GSourceCallbackFuncs
*old_cb_funcs
;
1244 source
->flags
&= ~G_HOOK_FLAG_ACTIVE
;
1246 old_cb_data
= source
->callback_data
;
1247 old_cb_funcs
= source
->callback_funcs
;
1249 source
->callback_data
= NULL
;
1250 source
->callback_funcs
= NULL
;
1254 UNLOCK_CONTEXT (context
);
1255 old_cb_funcs
->unref (old_cb_data
);
1256 LOCK_CONTEXT (context
);
1259 if (!SOURCE_BLOCKED (source
))
1261 tmp_list
= source
->poll_fds
;
1264 g_main_context_remove_poll_unlocked (context
, tmp_list
->data
);
1265 tmp_list
= tmp_list
->next
;
1268 for (tmp_list
= source
->priv
->fds
; tmp_list
; tmp_list
= tmp_list
->next
)
1269 g_main_context_remove_poll_unlocked (context
, tmp_list
->data
);
1272 while (source
->priv
->child_sources
)
1273 g_child_source_remove_internal (source
->priv
->child_sources
->data
, context
);
1275 if (source
->priv
->parent_source
)
1276 g_child_source_remove_internal (source
, context
);
1278 g_source_unref_internal (source
, context
, TRUE
);
1282 UNLOCK_CONTEXT (context
);
1287 * @source: a #GSource
1289 * Removes a source from its #GMainContext, if any, and mark it as
1290 * destroyed. The source cannot be subsequently added to another
1291 * context. It is safe to call this on sources which have already been
1292 * removed from their context.
1295 g_source_destroy (GSource
*source
)
1297 GMainContext
*context
;
1299 g_return_if_fail (source
!= NULL
);
1301 context
= source
->context
;
1304 g_source_destroy_internal (source
, context
, FALSE
);
1306 source
->flags
&= ~G_HOOK_FLAG_ACTIVE
;
1311 * @source: a #GSource
1313 * Returns the numeric ID for a particular source. The ID of a source
1314 * is a positive integer which is unique within a particular main loop
1315 * context. The reverse
1316 * mapping from ID to source is done by g_main_context_find_source_by_id().
1318 * Returns: the ID (greater than 0) for the source
1321 g_source_get_id (GSource
*source
)
1325 g_return_val_if_fail (source
!= NULL
, 0);
1326 g_return_val_if_fail (source
->context
!= NULL
, 0);
1328 LOCK_CONTEXT (source
->context
);
1329 result
= source
->source_id
;
1330 UNLOCK_CONTEXT (source
->context
);
1336 * g_source_get_context:
1337 * @source: a #GSource
1339 * Gets the #GMainContext with which the source is associated.
1341 * You can call this on a source that has been destroyed, provided
1342 * that the #GMainContext it was attached to still exists (in which
1343 * case it will return that #GMainContext). In particular, you can
1344 * always call this function on the source returned from
1345 * g_main_current_source(). But calling this function on a source
1346 * whose #GMainContext has been destroyed is an error.
1348 * Returns: (transfer none) (nullable): the #GMainContext with which the
1349 * source is associated, or %NULL if the context has not
1350 * yet been added to a source.
1353 g_source_get_context (GSource
*source
)
1355 g_return_val_if_fail (source
->context
!= NULL
|| !SOURCE_DESTROYED (source
), NULL
);
1357 return source
->context
;
1361 * g_source_add_poll:
1362 * @source:a #GSource
1363 * @fd: a #GPollFD structure holding information about a file
1364 * descriptor to watch.
1366 * Adds a file descriptor to the set of file descriptors polled for
1367 * this source. This is usually combined with g_source_new() to add an
1368 * event source. The event source's check function will typically test
1369 * the @revents field in the #GPollFD struct and return %TRUE if events need
1372 * This API is only intended to be used by implementations of #GSource.
1373 * Do not call this API on a #GSource that you did not create.
1375 * Using this API forces the linear scanning of event sources on each
1376 * main loop iteration. Newly-written event sources should try to use
1377 * g_source_add_unix_fd() instead of this API.
1380 g_source_add_poll (GSource
*source
,
1383 GMainContext
*context
;
1385 g_return_if_fail (source
!= NULL
);
1386 g_return_if_fail (fd
!= NULL
);
1387 g_return_if_fail (!SOURCE_DESTROYED (source
));
1389 context
= source
->context
;
1392 LOCK_CONTEXT (context
);
1394 source
->poll_fds
= g_slist_prepend (source
->poll_fds
, fd
);
1398 if (!SOURCE_BLOCKED (source
))
1399 g_main_context_add_poll_unlocked (context
, source
->priority
, fd
);
1400 UNLOCK_CONTEXT (context
);
1405 * g_source_remove_poll:
1406 * @source:a #GSource
1407 * @fd: a #GPollFD structure previously passed to g_source_add_poll().
1409 * Removes a file descriptor from the set of file descriptors polled for
1412 * This API is only intended to be used by implementations of #GSource.
1413 * Do not call this API on a #GSource that you did not create.
1416 g_source_remove_poll (GSource
*source
,
1419 GMainContext
*context
;
1421 g_return_if_fail (source
!= NULL
);
1422 g_return_if_fail (fd
!= NULL
);
1423 g_return_if_fail (!SOURCE_DESTROYED (source
));
1425 context
= source
->context
;
1428 LOCK_CONTEXT (context
);
1430 source
->poll_fds
= g_slist_remove (source
->poll_fds
, fd
);
1434 if (!SOURCE_BLOCKED (source
))
1435 g_main_context_remove_poll_unlocked (context
, fd
);
1436 UNLOCK_CONTEXT (context
);
1441 * g_source_add_child_source:
1442 * @source:a #GSource
1443 * @child_source: a second #GSource that @source should "poll"
1445 * Adds @child_source to @source as a "polled" source; when @source is
1446 * added to a #GMainContext, @child_source will be automatically added
1447 * with the same priority, when @child_source is triggered, it will
1448 * cause @source to dispatch (in addition to calling its own
1449 * callback), and when @source is destroyed, it will destroy
1450 * @child_source as well. (@source will also still be dispatched if
1451 * its own prepare/check functions indicate that it is ready.)
1453 * If you don't need @child_source to do anything on its own when it
1454 * triggers, you can call g_source_set_dummy_callback() on it to set a
1455 * callback that does nothing (except return %TRUE if appropriate).
1457 * @source will hold a reference on @child_source while @child_source
1458 * is attached to it.
1460 * This API is only intended to be used by implementations of #GSource.
1461 * Do not call this API on a #GSource that you did not create.
1466 g_source_add_child_source (GSource
*source
,
1467 GSource
*child_source
)
1469 GMainContext
*context
;
1471 g_return_if_fail (source
!= NULL
);
1472 g_return_if_fail (child_source
!= NULL
);
1473 g_return_if_fail (!SOURCE_DESTROYED (source
));
1474 g_return_if_fail (!SOURCE_DESTROYED (child_source
));
1475 g_return_if_fail (child_source
->context
== NULL
);
1476 g_return_if_fail (child_source
->priv
->parent_source
== NULL
);
1478 context
= source
->context
;
1481 LOCK_CONTEXT (context
);
1483 TRACE (GLIB_SOURCE_ADD_CHILD_SOURCE (source
, child_source
));
1485 source
->priv
->child_sources
= g_slist_prepend (source
->priv
->child_sources
,
1486 g_source_ref (child_source
));
1487 child_source
->priv
->parent_source
= source
;
1488 g_source_set_priority_unlocked (child_source
, NULL
, source
->priority
);
1489 if (SOURCE_BLOCKED (source
))
1490 block_source (child_source
);
1494 g_source_attach_unlocked (child_source
, context
, TRUE
);
1495 UNLOCK_CONTEXT (context
);
1500 g_child_source_remove_internal (GSource
*child_source
,
1501 GMainContext
*context
)
1503 GSource
*parent_source
= child_source
->priv
->parent_source
;
1505 parent_source
->priv
->child_sources
=
1506 g_slist_remove (parent_source
->priv
->child_sources
, child_source
);
1507 child_source
->priv
->parent_source
= NULL
;
1509 g_source_destroy_internal (child_source
, context
, TRUE
);
1510 g_source_unref_internal (child_source
, context
, TRUE
);
1514 * g_source_remove_child_source:
1515 * @source:a #GSource
1516 * @child_source: a #GSource previously passed to
1517 * g_source_add_child_source().
1519 * Detaches @child_source from @source and destroys it.
1521 * This API is only intended to be used by implementations of #GSource.
1522 * Do not call this API on a #GSource that you did not create.
1527 g_source_remove_child_source (GSource
*source
,
1528 GSource
*child_source
)
1530 GMainContext
*context
;
1532 g_return_if_fail (source
!= NULL
);
1533 g_return_if_fail (child_source
!= NULL
);
1534 g_return_if_fail (child_source
->priv
->parent_source
== source
);
1535 g_return_if_fail (!SOURCE_DESTROYED (source
));
1536 g_return_if_fail (!SOURCE_DESTROYED (child_source
));
1538 context
= source
->context
;
1541 LOCK_CONTEXT (context
);
1543 g_child_source_remove_internal (child_source
, context
);
1546 UNLOCK_CONTEXT (context
);
1550 g_source_callback_ref (gpointer cb_data
)
1552 GSourceCallback
*callback
= cb_data
;
1554 g_atomic_int_inc (&callback
->ref_count
);
1558 g_source_callback_unref (gpointer cb_data
)
1560 GSourceCallback
*callback
= cb_data
;
1562 if (g_atomic_int_dec_and_test (&callback
->ref_count
))
1564 if (callback
->notify
)
1565 callback
->notify (callback
->data
);
1571 g_source_callback_get (gpointer cb_data
,
1576 GSourceCallback
*callback
= cb_data
;
1578 *func
= callback
->func
;
1579 *data
= callback
->data
;
1582 static GSourceCallbackFuncs g_source_callback_funcs
= {
1583 g_source_callback_ref
,
1584 g_source_callback_unref
,
1585 g_source_callback_get
,
1589 * g_source_set_callback_indirect:
1590 * @source: the source
1591 * @callback_data: pointer to callback data "object"
1592 * @callback_funcs: functions for reference counting @callback_data
1593 * and getting the callback and data
1595 * Sets the callback function storing the data as a refcounted callback
1596 * "object". This is used internally. Note that calling
1597 * g_source_set_callback_indirect() assumes
1598 * an initial reference count on @callback_data, and thus
1599 * @callback_funcs->unref will eventually be called once more
1600 * than @callback_funcs->ref.
1603 g_source_set_callback_indirect (GSource
*source
,
1604 gpointer callback_data
,
1605 GSourceCallbackFuncs
*callback_funcs
)
1607 GMainContext
*context
;
1608 gpointer old_cb_data
;
1609 GSourceCallbackFuncs
*old_cb_funcs
;
1611 g_return_if_fail (source
!= NULL
);
1612 g_return_if_fail (callback_funcs
!= NULL
|| callback_data
== NULL
);
1614 context
= source
->context
;
1617 LOCK_CONTEXT (context
);
1619 if (callback_funcs
!= &g_source_callback_funcs
)
1620 TRACE (GLIB_SOURCE_SET_CALLBACK_INDIRECT (source
, callback_data
,
1621 callback_funcs
->ref
,
1622 callback_funcs
->unref
,
1623 callback_funcs
->get
));
1625 old_cb_data
= source
->callback_data
;
1626 old_cb_funcs
= source
->callback_funcs
;
1628 source
->callback_data
= callback_data
;
1629 source
->callback_funcs
= callback_funcs
;
1632 UNLOCK_CONTEXT (context
);
1635 old_cb_funcs
->unref (old_cb_data
);
1639 * g_source_set_callback:
1640 * @source: the source
1641 * @func: a callback function
1642 * @data: the data to pass to callback function
1643 * @notify: (nullable): a function to call when @data is no longer in use, or %NULL.
1645 * Sets the callback function for a source. The callback for a source is
1646 * called from the source's dispatch function.
1648 * The exact type of @func depends on the type of source; ie. you
1649 * should not count on @func being called with @data as its first
1652 * See [memory management of sources][mainloop-memory-management] for details
1653 * on how to handle memory management of @data.
1655 * Typically, you won't use this function. Instead use functions specific
1656 * to the type of source you are using.
1659 g_source_set_callback (GSource
*source
,
1662 GDestroyNotify notify
)
1664 GSourceCallback
*new_callback
;
1666 g_return_if_fail (source
!= NULL
);
1668 TRACE (GLIB_SOURCE_SET_CALLBACK (source
, func
, data
, notify
));
1670 new_callback
= g_new (GSourceCallback
, 1);
1672 new_callback
->ref_count
= 1;
1673 new_callback
->func
= func
;
1674 new_callback
->data
= data
;
1675 new_callback
->notify
= notify
;
1677 g_source_set_callback_indirect (source
, new_callback
, &g_source_callback_funcs
);
1682 * g_source_set_funcs:
1683 * @source: a #GSource
1684 * @funcs: the new #GSourceFuncs
1686 * Sets the source functions (can be used to override
1687 * default implementations) of an unattached source.
1692 g_source_set_funcs (GSource
*source
,
1693 GSourceFuncs
*funcs
)
1695 g_return_if_fail (source
!= NULL
);
1696 g_return_if_fail (source
->context
== NULL
);
1697 g_return_if_fail (source
->ref_count
> 0);
1698 g_return_if_fail (funcs
!= NULL
);
1700 source
->source_funcs
= funcs
;
1704 g_source_set_priority_unlocked (GSource
*source
,
1705 GMainContext
*context
,
1710 g_return_if_fail (source
->priv
->parent_source
== NULL
||
1711 source
->priv
->parent_source
->priority
== priority
);
1713 TRACE (GLIB_SOURCE_SET_PRIORITY (source
, context
, priority
));
1717 /* Remove the source from the context's source and then
1718 * add it back after so it is sorted in the correct place
1720 source_remove_from_context (source
, source
->context
);
1723 source
->priority
= priority
;
1727 source_add_to_context (source
, source
->context
);
1729 if (!SOURCE_BLOCKED (source
))
1731 tmp_list
= source
->poll_fds
;
1734 g_main_context_remove_poll_unlocked (context
, tmp_list
->data
);
1735 g_main_context_add_poll_unlocked (context
, priority
, tmp_list
->data
);
1737 tmp_list
= tmp_list
->next
;
1740 for (tmp_list
= source
->priv
->fds
; tmp_list
; tmp_list
= tmp_list
->next
)
1742 g_main_context_remove_poll_unlocked (context
, tmp_list
->data
);
1743 g_main_context_add_poll_unlocked (context
, priority
, tmp_list
->data
);
1748 if (source
->priv
->child_sources
)
1750 tmp_list
= source
->priv
->child_sources
;
1753 g_source_set_priority_unlocked (tmp_list
->data
, context
, priority
);
1754 tmp_list
= tmp_list
->next
;
1760 * g_source_set_priority:
1761 * @source: a #GSource
1762 * @priority: the new priority.
1764 * Sets the priority of a source. While the main loop is being run, a
1765 * source will be dispatched if it is ready to be dispatched and no
1766 * sources at a higher (numerically smaller) priority are ready to be
1769 * A child source always has the same priority as its parent. It is not
1770 * permitted to change the priority of a source once it has been added
1771 * as a child of another source.
1774 g_source_set_priority (GSource
*source
,
1777 GMainContext
*context
;
1779 g_return_if_fail (source
!= NULL
);
1780 g_return_if_fail (source
->priv
->parent_source
== NULL
);
1782 context
= source
->context
;
1785 LOCK_CONTEXT (context
);
1786 g_source_set_priority_unlocked (source
, context
, priority
);
1788 UNLOCK_CONTEXT (context
);
1792 * g_source_get_priority:
1793 * @source: a #GSource
1795 * Gets the priority of a source.
1797 * Returns: the priority of the source
1800 g_source_get_priority (GSource
*source
)
1802 g_return_val_if_fail (source
!= NULL
, 0);
1804 return source
->priority
;
1808 * g_source_set_ready_time:
1809 * @source: a #GSource
1810 * @ready_time: the monotonic time at which the source will be ready,
1811 * 0 for "immediately", -1 for "never"
1813 * Sets a #GSource to be dispatched when the given monotonic time is
1814 * reached (or passed). If the monotonic time is in the past (as it
1815 * always will be if @ready_time is 0) then the source will be
1816 * dispatched immediately.
1818 * If @ready_time is -1 then the source is never woken up on the basis
1819 * of the passage of time.
1821 * Dispatching the source does not reset the ready time. You should do
1822 * so yourself, from the source dispatch function.
1824 * Note that if you have a pair of sources where the ready time of one
1825 * suggests that it will be delivered first but the priority for the
1826 * other suggests that it would be delivered first, and the ready time
1827 * for both sources is reached during the same main context iteration,
1828 * then the order of dispatch is undefined.
1830 * It is a no-op to call this function on a #GSource which has already been
1831 * destroyed with g_source_destroy().
1833 * This API is only intended to be used by implementations of #GSource.
1834 * Do not call this API on a #GSource that you did not create.
1839 g_source_set_ready_time (GSource
*source
,
1842 GMainContext
*context
;
1844 g_return_if_fail (source
!= NULL
);
1845 g_return_if_fail (source
->ref_count
> 0);
1847 if (source
->priv
->ready_time
== ready_time
)
1850 context
= source
->context
;
1853 LOCK_CONTEXT (context
);
1855 source
->priv
->ready_time
= ready_time
;
1857 TRACE (GLIB_SOURCE_SET_READY_TIME (source
, ready_time
));
1861 /* Quite likely that we need to change the timeout on the poll */
1862 if (!SOURCE_BLOCKED (source
))
1863 conditional_wakeup (context
);
1864 UNLOCK_CONTEXT (context
);
1869 * g_source_get_ready_time:
1870 * @source: a #GSource
1872 * Gets the "ready time" of @source, as set by
1873 * g_source_set_ready_time().
1875 * Any time before the current monotonic time (including 0) is an
1876 * indication that the source will fire immediately.
1878 * Returns: the monotonic ready time, -1 for "never"
1881 g_source_get_ready_time (GSource
*source
)
1883 g_return_val_if_fail (source
!= NULL
, -1);
1885 return source
->priv
->ready_time
;
1889 * g_source_set_can_recurse:
1890 * @source: a #GSource
1891 * @can_recurse: whether recursion is allowed for this source
1893 * Sets whether a source can be called recursively. If @can_recurse is
1894 * %TRUE, then while the source is being dispatched then this source
1895 * will be processed normally. Otherwise, all processing of this
1896 * source is blocked until the dispatch function returns.
1899 g_source_set_can_recurse (GSource
*source
,
1900 gboolean can_recurse
)
1902 GMainContext
*context
;
1904 g_return_if_fail (source
!= NULL
);
1906 context
= source
->context
;
1909 LOCK_CONTEXT (context
);
1912 source
->flags
|= G_SOURCE_CAN_RECURSE
;
1914 source
->flags
&= ~G_SOURCE_CAN_RECURSE
;
1917 UNLOCK_CONTEXT (context
);
1921 * g_source_get_can_recurse:
1922 * @source: a #GSource
1924 * Checks whether a source is allowed to be called recursively.
1925 * see g_source_set_can_recurse().
1927 * Returns: whether recursion is allowed.
1930 g_source_get_can_recurse (GSource
*source
)
1932 g_return_val_if_fail (source
!= NULL
, FALSE
);
1934 return (source
->flags
& G_SOURCE_CAN_RECURSE
) != 0;
1939 * g_source_set_name:
1940 * @source: a #GSource
1941 * @name: debug name for the source
1943 * Sets a name for the source, used in debugging and profiling.
1944 * The name defaults to #NULL.
1946 * The source name should describe in a human-readable way
1947 * what the source does. For example, "X11 event queue"
1948 * or "GTK+ repaint idle handler" or whatever it is.
1950 * It is permitted to call this function multiple times, but is not
1951 * recommended due to the potential performance impact. For example,
1952 * one could change the name in the "check" function of a #GSourceFuncs
1953 * to include details like the event type in the source name.
1955 * Use caution if changing the name while another thread may be
1956 * accessing it with g_source_get_name(); that function does not copy
1957 * the value, and changing the value will free it while the other thread
1958 * may be attempting to use it.
1963 g_source_set_name (GSource
*source
,
1966 GMainContext
*context
;
1968 g_return_if_fail (source
!= NULL
);
1970 context
= source
->context
;
1973 LOCK_CONTEXT (context
);
1975 TRACE (GLIB_SOURCE_SET_NAME (source
, name
));
1977 /* setting back to NULL is allowed, just because it's
1978 * weird if get_name can return NULL but you can't
1982 g_free (source
->name
);
1983 source
->name
= g_strdup (name
);
1986 UNLOCK_CONTEXT (context
);
1990 * g_source_get_name:
1991 * @source: a #GSource
1993 * Gets a name for the source, used in debugging and profiling. The
1994 * name may be #NULL if it has never been set with g_source_set_name().
1996 * Returns: the name of the source
2001 g_source_get_name (GSource
*source
)
2003 g_return_val_if_fail (source
!= NULL
, NULL
);
2005 return source
->name
;
2009 * g_source_set_name_by_id:
2010 * @tag: a #GSource ID
2011 * @name: debug name for the source
2013 * Sets the name of a source using its ID.
2015 * This is a convenience utility to set source names from the return
2016 * value of g_idle_add(), g_timeout_add(), etc.
2018 * It is a programmer error to attempt to set the name of a non-existent
2021 * More specifically: source IDs can be reissued after a source has been
2022 * destroyed and therefore it is never valid to use this function with a
2023 * source ID which may have already been removed. An example is when
2024 * scheduling an idle to run in another thread with g_idle_add(): the
2025 * idle may already have run and been removed by the time this function
2026 * is called on its (now invalid) source ID. This source ID may have
2027 * been reissued, leading to the operation being performed against the
2033 g_source_set_name_by_id (guint tag
,
2038 g_return_if_fail (tag
> 0);
2040 source
= g_main_context_find_source_by_id (NULL
, tag
);
2044 g_source_set_name (source
, name
);
2050 * @source: a #GSource
2052 * Increases the reference count on a source by one.
2057 g_source_ref (GSource
*source
)
2059 GMainContext
*context
;
2061 g_return_val_if_fail (source
!= NULL
, NULL
);
2063 context
= source
->context
;
2066 LOCK_CONTEXT (context
);
2068 source
->ref_count
++;
2071 UNLOCK_CONTEXT (context
);
2076 /* g_source_unref() but possible to call within context lock
2079 g_source_unref_internal (GSource
*source
,
2080 GMainContext
*context
,
2083 gpointer old_cb_data
= NULL
;
2084 GSourceCallbackFuncs
*old_cb_funcs
= NULL
;
2086 g_return_if_fail (source
!= NULL
);
2088 if (!have_lock
&& context
)
2089 LOCK_CONTEXT (context
);
2091 source
->ref_count
--;
2092 if (source
->ref_count
== 0)
2094 TRACE (GLIB_SOURCE_BEFORE_FREE (source
, context
,
2095 source
->source_funcs
->finalize
));
2097 old_cb_data
= source
->callback_data
;
2098 old_cb_funcs
= source
->callback_funcs
;
2100 source
->callback_data
= NULL
;
2101 source
->callback_funcs
= NULL
;
2105 if (!SOURCE_DESTROYED (source
))
2106 g_warning (G_STRLOC
": ref_count == 0, but source was still attached to a context!");
2107 source_remove_from_context (source
, context
);
2109 g_hash_table_remove (context
->sources
, GUINT_TO_POINTER (source
->source_id
));
2112 if (source
->source_funcs
->finalize
)
2114 /* Temporarily increase the ref count again so that GSource methods
2115 * can be called from finalize(). */
2116 source
->ref_count
++;
2118 UNLOCK_CONTEXT (context
);
2119 source
->source_funcs
->finalize (source
);
2121 LOCK_CONTEXT (context
);
2122 source
->ref_count
--;
2127 /* Temporarily increase the ref count again so that GSource methods
2128 * can be called from callback_funcs.unref(). */
2129 source
->ref_count
++;
2131 UNLOCK_CONTEXT (context
);
2133 old_cb_funcs
->unref (old_cb_data
);
2136 LOCK_CONTEXT (context
);
2137 source
->ref_count
--;
2140 g_free (source
->name
);
2141 source
->name
= NULL
;
2143 g_slist_free (source
->poll_fds
);
2144 source
->poll_fds
= NULL
;
2146 g_slist_free_full (source
->priv
->fds
, g_free
);
2148 while (source
->priv
->child_sources
)
2150 GSource
*child_source
= source
->priv
->child_sources
->data
;
2152 source
->priv
->child_sources
=
2153 g_slist_remove (source
->priv
->child_sources
, child_source
);
2154 child_source
->priv
->parent_source
= NULL
;
2156 g_source_unref_internal (child_source
, context
, have_lock
);
2159 g_slice_free (GSourcePrivate
, source
->priv
);
2160 source
->priv
= NULL
;
2165 if (!have_lock
&& context
)
2166 UNLOCK_CONTEXT (context
);
2171 * @source: a #GSource
2173 * Decreases the reference count of a source by one. If the
2174 * resulting reference count is zero the source and associated
2175 * memory will be destroyed.
2178 g_source_unref (GSource
*source
)
2180 g_return_if_fail (source
!= NULL
);
2182 g_source_unref_internal (source
, source
->context
, FALSE
);
2186 * g_main_context_find_source_by_id:
2187 * @context: (nullable): a #GMainContext (if %NULL, the default context will be used)
2188 * @source_id: the source ID, as returned by g_source_get_id().
2190 * Finds a #GSource given a pair of context and ID.
2192 * It is a programmer error to attempt to lookup a non-existent source.
2194 * More specifically: source IDs can be reissued after a source has been
2195 * destroyed and therefore it is never valid to use this function with a
2196 * source ID which may have already been removed. An example is when
2197 * scheduling an idle to run in another thread with g_idle_add(): the
2198 * idle may already have run and been removed by the time this function
2199 * is called on its (now invalid) source ID. This source ID may have
2200 * been reissued, leading to the operation being performed against the
2203 * Returns: (transfer none): the #GSource
2206 g_main_context_find_source_by_id (GMainContext
*context
,
2211 g_return_val_if_fail (source_id
> 0, NULL
);
2213 if (context
== NULL
)
2214 context
= g_main_context_default ();
2216 LOCK_CONTEXT (context
);
2217 source
= g_hash_table_lookup (context
->sources
, GUINT_TO_POINTER (source_id
));
2218 UNLOCK_CONTEXT (context
);
2220 if (source
&& SOURCE_DESTROYED (source
))
2227 * g_main_context_find_source_by_funcs_user_data:
2228 * @context: (nullable): a #GMainContext (if %NULL, the default context will be used).
2229 * @funcs: the @source_funcs passed to g_source_new().
2230 * @user_data: the user data from the callback.
2232 * Finds a source with the given source functions and user data. If
2233 * multiple sources exist with the same source function and user data,
2234 * the first one found will be returned.
2236 * Returns: (transfer none): the source, if one was found, otherwise %NULL
2239 g_main_context_find_source_by_funcs_user_data (GMainContext
*context
,
2240 GSourceFuncs
*funcs
,
2246 g_return_val_if_fail (funcs
!= NULL
, NULL
);
2248 if (context
== NULL
)
2249 context
= g_main_context_default ();
2251 LOCK_CONTEXT (context
);
2253 g_source_iter_init (&iter
, context
, FALSE
);
2254 while (g_source_iter_next (&iter
, &source
))
2256 if (!SOURCE_DESTROYED (source
) &&
2257 source
->source_funcs
== funcs
&&
2258 source
->callback_funcs
)
2260 GSourceFunc callback
;
2261 gpointer callback_data
;
2263 source
->callback_funcs
->get (source
->callback_data
, source
, &callback
, &callback_data
);
2265 if (callback_data
== user_data
)
2269 g_source_iter_clear (&iter
);
2271 UNLOCK_CONTEXT (context
);
2277 * g_main_context_find_source_by_user_data:
2278 * @context: a #GMainContext
2279 * @user_data: the user_data for the callback.
2281 * Finds a source with the given user data for the callback. If
2282 * multiple sources exist with the same user data, the first
2283 * one found will be returned.
2285 * Returns: (transfer none): the source, if one was found, otherwise %NULL
2288 g_main_context_find_source_by_user_data (GMainContext
*context
,
2294 if (context
== NULL
)
2295 context
= g_main_context_default ();
2297 LOCK_CONTEXT (context
);
2299 g_source_iter_init (&iter
, context
, FALSE
);
2300 while (g_source_iter_next (&iter
, &source
))
2302 if (!SOURCE_DESTROYED (source
) &&
2303 source
->callback_funcs
)
2305 GSourceFunc callback
;
2306 gpointer callback_data
= NULL
;
2308 source
->callback_funcs
->get (source
->callback_data
, source
, &callback
, &callback_data
);
2310 if (callback_data
== user_data
)
2314 g_source_iter_clear (&iter
);
2316 UNLOCK_CONTEXT (context
);
2323 * @tag: the ID of the source to remove.
2325 * Removes the source with the given ID from the default main context. You must
2326 * use g_source_destroy() for sources added to a non-default main context.
2328 * The ID of a #GSource is given by g_source_get_id(), or will be
2329 * returned by the functions g_source_attach(), g_idle_add(),
2330 * g_idle_add_full(), g_timeout_add(), g_timeout_add_full(),
2331 * g_child_watch_add(), g_child_watch_add_full(), g_io_add_watch(), and
2332 * g_io_add_watch_full().
2334 * It is a programmer error to attempt to remove a non-existent source.
2336 * More specifically: source IDs can be reissued after a source has been
2337 * destroyed and therefore it is never valid to use this function with a
2338 * source ID which may have already been removed. An example is when
2339 * scheduling an idle to run in another thread with g_idle_add(): the
2340 * idle may already have run and been removed by the time this function
2341 * is called on its (now invalid) source ID. This source ID may have
2342 * been reissued, leading to the operation being performed against the
2345 * Returns: For historical reasons, this function always returns %TRUE
2348 g_source_remove (guint tag
)
2352 g_return_val_if_fail (tag
> 0, FALSE
);
2354 source
= g_main_context_find_source_by_id (NULL
, tag
);
2356 g_source_destroy (source
);
2358 g_critical ("Source ID %u was not found when attempting to remove it", tag
);
2360 return source
!= NULL
;
2364 * g_source_remove_by_user_data:
2365 * @user_data: the user_data for the callback.
2367 * Removes a source from the default main loop context given the user
2368 * data for the callback. If multiple sources exist with the same user
2369 * data, only one will be destroyed.
2371 * Returns: %TRUE if a source was found and removed.
2374 g_source_remove_by_user_data (gpointer user_data
)
2378 source
= g_main_context_find_source_by_user_data (NULL
, user_data
);
2381 g_source_destroy (source
);
2389 * g_source_remove_by_funcs_user_data:
2390 * @funcs: The @source_funcs passed to g_source_new()
2391 * @user_data: the user data for the callback
2393 * Removes a source from the default main loop context given the
2394 * source functions and user data. If multiple sources exist with the
2395 * same source functions and user data, only one will be destroyed.
2397 * Returns: %TRUE if a source was found and removed.
2400 g_source_remove_by_funcs_user_data (GSourceFuncs
*funcs
,
2405 g_return_val_if_fail (funcs
!= NULL
, FALSE
);
2407 source
= g_main_context_find_source_by_funcs_user_data (NULL
, funcs
, user_data
);
2410 g_source_destroy (source
);
2418 * g_clear_handle_id: (skip)
2419 * @tag_ptr: (not nullable): a pointer to the handler ID
2420 * @clear_func: (not nullable): the function to call to clear the handler
2422 * Clears a numeric handler, such as a #GSource ID.
2424 * @tag_ptr must be a valid pointer to the variable holding the handler.
2426 * If the ID is zero then this function does nothing.
2427 * Otherwise, clear_func() is called with the ID as a parameter, and the tag is
2430 * A macro is also included that allows this function to be used without
2435 #undef g_clear_handle_id
2437 g_clear_handle_id (guint
*tag_ptr
,
2438 GClearHandleFunc clear_func
)
2442 _handle_id
= *tag_ptr
;
2446 if (clear_func
!= NULL
)
2447 clear_func (_handle_id
);
2453 * g_source_add_unix_fd:
2454 * @source: a #GSource
2455 * @fd: the fd to monitor
2456 * @events: an event mask
2458 * Monitors @fd for the IO events in @events.
2460 * The tag returned by this function can be used to remove or modify the
2461 * monitoring of the fd using g_source_remove_unix_fd() or
2462 * g_source_modify_unix_fd().
2464 * It is not necessary to remove the fd before destroying the source; it
2465 * will be cleaned up automatically.
2467 * This API is only intended to be used by implementations of #GSource.
2468 * Do not call this API on a #GSource that you did not create.
2470 * As the name suggests, this function is not available on Windows.
2472 * Returns: (not nullable): an opaque tag
2477 g_source_add_unix_fd (GSource
*source
,
2479 GIOCondition events
)
2481 GMainContext
*context
;
2484 g_return_val_if_fail (source
!= NULL
, NULL
);
2485 g_return_val_if_fail (!SOURCE_DESTROYED (source
), NULL
);
2487 poll_fd
= g_new (GPollFD
, 1);
2489 poll_fd
->events
= events
;
2490 poll_fd
->revents
= 0;
2492 context
= source
->context
;
2495 LOCK_CONTEXT (context
);
2497 source
->priv
->fds
= g_slist_prepend (source
->priv
->fds
, poll_fd
);
2501 if (!SOURCE_BLOCKED (source
))
2502 g_main_context_add_poll_unlocked (context
, source
->priority
, poll_fd
);
2503 UNLOCK_CONTEXT (context
);
2510 * g_source_modify_unix_fd:
2511 * @source: a #GSource
2512 * @tag: (not nullable): the tag from g_source_add_unix_fd()
2513 * @new_events: the new event mask to watch
2515 * Updates the event mask to watch for the fd identified by @tag.
2517 * @tag is the tag returned from g_source_add_unix_fd().
2519 * If you want to remove a fd, don't set its event mask to zero.
2520 * Instead, call g_source_remove_unix_fd().
2522 * This API is only intended to be used by implementations of #GSource.
2523 * Do not call this API on a #GSource that you did not create.
2525 * As the name suggests, this function is not available on Windows.
2530 g_source_modify_unix_fd (GSource
*source
,
2532 GIOCondition new_events
)
2534 GMainContext
*context
;
2537 g_return_if_fail (source
!= NULL
);
2538 g_return_if_fail (g_slist_find (source
->priv
->fds
, tag
));
2540 context
= source
->context
;
2543 poll_fd
->events
= new_events
;
2546 g_main_context_wakeup (context
);
2550 * g_source_remove_unix_fd:
2551 * @source: a #GSource
2552 * @tag: (not nullable): the tag from g_source_add_unix_fd()
2554 * Reverses the effect of a previous call to g_source_add_unix_fd().
2556 * You only need to call this if you want to remove an fd from being
2557 * watched while keeping the same source around. In the normal case you
2558 * will just want to destroy the source.
2560 * This API is only intended to be used by implementations of #GSource.
2561 * Do not call this API on a #GSource that you did not create.
2563 * As the name suggests, this function is not available on Windows.
2568 g_source_remove_unix_fd (GSource
*source
,
2571 GMainContext
*context
;
2574 g_return_if_fail (source
!= NULL
);
2575 g_return_if_fail (g_slist_find (source
->priv
->fds
, tag
));
2577 context
= source
->context
;
2581 LOCK_CONTEXT (context
);
2583 source
->priv
->fds
= g_slist_remove (source
->priv
->fds
, poll_fd
);
2587 if (!SOURCE_BLOCKED (source
))
2588 g_main_context_remove_poll_unlocked (context
, poll_fd
);
2590 UNLOCK_CONTEXT (context
);
2597 * g_source_query_unix_fd:
2598 * @source: a #GSource
2599 * @tag: (not nullable): the tag from g_source_add_unix_fd()
2601 * Queries the events reported for the fd corresponding to @tag on
2602 * @source during the last poll.
2604 * The return value of this function is only defined when the function
2605 * is called from the check or dispatch functions for @source.
2607 * This API is only intended to be used by implementations of #GSource.
2608 * Do not call this API on a #GSource that you did not create.
2610 * As the name suggests, this function is not available on Windows.
2612 * Returns: the conditions reported on the fd
2617 g_source_query_unix_fd (GSource
*source
,
2622 g_return_val_if_fail (source
!= NULL
, 0);
2623 g_return_val_if_fail (g_slist_find (source
->priv
->fds
, tag
), 0);
2627 return poll_fd
->revents
;
2629 #endif /* G_OS_UNIX */
2632 * g_get_current_time:
2633 * @result: #GTimeVal structure in which to store current time.
2635 * Equivalent to the UNIX gettimeofday() function, but portable.
2637 * You may find g_get_real_time() to be more convenient.
2640 g_get_current_time (GTimeVal
*result
)
2645 g_return_if_fail (result
!= NULL
);
2647 /*this is required on alpha, there the timeval structs are int's
2648 not longs and a cast only would fail horribly*/
2649 gettimeofday (&r
, NULL
);
2650 result
->tv_sec
= r
.tv_sec
;
2651 result
->tv_usec
= r
.tv_usec
;
2656 g_return_if_fail (result
!= NULL
);
2658 GetSystemTimeAsFileTime (&ft
);
2659 memmove (&time64
, &ft
, sizeof (FILETIME
));
2661 /* Convert from 100s of nanoseconds since 1601-01-01
2662 * to Unix epoch. Yes, this is Y2038 unsafe.
2664 time64
-= G_GINT64_CONSTANT (116444736000000000);
2667 result
->tv_sec
= time64
/ 1000000;
2668 result
->tv_usec
= time64
% 1000000;
2675 * Queries the system wall-clock time.
2677 * This call is functionally equivalent to g_get_current_time() except
2678 * that the return value is often more convenient than dealing with a
2681 * You should only use this call if you are actually interested in the real
2682 * wall-clock time. g_get_monotonic_time() is probably more useful for
2683 * measuring intervals.
2685 * Returns: the number of microseconds since January 1, 1970 UTC.
2690 g_get_real_time (void)
2694 g_get_current_time (&tv
);
2696 return (((gint64
) tv
.tv_sec
) * 1000000) + tv
.tv_usec
;
2700 * g_get_monotonic_time:
2702 * Queries the system monotonic time.
2704 * The monotonic clock will always increase and doesn't suffer
2705 * discontinuities when the user (or NTP) changes the system time. It
2706 * may or may not continue to tick during times where the machine is
2709 * We try to use the clock that corresponds as closely as possible to
2710 * the passage of time as measured by system calls such as poll() but it
2711 * may not always be possible to do this.
2713 * Returns: the monotonic time, in microseconds
2717 #if defined (G_OS_WIN32)
2719 * time_usec = ticks_since_boot * usec_per_sec / ticks_per_sec
2721 * Doing (ticks_since_boot * usec_per_sec) before the division can overflow 64 bits
2722 * (ticks_since_boot / ticks_per_sec) and then multiply would not be accurate enough.
2723 * So for now we calculate (usec_per_sec / ticks_per_sec) and use floating point
2725 static gdouble g_monotonic_usec_per_tick
= 0;
2728 g_clock_win32_init (void)
2732 if (!QueryPerformanceFrequency (&freq
) || freq
.QuadPart
== 0)
2734 /* The documentation says that this should never happen */
2735 g_assert_not_reached ();
2739 g_monotonic_usec_per_tick
= (gdouble
)G_USEC_PER_SEC
/ freq
.QuadPart
;
2743 g_get_monotonic_time (void)
2745 if (G_LIKELY (g_monotonic_usec_per_tick
!= 0))
2747 LARGE_INTEGER ticks
;
2749 if (QueryPerformanceCounter (&ticks
))
2750 return (gint64
)(ticks
.QuadPart
* g_monotonic_usec_per_tick
);
2752 g_warning ("QueryPerformanceCounter Failed (%lu)", GetLastError ());
2753 g_monotonic_usec_per_tick
= 0;
2758 #elif defined(HAVE_MACH_MACH_TIME_H) /* Mac OS */
2760 g_get_monotonic_time (void)
2762 static mach_timebase_info_data_t timebase_info
;
2764 if (timebase_info
.denom
== 0)
2766 /* This is a fraction that we must use to scale
2767 * mach_absolute_time() by in order to reach nanoseconds.
2769 * We've only ever observed this to be 1/1, but maybe it could be
2770 * 1000/1 if mach time is microseconds already, or 1/1000 if
2771 * picoseconds. Try to deal nicely with that.
2773 mach_timebase_info (&timebase_info
);
2775 /* We actually want microseconds... */
2776 if (timebase_info
.numer
% 1000 == 0)
2777 timebase_info
.numer
/= 1000;
2779 timebase_info
.denom
*= 1000;
2781 /* We want to make the numer 1 to avoid having to multiply... */
2782 if (timebase_info
.denom
% timebase_info
.numer
== 0)
2784 timebase_info
.denom
/= timebase_info
.numer
;
2785 timebase_info
.numer
= 1;
2789 /* We could just multiply by timebase_info.numer below, but why
2790 * bother for a case that may never actually exist...
2792 * Plus -- performing the multiplication would risk integer
2793 * overflow. If we ever actually end up in this situation, we
2794 * should more carefully evaluate the correct course of action.
2796 mach_timebase_info (&timebase_info
); /* Get a fresh copy for a better message */
2797 g_error ("Got weird mach timebase info of %d/%d. Please file a bug against GLib.",
2798 timebase_info
.numer
, timebase_info
.denom
);
2802 return mach_absolute_time () / timebase_info
.denom
;
2806 g_get_monotonic_time (void)
2811 result
= clock_gettime (CLOCK_MONOTONIC
, &ts
);
2813 if G_UNLIKELY (result
!= 0)
2814 g_error ("GLib requires working CLOCK_MONOTONIC");
2816 return (((gint64
) ts
.tv_sec
) * 1000000) + (ts
.tv_nsec
/ 1000);
2821 g_main_dispatch_free (gpointer dispatch
)
2823 g_slice_free (GMainDispatch
, dispatch
);
2826 /* Running the main loop */
2828 static GMainDispatch
*
2831 static GPrivate depth_private
= G_PRIVATE_INIT (g_main_dispatch_free
);
2832 GMainDispatch
*dispatch
;
2834 dispatch
= g_private_get (&depth_private
);
2838 dispatch
= g_slice_new0 (GMainDispatch
);
2839 g_private_set (&depth_private
, dispatch
);
2848 * Returns the depth of the stack of calls to
2849 * g_main_context_dispatch() on any #GMainContext in the current thread.
2850 * That is, when called from the toplevel, it gives 0. When
2851 * called from within a callback from g_main_context_iteration()
2852 * (or g_main_loop_run(), etc.) it returns 1. When called from within
2853 * a callback to a recursive call to g_main_context_iteration(),
2854 * it returns 2. And so forth.
2856 * This function is useful in a situation like the following:
2857 * Imagine an extremely simple "garbage collected" system.
2859 * |[<!-- language="C" -->
2860 * static GList *free_list;
2863 * allocate_memory (gsize size)
2865 * gpointer result = g_malloc (size);
2866 * free_list = g_list_prepend (free_list, result);
2871 * free_allocated_memory (void)
2874 * for (l = free_list; l; l = l->next);
2876 * g_list_free (free_list);
2884 * g_main_context_iteration (NULL, TRUE);
2885 * free_allocated_memory();
2889 * This works from an application, however, if you want to do the same
2890 * thing from a library, it gets more difficult, since you no longer
2891 * control the main loop. You might think you can simply use an idle
2892 * function to make the call to free_allocated_memory(), but that
2893 * doesn't work, since the idle function could be called from a
2894 * recursive callback. This can be fixed by using g_main_depth()
2896 * |[<!-- language="C" -->
2898 * allocate_memory (gsize size)
2900 * FreeListBlock *block = g_new (FreeListBlock, 1);
2901 * block->mem = g_malloc (size);
2902 * block->depth = g_main_depth ();
2903 * free_list = g_list_prepend (free_list, block);
2904 * return block->mem;
2908 * free_allocated_memory (void)
2912 * int depth = g_main_depth ();
2913 * for (l = free_list; l; );
2915 * GList *next = l->next;
2916 * FreeListBlock *block = l->data;
2917 * if (block->depth > depth)
2919 * g_free (block->mem);
2921 * free_list = g_list_delete_link (free_list, l);
2929 * There is a temptation to use g_main_depth() to solve
2930 * problems with reentrancy. For instance, while waiting for data
2931 * to be received from the network in response to a menu item,
2932 * the menu item might be selected again. It might seem that
2933 * one could make the menu item's callback return immediately
2934 * and do nothing if g_main_depth() returns a value greater than 1.
2935 * However, this should be avoided since the user then sees selecting
2936 * the menu item do nothing. Furthermore, you'll find yourself adding
2937 * these checks all over your code, since there are doubtless many,
2938 * many things that the user could do. Instead, you can use the
2939 * following techniques:
2941 * 1. Use gtk_widget_set_sensitive() or modal dialogs to prevent
2942 * the user from interacting with elements while the main
2943 * loop is recursing.
2945 * 2. Avoid main loop recursion in situations where you can't handle
2946 * arbitrary callbacks. Instead, structure your code so that you
2947 * simply return to the main loop and then get called again when
2948 * there is more work to do.
2950 * Returns: The main loop recursion level in the current thread
2955 GMainDispatch
*dispatch
= get_dispatch ();
2956 return dispatch
->depth
;
2960 * g_main_current_source:
2962 * Returns the currently firing source for this thread.
2964 * Returns: (transfer none): The currently firing source or %NULL.
2969 g_main_current_source (void)
2971 GMainDispatch
*dispatch
= get_dispatch ();
2972 return dispatch
->source
;
2976 * g_source_is_destroyed:
2977 * @source: a #GSource
2979 * Returns whether @source has been destroyed.
2981 * This is important when you operate upon your objects
2982 * from within idle handlers, but may have freed the object
2983 * before the dispatch of your idle handler.
2985 * |[<!-- language="C" -->
2987 * idle_callback (gpointer data)
2989 * SomeWidget *self = data;
2991 * GDK_THREADS_ENTER ();
2992 * // do stuff with self
2993 * self->idle_id = 0;
2994 * GDK_THREADS_LEAVE ();
2996 * return G_SOURCE_REMOVE;
3000 * some_widget_do_stuff_later (SomeWidget *self)
3002 * self->idle_id = g_idle_add (idle_callback, self);
3006 * some_widget_finalize (GObject *object)
3008 * SomeWidget *self = SOME_WIDGET (object);
3010 * if (self->idle_id)
3011 * g_source_remove (self->idle_id);
3013 * G_OBJECT_CLASS (parent_class)->finalize (object);
3017 * This will fail in a multi-threaded application if the
3018 * widget is destroyed before the idle handler fires due
3019 * to the use after free in the callback. A solution, to
3020 * this particular problem, is to check to if the source
3021 * has already been destroy within the callback.
3023 * |[<!-- language="C" -->
3025 * idle_callback (gpointer data)
3027 * SomeWidget *self = data;
3029 * GDK_THREADS_ENTER ();
3030 * if (!g_source_is_destroyed (g_main_current_source ()))
3032 * // do stuff with self
3034 * GDK_THREADS_LEAVE ();
3040 * Calls to this function from a thread other than the one acquired by the
3041 * #GMainContext the #GSource is attached to are typically redundant, as the
3042 * source could be destroyed immediately after this function returns. However,
3043 * once a source is destroyed it cannot be un-destroyed, so this function can be
3044 * used for opportunistic checks from any thread.
3046 * Returns: %TRUE if the source has been destroyed
3051 g_source_is_destroyed (GSource
*source
)
3053 return SOURCE_DESTROYED (source
);
3056 /* Temporarily remove all this source's file descriptors from the
3057 * poll(), so that if data comes available for one of the file descriptors
3058 * we don't continually spin in the poll()
3060 /* HOLDS: source->context's lock */
3062 block_source (GSource
*source
)
3066 g_return_if_fail (!SOURCE_BLOCKED (source
));
3068 source
->flags
|= G_SOURCE_BLOCKED
;
3070 if (source
->context
)
3072 tmp_list
= source
->poll_fds
;
3075 g_main_context_remove_poll_unlocked (source
->context
, tmp_list
->data
);
3076 tmp_list
= tmp_list
->next
;
3079 for (tmp_list
= source
->priv
->fds
; tmp_list
; tmp_list
= tmp_list
->next
)
3080 g_main_context_remove_poll_unlocked (source
->context
, tmp_list
->data
);
3083 if (source
->priv
&& source
->priv
->child_sources
)
3085 tmp_list
= source
->priv
->child_sources
;
3088 block_source (tmp_list
->data
);
3089 tmp_list
= tmp_list
->next
;
3094 /* HOLDS: source->context's lock */
3096 unblock_source (GSource
*source
)
3100 g_return_if_fail (SOURCE_BLOCKED (source
)); /* Source already unblocked */
3101 g_return_if_fail (!SOURCE_DESTROYED (source
));
3103 source
->flags
&= ~G_SOURCE_BLOCKED
;
3105 tmp_list
= source
->poll_fds
;
3108 g_main_context_add_poll_unlocked (source
->context
, source
->priority
, tmp_list
->data
);
3109 tmp_list
= tmp_list
->next
;
3112 for (tmp_list
= source
->priv
->fds
; tmp_list
; tmp_list
= tmp_list
->next
)
3113 g_main_context_add_poll_unlocked (source
->context
, source
->priority
, tmp_list
->data
);
3115 if (source
->priv
&& source
->priv
->child_sources
)
3117 tmp_list
= source
->priv
->child_sources
;
3120 unblock_source (tmp_list
->data
);
3121 tmp_list
= tmp_list
->next
;
3126 /* HOLDS: context's lock */
3128 g_main_dispatch (GMainContext
*context
)
3130 GMainDispatch
*current
= get_dispatch ();
3133 for (i
= 0; i
< context
->pending_dispatches
->len
; i
++)
3135 GSource
*source
= context
->pending_dispatches
->pdata
[i
];
3137 context
->pending_dispatches
->pdata
[i
] = NULL
;
3140 source
->flags
&= ~G_SOURCE_READY
;
3142 if (!SOURCE_DESTROYED (source
))
3144 gboolean was_in_call
;
3145 gpointer user_data
= NULL
;
3146 GSourceFunc callback
= NULL
;
3147 GSourceCallbackFuncs
*cb_funcs
;
3149 gboolean need_destroy
;
3151 gboolean (*dispatch
) (GSource
*,
3154 GSource
*prev_source
;
3156 dispatch
= source
->source_funcs
->dispatch
;
3157 cb_funcs
= source
->callback_funcs
;
3158 cb_data
= source
->callback_data
;
3161 cb_funcs
->ref (cb_data
);
3163 if ((source
->flags
& G_SOURCE_CAN_RECURSE
) == 0)
3164 block_source (source
);
3166 was_in_call
= source
->flags
& G_HOOK_FLAG_IN_CALL
;
3167 source
->flags
|= G_HOOK_FLAG_IN_CALL
;
3170 cb_funcs
->get (cb_data
, source
, &callback
, &user_data
);
3172 UNLOCK_CONTEXT (context
);
3174 /* These operations are safe because 'current' is thread-local
3175 * and not modified from anywhere but this function.
3177 prev_source
= current
->source
;
3178 current
->source
= source
;
3181 TRACE (GLIB_MAIN_BEFORE_DISPATCH (g_source_get_name (source
), source
,
3182 dispatch
, callback
, user_data
));
3183 need_destroy
= !(* dispatch
) (source
, callback
, user_data
);
3184 TRACE (GLIB_MAIN_AFTER_DISPATCH (g_source_get_name (source
), source
,
3185 dispatch
, need_destroy
));
3187 current
->source
= prev_source
;
3191 cb_funcs
->unref (cb_data
);
3193 LOCK_CONTEXT (context
);
3196 source
->flags
&= ~G_HOOK_FLAG_IN_CALL
;
3198 if (SOURCE_BLOCKED (source
) && !SOURCE_DESTROYED (source
))
3199 unblock_source (source
);
3201 /* Note: this depends on the fact that we can't switch
3202 * sources from one main context to another
3204 if (need_destroy
&& !SOURCE_DESTROYED (source
))
3206 g_assert (source
->context
== context
);
3207 g_source_destroy_internal (source
, context
, TRUE
);
3211 SOURCE_UNREF (source
, context
);
3214 g_ptr_array_set_size (context
->pending_dispatches
, 0);
3218 * g_main_context_acquire:
3219 * @context: a #GMainContext
3221 * Tries to become the owner of the specified context.
3222 * If some other thread is the owner of the context,
3223 * returns %FALSE immediately. Ownership is properly
3224 * recursive: the owner can require ownership again
3225 * and will release ownership when g_main_context_release()
3226 * is called as many times as g_main_context_acquire().
3228 * You must be the owner of a context before you
3229 * can call g_main_context_prepare(), g_main_context_query(),
3230 * g_main_context_check(), g_main_context_dispatch().
3232 * Returns: %TRUE if the operation succeeded, and
3233 * this thread is now the owner of @context.
3236 g_main_context_acquire (GMainContext
*context
)
3238 gboolean result
= FALSE
;
3239 GThread
*self
= G_THREAD_SELF
;
3241 if (context
== NULL
)
3242 context
= g_main_context_default ();
3244 LOCK_CONTEXT (context
);
3246 if (!context
->owner
)
3248 context
->owner
= self
;
3249 g_assert (context
->owner_count
== 0);
3250 TRACE (GLIB_MAIN_CONTEXT_ACQUIRE (context
, TRUE
/* success */));
3253 if (context
->owner
== self
)
3255 context
->owner_count
++;
3260 TRACE (GLIB_MAIN_CONTEXT_ACQUIRE (context
, FALSE
/* failure */));
3263 UNLOCK_CONTEXT (context
);
3269 * g_main_context_release:
3270 * @context: a #GMainContext
3272 * Releases ownership of a context previously acquired by this thread
3273 * with g_main_context_acquire(). If the context was acquired multiple
3274 * times, the ownership will be released only when g_main_context_release()
3275 * is called as many times as it was acquired.
3278 g_main_context_release (GMainContext
*context
)
3280 if (context
== NULL
)
3281 context
= g_main_context_default ();
3283 LOCK_CONTEXT (context
);
3285 context
->owner_count
--;
3286 if (context
->owner_count
== 0)
3288 TRACE (GLIB_MAIN_CONTEXT_RELEASE (context
));
3290 context
->owner
= NULL
;
3292 if (context
->waiters
)
3294 GMainWaiter
*waiter
= context
->waiters
->data
;
3295 gboolean loop_internal_waiter
= (waiter
->mutex
== &context
->mutex
);
3296 context
->waiters
= g_slist_delete_link (context
->waiters
,
3298 if (!loop_internal_waiter
)
3299 g_mutex_lock (waiter
->mutex
);
3301 g_cond_signal (waiter
->cond
);
3303 if (!loop_internal_waiter
)
3304 g_mutex_unlock (waiter
->mutex
);
3308 UNLOCK_CONTEXT (context
);
3312 * g_main_context_wait:
3313 * @context: a #GMainContext
3314 * @cond: a condition variable
3315 * @mutex: a mutex, currently held
3317 * Tries to become the owner of the specified context,
3318 * as with g_main_context_acquire(). But if another thread
3319 * is the owner, atomically drop @mutex and wait on @cond until
3320 * that owner releases ownership or until @cond is signaled, then
3321 * try again (once) to become the owner.
3323 * Returns: %TRUE if the operation succeeded, and
3324 * this thread is now the owner of @context.
3327 g_main_context_wait (GMainContext
*context
,
3331 gboolean result
= FALSE
;
3332 GThread
*self
= G_THREAD_SELF
;
3333 gboolean loop_internal_waiter
;
3335 if (context
== NULL
)
3336 context
= g_main_context_default ();
3338 if G_UNLIKELY (cond
!= &context
->cond
|| mutex
!= &context
->mutex
)
3340 static gboolean warned
;
3344 g_critical ("WARNING!! g_main_context_wait() will be removed in a future release. "
3345 "If you see this message, please file a bug immediately.");
3350 loop_internal_waiter
= (mutex
== &context
->mutex
);
3352 if (!loop_internal_waiter
)
3353 LOCK_CONTEXT (context
);
3355 if (context
->owner
&& context
->owner
!= self
)
3360 waiter
.mutex
= mutex
;
3362 context
->waiters
= g_slist_append (context
->waiters
, &waiter
);
3364 if (!loop_internal_waiter
)
3365 UNLOCK_CONTEXT (context
);
3366 g_cond_wait (cond
, mutex
);
3367 if (!loop_internal_waiter
)
3368 LOCK_CONTEXT (context
);
3370 context
->waiters
= g_slist_remove (context
->waiters
, &waiter
);
3373 if (!context
->owner
)
3375 context
->owner
= self
;
3376 g_assert (context
->owner_count
== 0);
3379 if (context
->owner
== self
)
3381 context
->owner_count
++;
3385 if (!loop_internal_waiter
)
3386 UNLOCK_CONTEXT (context
);
3392 * g_main_context_prepare:
3393 * @context: a #GMainContext
3394 * @priority: location to store priority of highest priority
3395 * source already ready.
3397 * Prepares to poll sources within a main loop. The resulting information
3398 * for polling is determined by calling g_main_context_query ().
3400 * You must have successfully acquired the context with
3401 * g_main_context_acquire() before you may call this function.
3403 * Returns: %TRUE if some source is ready to be dispatched
3407 g_main_context_prepare (GMainContext
*context
,
3412 gint current_priority
= G_MAXINT
;
3416 if (context
== NULL
)
3417 context
= g_main_context_default ();
3419 LOCK_CONTEXT (context
);
3421 /* context->need_wakeup is protected by LOCK_CONTEXT/UNLOCK_CONTEXT,
3422 * so need not set it yet.
3425 context
->time_is_fresh
= FALSE
;
3427 if (context
->in_check_or_prepare
)
3429 g_warning ("g_main_context_prepare() called recursively from within a source's check() or "
3430 "prepare() member.");
3431 UNLOCK_CONTEXT (context
);
3435 TRACE (GLIB_MAIN_CONTEXT_BEFORE_PREPARE (context
));
3438 /* If recursing, finish up current dispatch, before starting over */
3439 if (context
->pending_dispatches
)
3442 g_main_dispatch (context
, ¤t_time
);
3444 UNLOCK_CONTEXT (context
);
3449 /* If recursing, clear list of pending dispatches */
3451 for (i
= 0; i
< context
->pending_dispatches
->len
; i
++)
3453 if (context
->pending_dispatches
->pdata
[i
])
3454 SOURCE_UNREF ((GSource
*)context
->pending_dispatches
->pdata
[i
], context
);
3456 g_ptr_array_set_size (context
->pending_dispatches
, 0);
3458 /* Prepare all sources */
3460 context
->timeout
= -1;
3462 g_source_iter_init (&iter
, context
, TRUE
);
3463 while (g_source_iter_next (&iter
, &source
))
3465 gint source_timeout
= -1;
3467 if (SOURCE_DESTROYED (source
) || SOURCE_BLOCKED (source
))
3469 if ((n_ready
> 0) && (source
->priority
> current_priority
))
3472 if (!(source
->flags
& G_SOURCE_READY
))
3475 gboolean (* prepare
) (GSource
*source
,
3478 prepare
= source
->source_funcs
->prepare
;
3482 context
->in_check_or_prepare
++;
3483 UNLOCK_CONTEXT (context
);
3485 result
= (* prepare
) (source
, &source_timeout
);
3486 TRACE (GLIB_MAIN_AFTER_PREPARE (source
, prepare
, source_timeout
));
3488 LOCK_CONTEXT (context
);
3489 context
->in_check_or_prepare
--;
3493 source_timeout
= -1;
3497 if (result
== FALSE
&& source
->priv
->ready_time
!= -1)
3499 if (!context
->time_is_fresh
)
3501 context
->time
= g_get_monotonic_time ();
3502 context
->time_is_fresh
= TRUE
;
3505 if (source
->priv
->ready_time
<= context
->time
)
3514 /* rounding down will lead to spinning, so always round up */
3515 timeout
= (source
->priv
->ready_time
- context
->time
+ 999) / 1000;
3517 if (source_timeout
< 0 || timeout
< source_timeout
)
3518 source_timeout
= timeout
;
3524 GSource
*ready_source
= source
;
3526 while (ready_source
)
3528 ready_source
->flags
|= G_SOURCE_READY
;
3529 ready_source
= ready_source
->priv
->parent_source
;
3534 if (source
->flags
& G_SOURCE_READY
)
3537 current_priority
= source
->priority
;
3538 context
->timeout
= 0;
3541 if (source_timeout
>= 0)
3543 if (context
->timeout
< 0)
3544 context
->timeout
= source_timeout
;
3546 context
->timeout
= MIN (context
->timeout
, source_timeout
);
3549 g_source_iter_clear (&iter
);
3550 /* See conditional_wakeup() where this is used */
3551 context
->need_wakeup
= (n_ready
== 0);
3553 TRACE (GLIB_MAIN_CONTEXT_AFTER_PREPARE (context
, current_priority
, n_ready
));
3555 UNLOCK_CONTEXT (context
);
3558 *priority
= current_priority
;
3560 return (n_ready
> 0);
3564 * g_main_context_query:
3565 * @context: a #GMainContext
3566 * @max_priority: maximum priority source to check
3567 * @timeout_: (out): location to store timeout to be used in polling
3568 * @fds: (out caller-allocates) (array length=n_fds): location to
3569 * store #GPollFD records that need to be polled.
3570 * @n_fds: (in): length of @fds.
3572 * Determines information necessary to poll this main loop.
3574 * You must have successfully acquired the context with
3575 * g_main_context_acquire() before you may call this function.
3577 * Returns: the number of records actually stored in @fds,
3578 * or, if more than @n_fds records need to be stored, the number
3579 * of records that need to be stored.
3582 g_main_context_query (GMainContext
*context
,
3589 GPollRec
*pollrec
, *lastpollrec
;
3592 LOCK_CONTEXT (context
);
3594 TRACE (GLIB_MAIN_CONTEXT_BEFORE_QUERY (context
, max_priority
));
3598 for (pollrec
= context
->poll_records
; pollrec
; pollrec
= pollrec
->next
)
3600 if (pollrec
->priority
> max_priority
)
3603 /* In direct contradiction to the Unix98 spec, IRIX runs into
3604 * difficulty if you pass in POLLERR, POLLHUP or POLLNVAL
3605 * flags in the events field of the pollfd while it should
3606 * just ignoring them. So we mask them out here.
3608 events
= pollrec
->fd
->events
& ~(G_IO_ERR
|G_IO_HUP
|G_IO_NVAL
);
3610 if (lastpollrec
&& pollrec
->fd
->fd
== lastpollrec
->fd
->fd
)
3612 if (n_poll
- 1 < n_fds
)
3613 fds
[n_poll
- 1].events
|= events
;
3619 fds
[n_poll
].fd
= pollrec
->fd
->fd
;
3620 fds
[n_poll
].events
= events
;
3621 fds
[n_poll
].revents
= 0;
3627 lastpollrec
= pollrec
;
3630 context
->poll_changed
= FALSE
;
3634 *timeout
= context
->timeout
;
3636 context
->time_is_fresh
= FALSE
;
3639 TRACE (GLIB_MAIN_CONTEXT_AFTER_QUERY (context
, context
->timeout
,
3642 UNLOCK_CONTEXT (context
);
3648 * g_main_context_check:
3649 * @context: a #GMainContext
3650 * @max_priority: the maximum numerical priority of sources to check
3651 * @fds: (array length=n_fds): array of #GPollFD's that was passed to
3652 * the last call to g_main_context_query()
3653 * @n_fds: return value of g_main_context_query()
3655 * Passes the results of polling back to the main loop.
3657 * You must have successfully acquired the context with
3658 * g_main_context_acquire() before you may call this function.
3660 * Returns: %TRUE if some sources are ready to be dispatched.
3663 g_main_context_check (GMainContext
*context
,
3674 LOCK_CONTEXT (context
);
3676 if (context
->in_check_or_prepare
)
3678 g_warning ("g_main_context_check() called recursively from within a source's check() or "
3679 "prepare() member.");
3680 UNLOCK_CONTEXT (context
);
3684 TRACE (GLIB_MAIN_CONTEXT_BEFORE_CHECK (context
, max_priority
, fds
, n_fds
));
3686 /* We don't need to wakeup during check or dispatch, because
3687 * all sources will be re-evaluated during prepare/query.
3689 context
->need_wakeup
= FALSE
;
3691 /* And if we have a wakeup pending, acknowledge it */
3692 for (i
= 0; i
< n_fds
; i
++)
3694 if (fds
[i
].fd
== context
->wake_up_rec
.fd
)
3698 TRACE (GLIB_MAIN_CONTEXT_WAKEUP_ACKNOWLEDGE (context
));
3699 g_wakeup_acknowledge (context
->wakeup
);
3705 /* If the set of poll file descriptors changed, bail out
3706 * and let the main loop rerun
3708 if (context
->poll_changed
)
3710 TRACE (GLIB_MAIN_CONTEXT_AFTER_CHECK (context
, 0));
3712 UNLOCK_CONTEXT (context
);
3716 pollrec
= context
->poll_records
;
3718 while (pollrec
&& i
< n_fds
)
3720 while (pollrec
&& pollrec
->fd
->fd
== fds
[i
].fd
)
3722 if (pollrec
->priority
<= max_priority
)
3724 pollrec
->fd
->revents
=
3725 fds
[i
].revents
& (pollrec
->fd
->events
| G_IO_ERR
| G_IO_HUP
| G_IO_NVAL
);
3727 pollrec
= pollrec
->next
;
3733 g_source_iter_init (&iter
, context
, TRUE
);
3734 while (g_source_iter_next (&iter
, &source
))
3736 if (SOURCE_DESTROYED (source
) || SOURCE_BLOCKED (source
))
3738 if ((n_ready
> 0) && (source
->priority
> max_priority
))
3741 if (!(source
->flags
& G_SOURCE_READY
))
3744 gboolean (* check
) (GSource
*source
);
3746 check
= source
->source_funcs
->check
;
3750 /* If the check function is set, call it. */
3751 context
->in_check_or_prepare
++;
3752 UNLOCK_CONTEXT (context
);
3754 result
= (* check
) (source
);
3756 TRACE (GLIB_MAIN_AFTER_CHECK (source
, check
, result
));
3758 LOCK_CONTEXT (context
);
3759 context
->in_check_or_prepare
--;
3764 if (result
== FALSE
)
3768 /* If not already explicitly flagged ready by ->check()
3769 * (or if we have no check) then we can still be ready if
3770 * any of our fds poll as ready.
3772 for (tmp_list
= source
->priv
->fds
; tmp_list
; tmp_list
= tmp_list
->next
)
3774 GPollFD
*pollfd
= tmp_list
->data
;
3776 if (pollfd
->revents
)
3784 if (result
== FALSE
&& source
->priv
->ready_time
!= -1)
3786 if (!context
->time_is_fresh
)
3788 context
->time
= g_get_monotonic_time ();
3789 context
->time_is_fresh
= TRUE
;
3792 if (source
->priv
->ready_time
<= context
->time
)
3798 GSource
*ready_source
= source
;
3800 while (ready_source
)
3802 ready_source
->flags
|= G_SOURCE_READY
;
3803 ready_source
= ready_source
->priv
->parent_source
;
3808 if (source
->flags
& G_SOURCE_READY
)
3810 source
->ref_count
++;
3811 g_ptr_array_add (context
->pending_dispatches
, source
);
3815 /* never dispatch sources with less priority than the first
3816 * one we choose to dispatch
3818 max_priority
= source
->priority
;
3821 g_source_iter_clear (&iter
);
3823 TRACE (GLIB_MAIN_CONTEXT_AFTER_CHECK (context
, n_ready
));
3825 UNLOCK_CONTEXT (context
);
3831 * g_main_context_dispatch:
3832 * @context: a #GMainContext
3834 * Dispatches all pending sources.
3836 * You must have successfully acquired the context with
3837 * g_main_context_acquire() before you may call this function.
3840 g_main_context_dispatch (GMainContext
*context
)
3842 LOCK_CONTEXT (context
);
3844 TRACE (GLIB_MAIN_CONTEXT_BEFORE_DISPATCH (context
));
3846 if (context
->pending_dispatches
->len
> 0)
3848 g_main_dispatch (context
);
3851 TRACE (GLIB_MAIN_CONTEXT_AFTER_DISPATCH (context
));
3853 UNLOCK_CONTEXT (context
);
3856 /* HOLDS context lock */
3858 g_main_context_iterate (GMainContext
*context
,
3865 gboolean some_ready
;
3866 gint nfds
, allocated_nfds
;
3867 GPollFD
*fds
= NULL
;
3869 UNLOCK_CONTEXT (context
);
3871 if (!g_main_context_acquire (context
))
3873 gboolean got_ownership
;
3875 LOCK_CONTEXT (context
);
3880 got_ownership
= g_main_context_wait (context
,
3888 LOCK_CONTEXT (context
);
3890 if (!context
->cached_poll_array
)
3892 context
->cached_poll_array_size
= context
->n_poll_records
;
3893 context
->cached_poll_array
= g_new (GPollFD
, context
->n_poll_records
);
3896 allocated_nfds
= context
->cached_poll_array_size
;
3897 fds
= context
->cached_poll_array
;
3899 UNLOCK_CONTEXT (context
);
3901 g_main_context_prepare (context
, &max_priority
);
3903 while ((nfds
= g_main_context_query (context
, max_priority
, &timeout
, fds
,
3904 allocated_nfds
)) > allocated_nfds
)
3906 LOCK_CONTEXT (context
);
3908 context
->cached_poll_array_size
= allocated_nfds
= nfds
;
3909 context
->cached_poll_array
= fds
= g_new (GPollFD
, nfds
);
3910 UNLOCK_CONTEXT (context
);
3916 g_main_context_poll (context
, timeout
, max_priority
, fds
, nfds
);
3918 some_ready
= g_main_context_check (context
, max_priority
, fds
, nfds
);
3921 g_main_context_dispatch (context
);
3923 g_main_context_release (context
);
3925 LOCK_CONTEXT (context
);
3931 * g_main_context_pending:
3932 * @context: (nullable): a #GMainContext (if %NULL, the default context will be used)
3934 * Checks if any sources have pending events for the given context.
3936 * Returns: %TRUE if events are pending.
3939 g_main_context_pending (GMainContext
*context
)
3944 context
= g_main_context_default();
3946 LOCK_CONTEXT (context
);
3947 retval
= g_main_context_iterate (context
, FALSE
, FALSE
, G_THREAD_SELF
);
3948 UNLOCK_CONTEXT (context
);
3954 * g_main_context_iteration:
3955 * @context: (nullable): a #GMainContext (if %NULL, the default context will be used)
3956 * @may_block: whether the call may block.
3958 * Runs a single iteration for the given main loop. This involves
3959 * checking to see if any event sources are ready to be processed,
3960 * then if no events sources are ready and @may_block is %TRUE, waiting
3961 * for a source to become ready, then dispatching the highest priority
3962 * events sources that are ready. Otherwise, if @may_block is %FALSE
3963 * sources are not waited to become ready, only those highest priority
3964 * events sources will be dispatched (if any), that are ready at this
3965 * given moment without further waiting.
3967 * Note that even when @may_block is %TRUE, it is still possible for
3968 * g_main_context_iteration() to return %FALSE, since the wait may
3969 * be interrupted for other reasons than an event source becoming ready.
3971 * Returns: %TRUE if events were dispatched.
3974 g_main_context_iteration (GMainContext
*context
, gboolean may_block
)
3979 context
= g_main_context_default();
3981 LOCK_CONTEXT (context
);
3982 retval
= g_main_context_iterate (context
, may_block
, TRUE
, G_THREAD_SELF
);
3983 UNLOCK_CONTEXT (context
);
3990 * @context: (nullable): a #GMainContext (if %NULL, the default context will be used).
3991 * @is_running: set to %TRUE to indicate that the loop is running. This
3992 * is not very important since calling g_main_loop_run() will set this to
3995 * Creates a new #GMainLoop structure.
3997 * Returns: a new #GMainLoop.
4000 g_main_loop_new (GMainContext
*context
,
4001 gboolean is_running
)
4006 context
= g_main_context_default();
4008 g_main_context_ref (context
);
4010 loop
= g_new0 (GMainLoop
, 1);
4011 loop
->context
= context
;
4012 loop
->is_running
= is_running
!= FALSE
;
4013 loop
->ref_count
= 1;
4015 TRACE (GLIB_MAIN_LOOP_NEW (loop
, context
));
4022 * @loop: a #GMainLoop
4024 * Increases the reference count on a #GMainLoop object by one.
4029 g_main_loop_ref (GMainLoop
*loop
)
4031 g_return_val_if_fail (loop
!= NULL
, NULL
);
4032 g_return_val_if_fail (g_atomic_int_get (&loop
->ref_count
) > 0, NULL
);
4034 g_atomic_int_inc (&loop
->ref_count
);
4040 * g_main_loop_unref:
4041 * @loop: a #GMainLoop
4043 * Decreases the reference count on a #GMainLoop object by one. If
4044 * the result is zero, free the loop and free all associated memory.
4047 g_main_loop_unref (GMainLoop
*loop
)
4049 g_return_if_fail (loop
!= NULL
);
4050 g_return_if_fail (g_atomic_int_get (&loop
->ref_count
) > 0);
4052 if (!g_atomic_int_dec_and_test (&loop
->ref_count
))
4055 g_main_context_unref (loop
->context
);
4061 * @loop: a #GMainLoop
4063 * Runs a main loop until g_main_loop_quit() is called on the loop.
4064 * If this is called for the thread of the loop's #GMainContext,
4065 * it will process events from the loop, otherwise it will
4069 g_main_loop_run (GMainLoop
*loop
)
4071 GThread
*self
= G_THREAD_SELF
;
4073 g_return_if_fail (loop
!= NULL
);
4074 g_return_if_fail (g_atomic_int_get (&loop
->ref_count
) > 0);
4076 if (!g_main_context_acquire (loop
->context
))
4078 gboolean got_ownership
= FALSE
;
4080 /* Another thread owns this context */
4081 LOCK_CONTEXT (loop
->context
);
4083 g_atomic_int_inc (&loop
->ref_count
);
4085 if (!loop
->is_running
)
4086 loop
->is_running
= TRUE
;
4088 while (loop
->is_running
&& !got_ownership
)
4089 got_ownership
= g_main_context_wait (loop
->context
,
4090 &loop
->context
->cond
,
4091 &loop
->context
->mutex
);
4093 if (!loop
->is_running
)
4095 UNLOCK_CONTEXT (loop
->context
);
4097 g_main_context_release (loop
->context
);
4098 g_main_loop_unref (loop
);
4102 g_assert (got_ownership
);
4105 LOCK_CONTEXT (loop
->context
);
4107 if (loop
->context
->in_check_or_prepare
)
4109 g_warning ("g_main_loop_run(): called recursively from within a source's "
4110 "check() or prepare() member, iteration not possible.");
4114 g_atomic_int_inc (&loop
->ref_count
);
4115 loop
->is_running
= TRUE
;
4116 while (loop
->is_running
)
4117 g_main_context_iterate (loop
->context
, TRUE
, TRUE
, self
);
4119 UNLOCK_CONTEXT (loop
->context
);
4121 g_main_context_release (loop
->context
);
4123 g_main_loop_unref (loop
);
4128 * @loop: a #GMainLoop
4130 * Stops a #GMainLoop from running. Any calls to g_main_loop_run()
4131 * for the loop will return.
4133 * Note that sources that have already been dispatched when
4134 * g_main_loop_quit() is called will still be executed.
4137 g_main_loop_quit (GMainLoop
*loop
)
4139 g_return_if_fail (loop
!= NULL
);
4140 g_return_if_fail (g_atomic_int_get (&loop
->ref_count
) > 0);
4142 LOCK_CONTEXT (loop
->context
);
4143 loop
->is_running
= FALSE
;
4144 g_wakeup_signal (loop
->context
->wakeup
);
4146 g_cond_broadcast (&loop
->context
->cond
);
4148 UNLOCK_CONTEXT (loop
->context
);
4150 TRACE (GLIB_MAIN_LOOP_QUIT (loop
));
4154 * g_main_loop_is_running:
4155 * @loop: a #GMainLoop.
4157 * Checks to see if the main loop is currently being run via g_main_loop_run().
4159 * Returns: %TRUE if the mainloop is currently being run.
4162 g_main_loop_is_running (GMainLoop
*loop
)
4164 g_return_val_if_fail (loop
!= NULL
, FALSE
);
4165 g_return_val_if_fail (g_atomic_int_get (&loop
->ref_count
) > 0, FALSE
);
4167 return loop
->is_running
;
4171 * g_main_loop_get_context:
4172 * @loop: a #GMainLoop.
4174 * Returns the #GMainContext of @loop.
4176 * Returns: (transfer none): the #GMainContext of @loop
4179 g_main_loop_get_context (GMainLoop
*loop
)
4181 g_return_val_if_fail (loop
!= NULL
, NULL
);
4182 g_return_val_if_fail (g_atomic_int_get (&loop
->ref_count
) > 0, NULL
);
4184 return loop
->context
;
4187 /* HOLDS: context's lock */
4189 g_main_context_poll (GMainContext
*context
,
4195 #ifdef G_MAIN_POLL_DEBUG
4201 GPollFunc poll_func
;
4203 if (n_fds
|| timeout
!= 0)
4207 #ifdef G_MAIN_POLL_DEBUG
4209 if (_g_main_poll_debug
)
4211 g_print ("polling context=%p n=%d timeout=%d\n",
4212 context
, n_fds
, timeout
);
4213 poll_timer
= g_timer_new ();
4217 LOCK_CONTEXT (context
);
4219 poll_func
= context
->poll_func
;
4221 UNLOCK_CONTEXT (context
);
4222 ret
= (*poll_func
) (fds
, n_fds
, timeout
);
4224 if (ret
< 0 && errsv
!= EINTR
)
4227 g_warning ("poll(2) failed due to: %s.",
4228 g_strerror (errsv
));
4230 /* If g_poll () returns -1, it has already called g_warning() */
4234 #ifdef G_MAIN_POLL_DEBUG
4235 if (_g_main_poll_debug
)
4237 LOCK_CONTEXT (context
);
4239 g_print ("g_main_poll(%d) timeout: %d - elapsed %12.10f seconds",
4242 g_timer_elapsed (poll_timer
, NULL
));
4243 g_timer_destroy (poll_timer
);
4244 pollrec
= context
->poll_records
;
4246 while (pollrec
!= NULL
)
4251 if (fds
[i
].fd
== pollrec
->fd
->fd
&&
4252 pollrec
->fd
->events
&&
4255 g_print (" [" G_POLLFD_FORMAT
" :", fds
[i
].fd
);
4256 if (fds
[i
].revents
& G_IO_IN
)
4258 if (fds
[i
].revents
& G_IO_OUT
)
4260 if (fds
[i
].revents
& G_IO_PRI
)
4262 if (fds
[i
].revents
& G_IO_ERR
)
4264 if (fds
[i
].revents
& G_IO_HUP
)
4266 if (fds
[i
].revents
& G_IO_NVAL
)
4272 pollrec
= pollrec
->next
;
4276 UNLOCK_CONTEXT (context
);
4279 } /* if (n_fds || timeout != 0) */
4283 * g_main_context_add_poll:
4284 * @context: (nullable): a #GMainContext (or %NULL for the default context)
4285 * @fd: a #GPollFD structure holding information about a file
4286 * descriptor to watch.
4287 * @priority: the priority for this file descriptor which should be
4288 * the same as the priority used for g_source_attach() to ensure that the
4289 * file descriptor is polled whenever the results may be needed.
4291 * Adds a file descriptor to the set of file descriptors polled for
4292 * this context. This will very seldom be used directly. Instead
4293 * a typical event source will use g_source_add_unix_fd() instead.
4296 g_main_context_add_poll (GMainContext
*context
,
4301 context
= g_main_context_default ();
4303 g_return_if_fail (g_atomic_int_get (&context
->ref_count
) > 0);
4304 g_return_if_fail (fd
);
4306 LOCK_CONTEXT (context
);
4307 g_main_context_add_poll_unlocked (context
, priority
, fd
);
4308 UNLOCK_CONTEXT (context
);
4311 /* HOLDS: main_loop_lock */
4313 g_main_context_add_poll_unlocked (GMainContext
*context
,
4317 GPollRec
*prevrec
, *nextrec
;
4318 GPollRec
*newrec
= g_slice_new (GPollRec
);
4320 /* This file descriptor may be checked before we ever poll */
4323 newrec
->priority
= priority
;
4326 nextrec
= context
->poll_records
;
4329 if (nextrec
->fd
->fd
> fd
->fd
)
4332 nextrec
= nextrec
->next
;
4336 prevrec
->next
= newrec
;
4338 context
->poll_records
= newrec
;
4340 newrec
->prev
= prevrec
;
4341 newrec
->next
= nextrec
;
4344 nextrec
->prev
= newrec
;
4346 context
->n_poll_records
++;
4348 context
->poll_changed
= TRUE
;
4350 /* Now wake up the main loop if it is waiting in the poll() */
4351 conditional_wakeup (context
);
4355 * g_main_context_remove_poll:
4356 * @context:a #GMainContext
4357 * @fd: a #GPollFD descriptor previously added with g_main_context_add_poll()
4359 * Removes file descriptor from the set of file descriptors to be
4360 * polled for a particular context.
4363 g_main_context_remove_poll (GMainContext
*context
,
4367 context
= g_main_context_default ();
4369 g_return_if_fail (g_atomic_int_get (&context
->ref_count
) > 0);
4370 g_return_if_fail (fd
);
4372 LOCK_CONTEXT (context
);
4373 g_main_context_remove_poll_unlocked (context
, fd
);
4374 UNLOCK_CONTEXT (context
);
4378 g_main_context_remove_poll_unlocked (GMainContext
*context
,
4381 GPollRec
*pollrec
, *prevrec
, *nextrec
;
4384 pollrec
= context
->poll_records
;
4388 nextrec
= pollrec
->next
;
4389 if (pollrec
->fd
== fd
)
4391 if (prevrec
!= NULL
)
4392 prevrec
->next
= nextrec
;
4394 context
->poll_records
= nextrec
;
4396 if (nextrec
!= NULL
)
4397 nextrec
->prev
= prevrec
;
4399 g_slice_free (GPollRec
, pollrec
);
4401 context
->n_poll_records
--;
4408 context
->poll_changed
= TRUE
;
4410 /* Now wake up the main loop if it is waiting in the poll() */
4411 conditional_wakeup (context
);
4415 * g_source_get_current_time:
4416 * @source: a #GSource
4417 * @timeval: #GTimeVal structure in which to store current time.
4419 * This function ignores @source and is otherwise the same as
4420 * g_get_current_time().
4422 * Deprecated: 2.28: use g_source_get_time() instead
4425 g_source_get_current_time (GSource
*source
,
4428 g_get_current_time (timeval
);
4432 * g_source_get_time:
4433 * @source: a #GSource
4435 * Gets the time to be used when checking this source. The advantage of
4436 * calling this function over calling g_get_monotonic_time() directly is
4437 * that when checking multiple sources, GLib can cache a single value
4438 * instead of having to repeatedly get the system monotonic time.
4440 * The time here is the system monotonic time, if available, or some
4441 * other reasonable alternative otherwise. See g_get_monotonic_time().
4443 * Returns: the monotonic time in microseconds
4448 g_source_get_time (GSource
*source
)
4450 GMainContext
*context
;
4453 g_return_val_if_fail (source
->context
!= NULL
, 0);
4455 context
= source
->context
;
4457 LOCK_CONTEXT (context
);
4459 if (!context
->time_is_fresh
)
4461 context
->time
= g_get_monotonic_time ();
4462 context
->time_is_fresh
= TRUE
;
4465 result
= context
->time
;
4467 UNLOCK_CONTEXT (context
);
4473 * g_main_context_set_poll_func:
4474 * @context: a #GMainContext
4475 * @func: the function to call to poll all file descriptors
4477 * Sets the function to use to handle polling of file descriptors. It
4478 * will be used instead of the poll() system call
4479 * (or GLib's replacement function, which is used where
4480 * poll() isn't available).
4482 * This function could possibly be used to integrate the GLib event
4483 * loop with an external event loop.
4486 g_main_context_set_poll_func (GMainContext
*context
,
4490 context
= g_main_context_default ();
4492 g_return_if_fail (g_atomic_int_get (&context
->ref_count
) > 0);
4494 LOCK_CONTEXT (context
);
4497 context
->poll_func
= func
;
4499 context
->poll_func
= g_poll
;
4501 UNLOCK_CONTEXT (context
);
4505 * g_main_context_get_poll_func:
4506 * @context: a #GMainContext
4508 * Gets the poll function set by g_main_context_set_poll_func().
4510 * Returns: the poll function
4513 g_main_context_get_poll_func (GMainContext
*context
)
4518 context
= g_main_context_default ();
4520 g_return_val_if_fail (g_atomic_int_get (&context
->ref_count
) > 0, NULL
);
4522 LOCK_CONTEXT (context
);
4523 result
= context
->poll_func
;
4524 UNLOCK_CONTEXT (context
);
4530 * g_main_context_wakeup:
4531 * @context: a #GMainContext
4533 * If @context is currently blocking in g_main_context_iteration()
4534 * waiting for a source to become ready, cause it to stop blocking
4535 * and return. Otherwise, cause the next invocation of
4536 * g_main_context_iteration() to return without blocking.
4538 * This API is useful for low-level control over #GMainContext; for
4539 * example, integrating it with main loop implementations such as
4542 * Another related use for this function is when implementing a main
4543 * loop with a termination condition, computed from multiple threads:
4545 * |[<!-- language="C" -->
4546 * #define NUM_TASKS 10
4547 * static volatile gint tasks_remaining = NUM_TASKS;
4550 * while (g_atomic_int_get (&tasks_remaining) != 0)
4551 * g_main_context_iteration (NULL, TRUE);
4555 * |[<!-- language="C" -->
4558 * if (g_atomic_int_dec_and_test (&tasks_remaining))
4559 * g_main_context_wakeup (NULL);
4563 g_main_context_wakeup (GMainContext
*context
)
4566 context
= g_main_context_default ();
4568 g_return_if_fail (g_atomic_int_get (&context
->ref_count
) > 0);
4570 TRACE (GLIB_MAIN_CONTEXT_WAKEUP (context
));
4572 g_wakeup_signal (context
->wakeup
);
4576 * g_main_context_is_owner:
4577 * @context: a #GMainContext
4579 * Determines whether this thread holds the (recursive)
4580 * ownership of this #GMainContext. This is useful to
4581 * know before waiting on another thread that may be
4582 * blocking to get ownership of @context.
4584 * Returns: %TRUE if current thread is owner of @context.
4589 g_main_context_is_owner (GMainContext
*context
)
4594 context
= g_main_context_default ();
4596 LOCK_CONTEXT (context
);
4597 is_owner
= context
->owner
== G_THREAD_SELF
;
4598 UNLOCK_CONTEXT (context
);
4606 g_timeout_set_expiration (GTimeoutSource
*timeout_source
,
4607 gint64 current_time
)
4611 expiration
= current_time
+ (guint64
) timeout_source
->interval
* 1000;
4613 if (timeout_source
->seconds
)
4616 static gint timer_perturb
= -1;
4618 if (timer_perturb
== -1)
4621 * we want a per machine/session unique 'random' value; try the dbus
4622 * address first, that has a UUID in it. If there is no dbus, use the
4623 * hostname for hashing.
4625 const char *session_bus_address
= g_getenv ("DBUS_SESSION_BUS_ADDRESS");
4626 if (!session_bus_address
)
4627 session_bus_address
= g_getenv ("HOSTNAME");
4628 if (session_bus_address
)
4629 timer_perturb
= ABS ((gint
) g_str_hash (session_bus_address
)) % 1000000;
4634 /* We want the microseconds part of the timeout to land on the
4635 * 'timer_perturb' mark, but we need to make sure we don't try to
4636 * set the timeout in the past. We do this by ensuring that we
4637 * always only *increase* the expiration time by adding a full
4638 * second in the case that the microsecond portion decreases.
4640 expiration
-= timer_perturb
;
4642 remainder
= expiration
% 1000000;
4643 if (remainder
>= 1000000/4)
4644 expiration
+= 1000000;
4646 expiration
-= remainder
;
4647 expiration
+= timer_perturb
;
4650 g_source_set_ready_time ((GSource
*) timeout_source
, expiration
);
4654 g_timeout_dispatch (GSource
*source
,
4655 GSourceFunc callback
,
4658 GTimeoutSource
*timeout_source
= (GTimeoutSource
*)source
;
4663 g_warning ("Timeout source dispatched without callback\n"
4664 "You must call g_source_set_callback().");
4668 again
= callback (user_data
);
4670 TRACE (GLIB_TIMEOUT_DISPATCH (source
, source
->context
, callback
, user_data
, again
));
4673 g_timeout_set_expiration (timeout_source
, g_source_get_time (source
));
4679 * g_timeout_source_new:
4680 * @interval: the timeout interval in milliseconds.
4682 * Creates a new timeout source.
4684 * The source will not initially be associated with any #GMainContext
4685 * and must be added to one with g_source_attach() before it will be
4688 * The interval given is in terms of monotonic time, not wall clock
4689 * time. See g_get_monotonic_time().
4691 * Returns: the newly-created timeout source
4694 g_timeout_source_new (guint interval
)
4696 GSource
*source
= g_source_new (&g_timeout_funcs
, sizeof (GTimeoutSource
));
4697 GTimeoutSource
*timeout_source
= (GTimeoutSource
*)source
;
4699 timeout_source
->interval
= interval
;
4700 g_timeout_set_expiration (timeout_source
, g_get_monotonic_time ());
4706 * g_timeout_source_new_seconds:
4707 * @interval: the timeout interval in seconds
4709 * Creates a new timeout source.
4711 * The source will not initially be associated with any #GMainContext
4712 * and must be added to one with g_source_attach() before it will be
4715 * The scheduling granularity/accuracy of this timeout source will be
4718 * The interval given in terms of monotonic time, not wall clock time.
4719 * See g_get_monotonic_time().
4721 * Returns: the newly-created timeout source
4726 g_timeout_source_new_seconds (guint interval
)
4728 GSource
*source
= g_source_new (&g_timeout_funcs
, sizeof (GTimeoutSource
));
4729 GTimeoutSource
*timeout_source
= (GTimeoutSource
*)source
;
4731 timeout_source
->interval
= 1000 * interval
;
4732 timeout_source
->seconds
= TRUE
;
4734 g_timeout_set_expiration (timeout_source
, g_get_monotonic_time ());
4741 * g_timeout_add_full: (rename-to g_timeout_add)
4742 * @priority: the priority of the timeout source. Typically this will be in
4743 * the range between #G_PRIORITY_DEFAULT and #G_PRIORITY_HIGH.
4744 * @interval: the time between calls to the function, in milliseconds
4745 * (1/1000ths of a second)
4746 * @function: function to call
4747 * @data: data to pass to @function
4748 * @notify: (nullable): function to call when the timeout is removed, or %NULL
4750 * Sets a function to be called at regular intervals, with the given
4751 * priority. The function is called repeatedly until it returns
4752 * %FALSE, at which point the timeout is automatically destroyed and
4753 * the function will not be called again. The @notify function is
4754 * called when the timeout is destroyed. The first call to the
4755 * function will be at the end of the first @interval.
4757 * Note that timeout functions may be delayed, due to the processing of other
4758 * event sources. Thus they should not be relied on for precise timing.
4759 * After each call to the timeout function, the time of the next
4760 * timeout is recalculated based on the current time and the given interval
4761 * (it does not try to 'catch up' time lost in delays).
4763 * See [memory management of sources][mainloop-memory-management] for details
4764 * on how to handle the return value and memory management of @data.
4766 * This internally creates a main loop source using g_timeout_source_new()
4767 * and attaches it to the global #GMainContext using g_source_attach(), so
4768 * the callback will be invoked in whichever thread is running that main
4769 * context. You can do these steps manually if you need greater control or to
4770 * use a custom main context.
4772 * The interval given in terms of monotonic time, not wall clock time.
4773 * See g_get_monotonic_time().
4775 * Returns: the ID (greater than 0) of the event source.
4778 g_timeout_add_full (gint priority
,
4780 GSourceFunc function
,
4782 GDestroyNotify notify
)
4787 g_return_val_if_fail (function
!= NULL
, 0);
4789 source
= g_timeout_source_new (interval
);
4791 if (priority
!= G_PRIORITY_DEFAULT
)
4792 g_source_set_priority (source
, priority
);
4794 g_source_set_callback (source
, function
, data
, notify
);
4795 id
= g_source_attach (source
, NULL
);
4797 TRACE (GLIB_TIMEOUT_ADD (source
, g_main_context_default (), id
, priority
, interval
, function
, data
));
4799 g_source_unref (source
);
4806 * @interval: the time between calls to the function, in milliseconds
4807 * (1/1000ths of a second)
4808 * @function: function to call
4809 * @data: data to pass to @function
4811 * Sets a function to be called at regular intervals, with the default
4812 * priority, #G_PRIORITY_DEFAULT. The function is called repeatedly
4813 * until it returns %FALSE, at which point the timeout is automatically
4814 * destroyed and the function will not be called again. The first call
4815 * to the function will be at the end of the first @interval.
4817 * Note that timeout functions may be delayed, due to the processing of other
4818 * event sources. Thus they should not be relied on for precise timing.
4819 * After each call to the timeout function, the time of the next
4820 * timeout is recalculated based on the current time and the given interval
4821 * (it does not try to 'catch up' time lost in delays).
4823 * See [memory management of sources][mainloop-memory-management] for details
4824 * on how to handle the return value and memory management of @data.
4826 * If you want to have a timer in the "seconds" range and do not care
4827 * about the exact time of the first call of the timer, use the
4828 * g_timeout_add_seconds() function; this function allows for more
4829 * optimizations and more efficient system power usage.
4831 * This internally creates a main loop source using g_timeout_source_new()
4832 * and attaches it to the global #GMainContext using g_source_attach(), so
4833 * the callback will be invoked in whichever thread is running that main
4834 * context. You can do these steps manually if you need greater control or to
4835 * use a custom main context.
4837 * The interval given is in terms of monotonic time, not wall clock
4838 * time. See g_get_monotonic_time().
4840 * Returns: the ID (greater than 0) of the event source.
4843 g_timeout_add (guint32 interval
,
4844 GSourceFunc function
,
4847 return g_timeout_add_full (G_PRIORITY_DEFAULT
,
4848 interval
, function
, data
, NULL
);
4852 * g_timeout_add_seconds_full: (rename-to g_timeout_add_seconds)
4853 * @priority: the priority of the timeout source. Typically this will be in
4854 * the range between #G_PRIORITY_DEFAULT and #G_PRIORITY_HIGH.
4855 * @interval: the time between calls to the function, in seconds
4856 * @function: function to call
4857 * @data: data to pass to @function
4858 * @notify: (nullable): function to call when the timeout is removed, or %NULL
4860 * Sets a function to be called at regular intervals, with @priority.
4861 * The function is called repeatedly until it returns %FALSE, at which
4862 * point the timeout is automatically destroyed and the function will
4863 * not be called again.
4865 * Unlike g_timeout_add(), this function operates at whole second granularity.
4866 * The initial starting point of the timer is determined by the implementation
4867 * and the implementation is expected to group multiple timers together so that
4868 * they fire all at the same time.
4869 * To allow this grouping, the @interval to the first timer is rounded
4870 * and can deviate up to one second from the specified interval.
4871 * Subsequent timer iterations will generally run at the specified interval.
4873 * Note that timeout functions may be delayed, due to the processing of other
4874 * event sources. Thus they should not be relied on for precise timing.
4875 * After each call to the timeout function, the time of the next
4876 * timeout is recalculated based on the current time and the given @interval
4878 * See [memory management of sources][mainloop-memory-management] for details
4879 * on how to handle the return value and memory management of @data.
4881 * If you want timing more precise than whole seconds, use g_timeout_add()
4884 * The grouping of timers to fire at the same time results in a more power
4885 * and CPU efficient behavior so if your timer is in multiples of seconds
4886 * and you don't require the first timer exactly one second from now, the
4887 * use of g_timeout_add_seconds() is preferred over g_timeout_add().
4889 * This internally creates a main loop source using
4890 * g_timeout_source_new_seconds() and attaches it to the main loop context
4891 * using g_source_attach(). You can do these steps manually if you need
4894 * The interval given is in terms of monotonic time, not wall clock
4895 * time. See g_get_monotonic_time().
4897 * Returns: the ID (greater than 0) of the event source.
4902 g_timeout_add_seconds_full (gint priority
,
4904 GSourceFunc function
,
4906 GDestroyNotify notify
)
4911 g_return_val_if_fail (function
!= NULL
, 0);
4913 source
= g_timeout_source_new_seconds (interval
);
4915 if (priority
!= G_PRIORITY_DEFAULT
)
4916 g_source_set_priority (source
, priority
);
4918 g_source_set_callback (source
, function
, data
, notify
);
4919 id
= g_source_attach (source
, NULL
);
4920 g_source_unref (source
);
4926 * g_timeout_add_seconds:
4927 * @interval: the time between calls to the function, in seconds
4928 * @function: function to call
4929 * @data: data to pass to @function
4931 * Sets a function to be called at regular intervals with the default
4932 * priority, #G_PRIORITY_DEFAULT. The function is called repeatedly until
4933 * it returns %FALSE, at which point the timeout is automatically destroyed
4934 * and the function will not be called again.
4936 * This internally creates a main loop source using
4937 * g_timeout_source_new_seconds() and attaches it to the main loop context
4938 * using g_source_attach(). You can do these steps manually if you need
4939 * greater control. Also see g_timeout_add_seconds_full().
4941 * Note that the first call of the timer may not be precise for timeouts
4942 * of one second. If you need finer precision and have such a timeout,
4943 * you may want to use g_timeout_add() instead.
4945 * See [memory management of sources][mainloop-memory-management] for details
4946 * on how to handle the return value and memory management of @data.
4948 * The interval given is in terms of monotonic time, not wall clock
4949 * time. See g_get_monotonic_time().
4951 * Returns: the ID (greater than 0) of the event source.
4956 g_timeout_add_seconds (guint interval
,
4957 GSourceFunc function
,
4960 g_return_val_if_fail (function
!= NULL
, 0);
4962 return g_timeout_add_seconds_full (G_PRIORITY_DEFAULT
, interval
, function
, data
, NULL
);
4965 /* Child watch functions */
4970 g_child_watch_prepare (GSource
*source
,
4978 g_child_watch_check (GSource
*source
)
4980 GChildWatchSource
*child_watch_source
;
4981 gboolean child_exited
;
4983 child_watch_source
= (GChildWatchSource
*) source
;
4985 child_exited
= child_watch_source
->poll
.revents
& G_IO_IN
;
4992 * Note: We do _not_ check for the special value of STILL_ACTIVE
4993 * since we know that the process has exited and doing so runs into
4994 * problems if the child process "happens to return STILL_ACTIVE(259)"
4995 * as Microsoft's Platform SDK puts it.
4997 if (!GetExitCodeProcess (child_watch_source
->pid
, &child_status
))
4999 gchar
*emsg
= g_win32_error_message (GetLastError ());
5000 g_warning (G_STRLOC
": GetExitCodeProcess() failed: %s", emsg
);
5003 child_watch_source
->child_status
= -1;
5006 child_watch_source
->child_status
= child_status
;
5009 return child_exited
;
5013 g_child_watch_finalize (GSource
*source
)
5017 #else /* G_OS_WIN32 */
5020 wake_source (GSource
*source
)
5022 GMainContext
*context
;
5024 /* This should be thread-safe:
5026 * - if the source is currently being added to a context, that
5027 * context will be woken up anyway
5029 * - if the source is currently being destroyed, we simply need not
5032 * - the memory for the source will remain valid until after the
5033 * source finalize function was called (which would remove the
5034 * source from the global list which we are currently holding the
5037 * - the GMainContext will either be NULL or point to a live
5040 * - the GMainContext will remain valid since we hold the
5041 * main_context_list lock
5043 * Since we are holding a lot of locks here, don't try to enter any
5044 * more GMainContext functions for fear of dealock -- just hit the
5045 * GWakeup and run. Even if that's safe now, it could easily become
5046 * unsafe with some very minor changes in the future, and signal
5047 * handling is not the most well-tested codepath.
5049 G_LOCK(main_context_list
);
5050 context
= source
->context
;
5052 g_wakeup_signal (context
->wakeup
);
5053 G_UNLOCK(main_context_list
);
5057 dispatch_unix_signals_unlocked (void)
5059 gboolean pending
[NSIG
];
5063 /* clear this first in case another one arrives while we're processing */
5064 any_unix_signal_pending
= FALSE
;
5066 /* We atomically test/clear the bit from the global array in case
5067 * other signals arrive while we are dispatching.
5069 * We then can safely use our own array below without worrying about
5072 for (i
= 0; i
< NSIG
; i
++)
5074 /* Be very careful with (the volatile) unix_signal_pending.
5076 * We must ensure that it's not possible that we clear it without
5077 * handling the signal. We therefore must ensure that our pending
5078 * array has a field set (ie: we will do something about the
5079 * signal) before we clear the item in unix_signal_pending.
5081 * Note specifically: we must check _our_ array.
5083 pending
[i
] = unix_signal_pending
[i
];
5085 unix_signal_pending
[i
] = FALSE
;
5088 /* handle GChildWatchSource instances */
5089 if (pending
[SIGCHLD
])
5091 /* The only way we can do this is to scan all of the children.
5093 * The docs promise that we will not reap children that we are not
5094 * explicitly watching, so that ties our hands from calling
5095 * waitpid(-1). We also can't use siginfo's si_pid field since if
5096 * multiple SIGCHLD arrive at the same time, one of them can be
5097 * dropped (since a given UNIX signal can only be pending once).
5099 for (node
= unix_child_watches
; node
; node
= node
->next
)
5101 GChildWatchSource
*source
= node
->data
;
5103 if (!source
->child_exited
)
5108 g_assert (source
->pid
> 0);
5110 pid
= waitpid (source
->pid
, &source
->child_status
, WNOHANG
);
5113 source
->child_exited
= TRUE
;
5114 wake_source ((GSource
*) source
);
5116 else if (pid
== -1 && errno
== ECHILD
)
5118 g_warning ("GChildWatchSource: Exit status of a child process was requested but ECHILD was received by waitpid(). See the documentation of g_child_watch_source_new() for possible causes.");
5119 source
->child_exited
= TRUE
;
5120 source
->child_status
= 0;
5121 wake_source ((GSource
*) source
);
5124 while (pid
== -1 && errno
== EINTR
);
5129 /* handle GUnixSignalWatchSource instances */
5130 for (node
= unix_signal_watches
; node
; node
= node
->next
)
5132 GUnixSignalWatchSource
*source
= node
->data
;
5134 if (!source
->pending
)
5136 if (pending
[source
->signum
])
5138 source
->pending
= TRUE
;
5140 wake_source ((GSource
*) source
);
5148 dispatch_unix_signals (void)
5150 G_LOCK(unix_signal_lock
);
5151 dispatch_unix_signals_unlocked ();
5152 G_UNLOCK(unix_signal_lock
);
5156 g_child_watch_prepare (GSource
*source
,
5159 GChildWatchSource
*child_watch_source
;
5161 child_watch_source
= (GChildWatchSource
*) source
;
5163 return child_watch_source
->child_exited
;
5167 g_child_watch_check (GSource
*source
)
5169 GChildWatchSource
*child_watch_source
;
5171 child_watch_source
= (GChildWatchSource
*) source
;
5173 return child_watch_source
->child_exited
;
5177 g_unix_signal_watch_prepare (GSource
*source
,
5180 GUnixSignalWatchSource
*unix_signal_source
;
5182 unix_signal_source
= (GUnixSignalWatchSource
*) source
;
5184 return unix_signal_source
->pending
;
5188 g_unix_signal_watch_check (GSource
*source
)
5190 GUnixSignalWatchSource
*unix_signal_source
;
5192 unix_signal_source
= (GUnixSignalWatchSource
*) source
;
5194 return unix_signal_source
->pending
;
5198 g_unix_signal_watch_dispatch (GSource
*source
,
5199 GSourceFunc callback
,
5202 GUnixSignalWatchSource
*unix_signal_source
;
5205 unix_signal_source
= (GUnixSignalWatchSource
*) source
;
5209 g_warning ("Unix signal source dispatched without callback\n"
5210 "You must call g_source_set_callback().");
5214 again
= (callback
) (user_data
);
5216 unix_signal_source
->pending
= FALSE
;
5222 ref_unix_signal_handler_unlocked (int signum
)
5224 /* Ensure we have the worker context */
5225 g_get_worker_context ();
5226 unix_signal_refcount
[signum
]++;
5227 if (unix_signal_refcount
[signum
] == 1)
5229 struct sigaction action
;
5230 action
.sa_handler
= g_unix_signal_handler
;
5231 sigemptyset (&action
.sa_mask
);
5233 action
.sa_flags
= SA_RESTART
| SA_NOCLDSTOP
;
5235 action
.sa_flags
= SA_NOCLDSTOP
;
5237 sigaction (signum
, &action
, NULL
);
5242 unref_unix_signal_handler_unlocked (int signum
)
5244 unix_signal_refcount
[signum
]--;
5245 if (unix_signal_refcount
[signum
] == 0)
5247 struct sigaction action
;
5248 memset (&action
, 0, sizeof (action
));
5249 action
.sa_handler
= SIG_DFL
;
5250 sigemptyset (&action
.sa_mask
);
5251 sigaction (signum
, &action
, NULL
);
5256 _g_main_create_unix_signal_watch (int signum
)
5259 GUnixSignalWatchSource
*unix_signal_source
;
5261 source
= g_source_new (&g_unix_signal_funcs
, sizeof (GUnixSignalWatchSource
));
5262 unix_signal_source
= (GUnixSignalWatchSource
*) source
;
5264 unix_signal_source
->signum
= signum
;
5265 unix_signal_source
->pending
= FALSE
;
5267 G_LOCK (unix_signal_lock
);
5268 ref_unix_signal_handler_unlocked (signum
);
5269 unix_signal_watches
= g_slist_prepend (unix_signal_watches
, unix_signal_source
);
5270 dispatch_unix_signals_unlocked ();
5271 G_UNLOCK (unix_signal_lock
);
5277 g_unix_signal_watch_finalize (GSource
*source
)
5279 GUnixSignalWatchSource
*unix_signal_source
;
5281 unix_signal_source
= (GUnixSignalWatchSource
*) source
;
5283 G_LOCK (unix_signal_lock
);
5284 unref_unix_signal_handler_unlocked (unix_signal_source
->signum
);
5285 unix_signal_watches
= g_slist_remove (unix_signal_watches
, source
);
5286 G_UNLOCK (unix_signal_lock
);
5290 g_child_watch_finalize (GSource
*source
)
5292 G_LOCK (unix_signal_lock
);
5293 unix_child_watches
= g_slist_remove (unix_child_watches
, source
);
5294 unref_unix_signal_handler_unlocked (SIGCHLD
);
5295 G_UNLOCK (unix_signal_lock
);
5298 #endif /* G_OS_WIN32 */
5301 g_child_watch_dispatch (GSource
*source
,
5302 GSourceFunc callback
,
5305 GChildWatchSource
*child_watch_source
;
5306 GChildWatchFunc child_watch_callback
= (GChildWatchFunc
) callback
;
5308 child_watch_source
= (GChildWatchSource
*) source
;
5312 g_warning ("Child watch source dispatched without callback\n"
5313 "You must call g_source_set_callback().");
5317 (child_watch_callback
) (child_watch_source
->pid
, child_watch_source
->child_status
, user_data
);
5319 /* We never keep a child watch source around as the child is gone */
5326 g_unix_signal_handler (int signum
)
5328 gint saved_errno
= errno
;
5330 unix_signal_pending
[signum
] = TRUE
;
5331 any_unix_signal_pending
= TRUE
;
5333 g_wakeup_signal (glib_worker_context
->wakeup
);
5335 errno
= saved_errno
;
5338 #endif /* !G_OS_WIN32 */
5341 * g_child_watch_source_new:
5342 * @pid: process to watch. On POSIX the positive pid of a child process. On
5343 * Windows a handle for a process (which doesn't have to be a child).
5345 * Creates a new child_watch source.
5347 * The source will not initially be associated with any #GMainContext
5348 * and must be added to one with g_source_attach() before it will be
5351 * Note that child watch sources can only be used in conjunction with
5352 * `g_spawn...` when the %G_SPAWN_DO_NOT_REAP_CHILD flag is used.
5354 * Note that on platforms where #GPid must be explicitly closed
5355 * (see g_spawn_close_pid()) @pid must not be closed while the
5356 * source is still active. Typically, you will want to call
5357 * g_spawn_close_pid() in the callback function for the source.
5359 * On POSIX platforms, the following restrictions apply to this API
5360 * due to limitations in POSIX process interfaces:
5362 * * @pid must be a child of this process
5363 * * @pid must be positive
5364 * * the application must not call `waitpid` with a non-positive
5365 * first argument, for instance in another thread
5366 * * the application must not wait for @pid to exit by any other
5367 * mechanism, including `waitpid(pid, ...)` or a second child-watch
5368 * source for the same @pid
5369 * * the application must not ignore SIGCHILD
5371 * If any of those conditions are not met, this and related APIs will
5372 * not work correctly. This can often be diagnosed via a GLib warning
5373 * stating that `ECHILD` was received by `waitpid`.
5375 * Calling `waitpid` for specific processes other than @pid remains a
5376 * valid thing to do.
5378 * Returns: the newly-created child watch source
5383 g_child_watch_source_new (GPid pid
)
5386 GChildWatchSource
*child_watch_source
;
5389 g_return_val_if_fail (pid
> 0, NULL
);
5392 source
= g_source_new (&g_child_watch_funcs
, sizeof (GChildWatchSource
));
5393 child_watch_source
= (GChildWatchSource
*)source
;
5395 child_watch_source
->pid
= pid
;
5398 child_watch_source
->poll
.fd
= (gintptr
) pid
;
5399 child_watch_source
->poll
.events
= G_IO_IN
;
5401 g_source_add_poll (source
, &child_watch_source
->poll
);
5402 #else /* G_OS_WIN32 */
5403 G_LOCK (unix_signal_lock
);
5404 ref_unix_signal_handler_unlocked (SIGCHLD
);
5405 unix_child_watches
= g_slist_prepend (unix_child_watches
, child_watch_source
);
5406 if (waitpid (pid
, &child_watch_source
->child_status
, WNOHANG
) > 0)
5407 child_watch_source
->child_exited
= TRUE
;
5408 G_UNLOCK (unix_signal_lock
);
5409 #endif /* G_OS_WIN32 */
5415 * g_child_watch_add_full: (rename-to g_child_watch_add)
5416 * @priority: the priority of the idle source. Typically this will be in the
5417 * range between #G_PRIORITY_DEFAULT_IDLE and #G_PRIORITY_HIGH_IDLE.
5418 * @pid: process to watch. On POSIX the positive pid of a child process. On
5419 * Windows a handle for a process (which doesn't have to be a child).
5420 * @function: function to call
5421 * @data: data to pass to @function
5422 * @notify: (nullable): function to call when the idle is removed, or %NULL
5424 * Sets a function to be called when the child indicated by @pid
5425 * exits, at the priority @priority.
5427 * If you obtain @pid from g_spawn_async() or g_spawn_async_with_pipes()
5428 * you will need to pass #G_SPAWN_DO_NOT_REAP_CHILD as flag to
5429 * the spawn function for the child watching to work.
5431 * In many programs, you will want to call g_spawn_check_exit_status()
5432 * in the callback to determine whether or not the child exited
5435 * Also, note that on platforms where #GPid must be explicitly closed
5436 * (see g_spawn_close_pid()) @pid must not be closed while the source
5437 * is still active. Typically, you should invoke g_spawn_close_pid()
5438 * in the callback function for the source.
5440 * GLib supports only a single callback per process id.
5441 * On POSIX platforms, the same restrictions mentioned for
5442 * g_child_watch_source_new() apply to this function.
5444 * This internally creates a main loop source using
5445 * g_child_watch_source_new() and attaches it to the main loop context
5446 * using g_source_attach(). You can do these steps manually if you
5447 * need greater control.
5449 * Returns: the ID (greater than 0) of the event source.
5454 g_child_watch_add_full (gint priority
,
5456 GChildWatchFunc function
,
5458 GDestroyNotify notify
)
5463 g_return_val_if_fail (function
!= NULL
, 0);
5465 g_return_val_if_fail (pid
> 0, 0);
5468 source
= g_child_watch_source_new (pid
);
5470 if (priority
!= G_PRIORITY_DEFAULT
)
5471 g_source_set_priority (source
, priority
);
5473 g_source_set_callback (source
, (GSourceFunc
) function
, data
, notify
);
5474 id
= g_source_attach (source
, NULL
);
5475 g_source_unref (source
);
5481 * g_child_watch_add:
5482 * @pid: process id to watch. On POSIX the positive pid of a child
5483 * process. On Windows a handle for a process (which doesn't have to be
5485 * @function: function to call
5486 * @data: data to pass to @function
5488 * Sets a function to be called when the child indicated by @pid
5489 * exits, at a default priority, #G_PRIORITY_DEFAULT.
5491 * If you obtain @pid from g_spawn_async() or g_spawn_async_with_pipes()
5492 * you will need to pass #G_SPAWN_DO_NOT_REAP_CHILD as flag to
5493 * the spawn function for the child watching to work.
5495 * Note that on platforms where #GPid must be explicitly closed
5496 * (see g_spawn_close_pid()) @pid must not be closed while the
5497 * source is still active. Typically, you will want to call
5498 * g_spawn_close_pid() in the callback function for the source.
5500 * GLib supports only a single callback per process id.
5501 * On POSIX platforms, the same restrictions mentioned for
5502 * g_child_watch_source_new() apply to this function.
5504 * This internally creates a main loop source using
5505 * g_child_watch_source_new() and attaches it to the main loop context
5506 * using g_source_attach(). You can do these steps manually if you
5507 * need greater control.
5509 * Returns: the ID (greater than 0) of the event source.
5514 g_child_watch_add (GPid pid
,
5515 GChildWatchFunc function
,
5518 return g_child_watch_add_full (G_PRIORITY_DEFAULT
, pid
, function
, data
, NULL
);
5522 /* Idle functions */
5525 g_idle_prepare (GSource
*source
,
5534 g_idle_check (GSource
*source
)
5540 g_idle_dispatch (GSource
*source
,
5541 GSourceFunc callback
,
5548 g_warning ("Idle source dispatched without callback\n"
5549 "You must call g_source_set_callback().");
5553 again
= callback (user_data
);
5555 TRACE (GLIB_IDLE_DISPATCH (source
, source
->context
, callback
, user_data
, again
));
5561 * g_idle_source_new:
5563 * Creates a new idle source.
5565 * The source will not initially be associated with any #GMainContext
5566 * and must be added to one with g_source_attach() before it will be
5567 * executed. Note that the default priority for idle sources is
5568 * %G_PRIORITY_DEFAULT_IDLE, as compared to other sources which
5569 * have a default priority of %G_PRIORITY_DEFAULT.
5571 * Returns: the newly-created idle source
5574 g_idle_source_new (void)
5578 source
= g_source_new (&g_idle_funcs
, sizeof (GSource
));
5579 g_source_set_priority (source
, G_PRIORITY_DEFAULT_IDLE
);
5585 * g_idle_add_full: (rename-to g_idle_add)
5586 * @priority: the priority of the idle source. Typically this will be in the
5587 * range between #G_PRIORITY_DEFAULT_IDLE and #G_PRIORITY_HIGH_IDLE.
5588 * @function: function to call
5589 * @data: data to pass to @function
5590 * @notify: (nullable): function to call when the idle is removed, or %NULL
5592 * Adds a function to be called whenever there are no higher priority
5593 * events pending. If the function returns %FALSE it is automatically
5594 * removed from the list of event sources and will not be called again.
5596 * See [memory management of sources][mainloop-memory-management] for details
5597 * on how to handle the return value and memory management of @data.
5599 * This internally creates a main loop source using g_idle_source_new()
5600 * and attaches it to the global #GMainContext using g_source_attach(), so
5601 * the callback will be invoked in whichever thread is running that main
5602 * context. You can do these steps manually if you need greater control or to
5603 * use a custom main context.
5605 * Returns: the ID (greater than 0) of the event source.
5608 g_idle_add_full (gint priority
,
5609 GSourceFunc function
,
5611 GDestroyNotify notify
)
5616 g_return_val_if_fail (function
!= NULL
, 0);
5618 source
= g_idle_source_new ();
5620 if (priority
!= G_PRIORITY_DEFAULT_IDLE
)
5621 g_source_set_priority (source
, priority
);
5623 g_source_set_callback (source
, function
, data
, notify
);
5624 id
= g_source_attach (source
, NULL
);
5626 TRACE (GLIB_IDLE_ADD (source
, g_main_context_default (), id
, priority
, function
, data
));
5628 g_source_unref (source
);
5635 * @function: function to call
5636 * @data: data to pass to @function.
5638 * Adds a function to be called whenever there are no higher priority
5639 * events pending to the default main loop. The function is given the
5640 * default idle priority, #G_PRIORITY_DEFAULT_IDLE. If the function
5641 * returns %FALSE it is automatically removed from the list of event
5642 * sources and will not be called again.
5644 * See [memory management of sources][mainloop-memory-management] for details
5645 * on how to handle the return value and memory management of @data.
5647 * This internally creates a main loop source using g_idle_source_new()
5648 * and attaches it to the global #GMainContext using g_source_attach(), so
5649 * the callback will be invoked in whichever thread is running that main
5650 * context. You can do these steps manually if you need greater control or to
5651 * use a custom main context.
5653 * Returns: the ID (greater than 0) of the event source.
5656 g_idle_add (GSourceFunc function
,
5659 return g_idle_add_full (G_PRIORITY_DEFAULT_IDLE
, function
, data
, NULL
);
5663 * g_idle_remove_by_data:
5664 * @data: the data for the idle source's callback.
5666 * Removes the idle function with the given data.
5668 * Returns: %TRUE if an idle source was found and removed.
5671 g_idle_remove_by_data (gpointer data
)
5673 return g_source_remove_by_funcs_user_data (&g_idle_funcs
, data
);
5677 * g_main_context_invoke:
5678 * @context: (nullable): a #GMainContext, or %NULL
5679 * @function: function to call
5680 * @data: data to pass to @function
5682 * Invokes a function in such a way that @context is owned during the
5683 * invocation of @function.
5685 * If @context is %NULL then the global default main context — as
5686 * returned by g_main_context_default() — is used.
5688 * If @context is owned by the current thread, @function is called
5689 * directly. Otherwise, if @context is the thread-default main context
5690 * of the current thread and g_main_context_acquire() succeeds, then
5691 * @function is called and g_main_context_release() is called
5694 * In any other case, an idle source is created to call @function and
5695 * that source is attached to @context (presumably to be run in another
5696 * thread). The idle source is attached with #G_PRIORITY_DEFAULT
5697 * priority. If you want a different priority, use
5698 * g_main_context_invoke_full().
5700 * Note that, as with normal idle functions, @function should probably
5701 * return %FALSE. If it returns %TRUE, it will be continuously run in a
5702 * loop (and may prevent this call from returning).
5707 g_main_context_invoke (GMainContext
*context
,
5708 GSourceFunc function
,
5711 g_main_context_invoke_full (context
,
5713 function
, data
, NULL
);
5717 * g_main_context_invoke_full:
5718 * @context: (nullable): a #GMainContext, or %NULL
5719 * @priority: the priority at which to run @function
5720 * @function: function to call
5721 * @data: data to pass to @function
5722 * @notify: (nullable): a function to call when @data is no longer in use, or %NULL.
5724 * Invokes a function in such a way that @context is owned during the
5725 * invocation of @function.
5727 * This function is the same as g_main_context_invoke() except that it
5728 * lets you specify the priority in case @function ends up being
5729 * scheduled as an idle and also lets you give a #GDestroyNotify for @data.
5731 * @notify should not assume that it is called from any particular
5732 * thread or with any particular context acquired.
5737 g_main_context_invoke_full (GMainContext
*context
,
5739 GSourceFunc function
,
5741 GDestroyNotify notify
)
5743 g_return_if_fail (function
!= NULL
);
5746 context
= g_main_context_default ();
5748 if (g_main_context_is_owner (context
))
5750 while (function (data
));
5757 GMainContext
*thread_default
;
5759 thread_default
= g_main_context_get_thread_default ();
5761 if (!thread_default
)
5762 thread_default
= g_main_context_default ();
5764 if (thread_default
== context
&& g_main_context_acquire (context
))
5766 while (function (data
));
5768 g_main_context_release (context
);
5777 source
= g_idle_source_new ();
5778 g_source_set_priority (source
, priority
);
5779 g_source_set_callback (source
, function
, data
, notify
);
5780 g_source_attach (source
, context
);
5781 g_source_unref (source
);
5787 glib_worker_main (gpointer data
)
5791 g_main_context_iteration (glib_worker_context
, TRUE
);
5794 if (any_unix_signal_pending
)
5795 dispatch_unix_signals ();
5799 return NULL
; /* worst GCC warning message ever... */
5803 g_get_worker_context (void)
5805 static gsize initialised
;
5807 if (g_once_init_enter (&initialised
))
5809 /* mask all signals in the worker thread */
5815 pthread_sigmask (SIG_SETMASK
, &all
, &prev_mask
);
5817 glib_worker_context
= g_main_context_new ();
5818 g_thread_new ("gmain", glib_worker_main
, NULL
);
5820 pthread_sigmask (SIG_SETMASK
, &prev_mask
, NULL
);
5822 g_once_init_leave (&initialised
, TRUE
);
5825 return glib_worker_context
;