meson: Use glib-mkenums directly instead of via build_mkenum.py
[glib.git] / glib / gmain.c
blob65665711d44c1b60615fcba4d8dac136116b9b4a
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/.
29 * MT safe
32 #include "config.h"
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 */
42 #ifdef _WIN32
43 /* Always enable debugging printout on Windows, as it is more often
44 * needed there...
46 #define G_MAIN_POLL_DEBUG
47 #endif
49 #ifdef G_OS_UNIX
50 #include "glib-unix.h"
51 #include <pthread.h>
52 #ifdef HAVE_EVENTFD
53 #include <sys/eventfd.h>
54 #endif
55 #endif
57 #include <signal.h>
58 #include <sys/types.h>
59 #include <time.h>
60 #include <stdlib.h>
61 #ifdef HAVE_SYS_TIME_H
62 #include <sys/time.h>
63 #endif /* HAVE_SYS_TIME_H */
64 #ifdef G_OS_UNIX
65 #include <unistd.h>
66 #endif /* G_OS_UNIX */
67 #include <errno.h>
68 #include <string.h>
70 #ifdef G_OS_WIN32
71 #define STRICT
72 #include <windows.h>
73 #endif /* G_OS_WIN32 */
75 #ifdef HAVE_MACH_MACH_TIME_H
76 #include <mach/mach_time.h>
77 #endif
79 #include "glib_trace.h"
81 #include "gmain.h"
83 #include "garray.h"
84 #include "giochannel.h"
85 #include "ghash.h"
86 #include "ghook.h"
87 #include "gqueue.h"
88 #include "gstrfuncs.h"
89 #include "gtestutils.h"
91 #ifdef G_OS_WIN32
92 #include "gwin32.h"
93 #endif
95 #ifdef G_MAIN_POLL_DEBUG
96 #include "gtimer.h"
97 #endif
99 #include "gwakeup.h"
100 #include "gmain-internal.h"
101 #include "glib-init.h"
102 #include "glib-private.h"
105 * SECTION:main
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.
217 /* Types */
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;
225 typedef enum
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)
230 } GSourceFlags;
232 typedef struct _GSourceList GSourceList;
234 struct _GSourceList
236 GSource *head, *tail;
237 gint priority;
240 typedef struct _GMainWaiter GMainWaiter;
242 struct _GMainWaiter
244 GCond *cond;
245 GMutex *mutex;
248 typedef struct _GMainDispatch GMainDispatch;
250 struct _GMainDispatch
252 gint depth;
253 GSource *source;
256 #ifdef G_MAIN_POLL_DEBUG
257 gboolean _g_main_poll_debug = FALSE;
258 #endif
260 struct _GMainContext
262 /* The following lock is used for both the list of sources
263 * and the list of poll records
265 GMutex mutex;
266 GCond cond;
267 GThread *owner;
268 guint owner_count;
269 GSList *waiters;
271 gint ref_count;
273 GHashTable *sources; /* guint -> GSource */
275 GPtrArray *pending_dispatches;
276 gint timeout; /* Timeout for current iteration */
278 guint next_id;
279 GList *source_lists;
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;
288 GWakeup *wakeup;
290 GPollFD wake_up_rec;
292 /* Flag indicating whether the set of fd's changed during a poll */
293 gboolean poll_changed;
295 GPollFunc poll_func;
297 gint64 time;
298 gboolean time_is_fresh;
301 struct _GSourceCallback
303 guint ref_count;
304 GSourceFunc func;
305 gpointer data;
306 GDestroyNotify notify;
309 struct _GMainLoop
311 GMainContext *context;
312 gboolean is_running;
313 gint ref_count;
316 struct _GTimeoutSource
318 GSource source;
319 guint interval;
320 gboolean seconds;
323 struct _GChildWatchSource
325 GSource source;
326 GPid pid;
327 gint child_status;
328 #ifdef G_OS_WIN32
329 GPollFD poll;
330 #else /* G_OS_WIN32 */
331 gboolean child_exited;
332 #endif /* G_OS_WIN32 */
335 struct _GUnixSignalWatchSource
337 GSource source;
338 int signum;
339 gboolean pending;
342 struct _GPollRec
344 GPollFD *fd;
345 GPollRec *prev;
346 GPollRec *next;
347 gint priority;
350 struct _GSourcePrivate
352 GSList *child_sources;
353 GSource *parent_source;
355 gint64 ready_time;
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.
360 GSList *fds;
363 typedef struct _GSourceIter
365 GMainContext *context;
366 gboolean may_modify;
367 GList *current_list;
368 GSource *source;
369 } GSourceIter;
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) \
379 G_STMT_START { \
380 if ((source)->ref_count > 1) \
381 (source)->ref_count--; \
382 else \
383 g_source_unref_internal ((source), (context), TRUE); \
384 } G_STMT_END
387 /* Forward declarations */
389 static void g_source_unref_internal (GSource *source,
390 GMainContext *context,
391 gboolean have_lock);
392 static void g_source_destroy_internal (GSource *source,
393 GMainContext *context,
394 gboolean have_lock);
395 static void g_source_set_priority_unlocked (GSource *source,
396 GMainContext *context,
397 gint priority);
398 static void g_child_source_remove_internal (GSource *child_source,
399 GMainContext *context);
401 static void g_main_context_poll (GMainContext *context,
402 gint timeout,
403 gint priority,
404 GPollFD *fds,
405 gint n_fds);
406 static void g_main_context_add_poll_unlocked (GMainContext *context,
407 gint priority,
408 GPollFD *fd);
409 static void g_main_context_remove_poll_unlocked (GMainContext *context,
410 GPollFD *fd);
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,
416 GSource **source);
417 static void g_source_iter_clear (GSourceIter *iter);
419 static gboolean g_timeout_dispatch (GSource *source,
420 GSourceFunc callback,
421 gpointer user_data);
422 static gboolean g_child_watch_prepare (GSource *source,
423 gint *timeout);
424 static gboolean g_child_watch_check (GSource *source);
425 static gboolean g_child_watch_dispatch (GSource *source,
426 GSourceFunc callback,
427 gpointer user_data);
428 static void g_child_watch_finalize (GSource *source);
429 #ifdef G_OS_UNIX
430 static void g_unix_signal_handler (int signum);
431 static gboolean g_unix_signal_watch_prepare (GSource *source,
432 gint *timeout);
433 static gboolean g_unix_signal_watch_check (GSource *source);
434 static gboolean g_unix_signal_watch_dispatch (GSource *source,
435 GSourceFunc callback,
436 gpointer user_data);
437 static void g_unix_signal_watch_finalize (GSource *source);
438 #endif
439 static gboolean g_idle_prepare (GSource *source,
440 gint *timeout);
441 static gboolean g_idle_check (GSource *source);
442 static gboolean g_idle_dispatch (GSource *source,
443 GSourceFunc callback,
444 gpointer user_data);
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;
453 #ifndef G_OS_WIN32
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;
462 #else
463 static volatile int unix_signal_pending[NSIG];
464 static volatile int any_unix_signal_pending;
465 #endif
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 =
486 NULL, /* prepare */
487 NULL, /* check */
488 g_timeout_dispatch,
489 NULL
492 GSourceFuncs g_child_watch_funcs =
494 g_child_watch_prepare,
495 g_child_watch_check,
496 g_child_watch_dispatch,
497 g_child_watch_finalize
500 GSourceFuncs g_idle_funcs =
502 g_idle_prepare,
503 g_idle_check,
504 g_idle_dispatch,
505 NULL
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)
516 GMainContext *
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);
524 return context;
527 static inline void
528 poll_rec_list_free (GMainContext *context,
529 GPollRec *list)
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.
541 void
542 g_main_context_unref (GMainContext *context)
544 GSourceIter iter;
545 GSource *source;
546 GList *sl_iter;
547 GSourceList *list;
548 guint i;
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))
554 return;
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);
593 g_free (context);
596 /* Helper function used by mainloop/overflow test.
598 GMainContext *
599 g_main_context_new_with_next_id (guint next_id)
601 GMainContext *ret = g_main_context_new ();
603 ret->next_id = next_id;
605 return ret;
609 * g_main_context_new:
611 * Creates a new #GMainContext structure.
613 * Returns: the new #GMainContext
615 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;
626 #endif
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);
668 #endif
670 G_UNLOCK (main_context_list);
672 return context;
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.
685 GMainContext *
686 g_main_context_default (void)
688 /* Slow, but safe */
690 G_LOCK (main_loop);
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);
701 #endif
704 G_UNLOCK (main_loop);
706 return default_main_context;
709 static void
710 free_context (gpointer data)
712 GMainContext *context = data;
714 TRACE (GLIB_MAIN_CONTEXT_FREE (context));
716 g_main_context_release (context);
717 if (context)
718 g_main_context_unref (context);
721 static void
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
749 * thread.
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().
772 * Since: 2.22
774 void
775 g_main_context_push_thread_default (GMainContext *context)
777 GQueue *stack;
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 ())
784 context = NULL;
785 else if (context)
786 g_main_context_ref (context);
788 stack = g_private_get (&thread_context_stack);
789 if (!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).
807 * Since: 2.22
809 void
810 g_main_context_pop_thread_default (GMainContext *context)
812 GQueue *stack;
814 if (context == g_main_context_default ())
815 context = NULL;
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);
827 if (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.
849 * Since: 2.22
851 GMainContext *
852 g_main_context_get_thread_default (void)
854 GQueue *stack;
856 stack = g_private_get (&thread_context_stack);
857 if (stack)
858 return g_queue_peek_head (stack);
859 else
860 return NULL;
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.
876 * Since: 2.32
878 GMainContext *
879 g_main_context_ref_thread_default (void)
881 GMainContext *context;
883 context = g_main_context_get_thread_default ();
884 if (!context)
885 context = g_main_context_default ();
886 return g_main_context_ref (context);
889 /* Hooks for adding to the main loop */
892 * g_source_new:
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
904 * executed.
906 * Returns: the newly-created #GSource.
908 GSource *
909 g_source_new (GSourceFuncs *source_funcs,
910 guint struct_size)
912 GSource *source;
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,
932 struct_size));
934 return source;
937 /* Holds context's lock */
938 static void
939 g_source_iter_init (GSourceIter *iter,
940 GMainContext *context,
941 gboolean may_modify)
943 iter->context = context;
944 iter->current_list = NULL;
945 iter->source = NULL;
946 iter->may_modify = may_modify;
949 /* Holds context's lock */
950 static gboolean
951 g_source_iter_next (GSourceIter *iter, GSource **source)
953 GSource *next_source;
955 if (iter->source)
956 next_source = iter->source->next;
957 else
958 next_source = NULL;
960 if (!next_source)
962 if (iter->current_list)
963 iter->current_list = iter->current_list->next;
964 else
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.
994 static void
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,
1008 gint priority,
1009 gboolean create)
1011 GList *iter, *last;
1012 GSourceList *source_list;
1014 last = NULL;
1015 for (iter = context->source_lists; iter != NULL; last = iter, iter = iter->next)
1017 source_list = iter->data;
1019 if (source_list->priority == priority)
1020 return source_list;
1022 if (source_list->priority > priority)
1024 if (!create)
1025 return NULL;
1027 source_list = g_slice_new0 (GSourceList);
1028 source_list->priority = priority;
1029 context->source_lists = g_list_insert_before (context->source_lists,
1030 iter,
1031 source_list);
1032 return source_list;
1036 if (!create)
1037 return NULL;
1039 source_list = g_slice_new0 (GSourceList);
1040 source_list->priority = priority;
1042 if (!last)
1043 context->source_lists = g_list_append (NULL, source_list);
1044 else
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);
1051 return source_list;
1054 /* Holds context's lock
1056 static void
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;
1073 else
1075 prev = source_list->tail;
1076 next = NULL;
1079 source->next = next;
1080 if (next)
1081 next->prev = source;
1082 else
1083 source_list->tail = source;
1085 source->prev = prev;
1086 if (prev)
1087 prev->next = source;
1088 else
1089 source_list->head = source;
1092 /* Holds context's lock
1094 static void
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);
1103 if (source->prev)
1104 source->prev->next = source->next;
1105 else
1106 source_list->head = source->next;
1108 if (source->next)
1109 source->next->prev = source->prev;
1110 else
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.
1129 static void
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);
1140 static guint
1141 g_source_attach_unlocked (GSource *source,
1142 GMainContext *context,
1143 gboolean do_wakeup)
1145 GSList *tmp_list;
1146 guint id;
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;
1166 while (tmp_list)
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;
1177 while (tmp_list)
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.
1186 if (do_wakeup)
1187 conditional_wakeup (context);
1189 return source->source_id;
1193 * g_source_attach:
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
1201 * #GMainContext.
1203 guint
1204 g_source_attach (GSource *source,
1205 GMainContext *context)
1207 guint result = 0;
1209 g_return_val_if_fail (source->context == NULL, 0);
1210 g_return_val_if_fail (!SOURCE_DESTROYED (source), 0);
1212 if (!context)
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,
1220 result));
1222 UNLOCK_CONTEXT (context);
1224 return result;
1227 static void
1228 g_source_destroy_internal (GSource *source,
1229 GMainContext *context,
1230 gboolean have_lock)
1232 TRACE (GLIB_MAIN_SOURCE_DESTROY (g_source_get_name (source), source,
1233 context));
1235 if (!have_lock)
1236 LOCK_CONTEXT (context);
1238 if (!SOURCE_DESTROYED (source))
1240 GSList *tmp_list;
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;
1252 if (old_cb_funcs)
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;
1262 while (tmp_list)
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);
1281 if (!have_lock)
1282 UNLOCK_CONTEXT (context);
1286 * g_source_destroy:
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.
1294 void
1295 g_source_destroy (GSource *source)
1297 GMainContext *context;
1299 g_return_if_fail (source != NULL);
1301 context = source->context;
1303 if (context)
1304 g_source_destroy_internal (source, context, FALSE);
1305 else
1306 source->flags &= ~G_HOOK_FLAG_ACTIVE;
1310 * g_source_get_id:
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
1320 guint
1321 g_source_get_id (GSource *source)
1323 guint result;
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);
1332 return result;
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.
1352 GMainContext *
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
1370 * to be processed.
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.
1379 void
1380 g_source_add_poll (GSource *source,
1381 GPollFD *fd)
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;
1391 if (context)
1392 LOCK_CONTEXT (context);
1394 source->poll_fds = g_slist_prepend (source->poll_fds, fd);
1396 if (context)
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
1410 * this source.
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.
1415 void
1416 g_source_remove_poll (GSource *source,
1417 GPollFD *fd)
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;
1427 if (context)
1428 LOCK_CONTEXT (context);
1430 source->poll_fds = g_slist_remove (source->poll_fds, fd);
1432 if (context)
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.
1463 * Since: 2.28
1465 void
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;
1480 if (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);
1492 if (context)
1494 g_source_attach_unlocked (child_source, context, TRUE);
1495 UNLOCK_CONTEXT (context);
1499 static void
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.
1524 * Since: 2.28
1526 void
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;
1540 if (context)
1541 LOCK_CONTEXT (context);
1543 g_child_source_remove_internal (child_source, context);
1545 if (context)
1546 UNLOCK_CONTEXT (context);
1549 static void
1550 g_source_callback_ref (gpointer cb_data)
1552 GSourceCallback *callback = cb_data;
1554 callback->ref_count++;
1557 static void
1558 g_source_callback_unref (gpointer cb_data)
1560 GSourceCallback *callback = cb_data;
1562 callback->ref_count--;
1563 if (callback->ref_count == 0)
1565 if (callback->notify)
1566 callback->notify (callback->data);
1567 g_free (callback);
1571 static void
1572 g_source_callback_get (gpointer cb_data,
1573 GSource *source,
1574 GSourceFunc *func,
1575 gpointer *data)
1577 GSourceCallback *callback = cb_data;
1579 *func = callback->func;
1580 *data = callback->data;
1583 static GSourceCallbackFuncs g_source_callback_funcs = {
1584 g_source_callback_ref,
1585 g_source_callback_unref,
1586 g_source_callback_get,
1590 * g_source_set_callback_indirect:
1591 * @source: the source
1592 * @callback_data: pointer to callback data "object"
1593 * @callback_funcs: functions for reference counting @callback_data
1594 * and getting the callback and data
1596 * Sets the callback function storing the data as a refcounted callback
1597 * "object". This is used internally. Note that calling
1598 * g_source_set_callback_indirect() assumes
1599 * an initial reference count on @callback_data, and thus
1600 * @callback_funcs->unref will eventually be called once more
1601 * than @callback_funcs->ref.
1603 void
1604 g_source_set_callback_indirect (GSource *source,
1605 gpointer callback_data,
1606 GSourceCallbackFuncs *callback_funcs)
1608 GMainContext *context;
1609 gpointer old_cb_data;
1610 GSourceCallbackFuncs *old_cb_funcs;
1612 g_return_if_fail (source != NULL);
1613 g_return_if_fail (callback_funcs != NULL || callback_data == NULL);
1615 context = source->context;
1617 if (context)
1618 LOCK_CONTEXT (context);
1620 if (callback_funcs != &g_source_callback_funcs)
1621 TRACE (GLIB_SOURCE_SET_CALLBACK_INDIRECT (source, callback_data,
1622 callback_funcs->ref,
1623 callback_funcs->unref,
1624 callback_funcs->get));
1626 old_cb_data = source->callback_data;
1627 old_cb_funcs = source->callback_funcs;
1629 source->callback_data = callback_data;
1630 source->callback_funcs = callback_funcs;
1632 if (context)
1633 UNLOCK_CONTEXT (context);
1635 if (old_cb_funcs)
1636 old_cb_funcs->unref (old_cb_data);
1640 * g_source_set_callback:
1641 * @source: the source
1642 * @func: a callback function
1643 * @data: the data to pass to callback function
1644 * @notify: (nullable): a function to call when @data is no longer in use, or %NULL.
1646 * Sets the callback function for a source. The callback for a source is
1647 * called from the source's dispatch function.
1649 * The exact type of @func depends on the type of source; ie. you
1650 * should not count on @func being called with @data as its first
1651 * parameter.
1653 * See [memory management of sources][mainloop-memory-management] for details
1654 * on how to handle memory management of @data.
1656 * Typically, you won't use this function. Instead use functions specific
1657 * to the type of source you are using.
1659 void
1660 g_source_set_callback (GSource *source,
1661 GSourceFunc func,
1662 gpointer data,
1663 GDestroyNotify notify)
1665 GSourceCallback *new_callback;
1667 g_return_if_fail (source != NULL);
1669 TRACE (GLIB_SOURCE_SET_CALLBACK (source, func, data, notify));
1671 new_callback = g_new (GSourceCallback, 1);
1673 new_callback->ref_count = 1;
1674 new_callback->func = func;
1675 new_callback->data = data;
1676 new_callback->notify = notify;
1678 g_source_set_callback_indirect (source, new_callback, &g_source_callback_funcs);
1683 * g_source_set_funcs:
1684 * @source: a #GSource
1685 * @funcs: the new #GSourceFuncs
1687 * Sets the source functions (can be used to override
1688 * default implementations) of an unattached source.
1690 * Since: 2.12
1692 void
1693 g_source_set_funcs (GSource *source,
1694 GSourceFuncs *funcs)
1696 g_return_if_fail (source != NULL);
1697 g_return_if_fail (source->context == NULL);
1698 g_return_if_fail (source->ref_count > 0);
1699 g_return_if_fail (funcs != NULL);
1701 source->source_funcs = funcs;
1704 static void
1705 g_source_set_priority_unlocked (GSource *source,
1706 GMainContext *context,
1707 gint priority)
1709 GSList *tmp_list;
1711 g_return_if_fail (source->priv->parent_source == NULL ||
1712 source->priv->parent_source->priority == priority);
1714 TRACE (GLIB_SOURCE_SET_PRIORITY (source, context, priority));
1716 if (context)
1718 /* Remove the source from the context's source and then
1719 * add it back after so it is sorted in the correct place
1721 source_remove_from_context (source, source->context);
1724 source->priority = priority;
1726 if (context)
1728 source_add_to_context (source, source->context);
1730 if (!SOURCE_BLOCKED (source))
1732 tmp_list = source->poll_fds;
1733 while (tmp_list)
1735 g_main_context_remove_poll_unlocked (context, tmp_list->data);
1736 g_main_context_add_poll_unlocked (context, priority, tmp_list->data);
1738 tmp_list = tmp_list->next;
1741 for (tmp_list = source->priv->fds; tmp_list; tmp_list = tmp_list->next)
1743 g_main_context_remove_poll_unlocked (context, tmp_list->data);
1744 g_main_context_add_poll_unlocked (context, priority, tmp_list->data);
1749 if (source->priv->child_sources)
1751 tmp_list = source->priv->child_sources;
1752 while (tmp_list)
1754 g_source_set_priority_unlocked (tmp_list->data, context, priority);
1755 tmp_list = tmp_list->next;
1761 * g_source_set_priority:
1762 * @source: a #GSource
1763 * @priority: the new priority.
1765 * Sets the priority of a source. While the main loop is being run, a
1766 * source will be dispatched if it is ready to be dispatched and no
1767 * sources at a higher (numerically smaller) priority are ready to be
1768 * dispatched.
1770 * A child source always has the same priority as its parent. It is not
1771 * permitted to change the priority of a source once it has been added
1772 * as a child of another source.
1774 void
1775 g_source_set_priority (GSource *source,
1776 gint priority)
1778 GMainContext *context;
1780 g_return_if_fail (source != NULL);
1781 g_return_if_fail (source->priv->parent_source == NULL);
1783 context = source->context;
1785 if (context)
1786 LOCK_CONTEXT (context);
1787 g_source_set_priority_unlocked (source, context, priority);
1788 if (context)
1789 UNLOCK_CONTEXT (source->context);
1793 * g_source_get_priority:
1794 * @source: a #GSource
1796 * Gets the priority of a source.
1798 * Returns: the priority of the source
1800 gint
1801 g_source_get_priority (GSource *source)
1803 g_return_val_if_fail (source != NULL, 0);
1805 return source->priority;
1809 * g_source_set_ready_time:
1810 * @source: a #GSource
1811 * @ready_time: the monotonic time at which the source will be ready,
1812 * 0 for "immediately", -1 for "never"
1814 * Sets a #GSource to be dispatched when the given monotonic time is
1815 * reached (or passed). If the monotonic time is in the past (as it
1816 * always will be if @ready_time is 0) then the source will be
1817 * dispatched immediately.
1819 * If @ready_time is -1 then the source is never woken up on the basis
1820 * of the passage of time.
1822 * Dispatching the source does not reset the ready time. You should do
1823 * so yourself, from the source dispatch function.
1825 * Note that if you have a pair of sources where the ready time of one
1826 * suggests that it will be delivered first but the priority for the
1827 * other suggests that it would be delivered first, and the ready time
1828 * for both sources is reached during the same main context iteration
1829 * then the order of dispatch is undefined.
1831 * It is a no-op to call this function on a #GSource which has already been
1832 * destroyed with g_source_destroy().
1834 * This API is only intended to be used by implementations of #GSource.
1835 * Do not call this API on a #GSource that you did not create.
1837 * Since: 2.36
1839 void
1840 g_source_set_ready_time (GSource *source,
1841 gint64 ready_time)
1843 GMainContext *context;
1845 g_return_if_fail (source != NULL);
1846 g_return_if_fail (source->ref_count > 0);
1848 if (source->priv->ready_time == ready_time)
1849 return;
1851 context = source->context;
1853 if (context)
1854 LOCK_CONTEXT (context);
1856 source->priv->ready_time = ready_time;
1858 TRACE (GLIB_SOURCE_SET_READY_TIME (source, ready_time));
1860 if (context)
1862 /* Quite likely that we need to change the timeout on the poll */
1863 if (!SOURCE_BLOCKED (source))
1864 conditional_wakeup (context);
1865 UNLOCK_CONTEXT (context);
1870 * g_source_get_ready_time:
1871 * @source: a #GSource
1873 * Gets the "ready time" of @source, as set by
1874 * g_source_set_ready_time().
1876 * Any time before the current monotonic time (including 0) is an
1877 * indication that the source will fire immediately.
1879 * Returns: the monotonic ready time, -1 for "never"
1881 gint64
1882 g_source_get_ready_time (GSource *source)
1884 g_return_val_if_fail (source != NULL, -1);
1886 return source->priv->ready_time;
1890 * g_source_set_can_recurse:
1891 * @source: a #GSource
1892 * @can_recurse: whether recursion is allowed for this source
1894 * Sets whether a source can be called recursively. If @can_recurse is
1895 * %TRUE, then while the source is being dispatched then this source
1896 * will be processed normally. Otherwise, all processing of this
1897 * source is blocked until the dispatch function returns.
1899 void
1900 g_source_set_can_recurse (GSource *source,
1901 gboolean can_recurse)
1903 GMainContext *context;
1905 g_return_if_fail (source != NULL);
1907 context = source->context;
1909 if (context)
1910 LOCK_CONTEXT (context);
1912 if (can_recurse)
1913 source->flags |= G_SOURCE_CAN_RECURSE;
1914 else
1915 source->flags &= ~G_SOURCE_CAN_RECURSE;
1917 if (context)
1918 UNLOCK_CONTEXT (context);
1922 * g_source_get_can_recurse:
1923 * @source: a #GSource
1925 * Checks whether a source is allowed to be called recursively.
1926 * see g_source_set_can_recurse().
1928 * Returns: whether recursion is allowed.
1930 gboolean
1931 g_source_get_can_recurse (GSource *source)
1933 g_return_val_if_fail (source != NULL, FALSE);
1935 return (source->flags & G_SOURCE_CAN_RECURSE) != 0;
1940 * g_source_set_name:
1941 * @source: a #GSource
1942 * @name: debug name for the source
1944 * Sets a name for the source, used in debugging and profiling.
1945 * The name defaults to #NULL.
1947 * The source name should describe in a human-readable way
1948 * what the source does. For example, "X11 event queue"
1949 * or "GTK+ repaint idle handler" or whatever it is.
1951 * It is permitted to call this function multiple times, but is not
1952 * recommended due to the potential performance impact. For example,
1953 * one could change the name in the "check" function of a #GSourceFuncs
1954 * to include details like the event type in the source name.
1956 * Use caution if changing the name while another thread may be
1957 * accessing it with g_source_get_name(); that function does not copy
1958 * the value, and changing the value will free it while the other thread
1959 * may be attempting to use it.
1961 * Since: 2.26
1963 void
1964 g_source_set_name (GSource *source,
1965 const char *name)
1967 GMainContext *context;
1969 g_return_if_fail (source != NULL);
1971 context = source->context;
1973 if (context)
1974 LOCK_CONTEXT (context);
1976 TRACE (GLIB_SOURCE_SET_NAME (source, name));
1978 /* setting back to NULL is allowed, just because it's
1979 * weird if get_name can return NULL but you can't
1980 * set that.
1983 g_free (source->name);
1984 source->name = g_strdup (name);
1986 if (context)
1987 UNLOCK_CONTEXT (context);
1991 * g_source_get_name:
1992 * @source: a #GSource
1994 * Gets a name for the source, used in debugging and profiling. The
1995 * name may be #NULL if it has never been set with g_source_set_name().
1997 * Returns: the name of the source
1999 * Since: 2.26
2001 const char *
2002 g_source_get_name (GSource *source)
2004 g_return_val_if_fail (source != NULL, NULL);
2006 return source->name;
2010 * g_source_set_name_by_id:
2011 * @tag: a #GSource ID
2012 * @name: debug name for the source
2014 * Sets the name of a source using its ID.
2016 * This is a convenience utility to set source names from the return
2017 * value of g_idle_add(), g_timeout_add(), etc.
2019 * It is a programmer error to attempt to set the name of a non-existent
2020 * source.
2022 * More specifically: source IDs can be reissued after a source has been
2023 * destroyed and therefore it is never valid to use this function with a
2024 * source ID which may have already been removed. An example is when
2025 * scheduling an idle to run in another thread with g_idle_add(): the
2026 * idle may already have run and been removed by the time this function
2027 * is called on its (now invalid) source ID. This source ID may have
2028 * been reissued, leading to the operation being performed against the
2029 * wrong source.
2031 * Since: 2.26
2033 void
2034 g_source_set_name_by_id (guint tag,
2035 const char *name)
2037 GSource *source;
2039 g_return_if_fail (tag > 0);
2041 source = g_main_context_find_source_by_id (NULL, tag);
2042 if (source == NULL)
2043 return;
2045 g_source_set_name (source, name);
2050 * g_source_ref:
2051 * @source: a #GSource
2053 * Increases the reference count on a source by one.
2055 * Returns: @source
2057 GSource *
2058 g_source_ref (GSource *source)
2060 GMainContext *context;
2062 g_return_val_if_fail (source != NULL, NULL);
2064 context = source->context;
2066 if (context)
2067 LOCK_CONTEXT (context);
2069 source->ref_count++;
2071 if (context)
2072 UNLOCK_CONTEXT (context);
2074 return source;
2077 /* g_source_unref() but possible to call within context lock
2079 static void
2080 g_source_unref_internal (GSource *source,
2081 GMainContext *context,
2082 gboolean have_lock)
2084 gpointer old_cb_data = NULL;
2085 GSourceCallbackFuncs *old_cb_funcs = NULL;
2087 g_return_if_fail (source != NULL);
2089 if (!have_lock && context)
2090 LOCK_CONTEXT (context);
2092 source->ref_count--;
2093 if (source->ref_count == 0)
2095 TRACE (GLIB_SOURCE_BEFORE_FREE (source, context,
2096 source->source_funcs->finalize));
2098 old_cb_data = source->callback_data;
2099 old_cb_funcs = source->callback_funcs;
2101 source->callback_data = NULL;
2102 source->callback_funcs = NULL;
2104 if (context)
2106 if (!SOURCE_DESTROYED (source))
2107 g_warning (G_STRLOC ": ref_count == 0, but source was still attached to a context!");
2108 source_remove_from_context (source, context);
2110 g_hash_table_remove (context->sources, GUINT_TO_POINTER (source->source_id));
2113 if (source->source_funcs->finalize)
2115 /* Temporarily increase the ref count again so that GSource methods
2116 * can be called from finalize(). */
2117 source->ref_count++;
2118 if (context)
2119 UNLOCK_CONTEXT (context);
2120 source->source_funcs->finalize (source);
2121 if (context)
2122 LOCK_CONTEXT (context);
2123 source->ref_count--;
2126 g_free (source->name);
2127 source->name = NULL;
2129 g_slist_free (source->poll_fds);
2130 source->poll_fds = NULL;
2132 g_slist_free_full (source->priv->fds, g_free);
2134 while (source->priv->child_sources)
2136 GSource *child_source = source->priv->child_sources->data;
2138 source->priv->child_sources =
2139 g_slist_remove (source->priv->child_sources, child_source);
2140 child_source->priv->parent_source = NULL;
2142 g_source_unref_internal (child_source, context, have_lock);
2145 g_slice_free (GSourcePrivate, source->priv);
2146 source->priv = NULL;
2148 g_free (source);
2151 if (!have_lock && context)
2152 UNLOCK_CONTEXT (context);
2154 if (old_cb_funcs)
2156 if (have_lock)
2157 UNLOCK_CONTEXT (context);
2159 old_cb_funcs->unref (old_cb_data);
2161 if (have_lock)
2162 LOCK_CONTEXT (context);
2167 * g_source_unref:
2168 * @source: a #GSource
2170 * Decreases the reference count of a source by one. If the
2171 * resulting reference count is zero the source and associated
2172 * memory will be destroyed.
2174 void
2175 g_source_unref (GSource *source)
2177 g_return_if_fail (source != NULL);
2179 g_source_unref_internal (source, source->context, FALSE);
2183 * g_main_context_find_source_by_id:
2184 * @context: (nullable): a #GMainContext (if %NULL, the default context will be used)
2185 * @source_id: the source ID, as returned by g_source_get_id().
2187 * Finds a #GSource given a pair of context and ID.
2189 * It is a programmer error to attempt to lookup a non-existent source.
2191 * More specifically: source IDs can be reissued after a source has been
2192 * destroyed and therefore it is never valid to use this function with a
2193 * source ID which may have already been removed. An example is when
2194 * scheduling an idle to run in another thread with g_idle_add(): the
2195 * idle may already have run and been removed by the time this function
2196 * is called on its (now invalid) source ID. This source ID may have
2197 * been reissued, leading to the operation being performed against the
2198 * wrong source.
2200 * Returns: (transfer none): the #GSource
2202 GSource *
2203 g_main_context_find_source_by_id (GMainContext *context,
2204 guint source_id)
2206 GSource *source;
2208 g_return_val_if_fail (source_id > 0, NULL);
2210 if (context == NULL)
2211 context = g_main_context_default ();
2213 LOCK_CONTEXT (context);
2214 source = g_hash_table_lookup (context->sources, GUINT_TO_POINTER (source_id));
2215 UNLOCK_CONTEXT (context);
2217 if (source && SOURCE_DESTROYED (source))
2218 source = NULL;
2220 return source;
2224 * g_main_context_find_source_by_funcs_user_data:
2225 * @context: (nullable): a #GMainContext (if %NULL, the default context will be used).
2226 * @funcs: the @source_funcs passed to g_source_new().
2227 * @user_data: the user data from the callback.
2229 * Finds a source with the given source functions and user data. If
2230 * multiple sources exist with the same source function and user data,
2231 * the first one found will be returned.
2233 * Returns: (transfer none): the source, if one was found, otherwise %NULL
2235 GSource *
2236 g_main_context_find_source_by_funcs_user_data (GMainContext *context,
2237 GSourceFuncs *funcs,
2238 gpointer user_data)
2240 GSourceIter iter;
2241 GSource *source;
2243 g_return_val_if_fail (funcs != NULL, NULL);
2245 if (context == NULL)
2246 context = g_main_context_default ();
2248 LOCK_CONTEXT (context);
2250 g_source_iter_init (&iter, context, FALSE);
2251 while (g_source_iter_next (&iter, &source))
2253 if (!SOURCE_DESTROYED (source) &&
2254 source->source_funcs == funcs &&
2255 source->callback_funcs)
2257 GSourceFunc callback;
2258 gpointer callback_data;
2260 source->callback_funcs->get (source->callback_data, source, &callback, &callback_data);
2262 if (callback_data == user_data)
2263 break;
2266 g_source_iter_clear (&iter);
2268 UNLOCK_CONTEXT (context);
2270 return source;
2274 * g_main_context_find_source_by_user_data:
2275 * @context: a #GMainContext
2276 * @user_data: the user_data for the callback.
2278 * Finds a source with the given user data for the callback. If
2279 * multiple sources exist with the same user data, the first
2280 * one found will be returned.
2282 * Returns: (transfer none): the source, if one was found, otherwise %NULL
2284 GSource *
2285 g_main_context_find_source_by_user_data (GMainContext *context,
2286 gpointer user_data)
2288 GSourceIter iter;
2289 GSource *source;
2291 if (context == NULL)
2292 context = g_main_context_default ();
2294 LOCK_CONTEXT (context);
2296 g_source_iter_init (&iter, context, FALSE);
2297 while (g_source_iter_next (&iter, &source))
2299 if (!SOURCE_DESTROYED (source) &&
2300 source->callback_funcs)
2302 GSourceFunc callback;
2303 gpointer callback_data = NULL;
2305 source->callback_funcs->get (source->callback_data, source, &callback, &callback_data);
2307 if (callback_data == user_data)
2308 break;
2311 g_source_iter_clear (&iter);
2313 UNLOCK_CONTEXT (context);
2315 return source;
2319 * g_source_remove:
2320 * @tag: the ID of the source to remove.
2322 * Removes the source with the given id from the default main context.
2324 * The id of a #GSource is given by g_source_get_id(), or will be
2325 * returned by the functions g_source_attach(), g_idle_add(),
2326 * g_idle_add_full(), g_timeout_add(), g_timeout_add_full(),
2327 * g_child_watch_add(), g_child_watch_add_full(), g_io_add_watch(), and
2328 * g_io_add_watch_full().
2330 * See also g_source_destroy(). You must use g_source_destroy() for sources
2331 * added to a non-default main context.
2333 * It is a programmer error to attempt to remove a non-existent source.
2335 * More specifically: source IDs can be reissued after a source has been
2336 * destroyed and therefore it is never valid to use this function with a
2337 * source ID which may have already been removed. An example is when
2338 * scheduling an idle to run in another thread with g_idle_add(): the
2339 * idle may already have run and been removed by the time this function
2340 * is called on its (now invalid) source ID. This source ID may have
2341 * been reissued, leading to the operation being performed against the
2342 * wrong source.
2344 * Returns: For historical reasons, this function always returns %TRUE
2346 gboolean
2347 g_source_remove (guint tag)
2349 GSource *source;
2351 g_return_val_if_fail (tag > 0, FALSE);
2353 source = g_main_context_find_source_by_id (NULL, tag);
2354 if (source)
2355 g_source_destroy (source);
2356 else
2357 g_critical ("Source ID %u was not found when attempting to remove it", tag);
2359 return source != NULL;
2363 * g_source_remove_by_user_data:
2364 * @user_data: the user_data for the callback.
2366 * Removes a source from the default main loop context given the user
2367 * data for the callback. If multiple sources exist with the same user
2368 * data, only one will be destroyed.
2370 * Returns: %TRUE if a source was found and removed.
2372 gboolean
2373 g_source_remove_by_user_data (gpointer user_data)
2375 GSource *source;
2377 source = g_main_context_find_source_by_user_data (NULL, user_data);
2378 if (source)
2380 g_source_destroy (source);
2381 return TRUE;
2383 else
2384 return FALSE;
2388 * g_source_remove_by_funcs_user_data:
2389 * @funcs: The @source_funcs passed to g_source_new()
2390 * @user_data: the user data for the callback
2392 * Removes a source from the default main loop context given the
2393 * source functions and user data. If multiple sources exist with the
2394 * same source functions and user data, only one will be destroyed.
2396 * Returns: %TRUE if a source was found and removed.
2398 gboolean
2399 g_source_remove_by_funcs_user_data (GSourceFuncs *funcs,
2400 gpointer user_data)
2402 GSource *source;
2404 g_return_val_if_fail (funcs != NULL, FALSE);
2406 source = g_main_context_find_source_by_funcs_user_data (NULL, funcs, user_data);
2407 if (source)
2409 g_source_destroy (source);
2410 return TRUE;
2412 else
2413 return FALSE;
2416 #ifdef G_OS_UNIX
2418 * g_source_add_unix_fd:
2419 * @source: a #GSource
2420 * @fd: the fd to monitor
2421 * @events: an event mask
2423 * Monitors @fd for the IO events in @events.
2425 * The tag returned by this function can be used to remove or modify the
2426 * monitoring of the fd using g_source_remove_unix_fd() or
2427 * g_source_modify_unix_fd().
2429 * It is not necessary to remove the fd before destroying the source; it
2430 * will be cleaned up automatically.
2432 * This API is only intended to be used by implementations of #GSource.
2433 * Do not call this API on a #GSource that you did not create.
2435 * As the name suggests, this function is not available on Windows.
2437 * Returns: (not nullable): an opaque tag
2439 * Since: 2.36
2441 gpointer
2442 g_source_add_unix_fd (GSource *source,
2443 gint fd,
2444 GIOCondition events)
2446 GMainContext *context;
2447 GPollFD *poll_fd;
2449 g_return_val_if_fail (source != NULL, NULL);
2450 g_return_val_if_fail (!SOURCE_DESTROYED (source), NULL);
2452 poll_fd = g_new (GPollFD, 1);
2453 poll_fd->fd = fd;
2454 poll_fd->events = events;
2455 poll_fd->revents = 0;
2457 context = source->context;
2459 if (context)
2460 LOCK_CONTEXT (context);
2462 source->priv->fds = g_slist_prepend (source->priv->fds, poll_fd);
2464 if (context)
2466 if (!SOURCE_BLOCKED (source))
2467 g_main_context_add_poll_unlocked (context, source->priority, poll_fd);
2468 UNLOCK_CONTEXT (context);
2471 return poll_fd;
2475 * g_source_modify_unix_fd:
2476 * @source: a #GSource
2477 * @tag: (not nullable): the tag from g_source_add_unix_fd()
2478 * @new_events: the new event mask to watch
2480 * Updates the event mask to watch for the fd identified by @tag.
2482 * @tag is the tag returned from g_source_add_unix_fd().
2484 * If you want to remove a fd, don't set its event mask to zero.
2485 * Instead, call g_source_remove_unix_fd().
2487 * This API is only intended to be used by implementations of #GSource.
2488 * Do not call this API on a #GSource that you did not create.
2490 * As the name suggests, this function is not available on Windows.
2492 * Since: 2.36
2494 void
2495 g_source_modify_unix_fd (GSource *source,
2496 gpointer tag,
2497 GIOCondition new_events)
2499 GMainContext *context;
2500 GPollFD *poll_fd;
2502 g_return_if_fail (source != NULL);
2503 g_return_if_fail (g_slist_find (source->priv->fds, tag));
2505 context = source->context;
2506 poll_fd = tag;
2508 poll_fd->events = new_events;
2510 if (context)
2511 g_main_context_wakeup (context);
2515 * g_source_remove_unix_fd:
2516 * @source: a #GSource
2517 * @tag: (not nullable): the tag from g_source_add_unix_fd()
2519 * Reverses the effect of a previous call to g_source_add_unix_fd().
2521 * You only need to call this if you want to remove an fd from being
2522 * watched while keeping the same source around. In the normal case you
2523 * will just want to destroy the source.
2525 * This API is only intended to be used by implementations of #GSource.
2526 * Do not call this API on a #GSource that you did not create.
2528 * As the name suggests, this function is not available on Windows.
2530 * Since: 2.36
2532 void
2533 g_source_remove_unix_fd (GSource *source,
2534 gpointer tag)
2536 GMainContext *context;
2537 GPollFD *poll_fd;
2539 g_return_if_fail (source != NULL);
2540 g_return_if_fail (g_slist_find (source->priv->fds, tag));
2542 context = source->context;
2543 poll_fd = tag;
2545 if (context)
2546 LOCK_CONTEXT (context);
2548 source->priv->fds = g_slist_remove (source->priv->fds, poll_fd);
2550 if (context)
2552 if (!SOURCE_BLOCKED (source))
2553 g_main_context_remove_poll_unlocked (context, poll_fd);
2555 UNLOCK_CONTEXT (context);
2558 g_free (poll_fd);
2562 * g_source_query_unix_fd:
2563 * @source: a #GSource
2564 * @tag: (not nullable): the tag from g_source_add_unix_fd()
2566 * Queries the events reported for the fd corresponding to @tag on
2567 * @source during the last poll.
2569 * The return value of this function is only defined when the function
2570 * is called from the check or dispatch functions for @source.
2572 * This API is only intended to be used by implementations of #GSource.
2573 * Do not call this API on a #GSource that you did not create.
2575 * As the name suggests, this function is not available on Windows.
2577 * Returns: the conditions reported on the fd
2579 * Since: 2.36
2581 GIOCondition
2582 g_source_query_unix_fd (GSource *source,
2583 gpointer tag)
2585 GPollFD *poll_fd;
2587 g_return_val_if_fail (source != NULL, 0);
2588 g_return_val_if_fail (g_slist_find (source->priv->fds, tag), 0);
2590 poll_fd = tag;
2592 return poll_fd->revents;
2594 #endif /* G_OS_UNIX */
2597 * g_get_current_time:
2598 * @result: #GTimeVal structure in which to store current time.
2600 * Equivalent to the UNIX gettimeofday() function, but portable.
2602 * You may find g_get_real_time() to be more convenient.
2604 void
2605 g_get_current_time (GTimeVal *result)
2607 #ifndef G_OS_WIN32
2608 struct timeval r;
2610 g_return_if_fail (result != NULL);
2612 /*this is required on alpha, there the timeval structs are int's
2613 not longs and a cast only would fail horribly*/
2614 gettimeofday (&r, NULL);
2615 result->tv_sec = r.tv_sec;
2616 result->tv_usec = r.tv_usec;
2617 #else
2618 FILETIME ft;
2619 guint64 time64;
2621 g_return_if_fail (result != NULL);
2623 GetSystemTimeAsFileTime (&ft);
2624 memmove (&time64, &ft, sizeof (FILETIME));
2626 /* Convert from 100s of nanoseconds since 1601-01-01
2627 * to Unix epoch. Yes, this is Y2038 unsafe.
2629 time64 -= G_GINT64_CONSTANT (116444736000000000);
2630 time64 /= 10;
2632 result->tv_sec = time64 / 1000000;
2633 result->tv_usec = time64 % 1000000;
2634 #endif
2638 * g_get_real_time:
2640 * Queries the system wall-clock time.
2642 * This call is functionally equivalent to g_get_current_time() except
2643 * that the return value is often more convenient than dealing with a
2644 * #GTimeVal.
2646 * You should only use this call if you are actually interested in the real
2647 * wall-clock time. g_get_monotonic_time() is probably more useful for
2648 * measuring intervals.
2650 * Returns: the number of microseconds since January 1, 1970 UTC.
2652 * Since: 2.28
2654 gint64
2655 g_get_real_time (void)
2657 GTimeVal tv;
2659 g_get_current_time (&tv);
2661 return (((gint64) tv.tv_sec) * 1000000) + tv.tv_usec;
2665 * g_get_monotonic_time:
2667 * Queries the system monotonic time.
2669 * The monotonic clock will always increase and doesn't suffer
2670 * discontinuities when the user (or NTP) changes the system time. It
2671 * may or may not continue to tick during times where the machine is
2672 * suspended.
2674 * We try to use the clock that corresponds as closely as possible to
2675 * the passage of time as measured by system calls such as poll() but it
2676 * may not always be possible to do this.
2678 * Returns: the monotonic time, in microseconds
2680 * Since: 2.28
2682 #if defined (G_OS_WIN32)
2683 /* NOTE:
2684 * time_usec = ticks_since_boot * usec_per_sec / ticks_per_sec
2686 * Doing (ticks_since_boot * usec_per_sec) before the division can overflow 64 bits
2687 * (ticks_since_boot / ticks_per_sec) and then multiply would not be accurate enough.
2688 * So for now we calculate (usec_per_sec / ticks_per_sec) and use floating point
2690 static gdouble g_monotonic_usec_per_tick = 0;
2692 void
2693 g_clock_win32_init (void)
2695 LARGE_INTEGER freq;
2697 if (!QueryPerformanceFrequency (&freq) || freq.QuadPart == 0)
2699 /* The documentation says that this should never happen */
2700 g_assert_not_reached ();
2701 return;
2704 g_monotonic_usec_per_tick = (gdouble)G_USEC_PER_SEC / freq.QuadPart;
2707 gint64
2708 g_get_monotonic_time (void)
2710 if (G_LIKELY (g_monotonic_usec_per_tick != 0))
2712 LARGE_INTEGER ticks;
2714 if (QueryPerformanceCounter (&ticks))
2715 return (gint64)(ticks.QuadPart * g_monotonic_usec_per_tick);
2717 g_warning ("QueryPerformanceCounter Failed (%lu)", GetLastError ());
2718 g_monotonic_usec_per_tick = 0;
2721 return 0;
2723 #elif defined(HAVE_MACH_MACH_TIME_H) /* Mac OS */
2724 gint64
2725 g_get_monotonic_time (void)
2727 static mach_timebase_info_data_t timebase_info;
2729 if (timebase_info.denom == 0)
2731 /* This is a fraction that we must use to scale
2732 * mach_absolute_time() by in order to reach nanoseconds.
2734 * We've only ever observed this to be 1/1, but maybe it could be
2735 * 1000/1 if mach time is microseconds already, or 1/1000 if
2736 * picoseconds. Try to deal nicely with that.
2738 mach_timebase_info (&timebase_info);
2740 /* We actually want microseconds... */
2741 if (timebase_info.numer % 1000 == 0)
2742 timebase_info.numer /= 1000;
2743 else
2744 timebase_info.denom *= 1000;
2746 /* We want to make the numer 1 to avoid having to multiply... */
2747 if (timebase_info.denom % timebase_info.numer == 0)
2749 timebase_info.denom /= timebase_info.numer;
2750 timebase_info.numer = 1;
2752 else
2754 /* We could just multiply by timebase_info.numer below, but why
2755 * bother for a case that may never actually exist...
2757 * Plus -- performing the multiplication would risk integer
2758 * overflow. If we ever actually end up in this situation, we
2759 * should more carefully evaluate the correct course of action.
2761 mach_timebase_info (&timebase_info); /* Get a fresh copy for a better message */
2762 g_error ("Got weird mach timebase info of %d/%d. Please file a bug against GLib.",
2763 timebase_info.numer, timebase_info.denom);
2767 return mach_absolute_time () / timebase_info.denom;
2769 #else
2770 gint64
2771 g_get_monotonic_time (void)
2773 struct timespec ts;
2774 gint result;
2776 result = clock_gettime (CLOCK_MONOTONIC, &ts);
2778 if G_UNLIKELY (result != 0)
2779 g_error ("GLib requires working CLOCK_MONOTONIC");
2781 return (((gint64) ts.tv_sec) * 1000000) + (ts.tv_nsec / 1000);
2783 #endif
2785 static void
2786 g_main_dispatch_free (gpointer dispatch)
2788 g_slice_free (GMainDispatch, dispatch);
2791 /* Running the main loop */
2793 static GMainDispatch *
2794 get_dispatch (void)
2796 static GPrivate depth_private = G_PRIVATE_INIT (g_main_dispatch_free);
2797 GMainDispatch *dispatch;
2799 dispatch = g_private_get (&depth_private);
2801 if (!dispatch)
2803 dispatch = g_slice_new0 (GMainDispatch);
2804 g_private_set (&depth_private, dispatch);
2807 return dispatch;
2811 * g_main_depth:
2813 * Returns the depth of the stack of calls to
2814 * g_main_context_dispatch() on any #GMainContext in the current thread.
2815 * That is, when called from the toplevel, it gives 0. When
2816 * called from within a callback from g_main_context_iteration()
2817 * (or g_main_loop_run(), etc.) it returns 1. When called from within
2818 * a callback to a recursive call to g_main_context_iteration(),
2819 * it returns 2. And so forth.
2821 * This function is useful in a situation like the following:
2822 * Imagine an extremely simple "garbage collected" system.
2824 * |[<!-- language="C" -->
2825 * static GList *free_list;
2827 * gpointer
2828 * allocate_memory (gsize size)
2829 * {
2830 * gpointer result = g_malloc (size);
2831 * free_list = g_list_prepend (free_list, result);
2832 * return result;
2835 * void
2836 * free_allocated_memory (void)
2838 * GList *l;
2839 * for (l = free_list; l; l = l->next);
2840 * g_free (l->data);
2841 * g_list_free (free_list);
2842 * free_list = NULL;
2845 * [...]
2847 * while (TRUE);
2849 * g_main_context_iteration (NULL, TRUE);
2850 * free_allocated_memory();
2852 * ]|
2854 * This works from an application, however, if you want to do the same
2855 * thing from a library, it gets more difficult, since you no longer
2856 * control the main loop. You might think you can simply use an idle
2857 * function to make the call to free_allocated_memory(), but that
2858 * doesn't work, since the idle function could be called from a
2859 * recursive callback. This can be fixed by using g_main_depth()
2861 * |[<!-- language="C" -->
2862 * gpointer
2863 * allocate_memory (gsize size)
2864 * {
2865 * FreeListBlock *block = g_new (FreeListBlock, 1);
2866 * block->mem = g_malloc (size);
2867 * block->depth = g_main_depth ();
2868 * free_list = g_list_prepend (free_list, block);
2869 * return block->mem;
2872 * void
2873 * free_allocated_memory (void)
2875 * GList *l;
2877 * int depth = g_main_depth ();
2878 * for (l = free_list; l; );
2880 * GList *next = l->next;
2881 * FreeListBlock *block = l->data;
2882 * if (block->depth > depth)
2884 * g_free (block->mem);
2885 * g_free (block);
2886 * free_list = g_list_delete_link (free_list, l);
2889 * l = next;
2892 * ]|
2894 * There is a temptation to use g_main_depth() to solve
2895 * problems with reentrancy. For instance, while waiting for data
2896 * to be received from the network in response to a menu item,
2897 * the menu item might be selected again. It might seem that
2898 * one could make the menu item's callback return immediately
2899 * and do nothing if g_main_depth() returns a value greater than 1.
2900 * However, this should be avoided since the user then sees selecting
2901 * the menu item do nothing. Furthermore, you'll find yourself adding
2902 * these checks all over your code, since there are doubtless many,
2903 * many things that the user could do. Instead, you can use the
2904 * following techniques:
2906 * 1. Use gtk_widget_set_sensitive() or modal dialogs to prevent
2907 * the user from interacting with elements while the main
2908 * loop is recursing.
2910 * 2. Avoid main loop recursion in situations where you can't handle
2911 * arbitrary callbacks. Instead, structure your code so that you
2912 * simply return to the main loop and then get called again when
2913 * there is more work to do.
2915 * Returns: The main loop recursion level in the current thread
2918 g_main_depth (void)
2920 GMainDispatch *dispatch = get_dispatch ();
2921 return dispatch->depth;
2925 * g_main_current_source:
2927 * Returns the currently firing source for this thread.
2929 * Returns: (transfer none): The currently firing source or %NULL.
2931 * Since: 2.12
2933 GSource *
2934 g_main_current_source (void)
2936 GMainDispatch *dispatch = get_dispatch ();
2937 return dispatch->source;
2941 * g_source_is_destroyed:
2942 * @source: a #GSource
2944 * Returns whether @source has been destroyed.
2946 * This is important when you operate upon your objects
2947 * from within idle handlers, but may have freed the object
2948 * before the dispatch of your idle handler.
2950 * |[<!-- language="C" -->
2951 * static gboolean
2952 * idle_callback (gpointer data)
2954 * SomeWidget *self = data;
2956 * GDK_THREADS_ENTER ();
2957 * // do stuff with self
2958 * self->idle_id = 0;
2959 * GDK_THREADS_LEAVE ();
2961 * return G_SOURCE_REMOVE;
2964 * static void
2965 * some_widget_do_stuff_later (SomeWidget *self)
2967 * self->idle_id = g_idle_add (idle_callback, self);
2970 * static void
2971 * some_widget_finalize (GObject *object)
2973 * SomeWidget *self = SOME_WIDGET (object);
2975 * if (self->idle_id)
2976 * g_source_remove (self->idle_id);
2978 * G_OBJECT_CLASS (parent_class)->finalize (object);
2980 * ]|
2982 * This will fail in a multi-threaded application if the
2983 * widget is destroyed before the idle handler fires due
2984 * to the use after free in the callback. A solution, to
2985 * this particular problem, is to check to if the source
2986 * has already been destroy within the callback.
2988 * |[<!-- language="C" -->
2989 * static gboolean
2990 * idle_callback (gpointer data)
2992 * SomeWidget *self = data;
2994 * GDK_THREADS_ENTER ();
2995 * if (!g_source_is_destroyed (g_main_current_source ()))
2997 * // do stuff with self
2999 * GDK_THREADS_LEAVE ();
3001 * return FALSE;
3003 * ]|
3005 * Calls to this function from a thread other than the one acquired by the
3006 * #GMainContext the #GSource is attached to are typically redundant, as the
3007 * source could be destroyed immediately after this function returns. However,
3008 * once a source is destroyed it cannot be un-destroyed, so this function can be
3009 * used for opportunistic checks from any thread.
3011 * Returns: %TRUE if the source has been destroyed
3013 * Since: 2.12
3015 gboolean
3016 g_source_is_destroyed (GSource *source)
3018 return SOURCE_DESTROYED (source);
3021 /* Temporarily remove all this source's file descriptors from the
3022 * poll(), so that if data comes available for one of the file descriptors
3023 * we don't continually spin in the poll()
3025 /* HOLDS: source->context's lock */
3026 static void
3027 block_source (GSource *source)
3029 GSList *tmp_list;
3031 g_return_if_fail (!SOURCE_BLOCKED (source));
3033 source->flags |= G_SOURCE_BLOCKED;
3035 if (source->context)
3037 tmp_list = source->poll_fds;
3038 while (tmp_list)
3040 g_main_context_remove_poll_unlocked (source->context, tmp_list->data);
3041 tmp_list = tmp_list->next;
3044 for (tmp_list = source->priv->fds; tmp_list; tmp_list = tmp_list->next)
3045 g_main_context_remove_poll_unlocked (source->context, tmp_list->data);
3048 if (source->priv && source->priv->child_sources)
3050 tmp_list = source->priv->child_sources;
3051 while (tmp_list)
3053 block_source (tmp_list->data);
3054 tmp_list = tmp_list->next;
3059 /* HOLDS: source->context's lock */
3060 static void
3061 unblock_source (GSource *source)
3063 GSList *tmp_list;
3065 g_return_if_fail (SOURCE_BLOCKED (source)); /* Source already unblocked */
3066 g_return_if_fail (!SOURCE_DESTROYED (source));
3068 source->flags &= ~G_SOURCE_BLOCKED;
3070 tmp_list = source->poll_fds;
3071 while (tmp_list)
3073 g_main_context_add_poll_unlocked (source->context, source->priority, tmp_list->data);
3074 tmp_list = tmp_list->next;
3077 for (tmp_list = source->priv->fds; tmp_list; tmp_list = tmp_list->next)
3078 g_main_context_add_poll_unlocked (source->context, source->priority, tmp_list->data);
3080 if (source->priv && source->priv->child_sources)
3082 tmp_list = source->priv->child_sources;
3083 while (tmp_list)
3085 unblock_source (tmp_list->data);
3086 tmp_list = tmp_list->next;
3091 /* HOLDS: context's lock */
3092 static void
3093 g_main_dispatch (GMainContext *context)
3095 GMainDispatch *current = get_dispatch ();
3096 guint i;
3098 for (i = 0; i < context->pending_dispatches->len; i++)
3100 GSource *source = context->pending_dispatches->pdata[i];
3102 context->pending_dispatches->pdata[i] = NULL;
3103 g_assert (source);
3105 source->flags &= ~G_SOURCE_READY;
3107 if (!SOURCE_DESTROYED (source))
3109 gboolean was_in_call;
3110 gpointer user_data = NULL;
3111 GSourceFunc callback = NULL;
3112 GSourceCallbackFuncs *cb_funcs;
3113 gpointer cb_data;
3114 gboolean need_destroy;
3116 gboolean (*dispatch) (GSource *,
3117 GSourceFunc,
3118 gpointer);
3119 GSource *prev_source;
3121 dispatch = source->source_funcs->dispatch;
3122 cb_funcs = source->callback_funcs;
3123 cb_data = source->callback_data;
3125 if (cb_funcs)
3126 cb_funcs->ref (cb_data);
3128 if ((source->flags & G_SOURCE_CAN_RECURSE) == 0)
3129 block_source (source);
3131 was_in_call = source->flags & G_HOOK_FLAG_IN_CALL;
3132 source->flags |= G_HOOK_FLAG_IN_CALL;
3134 if (cb_funcs)
3135 cb_funcs->get (cb_data, source, &callback, &user_data);
3137 UNLOCK_CONTEXT (context);
3139 /* These operations are safe because 'current' is thread-local
3140 * and not modified from anywhere but this function.
3142 prev_source = current->source;
3143 current->source = source;
3144 current->depth++;
3146 TRACE (GLIB_MAIN_BEFORE_DISPATCH (g_source_get_name (source), source,
3147 dispatch, callback, user_data));
3148 need_destroy = !(* dispatch) (source, callback, user_data);
3149 TRACE (GLIB_MAIN_AFTER_DISPATCH (g_source_get_name (source), source,
3150 dispatch, need_destroy));
3152 current->source = prev_source;
3153 current->depth--;
3155 if (cb_funcs)
3156 cb_funcs->unref (cb_data);
3158 LOCK_CONTEXT (context);
3160 if (!was_in_call)
3161 source->flags &= ~G_HOOK_FLAG_IN_CALL;
3163 if (SOURCE_BLOCKED (source) && !SOURCE_DESTROYED (source))
3164 unblock_source (source);
3166 /* Note: this depends on the fact that we can't switch
3167 * sources from one main context to another
3169 if (need_destroy && !SOURCE_DESTROYED (source))
3171 g_assert (source->context == context);
3172 g_source_destroy_internal (source, context, TRUE);
3176 SOURCE_UNREF (source, context);
3179 g_ptr_array_set_size (context->pending_dispatches, 0);
3183 * g_main_context_acquire:
3184 * @context: a #GMainContext
3186 * Tries to become the owner of the specified context.
3187 * If some other thread is the owner of the context,
3188 * returns %FALSE immediately. Ownership is properly
3189 * recursive: the owner can require ownership again
3190 * and will release ownership when g_main_context_release()
3191 * is called as many times as g_main_context_acquire().
3193 * You must be the owner of a context before you
3194 * can call g_main_context_prepare(), g_main_context_query(),
3195 * g_main_context_check(), g_main_context_dispatch().
3197 * Returns: %TRUE if the operation succeeded, and
3198 * this thread is now the owner of @context.
3200 gboolean
3201 g_main_context_acquire (GMainContext *context)
3203 gboolean result = FALSE;
3204 GThread *self = G_THREAD_SELF;
3206 if (context == NULL)
3207 context = g_main_context_default ();
3209 LOCK_CONTEXT (context);
3211 if (!context->owner)
3213 context->owner = self;
3214 g_assert (context->owner_count == 0);
3215 TRACE (GLIB_MAIN_CONTEXT_ACQUIRE (context, TRUE /* success */));
3218 if (context->owner == self)
3220 context->owner_count++;
3221 result = TRUE;
3223 else
3225 TRACE (GLIB_MAIN_CONTEXT_ACQUIRE (context, FALSE /* failure */));
3228 UNLOCK_CONTEXT (context);
3230 return result;
3234 * g_main_context_release:
3235 * @context: a #GMainContext
3237 * Releases ownership of a context previously acquired by this thread
3238 * with g_main_context_acquire(). If the context was acquired multiple
3239 * times, the ownership will be released only when g_main_context_release()
3240 * is called as many times as it was acquired.
3242 void
3243 g_main_context_release (GMainContext *context)
3245 if (context == NULL)
3246 context = g_main_context_default ();
3248 LOCK_CONTEXT (context);
3250 context->owner_count--;
3251 if (context->owner_count == 0)
3253 TRACE (GLIB_MAIN_CONTEXT_RELEASE (context));
3255 context->owner = NULL;
3257 if (context->waiters)
3259 GMainWaiter *waiter = context->waiters->data;
3260 gboolean loop_internal_waiter = (waiter->mutex == &context->mutex);
3261 context->waiters = g_slist_delete_link (context->waiters,
3262 context->waiters);
3263 if (!loop_internal_waiter)
3264 g_mutex_lock (waiter->mutex);
3266 g_cond_signal (waiter->cond);
3268 if (!loop_internal_waiter)
3269 g_mutex_unlock (waiter->mutex);
3273 UNLOCK_CONTEXT (context);
3277 * g_main_context_wait:
3278 * @context: a #GMainContext
3279 * @cond: a condition variable
3280 * @mutex: a mutex, currently held
3282 * Tries to become the owner of the specified context,
3283 * as with g_main_context_acquire(). But if another thread
3284 * is the owner, atomically drop @mutex and wait on @cond until
3285 * that owner releases ownership or until @cond is signaled, then
3286 * try again (once) to become the owner.
3288 * Returns: %TRUE if the operation succeeded, and
3289 * this thread is now the owner of @context.
3291 gboolean
3292 g_main_context_wait (GMainContext *context,
3293 GCond *cond,
3294 GMutex *mutex)
3296 gboolean result = FALSE;
3297 GThread *self = G_THREAD_SELF;
3298 gboolean loop_internal_waiter;
3300 if (context == NULL)
3301 context = g_main_context_default ();
3303 if G_UNLIKELY (cond != &context->cond || mutex != &context->mutex)
3305 static gboolean warned;
3307 if (!warned)
3309 g_critical ("WARNING!! g_main_context_wait() will be removed in a future release. "
3310 "If you see this message, please file a bug immediately.");
3311 warned = TRUE;
3315 loop_internal_waiter = (mutex == &context->mutex);
3317 if (!loop_internal_waiter)
3318 LOCK_CONTEXT (context);
3320 if (context->owner && context->owner != self)
3322 GMainWaiter waiter;
3324 waiter.cond = cond;
3325 waiter.mutex = mutex;
3327 context->waiters = g_slist_append (context->waiters, &waiter);
3329 if (!loop_internal_waiter)
3330 UNLOCK_CONTEXT (context);
3331 g_cond_wait (cond, mutex);
3332 if (!loop_internal_waiter)
3333 LOCK_CONTEXT (context);
3335 context->waiters = g_slist_remove (context->waiters, &waiter);
3338 if (!context->owner)
3340 context->owner = self;
3341 g_assert (context->owner_count == 0);
3344 if (context->owner == self)
3346 context->owner_count++;
3347 result = TRUE;
3350 if (!loop_internal_waiter)
3351 UNLOCK_CONTEXT (context);
3353 return result;
3357 * g_main_context_prepare:
3358 * @context: a #GMainContext
3359 * @priority: location to store priority of highest priority
3360 * source already ready.
3362 * Prepares to poll sources within a main loop. The resulting information
3363 * for polling is determined by calling g_main_context_query ().
3365 * You must have successfully acquired the context with
3366 * g_main_context_acquire() before you may call this function.
3368 * Returns: %TRUE if some source is ready to be dispatched
3369 * prior to polling.
3371 gboolean
3372 g_main_context_prepare (GMainContext *context,
3373 gint *priority)
3375 guint i;
3376 gint n_ready = 0;
3377 gint current_priority = G_MAXINT;
3378 GSource *source;
3379 GSourceIter iter;
3381 if (context == NULL)
3382 context = g_main_context_default ();
3384 LOCK_CONTEXT (context);
3386 /* context->need_wakeup is protected by LOCK_CONTEXT/UNLOCK_CONTEXT,
3387 * so need not set it yet.
3390 context->time_is_fresh = FALSE;
3392 if (context->in_check_or_prepare)
3394 g_warning ("g_main_context_prepare() called recursively from within a source's check() or "
3395 "prepare() member.");
3396 UNLOCK_CONTEXT (context);
3397 return FALSE;
3400 TRACE (GLIB_MAIN_CONTEXT_BEFORE_PREPARE (context));
3402 #if 0
3403 /* If recursing, finish up current dispatch, before starting over */
3404 if (context->pending_dispatches)
3406 if (dispatch)
3407 g_main_dispatch (context, &current_time);
3409 UNLOCK_CONTEXT (context);
3410 return TRUE;
3412 #endif
3414 /* If recursing, clear list of pending dispatches */
3416 for (i = 0; i < context->pending_dispatches->len; i++)
3418 if (context->pending_dispatches->pdata[i])
3419 SOURCE_UNREF ((GSource *)context->pending_dispatches->pdata[i], context);
3421 g_ptr_array_set_size (context->pending_dispatches, 0);
3423 /* Prepare all sources */
3425 context->timeout = -1;
3427 g_source_iter_init (&iter, context, TRUE);
3428 while (g_source_iter_next (&iter, &source))
3430 gint source_timeout = -1;
3432 if (SOURCE_DESTROYED (source) || SOURCE_BLOCKED (source))
3433 continue;
3434 if ((n_ready > 0) && (source->priority > current_priority))
3435 break;
3437 if (!(source->flags & G_SOURCE_READY))
3439 gboolean result;
3440 gboolean (* prepare) (GSource *source,
3441 gint *timeout);
3443 prepare = source->source_funcs->prepare;
3445 if (prepare)
3447 context->in_check_or_prepare++;
3448 UNLOCK_CONTEXT (context);
3450 result = (* prepare) (source, &source_timeout);
3451 TRACE (GLIB_MAIN_AFTER_PREPARE (source, prepare, source_timeout));
3453 LOCK_CONTEXT (context);
3454 context->in_check_or_prepare--;
3456 else
3458 source_timeout = -1;
3459 result = FALSE;
3462 if (result == FALSE && source->priv->ready_time != -1)
3464 if (!context->time_is_fresh)
3466 context->time = g_get_monotonic_time ();
3467 context->time_is_fresh = TRUE;
3470 if (source->priv->ready_time <= context->time)
3472 source_timeout = 0;
3473 result = TRUE;
3475 else
3477 gint timeout;
3479 /* rounding down will lead to spinning, so always round up */
3480 timeout = (source->priv->ready_time - context->time + 999) / 1000;
3482 if (source_timeout < 0 || timeout < source_timeout)
3483 source_timeout = timeout;
3487 if (result)
3489 GSource *ready_source = source;
3491 while (ready_source)
3493 ready_source->flags |= G_SOURCE_READY;
3494 ready_source = ready_source->priv->parent_source;
3499 if (source->flags & G_SOURCE_READY)
3501 n_ready++;
3502 current_priority = source->priority;
3503 context->timeout = 0;
3506 if (source_timeout >= 0)
3508 if (context->timeout < 0)
3509 context->timeout = source_timeout;
3510 else
3511 context->timeout = MIN (context->timeout, source_timeout);
3514 g_source_iter_clear (&iter);
3515 /* See conditional_wakeup() where this is used */
3516 context->need_wakeup = (n_ready == 0);
3518 TRACE (GLIB_MAIN_CONTEXT_AFTER_PREPARE (context, current_priority, n_ready));
3520 UNLOCK_CONTEXT (context);
3522 if (priority)
3523 *priority = current_priority;
3525 return (n_ready > 0);
3529 * g_main_context_query:
3530 * @context: a #GMainContext
3531 * @max_priority: maximum priority source to check
3532 * @timeout_: (out): location to store timeout to be used in polling
3533 * @fds: (out caller-allocates) (array length=n_fds): location to
3534 * store #GPollFD records that need to be polled.
3535 * @n_fds: (in): length of @fds.
3537 * Determines information necessary to poll this main loop.
3539 * You must have successfully acquired the context with
3540 * g_main_context_acquire() before you may call this function.
3542 * Returns: the number of records actually stored in @fds,
3543 * or, if more than @n_fds records need to be stored, the number
3544 * of records that need to be stored.
3546 gint
3547 g_main_context_query (GMainContext *context,
3548 gint max_priority,
3549 gint *timeout,
3550 GPollFD *fds,
3551 gint n_fds)
3553 gint n_poll;
3554 GPollRec *pollrec, *lastpollrec;
3555 gushort events;
3557 LOCK_CONTEXT (context);
3559 TRACE (GLIB_MAIN_CONTEXT_BEFORE_QUERY (context, max_priority));
3561 n_poll = 0;
3562 lastpollrec = NULL;
3563 for (pollrec = context->poll_records; pollrec; pollrec = pollrec->next)
3565 if (pollrec->priority > max_priority)
3566 continue;
3568 /* In direct contradiction to the Unix98 spec, IRIX runs into
3569 * difficulty if you pass in POLLERR, POLLHUP or POLLNVAL
3570 * flags in the events field of the pollfd while it should
3571 * just ignoring them. So we mask them out here.
3573 events = pollrec->fd->events & ~(G_IO_ERR|G_IO_HUP|G_IO_NVAL);
3575 if (lastpollrec && pollrec->fd->fd == lastpollrec->fd->fd)
3577 if (n_poll - 1 < n_fds)
3578 fds[n_poll - 1].events |= events;
3580 else
3582 if (n_poll < n_fds)
3584 fds[n_poll].fd = pollrec->fd->fd;
3585 fds[n_poll].events = events;
3586 fds[n_poll].revents = 0;
3589 n_poll++;
3592 lastpollrec = pollrec;
3595 context->poll_changed = FALSE;
3597 if (timeout)
3599 *timeout = context->timeout;
3600 if (*timeout != 0)
3601 context->time_is_fresh = FALSE;
3604 TRACE (GLIB_MAIN_CONTEXT_AFTER_QUERY (context, context->timeout,
3605 fds, n_poll));
3607 UNLOCK_CONTEXT (context);
3609 return n_poll;
3613 * g_main_context_check:
3614 * @context: a #GMainContext
3615 * @max_priority: the maximum numerical priority of sources to check
3616 * @fds: (array length=n_fds): array of #GPollFD's that was passed to
3617 * the last call to g_main_context_query()
3618 * @n_fds: return value of g_main_context_query()
3620 * Passes the results of polling back to the main loop.
3622 * You must have successfully acquired the context with
3623 * g_main_context_acquire() before you may call this function.
3625 * Returns: %TRUE if some sources are ready to be dispatched.
3627 gboolean
3628 g_main_context_check (GMainContext *context,
3629 gint max_priority,
3630 GPollFD *fds,
3631 gint n_fds)
3633 GSource *source;
3634 GSourceIter iter;
3635 GPollRec *pollrec;
3636 gint n_ready = 0;
3637 gint i;
3639 LOCK_CONTEXT (context);
3641 if (context->in_check_or_prepare)
3643 g_warning ("g_main_context_check() called recursively from within a source's check() or "
3644 "prepare() member.");
3645 UNLOCK_CONTEXT (context);
3646 return FALSE;
3649 TRACE (GLIB_MAIN_CONTEXT_BEFORE_CHECK (context, max_priority, fds, n_fds));
3651 /* We don't need to wakeup during check or dispatch, because
3652 * all sources will be re-evaluated during prepare/query.
3654 context->need_wakeup = FALSE;
3656 /* And if we have a wakeup pending, acknowledge it */
3657 for (i = 0; i < n_fds; i++)
3659 if (fds[i].fd == context->wake_up_rec.fd)
3661 if (fds[i].revents)
3663 TRACE (GLIB_MAIN_CONTEXT_WAKEUP_ACKNOWLEDGE (context));
3664 g_wakeup_acknowledge (context->wakeup);
3666 break;
3670 /* If the set of poll file descriptors changed, bail out
3671 * and let the main loop rerun
3673 if (context->poll_changed)
3675 TRACE (GLIB_MAIN_CONTEXT_AFTER_CHECK (context, 0));
3677 UNLOCK_CONTEXT (context);
3678 return FALSE;
3681 pollrec = context->poll_records;
3682 i = 0;
3683 while (pollrec && i < n_fds)
3685 while (pollrec && pollrec->fd->fd == fds[i].fd)
3687 if (pollrec->priority <= max_priority)
3689 pollrec->fd->revents =
3690 fds[i].revents & (pollrec->fd->events | G_IO_ERR | G_IO_HUP | G_IO_NVAL);
3692 pollrec = pollrec->next;
3695 i++;
3698 g_source_iter_init (&iter, context, TRUE);
3699 while (g_source_iter_next (&iter, &source))
3701 if (SOURCE_DESTROYED (source) || SOURCE_BLOCKED (source))
3702 continue;
3703 if ((n_ready > 0) && (source->priority > max_priority))
3704 break;
3706 if (!(source->flags & G_SOURCE_READY))
3708 gboolean result;
3709 gboolean (* check) (GSource *source);
3711 check = source->source_funcs->check;
3713 if (check)
3715 /* If the check function is set, call it. */
3716 context->in_check_or_prepare++;
3717 UNLOCK_CONTEXT (context);
3719 result = (* check) (source);
3721 TRACE (GLIB_MAIN_AFTER_CHECK (source, check, result));
3723 LOCK_CONTEXT (context);
3724 context->in_check_or_prepare--;
3726 else
3727 result = FALSE;
3729 if (result == FALSE)
3731 GSList *tmp_list;
3733 /* If not already explicitly flagged ready by ->check()
3734 * (or if we have no check) then we can still be ready if
3735 * any of our fds poll as ready.
3737 for (tmp_list = source->priv->fds; tmp_list; tmp_list = tmp_list->next)
3739 GPollFD *pollfd = tmp_list->data;
3741 if (pollfd->revents)
3743 result = TRUE;
3744 break;
3749 if (result == FALSE && source->priv->ready_time != -1)
3751 if (!context->time_is_fresh)
3753 context->time = g_get_monotonic_time ();
3754 context->time_is_fresh = TRUE;
3757 if (source->priv->ready_time <= context->time)
3758 result = TRUE;
3761 if (result)
3763 GSource *ready_source = source;
3765 while (ready_source)
3767 ready_source->flags |= G_SOURCE_READY;
3768 ready_source = ready_source->priv->parent_source;
3773 if (source->flags & G_SOURCE_READY)
3775 source->ref_count++;
3776 g_ptr_array_add (context->pending_dispatches, source);
3778 n_ready++;
3780 /* never dispatch sources with less priority than the first
3781 * one we choose to dispatch
3783 max_priority = source->priority;
3786 g_source_iter_clear (&iter);
3788 TRACE (GLIB_MAIN_CONTEXT_AFTER_CHECK (context, n_ready));
3790 UNLOCK_CONTEXT (context);
3792 return n_ready > 0;
3796 * g_main_context_dispatch:
3797 * @context: a #GMainContext
3799 * Dispatches all pending sources.
3801 * You must have successfully acquired the context with
3802 * g_main_context_acquire() before you may call this function.
3804 void
3805 g_main_context_dispatch (GMainContext *context)
3807 LOCK_CONTEXT (context);
3809 TRACE (GLIB_MAIN_CONTEXT_BEFORE_DISPATCH (context));
3811 if (context->pending_dispatches->len > 0)
3813 g_main_dispatch (context);
3816 TRACE (GLIB_MAIN_CONTEXT_AFTER_DISPATCH (context));
3818 UNLOCK_CONTEXT (context);
3821 /* HOLDS context lock */
3822 static gboolean
3823 g_main_context_iterate (GMainContext *context,
3824 gboolean block,
3825 gboolean dispatch,
3826 GThread *self)
3828 gint max_priority;
3829 gint timeout;
3830 gboolean some_ready;
3831 gint nfds, allocated_nfds;
3832 GPollFD *fds = NULL;
3834 UNLOCK_CONTEXT (context);
3836 if (!g_main_context_acquire (context))
3838 gboolean got_ownership;
3840 LOCK_CONTEXT (context);
3842 if (!block)
3843 return FALSE;
3845 got_ownership = g_main_context_wait (context,
3846 &context->cond,
3847 &context->mutex);
3849 if (!got_ownership)
3850 return FALSE;
3852 else
3853 LOCK_CONTEXT (context);
3855 if (!context->cached_poll_array)
3857 context->cached_poll_array_size = context->n_poll_records;
3858 context->cached_poll_array = g_new (GPollFD, context->n_poll_records);
3861 allocated_nfds = context->cached_poll_array_size;
3862 fds = context->cached_poll_array;
3864 UNLOCK_CONTEXT (context);
3866 g_main_context_prepare (context, &max_priority);
3868 while ((nfds = g_main_context_query (context, max_priority, &timeout, fds,
3869 allocated_nfds)) > allocated_nfds)
3871 LOCK_CONTEXT (context);
3872 g_free (fds);
3873 context->cached_poll_array_size = allocated_nfds = nfds;
3874 context->cached_poll_array = fds = g_new (GPollFD, nfds);
3875 UNLOCK_CONTEXT (context);
3878 if (!block)
3879 timeout = 0;
3881 g_main_context_poll (context, timeout, max_priority, fds, nfds);
3883 some_ready = g_main_context_check (context, max_priority, fds, nfds);
3885 if (dispatch)
3886 g_main_context_dispatch (context);
3888 g_main_context_release (context);
3890 LOCK_CONTEXT (context);
3892 return some_ready;
3896 * g_main_context_pending:
3897 * @context: (nullable): a #GMainContext (if %NULL, the default context will be used)
3899 * Checks if any sources have pending events for the given context.
3901 * Returns: %TRUE if events are pending.
3903 gboolean
3904 g_main_context_pending (GMainContext *context)
3906 gboolean retval;
3908 if (!context)
3909 context = g_main_context_default();
3911 LOCK_CONTEXT (context);
3912 retval = g_main_context_iterate (context, FALSE, FALSE, G_THREAD_SELF);
3913 UNLOCK_CONTEXT (context);
3915 return retval;
3919 * g_main_context_iteration:
3920 * @context: (nullable): a #GMainContext (if %NULL, the default context will be used)
3921 * @may_block: whether the call may block.
3923 * Runs a single iteration for the given main loop. This involves
3924 * checking to see if any event sources are ready to be processed,
3925 * then if no events sources are ready and @may_block is %TRUE, waiting
3926 * for a source to become ready, then dispatching the highest priority
3927 * events sources that are ready. Otherwise, if @may_block is %FALSE
3928 * sources are not waited to become ready, only those highest priority
3929 * events sources will be dispatched (if any), that are ready at this
3930 * given moment without further waiting.
3932 * Note that even when @may_block is %TRUE, it is still possible for
3933 * g_main_context_iteration() to return %FALSE, since the wait may
3934 * be interrupted for other reasons than an event source becoming ready.
3936 * Returns: %TRUE if events were dispatched.
3938 gboolean
3939 g_main_context_iteration (GMainContext *context, gboolean may_block)
3941 gboolean retval;
3943 if (!context)
3944 context = g_main_context_default();
3946 LOCK_CONTEXT (context);
3947 retval = g_main_context_iterate (context, may_block, TRUE, G_THREAD_SELF);
3948 UNLOCK_CONTEXT (context);
3950 return retval;
3954 * g_main_loop_new:
3955 * @context: (nullable): a #GMainContext (if %NULL, the default context will be used).
3956 * @is_running: set to %TRUE to indicate that the loop is running. This
3957 * is not very important since calling g_main_loop_run() will set this to
3958 * %TRUE anyway.
3960 * Creates a new #GMainLoop structure.
3962 * Returns: a new #GMainLoop.
3964 GMainLoop *
3965 g_main_loop_new (GMainContext *context,
3966 gboolean is_running)
3968 GMainLoop *loop;
3970 if (!context)
3971 context = g_main_context_default();
3973 g_main_context_ref (context);
3975 loop = g_new0 (GMainLoop, 1);
3976 loop->context = context;
3977 loop->is_running = is_running != FALSE;
3978 loop->ref_count = 1;
3980 TRACE (GLIB_MAIN_LOOP_NEW (loop, context));
3982 return loop;
3986 * g_main_loop_ref:
3987 * @loop: a #GMainLoop
3989 * Increases the reference count on a #GMainLoop object by one.
3991 * Returns: @loop
3993 GMainLoop *
3994 g_main_loop_ref (GMainLoop *loop)
3996 g_return_val_if_fail (loop != NULL, NULL);
3997 g_return_val_if_fail (g_atomic_int_get (&loop->ref_count) > 0, NULL);
3999 g_atomic_int_inc (&loop->ref_count);
4001 return loop;
4005 * g_main_loop_unref:
4006 * @loop: a #GMainLoop
4008 * Decreases the reference count on a #GMainLoop object by one. If
4009 * the result is zero, free the loop and free all associated memory.
4011 void
4012 g_main_loop_unref (GMainLoop *loop)
4014 g_return_if_fail (loop != NULL);
4015 g_return_if_fail (g_atomic_int_get (&loop->ref_count) > 0);
4017 if (!g_atomic_int_dec_and_test (&loop->ref_count))
4018 return;
4020 g_main_context_unref (loop->context);
4021 g_free (loop);
4025 * g_main_loop_run:
4026 * @loop: a #GMainLoop
4028 * Runs a main loop until g_main_loop_quit() is called on the loop.
4029 * If this is called for the thread of the loop's #GMainContext,
4030 * it will process events from the loop, otherwise it will
4031 * simply wait.
4033 void
4034 g_main_loop_run (GMainLoop *loop)
4036 GThread *self = G_THREAD_SELF;
4038 g_return_if_fail (loop != NULL);
4039 g_return_if_fail (g_atomic_int_get (&loop->ref_count) > 0);
4041 if (!g_main_context_acquire (loop->context))
4043 gboolean got_ownership = FALSE;
4045 /* Another thread owns this context */
4046 LOCK_CONTEXT (loop->context);
4048 g_atomic_int_inc (&loop->ref_count);
4050 if (!loop->is_running)
4051 loop->is_running = TRUE;
4053 while (loop->is_running && !got_ownership)
4054 got_ownership = g_main_context_wait (loop->context,
4055 &loop->context->cond,
4056 &loop->context->mutex);
4058 if (!loop->is_running)
4060 UNLOCK_CONTEXT (loop->context);
4061 if (got_ownership)
4062 g_main_context_release (loop->context);
4063 g_main_loop_unref (loop);
4064 return;
4067 g_assert (got_ownership);
4069 else
4070 LOCK_CONTEXT (loop->context);
4072 if (loop->context->in_check_or_prepare)
4074 g_warning ("g_main_loop_run(): called recursively from within a source's "
4075 "check() or prepare() member, iteration not possible.");
4076 return;
4079 g_atomic_int_inc (&loop->ref_count);
4080 loop->is_running = TRUE;
4081 while (loop->is_running)
4082 g_main_context_iterate (loop->context, TRUE, TRUE, self);
4084 UNLOCK_CONTEXT (loop->context);
4086 g_main_context_release (loop->context);
4088 g_main_loop_unref (loop);
4092 * g_main_loop_quit:
4093 * @loop: a #GMainLoop
4095 * Stops a #GMainLoop from running. Any calls to g_main_loop_run()
4096 * for the loop will return.
4098 * Note that sources that have already been dispatched when
4099 * g_main_loop_quit() is called will still be executed.
4101 void
4102 g_main_loop_quit (GMainLoop *loop)
4104 g_return_if_fail (loop != NULL);
4105 g_return_if_fail (g_atomic_int_get (&loop->ref_count) > 0);
4107 LOCK_CONTEXT (loop->context);
4108 loop->is_running = FALSE;
4109 g_wakeup_signal (loop->context->wakeup);
4111 g_cond_broadcast (&loop->context->cond);
4113 UNLOCK_CONTEXT (loop->context);
4115 TRACE (GLIB_MAIN_LOOP_QUIT (loop));
4119 * g_main_loop_is_running:
4120 * @loop: a #GMainLoop.
4122 * Checks to see if the main loop is currently being run via g_main_loop_run().
4124 * Returns: %TRUE if the mainloop is currently being run.
4126 gboolean
4127 g_main_loop_is_running (GMainLoop *loop)
4129 g_return_val_if_fail (loop != NULL, FALSE);
4130 g_return_val_if_fail (g_atomic_int_get (&loop->ref_count) > 0, FALSE);
4132 return loop->is_running;
4136 * g_main_loop_get_context:
4137 * @loop: a #GMainLoop.
4139 * Returns the #GMainContext of @loop.
4141 * Returns: (transfer none): the #GMainContext of @loop
4143 GMainContext *
4144 g_main_loop_get_context (GMainLoop *loop)
4146 g_return_val_if_fail (loop != NULL, NULL);
4147 g_return_val_if_fail (g_atomic_int_get (&loop->ref_count) > 0, NULL);
4149 return loop->context;
4152 /* HOLDS: context's lock */
4153 static void
4154 g_main_context_poll (GMainContext *context,
4155 gint timeout,
4156 gint priority,
4157 GPollFD *fds,
4158 gint n_fds)
4160 #ifdef G_MAIN_POLL_DEBUG
4161 GTimer *poll_timer;
4162 GPollRec *pollrec;
4163 gint i;
4164 #endif
4166 GPollFunc poll_func;
4168 if (n_fds || timeout != 0)
4170 #ifdef G_MAIN_POLL_DEBUG
4171 poll_timer = NULL;
4172 if (_g_main_poll_debug)
4174 g_print ("polling context=%p n=%d timeout=%d\n",
4175 context, n_fds, timeout);
4176 poll_timer = g_timer_new ();
4178 #endif
4180 LOCK_CONTEXT (context);
4182 poll_func = context->poll_func;
4184 UNLOCK_CONTEXT (context);
4185 if ((*poll_func) (fds, n_fds, timeout) < 0 && errno != EINTR)
4187 #ifndef G_OS_WIN32
4188 g_warning ("poll(2) failed due to: %s.",
4189 g_strerror (errno));
4190 #else
4191 /* If g_poll () returns -1, it has already called g_warning() */
4192 #endif
4195 #ifdef G_MAIN_POLL_DEBUG
4196 if (_g_main_poll_debug)
4198 LOCK_CONTEXT (context);
4200 g_print ("g_main_poll(%d) timeout: %d - elapsed %12.10f seconds",
4201 n_fds,
4202 timeout,
4203 g_timer_elapsed (poll_timer, NULL));
4204 g_timer_destroy (poll_timer);
4205 pollrec = context->poll_records;
4207 while (pollrec != NULL)
4209 i = 0;
4210 while (i < n_fds)
4212 if (fds[i].fd == pollrec->fd->fd &&
4213 pollrec->fd->events &&
4214 fds[i].revents)
4216 g_print (" [" G_POLLFD_FORMAT " :", fds[i].fd);
4217 if (fds[i].revents & G_IO_IN)
4218 g_print ("i");
4219 if (fds[i].revents & G_IO_OUT)
4220 g_print ("o");
4221 if (fds[i].revents & G_IO_PRI)
4222 g_print ("p");
4223 if (fds[i].revents & G_IO_ERR)
4224 g_print ("e");
4225 if (fds[i].revents & G_IO_HUP)
4226 g_print ("h");
4227 if (fds[i].revents & G_IO_NVAL)
4228 g_print ("n");
4229 g_print ("]");
4231 i++;
4233 pollrec = pollrec->next;
4235 g_print ("\n");
4237 UNLOCK_CONTEXT (context);
4239 #endif
4240 } /* if (n_fds || timeout != 0) */
4244 * g_main_context_add_poll:
4245 * @context: (nullable): a #GMainContext (or %NULL for the default context)
4246 * @fd: a #GPollFD structure holding information about a file
4247 * descriptor to watch.
4248 * @priority: the priority for this file descriptor which should be
4249 * the same as the priority used for g_source_attach() to ensure that the
4250 * file descriptor is polled whenever the results may be needed.
4252 * Adds a file descriptor to the set of file descriptors polled for
4253 * this context. This will very seldom be used directly. Instead
4254 * a typical event source will use g_source_add_unix_fd() instead.
4256 void
4257 g_main_context_add_poll (GMainContext *context,
4258 GPollFD *fd,
4259 gint priority)
4261 if (!context)
4262 context = g_main_context_default ();
4264 g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
4265 g_return_if_fail (fd);
4267 LOCK_CONTEXT (context);
4268 g_main_context_add_poll_unlocked (context, priority, fd);
4269 UNLOCK_CONTEXT (context);
4272 /* HOLDS: main_loop_lock */
4273 static void
4274 g_main_context_add_poll_unlocked (GMainContext *context,
4275 gint priority,
4276 GPollFD *fd)
4278 GPollRec *prevrec, *nextrec;
4279 GPollRec *newrec = g_slice_new (GPollRec);
4281 /* This file descriptor may be checked before we ever poll */
4282 fd->revents = 0;
4283 newrec->fd = fd;
4284 newrec->priority = priority;
4286 prevrec = NULL;
4287 nextrec = context->poll_records;
4288 while (nextrec)
4290 if (nextrec->fd->fd > fd->fd)
4291 break;
4292 prevrec = nextrec;
4293 nextrec = nextrec->next;
4296 if (prevrec)
4297 prevrec->next = newrec;
4298 else
4299 context->poll_records = newrec;
4301 newrec->prev = prevrec;
4302 newrec->next = nextrec;
4304 if (nextrec)
4305 nextrec->prev = newrec;
4307 context->n_poll_records++;
4309 context->poll_changed = TRUE;
4311 /* Now wake up the main loop if it is waiting in the poll() */
4312 conditional_wakeup (context);
4316 * g_main_context_remove_poll:
4317 * @context:a #GMainContext
4318 * @fd: a #GPollFD descriptor previously added with g_main_context_add_poll()
4320 * Removes file descriptor from the set of file descriptors to be
4321 * polled for a particular context.
4323 void
4324 g_main_context_remove_poll (GMainContext *context,
4325 GPollFD *fd)
4327 if (!context)
4328 context = g_main_context_default ();
4330 g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
4331 g_return_if_fail (fd);
4333 LOCK_CONTEXT (context);
4334 g_main_context_remove_poll_unlocked (context, fd);
4335 UNLOCK_CONTEXT (context);
4338 static void
4339 g_main_context_remove_poll_unlocked (GMainContext *context,
4340 GPollFD *fd)
4342 GPollRec *pollrec, *prevrec, *nextrec;
4344 prevrec = NULL;
4345 pollrec = context->poll_records;
4347 while (pollrec)
4349 nextrec = pollrec->next;
4350 if (pollrec->fd == fd)
4352 if (prevrec != NULL)
4353 prevrec->next = nextrec;
4354 else
4355 context->poll_records = nextrec;
4357 if (nextrec != NULL)
4358 nextrec->prev = prevrec;
4360 g_slice_free (GPollRec, pollrec);
4362 context->n_poll_records--;
4363 break;
4365 prevrec = pollrec;
4366 pollrec = nextrec;
4369 context->poll_changed = TRUE;
4371 /* Now wake up the main loop if it is waiting in the poll() */
4372 conditional_wakeup (context);
4376 * g_source_get_current_time:
4377 * @source: a #GSource
4378 * @timeval: #GTimeVal structure in which to store current time.
4380 * This function ignores @source and is otherwise the same as
4381 * g_get_current_time().
4383 * Deprecated: 2.28: use g_source_get_time() instead
4385 void
4386 g_source_get_current_time (GSource *source,
4387 GTimeVal *timeval)
4389 g_get_current_time (timeval);
4393 * g_source_get_time:
4394 * @source: a #GSource
4396 * Gets the time to be used when checking this source. The advantage of
4397 * calling this function over calling g_get_monotonic_time() directly is
4398 * that when checking multiple sources, GLib can cache a single value
4399 * instead of having to repeatedly get the system monotonic time.
4401 * The time here is the system monotonic time, if available, or some
4402 * other reasonable alternative otherwise. See g_get_monotonic_time().
4404 * Returns: the monotonic time in microseconds
4406 * Since: 2.28
4408 gint64
4409 g_source_get_time (GSource *source)
4411 GMainContext *context;
4412 gint64 result;
4414 g_return_val_if_fail (source->context != NULL, 0);
4416 context = source->context;
4418 LOCK_CONTEXT (context);
4420 if (!context->time_is_fresh)
4422 context->time = g_get_monotonic_time ();
4423 context->time_is_fresh = TRUE;
4426 result = context->time;
4428 UNLOCK_CONTEXT (context);
4430 return result;
4434 * g_main_context_set_poll_func:
4435 * @context: a #GMainContext
4436 * @func: the function to call to poll all file descriptors
4438 * Sets the function to use to handle polling of file descriptors. It
4439 * will be used instead of the poll() system call
4440 * (or GLib's replacement function, which is used where
4441 * poll() isn't available).
4443 * This function could possibly be used to integrate the GLib event
4444 * loop with an external event loop.
4446 void
4447 g_main_context_set_poll_func (GMainContext *context,
4448 GPollFunc func)
4450 if (!context)
4451 context = g_main_context_default ();
4453 g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
4455 LOCK_CONTEXT (context);
4457 if (func)
4458 context->poll_func = func;
4459 else
4460 context->poll_func = g_poll;
4462 UNLOCK_CONTEXT (context);
4466 * g_main_context_get_poll_func:
4467 * @context: a #GMainContext
4469 * Gets the poll function set by g_main_context_set_poll_func().
4471 * Returns: the poll function
4473 GPollFunc
4474 g_main_context_get_poll_func (GMainContext *context)
4476 GPollFunc result;
4478 if (!context)
4479 context = g_main_context_default ();
4481 g_return_val_if_fail (g_atomic_int_get (&context->ref_count) > 0, NULL);
4483 LOCK_CONTEXT (context);
4484 result = context->poll_func;
4485 UNLOCK_CONTEXT (context);
4487 return result;
4491 * g_main_context_wakeup:
4492 * @context: a #GMainContext
4494 * If @context is currently blocking in g_main_context_iteration()
4495 * waiting for a source to become ready, cause it to stop blocking
4496 * and return. Otherwise, cause the next invocation of
4497 * g_main_context_iteration() to return without blocking.
4499 * This API is useful for low-level control over #GMainContext; for
4500 * example, integrating it with main loop implementations such as
4501 * #GMainLoop.
4503 * Another related use for this function is when implementing a main
4504 * loop with a termination condition, computed from multiple threads:
4506 * |[<!-- language="C" -->
4507 * #define NUM_TASKS 10
4508 * static volatile gint tasks_remaining = NUM_TASKS;
4509 * ...
4511 * while (g_atomic_int_get (&tasks_remaining) != 0)
4512 * g_main_context_iteration (NULL, TRUE);
4513 * ]|
4515 * Then in a thread:
4516 * |[<!-- language="C" -->
4517 * perform_work();
4519 * if (g_atomic_int_dec_and_test (&tasks_remaining))
4520 * g_main_context_wakeup (NULL);
4521 * ]|
4523 void
4524 g_main_context_wakeup (GMainContext *context)
4526 if (!context)
4527 context = g_main_context_default ();
4529 g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
4531 TRACE (GLIB_MAIN_CONTEXT_WAKEUP (context));
4533 g_wakeup_signal (context->wakeup);
4537 * g_main_context_is_owner:
4538 * @context: a #GMainContext
4540 * Determines whether this thread holds the (recursive)
4541 * ownership of this #GMainContext. This is useful to
4542 * know before waiting on another thread that may be
4543 * blocking to get ownership of @context.
4545 * Returns: %TRUE if current thread is owner of @context.
4547 * Since: 2.10
4549 gboolean
4550 g_main_context_is_owner (GMainContext *context)
4552 gboolean is_owner;
4554 if (!context)
4555 context = g_main_context_default ();
4557 LOCK_CONTEXT (context);
4558 is_owner = context->owner == G_THREAD_SELF;
4559 UNLOCK_CONTEXT (context);
4561 return is_owner;
4564 /* Timeouts */
4566 static void
4567 g_timeout_set_expiration (GTimeoutSource *timeout_source,
4568 gint64 current_time)
4570 gint64 expiration;
4572 expiration = current_time + (guint64) timeout_source->interval * 1000;
4574 if (timeout_source->seconds)
4576 gint64 remainder;
4577 static gint timer_perturb = -1;
4579 if (timer_perturb == -1)
4582 * we want a per machine/session unique 'random' value; try the dbus
4583 * address first, that has a UUID in it. If there is no dbus, use the
4584 * hostname for hashing.
4586 const char *session_bus_address = g_getenv ("DBUS_SESSION_BUS_ADDRESS");
4587 if (!session_bus_address)
4588 session_bus_address = g_getenv ("HOSTNAME");
4589 if (session_bus_address)
4590 timer_perturb = ABS ((gint) g_str_hash (session_bus_address)) % 1000000;
4591 else
4592 timer_perturb = 0;
4595 /* We want the microseconds part of the timeout to land on the
4596 * 'timer_perturb' mark, but we need to make sure we don't try to
4597 * set the timeout in the past. We do this by ensuring that we
4598 * always only *increase* the expiration time by adding a full
4599 * second in the case that the microsecond portion decreases.
4601 expiration -= timer_perturb;
4603 remainder = expiration % 1000000;
4604 if (remainder >= 1000000/4)
4605 expiration += 1000000;
4607 expiration -= remainder;
4608 expiration += timer_perturb;
4611 g_source_set_ready_time ((GSource *) timeout_source, expiration);
4614 static gboolean
4615 g_timeout_dispatch (GSource *source,
4616 GSourceFunc callback,
4617 gpointer user_data)
4619 GTimeoutSource *timeout_source = (GTimeoutSource *)source;
4620 gboolean again;
4622 if (!callback)
4624 g_warning ("Timeout source dispatched without callback\n"
4625 "You must call g_source_set_callback().");
4626 return FALSE;
4629 again = callback (user_data);
4631 TRACE (GLIB_TIMEOUT_DISPATCH (source, source->context, callback, user_data, again));
4633 if (again)
4634 g_timeout_set_expiration (timeout_source, g_source_get_time (source));
4636 return again;
4640 * g_timeout_source_new:
4641 * @interval: the timeout interval in milliseconds.
4643 * Creates a new timeout source.
4645 * The source will not initially be associated with any #GMainContext
4646 * and must be added to one with g_source_attach() before it will be
4647 * executed.
4649 * The interval given is in terms of monotonic time, not wall clock
4650 * time. See g_get_monotonic_time().
4652 * Returns: the newly-created timeout source
4654 GSource *
4655 g_timeout_source_new (guint interval)
4657 GSource *source = g_source_new (&g_timeout_funcs, sizeof (GTimeoutSource));
4658 GTimeoutSource *timeout_source = (GTimeoutSource *)source;
4660 timeout_source->interval = interval;
4661 g_timeout_set_expiration (timeout_source, g_get_monotonic_time ());
4663 return source;
4667 * g_timeout_source_new_seconds:
4668 * @interval: the timeout interval in seconds
4670 * Creates a new timeout source.
4672 * The source will not initially be associated with any #GMainContext
4673 * and must be added to one with g_source_attach() before it will be
4674 * executed.
4676 * The scheduling granularity/accuracy of this timeout source will be
4677 * in seconds.
4679 * The interval given in terms of monotonic time, not wall clock time.
4680 * See g_get_monotonic_time().
4682 * Returns: the newly-created timeout source
4684 * Since: 2.14
4686 GSource *
4687 g_timeout_source_new_seconds (guint interval)
4689 GSource *source = g_source_new (&g_timeout_funcs, sizeof (GTimeoutSource));
4690 GTimeoutSource *timeout_source = (GTimeoutSource *)source;
4692 timeout_source->interval = 1000 * interval;
4693 timeout_source->seconds = TRUE;
4695 g_timeout_set_expiration (timeout_source, g_get_monotonic_time ());
4697 return source;
4702 * g_timeout_add_full: (rename-to g_timeout_add)
4703 * @priority: the priority of the timeout source. Typically this will be in
4704 * the range between #G_PRIORITY_DEFAULT and #G_PRIORITY_HIGH.
4705 * @interval: the time between calls to the function, in milliseconds
4706 * (1/1000ths of a second)
4707 * @function: function to call
4708 * @data: data to pass to @function
4709 * @notify: (nullable): function to call when the timeout is removed, or %NULL
4711 * Sets a function to be called at regular intervals, with the given
4712 * priority. The function is called repeatedly until it returns
4713 * %FALSE, at which point the timeout is automatically destroyed and
4714 * the function will not be called again. The @notify function is
4715 * called when the timeout is destroyed. The first call to the
4716 * function will be at the end of the first @interval.
4718 * Note that timeout functions may be delayed, due to the processing of other
4719 * event sources. Thus they should not be relied on for precise timing.
4720 * After each call to the timeout function, the time of the next
4721 * timeout is recalculated based on the current time and the given interval
4722 * (it does not try to 'catch up' time lost in delays).
4724 * See [memory management of sources][mainloop-memory-management] for details
4725 * on how to handle the return value and memory management of @data.
4727 * This internally creates a main loop source using g_timeout_source_new()
4728 * and attaches it to the global #GMainContext using g_source_attach(), so
4729 * the callback will be invoked in whichever thread is running that main
4730 * context. You can do these steps manually if you need greater control or to
4731 * use a custom main context.
4733 * The interval given in terms of monotonic time, not wall clock time.
4734 * See g_get_monotonic_time().
4736 * Returns: the ID (greater than 0) of the event source.
4738 guint
4739 g_timeout_add_full (gint priority,
4740 guint interval,
4741 GSourceFunc function,
4742 gpointer data,
4743 GDestroyNotify notify)
4745 GSource *source;
4746 guint id;
4748 g_return_val_if_fail (function != NULL, 0);
4750 source = g_timeout_source_new (interval);
4752 if (priority != G_PRIORITY_DEFAULT)
4753 g_source_set_priority (source, priority);
4755 g_source_set_callback (source, function, data, notify);
4756 id = g_source_attach (source, NULL);
4758 TRACE (GLIB_TIMEOUT_ADD (source, g_main_context_default (), id, priority, interval, function, data));
4760 g_source_unref (source);
4762 return id;
4766 * g_timeout_add:
4767 * @interval: the time between calls to the function, in milliseconds
4768 * (1/1000ths of a second)
4769 * @function: function to call
4770 * @data: data to pass to @function
4772 * Sets a function to be called at regular intervals, with the default
4773 * priority, #G_PRIORITY_DEFAULT. The function is called repeatedly
4774 * until it returns %FALSE, at which point the timeout is automatically
4775 * destroyed and the function will not be called again. The first call
4776 * to the function will be at the end of the first @interval.
4778 * Note that timeout functions may be delayed, due to the processing of other
4779 * event sources. Thus they should not be relied on for precise timing.
4780 * After each call to the timeout function, the time of the next
4781 * timeout is recalculated based on the current time and the given interval
4782 * (it does not try to 'catch up' time lost in delays).
4784 * See [memory management of sources][mainloop-memory-management] for details
4785 * on how to handle the return value and memory management of @data.
4787 * If you want to have a timer in the "seconds" range and do not care
4788 * about the exact time of the first call of the timer, use the
4789 * g_timeout_add_seconds() function; this function allows for more
4790 * optimizations and more efficient system power usage.
4792 * This internally creates a main loop source using g_timeout_source_new()
4793 * and attaches it to the global #GMainContext using g_source_attach(), so
4794 * the callback will be invoked in whichever thread is running that main
4795 * context. You can do these steps manually if you need greater control or to
4796 * use a custom main context.
4798 * The interval given is in terms of monotonic time, not wall clock
4799 * time. See g_get_monotonic_time().
4801 * Returns: the ID (greater than 0) of the event source.
4803 guint
4804 g_timeout_add (guint32 interval,
4805 GSourceFunc function,
4806 gpointer data)
4808 return g_timeout_add_full (G_PRIORITY_DEFAULT,
4809 interval, function, data, NULL);
4813 * g_timeout_add_seconds_full: (rename-to g_timeout_add_seconds)
4814 * @priority: the priority of the timeout source. Typically this will be in
4815 * the range between #G_PRIORITY_DEFAULT and #G_PRIORITY_HIGH.
4816 * @interval: the time between calls to the function, in seconds
4817 * @function: function to call
4818 * @data: data to pass to @function
4819 * @notify: (nullable): function to call when the timeout is removed, or %NULL
4821 * Sets a function to be called at regular intervals, with @priority.
4822 * The function is called repeatedly until it returns %FALSE, at which
4823 * point the timeout is automatically destroyed and the function will
4824 * not be called again.
4826 * Unlike g_timeout_add(), this function operates at whole second granularity.
4827 * The initial starting point of the timer is determined by the implementation
4828 * and the implementation is expected to group multiple timers together so that
4829 * they fire all at the same time.
4830 * To allow this grouping, the @interval to the first timer is rounded
4831 * and can deviate up to one second from the specified interval.
4832 * Subsequent timer iterations will generally run at the specified interval.
4834 * Note that timeout functions may be delayed, due to the processing of other
4835 * event sources. Thus they should not be relied on for precise timing.
4836 * After each call to the timeout function, the time of the next
4837 * timeout is recalculated based on the current time and the given @interval
4839 * See [memory management of sources][mainloop-memory-management] for details
4840 * on how to handle the return value and memory management of @data.
4842 * If you want timing more precise than whole seconds, use g_timeout_add()
4843 * instead.
4845 * The grouping of timers to fire at the same time results in a more power
4846 * and CPU efficient behavior so if your timer is in multiples of seconds
4847 * and you don't require the first timer exactly one second from now, the
4848 * use of g_timeout_add_seconds() is preferred over g_timeout_add().
4850 * This internally creates a main loop source using
4851 * g_timeout_source_new_seconds() and attaches it to the main loop context
4852 * using g_source_attach(). You can do these steps manually if you need
4853 * greater control.
4855 * The interval given is in terms of monotonic time, not wall clock
4856 * time. See g_get_monotonic_time().
4858 * Returns: the ID (greater than 0) of the event source.
4860 * Since: 2.14
4862 guint
4863 g_timeout_add_seconds_full (gint priority,
4864 guint32 interval,
4865 GSourceFunc function,
4866 gpointer data,
4867 GDestroyNotify notify)
4869 GSource *source;
4870 guint id;
4872 g_return_val_if_fail (function != NULL, 0);
4874 source = g_timeout_source_new_seconds (interval);
4876 if (priority != G_PRIORITY_DEFAULT)
4877 g_source_set_priority (source, priority);
4879 g_source_set_callback (source, function, data, notify);
4880 id = g_source_attach (source, NULL);
4881 g_source_unref (source);
4883 return id;
4887 * g_timeout_add_seconds:
4888 * @interval: the time between calls to the function, in seconds
4889 * @function: function to call
4890 * @data: data to pass to @function
4892 * Sets a function to be called at regular intervals with the default
4893 * priority, #G_PRIORITY_DEFAULT. The function is called repeatedly until
4894 * it returns %FALSE, at which point the timeout is automatically destroyed
4895 * and the function will not be called again.
4897 * This internally creates a main loop source using
4898 * g_timeout_source_new_seconds() and attaches it to the main loop context
4899 * using g_source_attach(). You can do these steps manually if you need
4900 * greater control. Also see g_timeout_add_seconds_full().
4902 * Note that the first call of the timer may not be precise for timeouts
4903 * of one second. If you need finer precision and have such a timeout,
4904 * you may want to use g_timeout_add() instead.
4906 * See [memory management of sources][mainloop-memory-management] for details
4907 * on how to handle the return value and memory management of @data.
4909 * The interval given is in terms of monotonic time, not wall clock
4910 * time. See g_get_monotonic_time().
4912 * Returns: the ID (greater than 0) of the event source.
4914 * Since: 2.14
4916 guint
4917 g_timeout_add_seconds (guint interval,
4918 GSourceFunc function,
4919 gpointer data)
4921 g_return_val_if_fail (function != NULL, 0);
4923 return g_timeout_add_seconds_full (G_PRIORITY_DEFAULT, interval, function, data, NULL);
4926 /* Child watch functions */
4928 #ifdef G_OS_WIN32
4930 static gboolean
4931 g_child_watch_prepare (GSource *source,
4932 gint *timeout)
4934 *timeout = -1;
4935 return FALSE;
4938 static gboolean
4939 g_child_watch_check (GSource *source)
4941 GChildWatchSource *child_watch_source;
4942 gboolean child_exited;
4944 child_watch_source = (GChildWatchSource *) source;
4946 child_exited = child_watch_source->poll.revents & G_IO_IN;
4948 if (child_exited)
4950 DWORD child_status;
4953 * Note: We do _not_ check for the special value of STILL_ACTIVE
4954 * since we know that the process has exited and doing so runs into
4955 * problems if the child process "happens to return STILL_ACTIVE(259)"
4956 * as Microsoft's Platform SDK puts it.
4958 if (!GetExitCodeProcess (child_watch_source->pid, &child_status))
4960 gchar *emsg = g_win32_error_message (GetLastError ());
4961 g_warning (G_STRLOC ": GetExitCodeProcess() failed: %s", emsg);
4962 g_free (emsg);
4964 child_watch_source->child_status = -1;
4966 else
4967 child_watch_source->child_status = child_status;
4970 return child_exited;
4973 static void
4974 g_child_watch_finalize (GSource *source)
4978 #else /* G_OS_WIN32 */
4980 static void
4981 wake_source (GSource *source)
4983 GMainContext *context;
4985 /* This should be thread-safe:
4987 * - if the source is currently being added to a context, that
4988 * context will be woken up anyway
4990 * - if the source is currently being destroyed, we simply need not
4991 * to crash:
4993 * - the memory for the source will remain valid until after the
4994 * source finalize function was called (which would remove the
4995 * source from the global list which we are currently holding the
4996 * lock for)
4998 * - the GMainContext will either be NULL or point to a live
4999 * GMainContext
5001 * - the GMainContext will remain valid since we hold the
5002 * main_context_list lock
5004 * Since we are holding a lot of locks here, don't try to enter any
5005 * more GMainContext functions for fear of dealock -- just hit the
5006 * GWakeup and run. Even if that's safe now, it could easily become
5007 * unsafe with some very minor changes in the future, and signal
5008 * handling is not the most well-tested codepath.
5010 G_LOCK(main_context_list);
5011 context = source->context;
5012 if (context)
5013 g_wakeup_signal (context->wakeup);
5014 G_UNLOCK(main_context_list);
5017 static void
5018 dispatch_unix_signals_unlocked (void)
5020 gboolean pending[NSIG];
5021 GSList *node;
5022 gint i;
5024 /* clear this first incase another one arrives while we're processing */
5025 any_unix_signal_pending = FALSE;
5027 /* We atomically test/clear the bit from the global array in case
5028 * other signals arrive while we are dispatching.
5030 * We then can safely use our own array below without worrying about
5031 * races.
5033 for (i = 0; i < NSIG; i++)
5035 /* Be very careful with (the volatile) unix_signal_pending.
5037 * We must ensure that it's not possible that we clear it without
5038 * handling the signal. We therefore must ensure that our pending
5039 * array has a field set (ie: we will do something about the
5040 * signal) before we clear the item in unix_signal_pending.
5042 * Note specifically: we must check _our_ array.
5044 pending[i] = unix_signal_pending[i];
5045 if (pending[i])
5046 unix_signal_pending[i] = FALSE;
5049 /* handle GChildWatchSource instances */
5050 if (pending[SIGCHLD])
5052 /* The only way we can do this is to scan all of the children.
5054 * The docs promise that we will not reap children that we are not
5055 * explicitly watching, so that ties our hands from calling
5056 * waitpid(-1). We also can't use siginfo's si_pid field since if
5057 * multiple SIGCHLD arrive at the same time, one of them can be
5058 * dropped (since a given UNIX signal can only be pending once).
5060 for (node = unix_child_watches; node; node = node->next)
5062 GChildWatchSource *source = node->data;
5064 if (!source->child_exited)
5066 pid_t pid;
5069 g_assert (source->pid > 0);
5071 pid = waitpid (source->pid, &source->child_status, WNOHANG);
5072 if (pid > 0)
5074 source->child_exited = TRUE;
5075 wake_source ((GSource *) source);
5077 else if (pid == -1 && errno == ECHILD)
5079 g_warning ("GChildWatchSource: Exit status of a child process was requested but ECHILD was received by waitpid(). Most likely the process is ignoring SIGCHLD, or some other thread is invoking waitpid() with a nonpositive first argument; either behavior can break applications that use g_child_watch_add()/g_spawn_sync() either directly or indirectly.");
5080 source->child_exited = TRUE;
5081 source->child_status = 0;
5082 wake_source ((GSource *) source);
5085 while (pid == -1 && errno == EINTR);
5090 /* handle GUnixSignalWatchSource instances */
5091 for (node = unix_signal_watches; node; node = node->next)
5093 GUnixSignalWatchSource *source = node->data;
5095 if (!source->pending)
5097 if (pending[source->signum])
5099 source->pending = TRUE;
5101 wake_source ((GSource *) source);
5108 static void
5109 dispatch_unix_signals (void)
5111 G_LOCK(unix_signal_lock);
5112 dispatch_unix_signals_unlocked ();
5113 G_UNLOCK(unix_signal_lock);
5116 static gboolean
5117 g_child_watch_prepare (GSource *source,
5118 gint *timeout)
5120 GChildWatchSource *child_watch_source;
5122 child_watch_source = (GChildWatchSource *) source;
5124 return child_watch_source->child_exited;
5127 static gboolean
5128 g_child_watch_check (GSource *source)
5130 GChildWatchSource *child_watch_source;
5132 child_watch_source = (GChildWatchSource *) source;
5134 return child_watch_source->child_exited;
5137 static gboolean
5138 g_unix_signal_watch_prepare (GSource *source,
5139 gint *timeout)
5141 GUnixSignalWatchSource *unix_signal_source;
5143 unix_signal_source = (GUnixSignalWatchSource *) source;
5145 return unix_signal_source->pending;
5148 static gboolean
5149 g_unix_signal_watch_check (GSource *source)
5151 GUnixSignalWatchSource *unix_signal_source;
5153 unix_signal_source = (GUnixSignalWatchSource *) source;
5155 return unix_signal_source->pending;
5158 static gboolean
5159 g_unix_signal_watch_dispatch (GSource *source,
5160 GSourceFunc callback,
5161 gpointer user_data)
5163 GUnixSignalWatchSource *unix_signal_source;
5164 gboolean again;
5166 unix_signal_source = (GUnixSignalWatchSource *) source;
5168 if (!callback)
5170 g_warning ("Unix signal source dispatched without callback\n"
5171 "You must call g_source_set_callback().");
5172 return FALSE;
5175 again = (callback) (user_data);
5177 unix_signal_source->pending = FALSE;
5179 return again;
5182 static void
5183 ref_unix_signal_handler_unlocked (int signum)
5185 /* Ensure we have the worker context */
5186 g_get_worker_context ();
5187 unix_signal_refcount[signum]++;
5188 if (unix_signal_refcount[signum] == 1)
5190 struct sigaction action;
5191 action.sa_handler = g_unix_signal_handler;
5192 sigemptyset (&action.sa_mask);
5193 #ifdef SA_RESTART
5194 action.sa_flags = SA_RESTART | SA_NOCLDSTOP;
5195 #else
5196 action.sa_flags = SA_NOCLDSTOP;
5197 #endif
5198 sigaction (signum, &action, NULL);
5202 static void
5203 unref_unix_signal_handler_unlocked (int signum)
5205 unix_signal_refcount[signum]--;
5206 if (unix_signal_refcount[signum] == 0)
5208 struct sigaction action;
5209 memset (&action, 0, sizeof (action));
5210 action.sa_handler = SIG_DFL;
5211 sigemptyset (&action.sa_mask);
5212 sigaction (signum, &action, NULL);
5216 GSource *
5217 _g_main_create_unix_signal_watch (int signum)
5219 GSource *source;
5220 GUnixSignalWatchSource *unix_signal_source;
5222 source = g_source_new (&g_unix_signal_funcs, sizeof (GUnixSignalWatchSource));
5223 unix_signal_source = (GUnixSignalWatchSource *) source;
5225 unix_signal_source->signum = signum;
5226 unix_signal_source->pending = FALSE;
5228 G_LOCK (unix_signal_lock);
5229 ref_unix_signal_handler_unlocked (signum);
5230 unix_signal_watches = g_slist_prepend (unix_signal_watches, unix_signal_source);
5231 dispatch_unix_signals_unlocked ();
5232 G_UNLOCK (unix_signal_lock);
5234 return source;
5237 static void
5238 g_unix_signal_watch_finalize (GSource *source)
5240 GUnixSignalWatchSource *unix_signal_source;
5242 unix_signal_source = (GUnixSignalWatchSource *) source;
5244 G_LOCK (unix_signal_lock);
5245 unref_unix_signal_handler_unlocked (unix_signal_source->signum);
5246 unix_signal_watches = g_slist_remove (unix_signal_watches, source);
5247 G_UNLOCK (unix_signal_lock);
5250 static void
5251 g_child_watch_finalize (GSource *source)
5253 G_LOCK (unix_signal_lock);
5254 unix_child_watches = g_slist_remove (unix_child_watches, source);
5255 unref_unix_signal_handler_unlocked (SIGCHLD);
5256 G_UNLOCK (unix_signal_lock);
5259 #endif /* G_OS_WIN32 */
5261 static gboolean
5262 g_child_watch_dispatch (GSource *source,
5263 GSourceFunc callback,
5264 gpointer user_data)
5266 GChildWatchSource *child_watch_source;
5267 GChildWatchFunc child_watch_callback = (GChildWatchFunc) callback;
5269 child_watch_source = (GChildWatchSource *) source;
5271 if (!callback)
5273 g_warning ("Child watch source dispatched without callback\n"
5274 "You must call g_source_set_callback().");
5275 return FALSE;
5278 (child_watch_callback) (child_watch_source->pid, child_watch_source->child_status, user_data);
5280 /* We never keep a child watch source around as the child is gone */
5281 return FALSE;
5284 #ifndef G_OS_WIN32
5286 static void
5287 g_unix_signal_handler (int signum)
5289 gint saved_errno = errno;
5291 unix_signal_pending[signum] = TRUE;
5292 any_unix_signal_pending = TRUE;
5294 g_wakeup_signal (glib_worker_context->wakeup);
5296 errno = saved_errno;
5299 #endif /* !G_OS_WIN32 */
5302 * g_child_watch_source_new:
5303 * @pid: process to watch. On POSIX the positive pid of a child process. On
5304 * Windows a handle for a process (which doesn't have to be a child).
5306 * Creates a new child_watch source.
5308 * The source will not initially be associated with any #GMainContext
5309 * and must be added to one with g_source_attach() before it will be
5310 * executed.
5312 * Note that child watch sources can only be used in conjunction with
5313 * `g_spawn...` when the %G_SPAWN_DO_NOT_REAP_CHILD flag is used.
5315 * Note that on platforms where #GPid must be explicitly closed
5316 * (see g_spawn_close_pid()) @pid must not be closed while the
5317 * source is still active. Typically, you will want to call
5318 * g_spawn_close_pid() in the callback function for the source.
5320 * Note further that using g_child_watch_source_new() is not
5321 * compatible with calling `waitpid` with a nonpositive first
5322 * argument in the application. Calling waitpid() for individual
5323 * pids will still work fine.
5325 * Similarly, on POSIX platforms, the @pid passed to this function must
5326 * be greater than 0 (i.e. this function must wait for a specific child,
5327 * and cannot wait for one of many children by using a nonpositive argument).
5329 * Returns: the newly-created child watch source
5331 * Since: 2.4
5333 GSource *
5334 g_child_watch_source_new (GPid pid)
5336 GSource *source;
5337 GChildWatchSource *child_watch_source;
5339 #ifndef G_OS_WIN32
5340 g_return_val_if_fail (pid > 0, NULL);
5341 #endif
5343 source = g_source_new (&g_child_watch_funcs, sizeof (GChildWatchSource));
5344 child_watch_source = (GChildWatchSource *)source;
5346 child_watch_source->pid = pid;
5348 #ifdef G_OS_WIN32
5349 child_watch_source->poll.fd = (gintptr) pid;
5350 child_watch_source->poll.events = G_IO_IN;
5352 g_source_add_poll (source, &child_watch_source->poll);
5353 #else /* G_OS_WIN32 */
5354 G_LOCK (unix_signal_lock);
5355 ref_unix_signal_handler_unlocked (SIGCHLD);
5356 unix_child_watches = g_slist_prepend (unix_child_watches, child_watch_source);
5357 if (waitpid (pid, &child_watch_source->child_status, WNOHANG) > 0)
5358 child_watch_source->child_exited = TRUE;
5359 G_UNLOCK (unix_signal_lock);
5360 #endif /* G_OS_WIN32 */
5362 return source;
5366 * g_child_watch_add_full: (rename-to g_child_watch_add)
5367 * @priority: the priority of the idle source. Typically this will be in the
5368 * range between #G_PRIORITY_DEFAULT_IDLE and #G_PRIORITY_HIGH_IDLE.
5369 * @pid: process to watch. On POSIX the positive pid of a child process. On
5370 * Windows a handle for a process (which doesn't have to be a child).
5371 * @function: function to call
5372 * @data: data to pass to @function
5373 * @notify: (nullable): function to call when the idle is removed, or %NULL
5375 * Sets a function to be called when the child indicated by @pid
5376 * exits, at the priority @priority.
5378 * If you obtain @pid from g_spawn_async() or g_spawn_async_with_pipes()
5379 * you will need to pass #G_SPAWN_DO_NOT_REAP_CHILD as flag to
5380 * the spawn function for the child watching to work.
5382 * In many programs, you will want to call g_spawn_check_exit_status()
5383 * in the callback to determine whether or not the child exited
5384 * successfully.
5386 * Also, note that on platforms where #GPid must be explicitly closed
5387 * (see g_spawn_close_pid()) @pid must not be closed while the source
5388 * is still active. Typically, you should invoke g_spawn_close_pid()
5389 * in the callback function for the source.
5391 * GLib supports only a single callback per process id.
5393 * This internally creates a main loop source using
5394 * g_child_watch_source_new() and attaches it to the main loop context
5395 * using g_source_attach(). You can do these steps manually if you
5396 * need greater control.
5398 * Returns: the ID (greater than 0) of the event source.
5400 * Since: 2.4
5402 guint
5403 g_child_watch_add_full (gint priority,
5404 GPid pid,
5405 GChildWatchFunc function,
5406 gpointer data,
5407 GDestroyNotify notify)
5409 GSource *source;
5410 guint id;
5412 g_return_val_if_fail (function != NULL, 0);
5413 #ifndef G_OS_WIN32
5414 g_return_val_if_fail (pid > 0, 0);
5415 #endif
5417 source = g_child_watch_source_new (pid);
5419 if (priority != G_PRIORITY_DEFAULT)
5420 g_source_set_priority (source, priority);
5422 g_source_set_callback (source, (GSourceFunc) function, data, notify);
5423 id = g_source_attach (source, NULL);
5424 g_source_unref (source);
5426 return id;
5430 * g_child_watch_add:
5431 * @pid: process id to watch. On POSIX the positive pid of a child
5432 * process. On Windows a handle for a process (which doesn't have to be
5433 * a child).
5434 * @function: function to call
5435 * @data: data to pass to @function
5437 * Sets a function to be called when the child indicated by @pid
5438 * exits, at a default priority, #G_PRIORITY_DEFAULT.
5440 * If you obtain @pid from g_spawn_async() or g_spawn_async_with_pipes()
5441 * you will need to pass #G_SPAWN_DO_NOT_REAP_CHILD as flag to
5442 * the spawn function for the child watching to work.
5444 * Note that on platforms where #GPid must be explicitly closed
5445 * (see g_spawn_close_pid()) @pid must not be closed while the
5446 * source is still active. Typically, you will want to call
5447 * g_spawn_close_pid() in the callback function for the source.
5449 * GLib supports only a single callback per process id.
5451 * This internally creates a main loop source using
5452 * g_child_watch_source_new() and attaches it to the main loop context
5453 * using g_source_attach(). You can do these steps manually if you
5454 * need greater control.
5456 * Returns: the ID (greater than 0) of the event source.
5458 * Since: 2.4
5460 guint
5461 g_child_watch_add (GPid pid,
5462 GChildWatchFunc function,
5463 gpointer data)
5465 return g_child_watch_add_full (G_PRIORITY_DEFAULT, pid, function, data, NULL);
5469 /* Idle functions */
5471 static gboolean
5472 g_idle_prepare (GSource *source,
5473 gint *timeout)
5475 *timeout = 0;
5477 return TRUE;
5480 static gboolean
5481 g_idle_check (GSource *source)
5483 return TRUE;
5486 static gboolean
5487 g_idle_dispatch (GSource *source,
5488 GSourceFunc callback,
5489 gpointer user_data)
5491 gboolean again;
5493 if (!callback)
5495 g_warning ("Idle source dispatched without callback\n"
5496 "You must call g_source_set_callback().");
5497 return FALSE;
5500 again = callback (user_data);
5502 TRACE (GLIB_IDLE_DISPATCH (source, source->context, callback, user_data, again));
5504 return again;
5508 * g_idle_source_new:
5510 * Creates a new idle source.
5512 * The source will not initially be associated with any #GMainContext
5513 * and must be added to one with g_source_attach() before it will be
5514 * executed. Note that the default priority for idle sources is
5515 * %G_PRIORITY_DEFAULT_IDLE, as compared to other sources which
5516 * have a default priority of %G_PRIORITY_DEFAULT.
5518 * Returns: the newly-created idle source
5520 GSource *
5521 g_idle_source_new (void)
5523 GSource *source;
5525 source = g_source_new (&g_idle_funcs, sizeof (GSource));
5526 g_source_set_priority (source, G_PRIORITY_DEFAULT_IDLE);
5528 return source;
5532 * g_idle_add_full: (rename-to g_idle_add)
5533 * @priority: the priority of the idle source. Typically this will be in the
5534 * range between #G_PRIORITY_DEFAULT_IDLE and #G_PRIORITY_HIGH_IDLE.
5535 * @function: function to call
5536 * @data: data to pass to @function
5537 * @notify: (nullable): function to call when the idle is removed, or %NULL
5539 * Adds a function to be called whenever there are no higher priority
5540 * events pending. If the function returns %FALSE it is automatically
5541 * removed from the list of event sources and will not be called again.
5543 * See [memory management of sources][mainloop-memory-management] for details
5544 * on how to handle the return value and memory management of @data.
5546 * This internally creates a main loop source using g_idle_source_new()
5547 * and attaches it to the global #GMainContext using g_source_attach(), so
5548 * the callback will be invoked in whichever thread is running that main
5549 * context. You can do these steps manually if you need greater control or to
5550 * use a custom main context.
5552 * Returns: the ID (greater than 0) of the event source.
5554 guint
5555 g_idle_add_full (gint priority,
5556 GSourceFunc function,
5557 gpointer data,
5558 GDestroyNotify notify)
5560 GSource *source;
5561 guint id;
5563 g_return_val_if_fail (function != NULL, 0);
5565 source = g_idle_source_new ();
5567 if (priority != G_PRIORITY_DEFAULT_IDLE)
5568 g_source_set_priority (source, priority);
5570 g_source_set_callback (source, function, data, notify);
5571 id = g_source_attach (source, NULL);
5573 TRACE (GLIB_IDLE_ADD (source, g_main_context_default (), id, priority, function, data));
5575 g_source_unref (source);
5577 return id;
5581 * g_idle_add:
5582 * @function: function to call
5583 * @data: data to pass to @function.
5585 * Adds a function to be called whenever there are no higher priority
5586 * events pending to the default main loop. The function is given the
5587 * default idle priority, #G_PRIORITY_DEFAULT_IDLE. If the function
5588 * returns %FALSE it is automatically removed from the list of event
5589 * sources and will not be called again.
5591 * See [memory management of sources][mainloop-memory-management] for details
5592 * on how to handle the return value and memory management of @data.
5594 * This internally creates a main loop source using g_idle_source_new()
5595 * and attaches it to the global #GMainContext using g_source_attach(), so
5596 * the callback will be invoked in whichever thread is running that main
5597 * context. You can do these steps manually if you need greater control or to
5598 * use a custom main context.
5600 * Returns: the ID (greater than 0) of the event source.
5602 guint
5603 g_idle_add (GSourceFunc function,
5604 gpointer data)
5606 return g_idle_add_full (G_PRIORITY_DEFAULT_IDLE, function, data, NULL);
5610 * g_idle_remove_by_data:
5611 * @data: the data for the idle source's callback.
5613 * Removes the idle function with the given data.
5615 * Returns: %TRUE if an idle source was found and removed.
5617 gboolean
5618 g_idle_remove_by_data (gpointer data)
5620 return g_source_remove_by_funcs_user_data (&g_idle_funcs, data);
5624 * g_main_context_invoke:
5625 * @context: (nullable): a #GMainContext, or %NULL
5626 * @function: function to call
5627 * @data: data to pass to @function
5629 * Invokes a function in such a way that @context is owned during the
5630 * invocation of @function.
5632 * If @context is %NULL then the global default main context — as
5633 * returned by g_main_context_default() — is used.
5635 * If @context is owned by the current thread, @function is called
5636 * directly. Otherwise, if @context is the thread-default main context
5637 * of the current thread and g_main_context_acquire() succeeds, then
5638 * @function is called and g_main_context_release() is called
5639 * afterwards.
5641 * In any other case, an idle source is created to call @function and
5642 * that source is attached to @context (presumably to be run in another
5643 * thread). The idle source is attached with #G_PRIORITY_DEFAULT
5644 * priority. If you want a different priority, use
5645 * g_main_context_invoke_full().
5647 * Note that, as with normal idle functions, @function should probably
5648 * return %FALSE. If it returns %TRUE, it will be continuously run in a
5649 * loop (and may prevent this call from returning).
5651 * Since: 2.28
5653 void
5654 g_main_context_invoke (GMainContext *context,
5655 GSourceFunc function,
5656 gpointer data)
5658 g_main_context_invoke_full (context,
5659 G_PRIORITY_DEFAULT,
5660 function, data, NULL);
5664 * g_main_context_invoke_full:
5665 * @context: (nullable): a #GMainContext, or %NULL
5666 * @priority: the priority at which to run @function
5667 * @function: function to call
5668 * @data: data to pass to @function
5669 * @notify: (nullable): a function to call when @data is no longer in use, or %NULL.
5671 * Invokes a function in such a way that @context is owned during the
5672 * invocation of @function.
5674 * This function is the same as g_main_context_invoke() except that it
5675 * lets you specify the priority incase @function ends up being
5676 * scheduled as an idle and also lets you give a #GDestroyNotify for @data.
5678 * @notify should not assume that it is called from any particular
5679 * thread or with any particular context acquired.
5681 * Since: 2.28
5683 void
5684 g_main_context_invoke_full (GMainContext *context,
5685 gint priority,
5686 GSourceFunc function,
5687 gpointer data,
5688 GDestroyNotify notify)
5690 g_return_if_fail (function != NULL);
5692 if (!context)
5693 context = g_main_context_default ();
5695 if (g_main_context_is_owner (context))
5697 while (function (data));
5698 if (notify != NULL)
5699 notify (data);
5702 else
5704 GMainContext *thread_default;
5706 thread_default = g_main_context_get_thread_default ();
5708 if (!thread_default)
5709 thread_default = g_main_context_default ();
5711 if (thread_default == context && g_main_context_acquire (context))
5713 while (function (data));
5715 g_main_context_release (context);
5717 if (notify != NULL)
5718 notify (data);
5720 else
5722 GSource *source;
5724 source = g_idle_source_new ();
5725 g_source_set_priority (source, priority);
5726 g_source_set_callback (source, function, data, notify);
5727 g_source_attach (source, context);
5728 g_source_unref (source);
5733 static gpointer
5734 glib_worker_main (gpointer data)
5736 while (TRUE)
5738 g_main_context_iteration (glib_worker_context, TRUE);
5740 #ifdef G_OS_UNIX
5741 if (any_unix_signal_pending)
5742 dispatch_unix_signals ();
5743 #endif
5746 return NULL; /* worst GCC warning message ever... */
5749 GMainContext *
5750 g_get_worker_context (void)
5752 static gsize initialised;
5754 if (g_once_init_enter (&initialised))
5756 /* mask all signals in the worker thread */
5757 #ifdef G_OS_UNIX
5758 sigset_t prev_mask;
5759 sigset_t all;
5761 sigfillset (&all);
5762 pthread_sigmask (SIG_SETMASK, &all, &prev_mask);
5763 #endif
5764 glib_worker_context = g_main_context_new ();
5765 g_thread_new ("gmain", glib_worker_main, NULL);
5766 #ifdef G_OS_UNIX
5767 pthread_sigmask (SIG_SETMASK, &prev_mask, NULL);
5768 #endif
5769 g_once_init_leave (&initialised, TRUE);
5772 return glib_worker_context;