docs: Small improvements to glib-mkenums man page
[glib.git] / glib / gmain.c
bloba30eaa71f596f2ea9b1e7c6c6c59e648dfec80aa
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 volatile 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 gint in_check_or_prepare;
282 GPollRec *poll_records;
283 guint n_poll_records;
284 GPollFD *cached_poll_array;
285 guint cached_poll_array_size;
287 GWakeup *wakeup;
289 GPollFD wake_up_rec;
291 /* Flag indicating whether the set of fd's changed during a poll */
292 gboolean poll_changed;
294 GPollFunc poll_func;
296 gint64 time;
297 gboolean time_is_fresh;
300 struct _GSourceCallback
302 volatile gint ref_count;
303 GSourceFunc func;
304 gpointer data;
305 GDestroyNotify notify;
308 struct _GMainLoop
310 GMainContext *context;
311 gboolean is_running;
312 volatile gint ref_count;
315 struct _GTimeoutSource
317 GSource source;
318 guint interval;
319 gboolean seconds;
322 struct _GChildWatchSource
324 GSource source;
325 GPid pid;
326 gint child_status;
327 #ifdef G_OS_WIN32
328 GPollFD poll;
329 #else /* G_OS_WIN32 */
330 gboolean child_exited;
331 #endif /* G_OS_WIN32 */
334 struct _GUnixSignalWatchSource
336 GSource source;
337 int signum;
338 gboolean pending;
341 struct _GPollRec
343 GPollFD *fd;
344 GPollRec *prev;
345 GPollRec *next;
346 gint priority;
349 struct _GSourcePrivate
351 GSList *child_sources;
352 GSource *parent_source;
354 gint64 ready_time;
356 /* This is currently only used on UNIX, but we always declare it (and
357 * let it remain empty on Windows) to avoid #ifdef all over the place.
359 GSList *fds;
362 typedef struct _GSourceIter
364 GMainContext *context;
365 gboolean may_modify;
366 GList *current_list;
367 GSource *source;
368 } GSourceIter;
370 #define LOCK_CONTEXT(context) g_mutex_lock (&context->mutex)
371 #define UNLOCK_CONTEXT(context) g_mutex_unlock (&context->mutex)
372 #define G_THREAD_SELF g_thread_self ()
374 #define SOURCE_DESTROYED(source) (((source)->flags & G_HOOK_FLAG_ACTIVE) == 0)
375 #define SOURCE_BLOCKED(source) (((source)->flags & G_SOURCE_BLOCKED) != 0)
377 #define SOURCE_UNREF(source, context) \
378 G_STMT_START { \
379 if ((source)->ref_count > 1) \
380 (source)->ref_count--; \
381 else \
382 g_source_unref_internal ((source), (context), TRUE); \
383 } G_STMT_END
386 /* Forward declarations */
388 static void g_source_unref_internal (GSource *source,
389 GMainContext *context,
390 gboolean have_lock);
391 static void g_source_destroy_internal (GSource *source,
392 GMainContext *context,
393 gboolean have_lock);
394 static void g_source_set_priority_unlocked (GSource *source,
395 GMainContext *context,
396 gint priority);
397 static void g_child_source_remove_internal (GSource *child_source,
398 GMainContext *context);
400 static void g_main_context_poll (GMainContext *context,
401 gint timeout,
402 gint priority,
403 GPollFD *fds,
404 gint n_fds);
405 static void g_main_context_add_poll_unlocked (GMainContext *context,
406 gint priority,
407 GPollFD *fd);
408 static void g_main_context_remove_poll_unlocked (GMainContext *context,
409 GPollFD *fd);
411 static void g_source_iter_init (GSourceIter *iter,
412 GMainContext *context,
413 gboolean may_modify);
414 static gboolean g_source_iter_next (GSourceIter *iter,
415 GSource **source);
416 static void g_source_iter_clear (GSourceIter *iter);
418 static gboolean g_timeout_dispatch (GSource *source,
419 GSourceFunc callback,
420 gpointer user_data);
421 static gboolean g_child_watch_prepare (GSource *source,
422 gint *timeout);
423 static gboolean g_child_watch_check (GSource *source);
424 static gboolean g_child_watch_dispatch (GSource *source,
425 GSourceFunc callback,
426 gpointer user_data);
427 static void g_child_watch_finalize (GSource *source);
428 #ifdef G_OS_UNIX
429 static void g_unix_signal_handler (int signum);
430 static gboolean g_unix_signal_watch_prepare (GSource *source,
431 gint *timeout);
432 static gboolean g_unix_signal_watch_check (GSource *source);
433 static gboolean g_unix_signal_watch_dispatch (GSource *source,
434 GSourceFunc callback,
435 gpointer user_data);
436 static void g_unix_signal_watch_finalize (GSource *source);
437 #endif
438 static gboolean g_idle_prepare (GSource *source,
439 gint *timeout);
440 static gboolean g_idle_check (GSource *source);
441 static gboolean g_idle_dispatch (GSource *source,
442 GSourceFunc callback,
443 gpointer user_data);
445 static void block_source (GSource *source);
447 static GMainContext *glib_worker_context;
449 G_LOCK_DEFINE_STATIC (main_loop);
450 static GMainContext *default_main_context;
452 #ifndef G_OS_WIN32
455 /* UNIX signals work by marking one of these variables then waking the
456 * worker context to check on them and dispatch accordingly.
458 #ifdef HAVE_SIG_ATOMIC_T
459 static volatile sig_atomic_t unix_signal_pending[NSIG];
460 static volatile sig_atomic_t any_unix_signal_pending;
461 #else
462 static volatile int unix_signal_pending[NSIG];
463 static volatile int any_unix_signal_pending;
464 #endif
465 static volatile guint unix_signal_refcount[NSIG];
467 /* Guards all the data below */
468 G_LOCK_DEFINE_STATIC (unix_signal_lock);
469 static GSList *unix_signal_watches;
470 static GSList *unix_child_watches;
472 GSourceFuncs g_unix_signal_funcs =
474 g_unix_signal_watch_prepare,
475 g_unix_signal_watch_check,
476 g_unix_signal_watch_dispatch,
477 g_unix_signal_watch_finalize
479 #endif /* !G_OS_WIN32 */
480 G_LOCK_DEFINE_STATIC (main_context_list);
481 static GSList *main_context_list = NULL;
483 GSourceFuncs g_timeout_funcs =
485 NULL, /* prepare */
486 NULL, /* check */
487 g_timeout_dispatch,
488 NULL
491 GSourceFuncs g_child_watch_funcs =
493 g_child_watch_prepare,
494 g_child_watch_check,
495 g_child_watch_dispatch,
496 g_child_watch_finalize
499 GSourceFuncs g_idle_funcs =
501 g_idle_prepare,
502 g_idle_check,
503 g_idle_dispatch,
504 NULL
508 * g_main_context_ref:
509 * @context: a #GMainContext
511 * Increases the reference count on a #GMainContext object by one.
513 * Returns: the @context that was passed in (since 2.6)
515 GMainContext *
516 g_main_context_ref (GMainContext *context)
518 g_return_val_if_fail (context != NULL, NULL);
519 g_return_val_if_fail (g_atomic_int_get (&context->ref_count) > 0, NULL);
521 g_atomic_int_inc (&context->ref_count);
523 return context;
526 static inline void
527 poll_rec_list_free (GMainContext *context,
528 GPollRec *list)
530 g_slice_free_chain (GPollRec, list, next);
534 * g_main_context_unref:
535 * @context: a #GMainContext
537 * Decreases the reference count on a #GMainContext object by one. If
538 * the result is zero, free the context and free all associated memory.
540 void
541 g_main_context_unref (GMainContext *context)
543 GSourceIter iter;
544 GSource *source;
545 GList *sl_iter;
546 GSourceList *list;
547 guint i;
549 g_return_if_fail (context != NULL);
550 g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
552 if (!g_atomic_int_dec_and_test (&context->ref_count))
553 return;
555 G_LOCK (main_context_list);
556 main_context_list = g_slist_remove (main_context_list, context);
557 G_UNLOCK (main_context_list);
559 /* Free pending dispatches */
560 for (i = 0; i < context->pending_dispatches->len; i++)
561 g_source_unref_internal (context->pending_dispatches->pdata[i], context, FALSE);
563 /* g_source_iter_next() assumes the context is locked. */
564 LOCK_CONTEXT (context);
565 g_source_iter_init (&iter, context, TRUE);
566 while (g_source_iter_next (&iter, &source))
568 source->context = NULL;
569 g_source_destroy_internal (source, context, TRUE);
571 UNLOCK_CONTEXT (context);
573 for (sl_iter = context->source_lists; sl_iter; sl_iter = sl_iter->next)
575 list = sl_iter->data;
576 g_slice_free (GSourceList, list);
578 g_list_free (context->source_lists);
580 g_hash_table_destroy (context->sources);
582 g_mutex_clear (&context->mutex);
584 g_ptr_array_free (context->pending_dispatches, TRUE);
585 g_free (context->cached_poll_array);
587 poll_rec_list_free (context, context->poll_records);
589 g_wakeup_free (context->wakeup);
590 g_cond_clear (&context->cond);
592 g_free (context);
595 /* Helper function used by mainloop/overflow test.
597 GMainContext *
598 g_main_context_new_with_next_id (guint next_id)
600 GMainContext *ret = g_main_context_new ();
602 ret->next_id = next_id;
604 return ret;
608 * g_main_context_new:
610 * Creates a new #GMainContext structure.
612 * Returns: the new #GMainContext
614 GMainContext *
615 g_main_context_new (void)
617 static gsize initialised;
618 GMainContext *context;
620 if (g_once_init_enter (&initialised))
622 #ifdef G_MAIN_POLL_DEBUG
623 if (getenv ("G_MAIN_POLL_DEBUG") != NULL)
624 _g_main_poll_debug = TRUE;
625 #endif
627 g_once_init_leave (&initialised, TRUE);
630 context = g_new0 (GMainContext, 1);
632 TRACE (GLIB_MAIN_CONTEXT_NEW (context));
634 g_mutex_init (&context->mutex);
635 g_cond_init (&context->cond);
637 context->sources = g_hash_table_new (NULL, NULL);
638 context->owner = NULL;
639 context->waiters = NULL;
641 context->ref_count = 1;
643 context->next_id = 1;
645 context->source_lists = NULL;
647 context->poll_func = g_poll;
649 context->cached_poll_array = NULL;
650 context->cached_poll_array_size = 0;
652 context->pending_dispatches = g_ptr_array_new ();
654 context->time_is_fresh = FALSE;
656 context->wakeup = g_wakeup_new ();
657 g_wakeup_get_pollfd (context->wakeup, &context->wake_up_rec);
658 g_main_context_add_poll_unlocked (context, 0, &context->wake_up_rec);
660 G_LOCK (main_context_list);
661 main_context_list = g_slist_append (main_context_list, context);
663 #ifdef G_MAIN_POLL_DEBUG
664 if (_g_main_poll_debug)
665 g_print ("created context=%p\n", context);
666 #endif
668 G_UNLOCK (main_context_list);
670 return context;
674 * g_main_context_default:
676 * Returns the global default main context. This is the main context
677 * used for main loop functions when a main loop is not explicitly
678 * specified, and corresponds to the "main" main loop. See also
679 * g_main_context_get_thread_default().
681 * Returns: (transfer none): the global default main context.
683 GMainContext *
684 g_main_context_default (void)
686 /* Slow, but safe */
688 G_LOCK (main_loop);
690 if (!default_main_context)
692 default_main_context = g_main_context_new ();
694 TRACE (GLIB_MAIN_CONTEXT_DEFAULT (default_main_context));
696 #ifdef G_MAIN_POLL_DEBUG
697 if (_g_main_poll_debug)
698 g_print ("default context=%p\n", default_main_context);
699 #endif
702 G_UNLOCK (main_loop);
704 return default_main_context;
707 static void
708 free_context (gpointer data)
710 GMainContext *context = data;
712 TRACE (GLIB_MAIN_CONTEXT_FREE (context));
714 g_main_context_release (context);
715 if (context)
716 g_main_context_unref (context);
719 static void
720 free_context_stack (gpointer data)
722 g_queue_free_full((GQueue *) data, (GDestroyNotify) free_context);
725 static GPrivate thread_context_stack = G_PRIVATE_INIT (free_context_stack);
728 * g_main_context_push_thread_default:
729 * @context: (nullable): a #GMainContext, or %NULL for the global default context
731 * Acquires @context and sets it as the thread-default context for the
732 * current thread. This will cause certain asynchronous operations
733 * (such as most [gio][gio]-based I/O) which are
734 * started in this thread to run under @context and deliver their
735 * results to its main loop, rather than running under the global
736 * default context in the main thread. Note that calling this function
737 * changes the context returned by g_main_context_get_thread_default(),
738 * not the one returned by g_main_context_default(), so it does not affect
739 * the context used by functions like g_idle_add().
741 * Normally you would call this function shortly after creating a new
742 * thread, passing it a #GMainContext which will be run by a
743 * #GMainLoop in that thread, to set a new default context for all
744 * async operations in that thread. In this case you may not need to
745 * ever call g_main_context_pop_thread_default(), assuming you want the
746 * new #GMainContext to be the default for the whole lifecycle of the
747 * thread.
749 * If you don't have control over how the new thread was created (e.g.
750 * in the new thread isn't newly created, or if the thread life
751 * cycle is managed by a #GThreadPool), it is always suggested to wrap
752 * the logic that needs to use the new #GMainContext inside a
753 * g_main_context_push_thread_default() / g_main_context_pop_thread_default()
754 * pair, otherwise threads that are re-used will end up never explicitly
755 * releasing the #GMainContext reference they hold.
757 * In some cases you may want to schedule a single operation in a
758 * non-default context, or temporarily use a non-default context in
759 * the main thread. In that case, you can wrap the call to the
760 * asynchronous operation inside a
761 * g_main_context_push_thread_default() /
762 * g_main_context_pop_thread_default() pair, but it is up to you to
763 * ensure that no other asynchronous operations accidentally get
764 * started while the non-default context is active.
766 * Beware that libraries that predate this function may not correctly
767 * handle being used from a thread with a thread-default context. Eg,
768 * see g_file_supports_thread_contexts().
770 * Since: 2.22
772 void
773 g_main_context_push_thread_default (GMainContext *context)
775 GQueue *stack;
776 gboolean acquired_context;
778 acquired_context = g_main_context_acquire (context);
779 g_return_if_fail (acquired_context);
781 if (context == g_main_context_default ())
782 context = NULL;
783 else if (context)
784 g_main_context_ref (context);
786 stack = g_private_get (&thread_context_stack);
787 if (!stack)
789 stack = g_queue_new ();
790 g_private_set (&thread_context_stack, stack);
793 g_queue_push_head (stack, context);
795 TRACE (GLIB_MAIN_CONTEXT_PUSH_THREAD_DEFAULT (context));
799 * g_main_context_pop_thread_default:
800 * @context: (nullable): a #GMainContext object, or %NULL
802 * Pops @context off the thread-default context stack (verifying that
803 * it was on the top of the stack).
805 * Since: 2.22
807 void
808 g_main_context_pop_thread_default (GMainContext *context)
810 GQueue *stack;
812 if (context == g_main_context_default ())
813 context = NULL;
815 stack = g_private_get (&thread_context_stack);
817 g_return_if_fail (stack != NULL);
818 g_return_if_fail (g_queue_peek_head (stack) == context);
820 TRACE (GLIB_MAIN_CONTEXT_POP_THREAD_DEFAULT (context));
822 g_queue_pop_head (stack);
824 g_main_context_release (context);
825 if (context)
826 g_main_context_unref (context);
830 * g_main_context_get_thread_default:
832 * Gets the thread-default #GMainContext for this thread. Asynchronous
833 * operations that want to be able to be run in contexts other than
834 * the default one should call this method or
835 * g_main_context_ref_thread_default() to get a #GMainContext to add
836 * their #GSources to. (Note that even in single-threaded
837 * programs applications may sometimes want to temporarily push a
838 * non-default context, so it is not safe to assume that this will
839 * always return %NULL if you are running in the default thread.)
841 * If you need to hold a reference on the context, use
842 * g_main_context_ref_thread_default() instead.
844 * Returns: (transfer none): the thread-default #GMainContext, or
845 * %NULL if the thread-default context is the global default context.
847 * Since: 2.22
849 GMainContext *
850 g_main_context_get_thread_default (void)
852 GQueue *stack;
854 stack = g_private_get (&thread_context_stack);
855 if (stack)
856 return g_queue_peek_head (stack);
857 else
858 return NULL;
862 * g_main_context_ref_thread_default:
864 * Gets the thread-default #GMainContext for this thread, as with
865 * g_main_context_get_thread_default(), but also adds a reference to
866 * it with g_main_context_ref(). In addition, unlike
867 * g_main_context_get_thread_default(), if the thread-default context
868 * is the global default context, this will return that #GMainContext
869 * (with a ref added to it) rather than returning %NULL.
871 * Returns: (transfer full): the thread-default #GMainContext. Unref
872 * with g_main_context_unref() when you are done with it.
874 * Since: 2.32
876 GMainContext *
877 g_main_context_ref_thread_default (void)
879 GMainContext *context;
881 context = g_main_context_get_thread_default ();
882 if (!context)
883 context = g_main_context_default ();
884 return g_main_context_ref (context);
887 /* Hooks for adding to the main loop */
890 * g_source_new:
891 * @source_funcs: structure containing functions that implement
892 * the sources behavior.
893 * @struct_size: size of the #GSource structure to create.
895 * Creates a new #GSource structure. The size is specified to
896 * allow creating structures derived from #GSource that contain
897 * additional data. The size passed in must be at least
898 * `sizeof (GSource)`.
900 * The source will not initially be associated with any #GMainContext
901 * and must be added to one with g_source_attach() before it will be
902 * executed.
904 * Returns: the newly-created #GSource.
906 GSource *
907 g_source_new (GSourceFuncs *source_funcs,
908 guint struct_size)
910 GSource *source;
912 g_return_val_if_fail (source_funcs != NULL, NULL);
913 g_return_val_if_fail (struct_size >= sizeof (GSource), NULL);
915 source = (GSource*) g_malloc0 (struct_size);
916 source->priv = g_slice_new0 (GSourcePrivate);
917 source->source_funcs = source_funcs;
918 source->ref_count = 1;
920 source->priority = G_PRIORITY_DEFAULT;
922 source->flags = G_HOOK_FLAG_ACTIVE;
924 source->priv->ready_time = -1;
926 /* NULL/0 initialization for all other fields */
928 TRACE (GLIB_SOURCE_NEW (source, source_funcs->prepare, source_funcs->check,
929 source_funcs->dispatch, source_funcs->finalize,
930 struct_size));
932 return source;
935 /* Holds context's lock */
936 static void
937 g_source_iter_init (GSourceIter *iter,
938 GMainContext *context,
939 gboolean may_modify)
941 iter->context = context;
942 iter->current_list = NULL;
943 iter->source = NULL;
944 iter->may_modify = may_modify;
947 /* Holds context's lock */
948 static gboolean
949 g_source_iter_next (GSourceIter *iter, GSource **source)
951 GSource *next_source;
953 if (iter->source)
954 next_source = iter->source->next;
955 else
956 next_source = NULL;
958 if (!next_source)
960 if (iter->current_list)
961 iter->current_list = iter->current_list->next;
962 else
963 iter->current_list = iter->context->source_lists;
965 if (iter->current_list)
967 GSourceList *source_list = iter->current_list->data;
969 next_source = source_list->head;
973 /* Note: unreffing iter->source could potentially cause its
974 * GSourceList to be removed from source_lists (if iter->source is
975 * the only source in its list, and it is destroyed), so we have to
976 * keep it reffed until after we advance iter->current_list, above.
979 if (iter->source && iter->may_modify)
980 SOURCE_UNREF (iter->source, iter->context);
981 iter->source = next_source;
982 if (iter->source && iter->may_modify)
983 iter->source->ref_count++;
985 *source = iter->source;
986 return *source != NULL;
989 /* Holds context's lock. Only necessary to call if you broke out of
990 * the g_source_iter_next() loop early.
992 static void
993 g_source_iter_clear (GSourceIter *iter)
995 if (iter->source && iter->may_modify)
997 SOURCE_UNREF (iter->source, iter->context);
998 iter->source = NULL;
1002 /* Holds context's lock
1004 static GSourceList *
1005 find_source_list_for_priority (GMainContext *context,
1006 gint priority,
1007 gboolean create)
1009 GList *iter, *last;
1010 GSourceList *source_list;
1012 last = NULL;
1013 for (iter = context->source_lists; iter != NULL; last = iter, iter = iter->next)
1015 source_list = iter->data;
1017 if (source_list->priority == priority)
1018 return source_list;
1020 if (source_list->priority > priority)
1022 if (!create)
1023 return NULL;
1025 source_list = g_slice_new0 (GSourceList);
1026 source_list->priority = priority;
1027 context->source_lists = g_list_insert_before (context->source_lists,
1028 iter,
1029 source_list);
1030 return source_list;
1034 if (!create)
1035 return NULL;
1037 source_list = g_slice_new0 (GSourceList);
1038 source_list->priority = priority;
1040 if (!last)
1041 context->source_lists = g_list_append (NULL, source_list);
1042 else
1044 /* This just appends source_list to the end of
1045 * context->source_lists without having to walk the list again.
1047 last = g_list_append (last, source_list);
1049 return source_list;
1052 /* Holds context's lock
1054 static void
1055 source_add_to_context (GSource *source,
1056 GMainContext *context)
1058 GSourceList *source_list;
1059 GSource *prev, *next;
1061 source_list = find_source_list_for_priority (context, source->priority, TRUE);
1063 if (source->priv->parent_source)
1065 g_assert (source_list->head != NULL);
1067 /* Put the source immediately before its parent */
1068 prev = source->priv->parent_source->prev;
1069 next = source->priv->parent_source;
1071 else
1073 prev = source_list->tail;
1074 next = NULL;
1077 source->next = next;
1078 if (next)
1079 next->prev = source;
1080 else
1081 source_list->tail = source;
1083 source->prev = prev;
1084 if (prev)
1085 prev->next = source;
1086 else
1087 source_list->head = source;
1090 /* Holds context's lock
1092 static void
1093 source_remove_from_context (GSource *source,
1094 GMainContext *context)
1096 GSourceList *source_list;
1098 source_list = find_source_list_for_priority (context, source->priority, FALSE);
1099 g_return_if_fail (source_list != NULL);
1101 if (source->prev)
1102 source->prev->next = source->next;
1103 else
1104 source_list->head = source->next;
1106 if (source->next)
1107 source->next->prev = source->prev;
1108 else
1109 source_list->tail = source->prev;
1111 source->prev = NULL;
1112 source->next = NULL;
1114 if (source_list->head == NULL)
1116 context->source_lists = g_list_remove (context->source_lists, source_list);
1117 g_slice_free (GSourceList, source_list);
1121 /* See https://bugzilla.gnome.org/show_bug.cgi?id=761102 for
1122 * the introduction of this.
1124 * The main optimization is to avoid waking up the main
1125 * context if a change is made by the current owner.
1127 static void
1128 conditional_wakeup (GMainContext *context)
1130 /* We want to signal wakeups in two cases:
1131 * 1 When the context is owned by another thread
1132 * 2 When the context owner is NULL (two subcases)
1133 * 2a Possible if the context has never been acquired
1134 * 2b Or if the context has no current owner
1136 * At least case 2a) is necessary to ensure backwards compatibility with
1137 * qemu's use of GMainContext.
1138 * https://bugzilla.gnome.org/show_bug.cgi?id=761102#c14
1140 if (context->owner != G_THREAD_SELF)
1141 g_wakeup_signal (context->wakeup);
1144 static guint
1145 g_source_attach_unlocked (GSource *source,
1146 GMainContext *context,
1147 gboolean do_wakeup)
1149 GSList *tmp_list;
1150 guint id;
1152 /* The counter may have wrapped, so we must ensure that we do not
1153 * reuse the source id of an existing source.
1156 id = context->next_id++;
1157 while (id == 0 || g_hash_table_contains (context->sources, GUINT_TO_POINTER (id)));
1159 source->context = context;
1160 source->source_id = id;
1161 source->ref_count++;
1163 g_hash_table_insert (context->sources, GUINT_TO_POINTER (id), source);
1165 source_add_to_context (source, context);
1167 if (!SOURCE_BLOCKED (source))
1169 tmp_list = source->poll_fds;
1170 while (tmp_list)
1172 g_main_context_add_poll_unlocked (context, source->priority, tmp_list->data);
1173 tmp_list = tmp_list->next;
1176 for (tmp_list = source->priv->fds; tmp_list; tmp_list = tmp_list->next)
1177 g_main_context_add_poll_unlocked (context, source->priority, tmp_list->data);
1180 tmp_list = source->priv->child_sources;
1181 while (tmp_list)
1183 g_source_attach_unlocked (tmp_list->data, context, FALSE);
1184 tmp_list = tmp_list->next;
1187 /* If another thread has acquired the context, wake it up since it
1188 * might be in poll() right now.
1190 if (do_wakeup)
1191 conditional_wakeup (context);
1193 return source->source_id;
1197 * g_source_attach:
1198 * @source: a #GSource
1199 * @context: (nullable): a #GMainContext (if %NULL, the default context will be used)
1201 * Adds a #GSource to a @context so that it will be executed within
1202 * that context. Remove it by calling g_source_destroy().
1204 * Returns: the ID (greater than 0) for the source within the
1205 * #GMainContext.
1207 guint
1208 g_source_attach (GSource *source,
1209 GMainContext *context)
1211 guint result = 0;
1213 g_return_val_if_fail (source->context == NULL, 0);
1214 g_return_val_if_fail (!SOURCE_DESTROYED (source), 0);
1216 if (!context)
1217 context = g_main_context_default ();
1219 LOCK_CONTEXT (context);
1221 result = g_source_attach_unlocked (source, context, TRUE);
1223 TRACE (GLIB_MAIN_SOURCE_ATTACH (g_source_get_name (source), source, context,
1224 result));
1226 UNLOCK_CONTEXT (context);
1228 return result;
1231 static void
1232 g_source_destroy_internal (GSource *source,
1233 GMainContext *context,
1234 gboolean have_lock)
1236 TRACE (GLIB_MAIN_SOURCE_DESTROY (g_source_get_name (source), source,
1237 context));
1239 if (!have_lock)
1240 LOCK_CONTEXT (context);
1242 if (!SOURCE_DESTROYED (source))
1244 GSList *tmp_list;
1245 gpointer old_cb_data;
1246 GSourceCallbackFuncs *old_cb_funcs;
1248 source->flags &= ~G_HOOK_FLAG_ACTIVE;
1250 old_cb_data = source->callback_data;
1251 old_cb_funcs = source->callback_funcs;
1253 source->callback_data = NULL;
1254 source->callback_funcs = NULL;
1256 if (old_cb_funcs)
1258 UNLOCK_CONTEXT (context);
1259 old_cb_funcs->unref (old_cb_data);
1260 LOCK_CONTEXT (context);
1263 if (!SOURCE_BLOCKED (source))
1265 tmp_list = source->poll_fds;
1266 while (tmp_list)
1268 g_main_context_remove_poll_unlocked (context, tmp_list->data);
1269 tmp_list = tmp_list->next;
1272 for (tmp_list = source->priv->fds; tmp_list; tmp_list = tmp_list->next)
1273 g_main_context_remove_poll_unlocked (context, tmp_list->data);
1276 while (source->priv->child_sources)
1277 g_child_source_remove_internal (source->priv->child_sources->data, context);
1279 if (source->priv->parent_source)
1280 g_child_source_remove_internal (source, context);
1282 g_source_unref_internal (source, context, TRUE);
1285 if (!have_lock)
1286 UNLOCK_CONTEXT (context);
1290 * g_source_destroy:
1291 * @source: a #GSource
1293 * Removes a source from its #GMainContext, if any, and mark it as
1294 * destroyed. The source cannot be subsequently added to another
1295 * context. It is safe to call this on sources which have already been
1296 * removed from their context.
1298 void
1299 g_source_destroy (GSource *source)
1301 GMainContext *context;
1303 g_return_if_fail (source != NULL);
1305 context = source->context;
1307 if (context)
1308 g_source_destroy_internal (source, context, FALSE);
1309 else
1310 source->flags &= ~G_HOOK_FLAG_ACTIVE;
1314 * g_source_get_id:
1315 * @source: a #GSource
1317 * Returns the numeric ID for a particular source. The ID of a source
1318 * is a positive integer which is unique within a particular main loop
1319 * context. The reverse
1320 * mapping from ID to source is done by g_main_context_find_source_by_id().
1322 * Returns: the ID (greater than 0) for the source
1324 guint
1325 g_source_get_id (GSource *source)
1327 guint result;
1329 g_return_val_if_fail (source != NULL, 0);
1330 g_return_val_if_fail (source->context != NULL, 0);
1332 LOCK_CONTEXT (source->context);
1333 result = source->source_id;
1334 UNLOCK_CONTEXT (source->context);
1336 return result;
1340 * g_source_get_context:
1341 * @source: a #GSource
1343 * Gets the #GMainContext with which the source is associated.
1345 * You can call this on a source that has been destroyed, provided
1346 * that the #GMainContext it was attached to still exists (in which
1347 * case it will return that #GMainContext). In particular, you can
1348 * always call this function on the source returned from
1349 * g_main_current_source(). But calling this function on a source
1350 * whose #GMainContext has been destroyed is an error.
1352 * Returns: (transfer none) (nullable): the #GMainContext with which the
1353 * source is associated, or %NULL if the context has not
1354 * yet been added to a source.
1356 GMainContext *
1357 g_source_get_context (GSource *source)
1359 g_return_val_if_fail (source->context != NULL || !SOURCE_DESTROYED (source), NULL);
1361 return source->context;
1365 * g_source_add_poll:
1366 * @source:a #GSource
1367 * @fd: a #GPollFD structure holding information about a file
1368 * descriptor to watch.
1370 * Adds a file descriptor to the set of file descriptors polled for
1371 * this source. This is usually combined with g_source_new() to add an
1372 * event source. The event source's check function will typically test
1373 * the @revents field in the #GPollFD struct and return %TRUE if events need
1374 * to be processed.
1376 * This API is only intended to be used by implementations of #GSource.
1377 * Do not call this API on a #GSource that you did not create.
1379 * Using this API forces the linear scanning of event sources on each
1380 * main loop iteration. Newly-written event sources should try to use
1381 * g_source_add_unix_fd() instead of this API.
1383 void
1384 g_source_add_poll (GSource *source,
1385 GPollFD *fd)
1387 GMainContext *context;
1389 g_return_if_fail (source != NULL);
1390 g_return_if_fail (fd != NULL);
1391 g_return_if_fail (!SOURCE_DESTROYED (source));
1393 context = source->context;
1395 if (context)
1396 LOCK_CONTEXT (context);
1398 source->poll_fds = g_slist_prepend (source->poll_fds, fd);
1400 if (context)
1402 if (!SOURCE_BLOCKED (source))
1403 g_main_context_add_poll_unlocked (context, source->priority, fd);
1404 UNLOCK_CONTEXT (context);
1409 * g_source_remove_poll:
1410 * @source:a #GSource
1411 * @fd: a #GPollFD structure previously passed to g_source_add_poll().
1413 * Removes a file descriptor from the set of file descriptors polled for
1414 * this source.
1416 * This API is only intended to be used by implementations of #GSource.
1417 * Do not call this API on a #GSource that you did not create.
1419 void
1420 g_source_remove_poll (GSource *source,
1421 GPollFD *fd)
1423 GMainContext *context;
1425 g_return_if_fail (source != NULL);
1426 g_return_if_fail (fd != NULL);
1427 g_return_if_fail (!SOURCE_DESTROYED (source));
1429 context = source->context;
1431 if (context)
1432 LOCK_CONTEXT (context);
1434 source->poll_fds = g_slist_remove (source->poll_fds, fd);
1436 if (context)
1438 if (!SOURCE_BLOCKED (source))
1439 g_main_context_remove_poll_unlocked (context, fd);
1440 UNLOCK_CONTEXT (context);
1445 * g_source_add_child_source:
1446 * @source:a #GSource
1447 * @child_source: a second #GSource that @source should "poll"
1449 * Adds @child_source to @source as a "polled" source; when @source is
1450 * added to a #GMainContext, @child_source will be automatically added
1451 * with the same priority, when @child_source is triggered, it will
1452 * cause @source to dispatch (in addition to calling its own
1453 * callback), and when @source is destroyed, it will destroy
1454 * @child_source as well. (@source will also still be dispatched if
1455 * its own prepare/check functions indicate that it is ready.)
1457 * If you don't need @child_source to do anything on its own when it
1458 * triggers, you can call g_source_set_dummy_callback() on it to set a
1459 * callback that does nothing (except return %TRUE if appropriate).
1461 * @source will hold a reference on @child_source while @child_source
1462 * is attached to it.
1464 * This API is only intended to be used by implementations of #GSource.
1465 * Do not call this API on a #GSource that you did not create.
1467 * Since: 2.28
1469 void
1470 g_source_add_child_source (GSource *source,
1471 GSource *child_source)
1473 GMainContext *context;
1475 g_return_if_fail (source != NULL);
1476 g_return_if_fail (child_source != NULL);
1477 g_return_if_fail (!SOURCE_DESTROYED (source));
1478 g_return_if_fail (!SOURCE_DESTROYED (child_source));
1479 g_return_if_fail (child_source->context == NULL);
1480 g_return_if_fail (child_source->priv->parent_source == NULL);
1482 context = source->context;
1484 if (context)
1485 LOCK_CONTEXT (context);
1487 TRACE (GLIB_SOURCE_ADD_CHILD_SOURCE (source, child_source));
1489 source->priv->child_sources = g_slist_prepend (source->priv->child_sources,
1490 g_source_ref (child_source));
1491 child_source->priv->parent_source = source;
1492 g_source_set_priority_unlocked (child_source, NULL, source->priority);
1493 if (SOURCE_BLOCKED (source))
1494 block_source (child_source);
1496 if (context)
1498 g_source_attach_unlocked (child_source, context, TRUE);
1499 UNLOCK_CONTEXT (context);
1503 static void
1504 g_child_source_remove_internal (GSource *child_source,
1505 GMainContext *context)
1507 GSource *parent_source = child_source->priv->parent_source;
1509 parent_source->priv->child_sources =
1510 g_slist_remove (parent_source->priv->child_sources, child_source);
1511 child_source->priv->parent_source = NULL;
1513 g_source_destroy_internal (child_source, context, TRUE);
1514 g_source_unref_internal (child_source, context, TRUE);
1518 * g_source_remove_child_source:
1519 * @source:a #GSource
1520 * @child_source: a #GSource previously passed to
1521 * g_source_add_child_source().
1523 * Detaches @child_source from @source and destroys it.
1525 * This API is only intended to be used by implementations of #GSource.
1526 * Do not call this API on a #GSource that you did not create.
1528 * Since: 2.28
1530 void
1531 g_source_remove_child_source (GSource *source,
1532 GSource *child_source)
1534 GMainContext *context;
1536 g_return_if_fail (source != NULL);
1537 g_return_if_fail (child_source != NULL);
1538 g_return_if_fail (child_source->priv->parent_source == source);
1539 g_return_if_fail (!SOURCE_DESTROYED (source));
1540 g_return_if_fail (!SOURCE_DESTROYED (child_source));
1542 context = source->context;
1544 if (context)
1545 LOCK_CONTEXT (context);
1547 g_child_source_remove_internal (child_source, context);
1549 if (context)
1550 UNLOCK_CONTEXT (context);
1553 static void
1554 g_source_callback_ref (gpointer cb_data)
1556 GSourceCallback *callback = cb_data;
1558 g_atomic_int_inc (&callback->ref_count);
1561 static void
1562 g_source_callback_unref (gpointer cb_data)
1564 GSourceCallback *callback = cb_data;
1566 if (g_atomic_int_dec_and_test (&callback->ref_count))
1568 if (callback->notify)
1569 callback->notify (callback->data);
1570 g_free (callback);
1574 static void
1575 g_source_callback_get (gpointer cb_data,
1576 GSource *source,
1577 GSourceFunc *func,
1578 gpointer *data)
1580 GSourceCallback *callback = cb_data;
1582 *func = callback->func;
1583 *data = callback->data;
1586 static GSourceCallbackFuncs g_source_callback_funcs = {
1587 g_source_callback_ref,
1588 g_source_callback_unref,
1589 g_source_callback_get,
1593 * g_source_set_callback_indirect:
1594 * @source: the source
1595 * @callback_data: pointer to callback data "object"
1596 * @callback_funcs: functions for reference counting @callback_data
1597 * and getting the callback and data
1599 * Sets the callback function storing the data as a refcounted callback
1600 * "object". This is used internally. Note that calling
1601 * g_source_set_callback_indirect() assumes
1602 * an initial reference count on @callback_data, and thus
1603 * @callback_funcs->unref will eventually be called once more
1604 * than @callback_funcs->ref.
1606 void
1607 g_source_set_callback_indirect (GSource *source,
1608 gpointer callback_data,
1609 GSourceCallbackFuncs *callback_funcs)
1611 GMainContext *context;
1612 gpointer old_cb_data;
1613 GSourceCallbackFuncs *old_cb_funcs;
1615 g_return_if_fail (source != NULL);
1616 g_return_if_fail (callback_funcs != NULL || callback_data == NULL);
1618 context = source->context;
1620 if (context)
1621 LOCK_CONTEXT (context);
1623 if (callback_funcs != &g_source_callback_funcs)
1624 TRACE (GLIB_SOURCE_SET_CALLBACK_INDIRECT (source, callback_data,
1625 callback_funcs->ref,
1626 callback_funcs->unref,
1627 callback_funcs->get));
1629 old_cb_data = source->callback_data;
1630 old_cb_funcs = source->callback_funcs;
1632 source->callback_data = callback_data;
1633 source->callback_funcs = callback_funcs;
1635 if (context)
1636 UNLOCK_CONTEXT (context);
1638 if (old_cb_funcs)
1639 old_cb_funcs->unref (old_cb_data);
1643 * g_source_set_callback:
1644 * @source: the source
1645 * @func: a callback function
1646 * @data: the data to pass to callback function
1647 * @notify: (nullable): a function to call when @data is no longer in use, or %NULL.
1649 * Sets the callback function for a source. The callback for a source is
1650 * called from the source's dispatch function.
1652 * The exact type of @func depends on the type of source; ie. you
1653 * should not count on @func being called with @data as its first
1654 * parameter.
1656 * See [memory management of sources][mainloop-memory-management] for details
1657 * on how to handle memory management of @data.
1659 * Typically, you won't use this function. Instead use functions specific
1660 * to the type of source you are using.
1662 void
1663 g_source_set_callback (GSource *source,
1664 GSourceFunc func,
1665 gpointer data,
1666 GDestroyNotify notify)
1668 GSourceCallback *new_callback;
1670 g_return_if_fail (source != NULL);
1672 TRACE (GLIB_SOURCE_SET_CALLBACK (source, func, data, notify));
1674 new_callback = g_new (GSourceCallback, 1);
1676 new_callback->ref_count = 1;
1677 new_callback->func = func;
1678 new_callback->data = data;
1679 new_callback->notify = notify;
1681 g_source_set_callback_indirect (source, new_callback, &g_source_callback_funcs);
1686 * g_source_set_funcs:
1687 * @source: a #GSource
1688 * @funcs: the new #GSourceFuncs
1690 * Sets the source functions (can be used to override
1691 * default implementations) of an unattached source.
1693 * Since: 2.12
1695 void
1696 g_source_set_funcs (GSource *source,
1697 GSourceFuncs *funcs)
1699 g_return_if_fail (source != NULL);
1700 g_return_if_fail (source->context == NULL);
1701 g_return_if_fail (source->ref_count > 0);
1702 g_return_if_fail (funcs != NULL);
1704 source->source_funcs = funcs;
1707 static void
1708 g_source_set_priority_unlocked (GSource *source,
1709 GMainContext *context,
1710 gint priority)
1712 GSList *tmp_list;
1714 g_return_if_fail (source->priv->parent_source == NULL ||
1715 source->priv->parent_source->priority == priority);
1717 TRACE (GLIB_SOURCE_SET_PRIORITY (source, context, priority));
1719 if (context)
1721 /* Remove the source from the context's source and then
1722 * add it back after so it is sorted in the correct place
1724 source_remove_from_context (source, source->context);
1727 source->priority = priority;
1729 if (context)
1731 source_add_to_context (source, source->context);
1733 if (!SOURCE_BLOCKED (source))
1735 tmp_list = source->poll_fds;
1736 while (tmp_list)
1738 g_main_context_remove_poll_unlocked (context, tmp_list->data);
1739 g_main_context_add_poll_unlocked (context, priority, tmp_list->data);
1741 tmp_list = tmp_list->next;
1744 for (tmp_list = source->priv->fds; tmp_list; tmp_list = tmp_list->next)
1746 g_main_context_remove_poll_unlocked (context, tmp_list->data);
1747 g_main_context_add_poll_unlocked (context, priority, tmp_list->data);
1752 if (source->priv->child_sources)
1754 tmp_list = source->priv->child_sources;
1755 while (tmp_list)
1757 g_source_set_priority_unlocked (tmp_list->data, context, priority);
1758 tmp_list = tmp_list->next;
1764 * g_source_set_priority:
1765 * @source: a #GSource
1766 * @priority: the new priority.
1768 * Sets the priority of a source. While the main loop is being run, a
1769 * source will be dispatched if it is ready to be dispatched and no
1770 * sources at a higher (numerically smaller) priority are ready to be
1771 * dispatched.
1773 * A child source always has the same priority as its parent. It is not
1774 * permitted to change the priority of a source once it has been added
1775 * as a child of another source.
1777 void
1778 g_source_set_priority (GSource *source,
1779 gint priority)
1781 GMainContext *context;
1783 g_return_if_fail (source != NULL);
1784 g_return_if_fail (source->priv->parent_source == NULL);
1786 context = source->context;
1788 if (context)
1789 LOCK_CONTEXT (context);
1790 g_source_set_priority_unlocked (source, context, priority);
1791 if (context)
1792 UNLOCK_CONTEXT (context);
1796 * g_source_get_priority:
1797 * @source: a #GSource
1799 * Gets the priority of a source.
1801 * Returns: the priority of the source
1803 gint
1804 g_source_get_priority (GSource *source)
1806 g_return_val_if_fail (source != NULL, 0);
1808 return source->priority;
1812 * g_source_set_ready_time:
1813 * @source: a #GSource
1814 * @ready_time: the monotonic time at which the source will be ready,
1815 * 0 for "immediately", -1 for "never"
1817 * Sets a #GSource to be dispatched when the given monotonic time is
1818 * reached (or passed). If the monotonic time is in the past (as it
1819 * always will be if @ready_time is 0) then the source will be
1820 * dispatched immediately.
1822 * If @ready_time is -1 then the source is never woken up on the basis
1823 * of the passage of time.
1825 * Dispatching the source does not reset the ready time. You should do
1826 * so yourself, from the source dispatch function.
1828 * Note that if you have a pair of sources where the ready time of one
1829 * suggests that it will be delivered first but the priority for the
1830 * other suggests that it would be delivered first, and the ready time
1831 * for both sources is reached during the same main context iteration,
1832 * then the order of dispatch is undefined.
1834 * It is a no-op to call this function on a #GSource which has already been
1835 * destroyed with g_source_destroy().
1837 * This API is only intended to be used by implementations of #GSource.
1838 * Do not call this API on a #GSource that you did not create.
1840 * Since: 2.36
1842 void
1843 g_source_set_ready_time (GSource *source,
1844 gint64 ready_time)
1846 GMainContext *context;
1848 g_return_if_fail (source != NULL);
1849 /* We deliberately don't check for ref_count > 0 here, because that
1850 * breaks cancellable_source_cancelled() in GCancellable: it has no
1851 * way to find out that the last-unref has happened until the
1852 * finalize() function is called, but that's too late, because the
1853 * ref_count already has already reached 0 before that time.
1854 * However, priv is only poisoned (set to NULL) after finalize(),
1855 * so we can use this as a simple guard against use-after-free.
1856 * See https://bugzilla.gnome.org/show_bug.cgi?id=791754 */
1857 g_return_if_fail (source->priv != NULL);
1859 context = source->context;
1861 if (context)
1862 LOCK_CONTEXT (context);
1864 if (source->priv->ready_time == ready_time)
1866 if (context)
1867 UNLOCK_CONTEXT (context);
1869 return;
1872 source->priv->ready_time = ready_time;
1874 TRACE (GLIB_SOURCE_SET_READY_TIME (source, ready_time));
1876 if (context)
1878 /* Quite likely that we need to change the timeout on the poll */
1879 if (!SOURCE_BLOCKED (source))
1880 conditional_wakeup (context);
1881 UNLOCK_CONTEXT (context);
1886 * g_source_get_ready_time:
1887 * @source: a #GSource
1889 * Gets the "ready time" of @source, as set by
1890 * g_source_set_ready_time().
1892 * Any time before the current monotonic time (including 0) is an
1893 * indication that the source will fire immediately.
1895 * Returns: the monotonic ready time, -1 for "never"
1897 gint64
1898 g_source_get_ready_time (GSource *source)
1900 g_return_val_if_fail (source != NULL, -1);
1902 return source->priv->ready_time;
1906 * g_source_set_can_recurse:
1907 * @source: a #GSource
1908 * @can_recurse: whether recursion is allowed for this source
1910 * Sets whether a source can be called recursively. If @can_recurse is
1911 * %TRUE, then while the source is being dispatched then this source
1912 * will be processed normally. Otherwise, all processing of this
1913 * source is blocked until the dispatch function returns.
1915 void
1916 g_source_set_can_recurse (GSource *source,
1917 gboolean can_recurse)
1919 GMainContext *context;
1921 g_return_if_fail (source != NULL);
1923 context = source->context;
1925 if (context)
1926 LOCK_CONTEXT (context);
1928 if (can_recurse)
1929 source->flags |= G_SOURCE_CAN_RECURSE;
1930 else
1931 source->flags &= ~G_SOURCE_CAN_RECURSE;
1933 if (context)
1934 UNLOCK_CONTEXT (context);
1938 * g_source_get_can_recurse:
1939 * @source: a #GSource
1941 * Checks whether a source is allowed to be called recursively.
1942 * see g_source_set_can_recurse().
1944 * Returns: whether recursion is allowed.
1946 gboolean
1947 g_source_get_can_recurse (GSource *source)
1949 g_return_val_if_fail (source != NULL, FALSE);
1951 return (source->flags & G_SOURCE_CAN_RECURSE) != 0;
1956 * g_source_set_name:
1957 * @source: a #GSource
1958 * @name: debug name for the source
1960 * Sets a name for the source, used in debugging and profiling.
1961 * The name defaults to #NULL.
1963 * The source name should describe in a human-readable way
1964 * what the source does. For example, "X11 event queue"
1965 * or "GTK+ repaint idle handler" or whatever it is.
1967 * It is permitted to call this function multiple times, but is not
1968 * recommended due to the potential performance impact. For example,
1969 * one could change the name in the "check" function of a #GSourceFuncs
1970 * to include details like the event type in the source name.
1972 * Use caution if changing the name while another thread may be
1973 * accessing it with g_source_get_name(); that function does not copy
1974 * the value, and changing the value will free it while the other thread
1975 * may be attempting to use it.
1977 * Since: 2.26
1979 void
1980 g_source_set_name (GSource *source,
1981 const char *name)
1983 GMainContext *context;
1985 g_return_if_fail (source != NULL);
1987 context = source->context;
1989 if (context)
1990 LOCK_CONTEXT (context);
1992 TRACE (GLIB_SOURCE_SET_NAME (source, name));
1994 /* setting back to NULL is allowed, just because it's
1995 * weird if get_name can return NULL but you can't
1996 * set that.
1999 g_free (source->name);
2000 source->name = g_strdup (name);
2002 if (context)
2003 UNLOCK_CONTEXT (context);
2007 * g_source_get_name:
2008 * @source: a #GSource
2010 * Gets a name for the source, used in debugging and profiling. The
2011 * name may be #NULL if it has never been set with g_source_set_name().
2013 * Returns: the name of the source
2015 * Since: 2.26
2017 const char *
2018 g_source_get_name (GSource *source)
2020 g_return_val_if_fail (source != NULL, NULL);
2022 return source->name;
2026 * g_source_set_name_by_id:
2027 * @tag: a #GSource ID
2028 * @name: debug name for the source
2030 * Sets the name of a source using its ID.
2032 * This is a convenience utility to set source names from the return
2033 * value of g_idle_add(), g_timeout_add(), etc.
2035 * It is a programmer error to attempt to set the name of a non-existent
2036 * source.
2038 * More specifically: source IDs can be reissued after a source has been
2039 * destroyed and therefore it is never valid to use this function with a
2040 * source ID which may have already been removed. An example is when
2041 * scheduling an idle to run in another thread with g_idle_add(): the
2042 * idle may already have run and been removed by the time this function
2043 * is called on its (now invalid) source ID. This source ID may have
2044 * been reissued, leading to the operation being performed against the
2045 * wrong source.
2047 * Since: 2.26
2049 void
2050 g_source_set_name_by_id (guint tag,
2051 const char *name)
2053 GSource *source;
2055 g_return_if_fail (tag > 0);
2057 source = g_main_context_find_source_by_id (NULL, tag);
2058 if (source == NULL)
2059 return;
2061 g_source_set_name (source, name);
2066 * g_source_ref:
2067 * @source: a #GSource
2069 * Increases the reference count on a source by one.
2071 * Returns: @source
2073 GSource *
2074 g_source_ref (GSource *source)
2076 GMainContext *context;
2078 g_return_val_if_fail (source != NULL, NULL);
2080 context = source->context;
2082 if (context)
2083 LOCK_CONTEXT (context);
2085 source->ref_count++;
2087 if (context)
2088 UNLOCK_CONTEXT (context);
2090 return source;
2093 /* g_source_unref() but possible to call within context lock
2095 static void
2096 g_source_unref_internal (GSource *source,
2097 GMainContext *context,
2098 gboolean have_lock)
2100 gpointer old_cb_data = NULL;
2101 GSourceCallbackFuncs *old_cb_funcs = NULL;
2103 g_return_if_fail (source != NULL);
2105 if (!have_lock && context)
2106 LOCK_CONTEXT (context);
2108 source->ref_count--;
2109 if (source->ref_count == 0)
2111 TRACE (GLIB_SOURCE_BEFORE_FREE (source, context,
2112 source->source_funcs->finalize));
2114 old_cb_data = source->callback_data;
2115 old_cb_funcs = source->callback_funcs;
2117 source->callback_data = NULL;
2118 source->callback_funcs = NULL;
2120 if (context)
2122 if (!SOURCE_DESTROYED (source))
2123 g_warning (G_STRLOC ": ref_count == 0, but source was still attached to a context!");
2124 source_remove_from_context (source, context);
2126 g_hash_table_remove (context->sources, GUINT_TO_POINTER (source->source_id));
2129 if (source->source_funcs->finalize)
2131 /* Temporarily increase the ref count again so that GSource methods
2132 * can be called from finalize(). */
2133 source->ref_count++;
2134 if (context)
2135 UNLOCK_CONTEXT (context);
2136 source->source_funcs->finalize (source);
2137 if (context)
2138 LOCK_CONTEXT (context);
2139 source->ref_count--;
2142 if (old_cb_funcs)
2144 /* Temporarily increase the ref count again so that GSource methods
2145 * can be called from callback_funcs.unref(). */
2146 source->ref_count++;
2147 if (context)
2148 UNLOCK_CONTEXT (context);
2150 old_cb_funcs->unref (old_cb_data);
2152 if (context)
2153 LOCK_CONTEXT (context);
2154 source->ref_count--;
2157 g_free (source->name);
2158 source->name = NULL;
2160 g_slist_free (source->poll_fds);
2161 source->poll_fds = NULL;
2163 g_slist_free_full (source->priv->fds, g_free);
2165 while (source->priv->child_sources)
2167 GSource *child_source = source->priv->child_sources->data;
2169 source->priv->child_sources =
2170 g_slist_remove (source->priv->child_sources, child_source);
2171 child_source->priv->parent_source = NULL;
2173 g_source_unref_internal (child_source, context, have_lock);
2176 g_slice_free (GSourcePrivate, source->priv);
2177 source->priv = NULL;
2179 g_free (source);
2182 if (!have_lock && context)
2183 UNLOCK_CONTEXT (context);
2187 * g_source_unref:
2188 * @source: a #GSource
2190 * Decreases the reference count of a source by one. If the
2191 * resulting reference count is zero the source and associated
2192 * memory will be destroyed.
2194 void
2195 g_source_unref (GSource *source)
2197 g_return_if_fail (source != NULL);
2199 g_source_unref_internal (source, source->context, FALSE);
2203 * g_main_context_find_source_by_id:
2204 * @context: (nullable): a #GMainContext (if %NULL, the default context will be used)
2205 * @source_id: the source ID, as returned by g_source_get_id().
2207 * Finds a #GSource given a pair of context and ID.
2209 * It is a programmer error to attempt to lookup a non-existent source.
2211 * More specifically: source IDs can be reissued after a source has been
2212 * destroyed and therefore it is never valid to use this function with a
2213 * source ID which may have already been removed. An example is when
2214 * scheduling an idle to run in another thread with g_idle_add(): the
2215 * idle may already have run and been removed by the time this function
2216 * is called on its (now invalid) source ID. This source ID may have
2217 * been reissued, leading to the operation being performed against the
2218 * wrong source.
2220 * Returns: (transfer none): the #GSource
2222 GSource *
2223 g_main_context_find_source_by_id (GMainContext *context,
2224 guint source_id)
2226 GSource *source;
2228 g_return_val_if_fail (source_id > 0, NULL);
2230 if (context == NULL)
2231 context = g_main_context_default ();
2233 LOCK_CONTEXT (context);
2234 source = g_hash_table_lookup (context->sources, GUINT_TO_POINTER (source_id));
2235 UNLOCK_CONTEXT (context);
2237 if (source && SOURCE_DESTROYED (source))
2238 source = NULL;
2240 return source;
2244 * g_main_context_find_source_by_funcs_user_data:
2245 * @context: (nullable): a #GMainContext (if %NULL, the default context will be used).
2246 * @funcs: the @source_funcs passed to g_source_new().
2247 * @user_data: the user data from the callback.
2249 * Finds a source with the given source functions and user data. If
2250 * multiple sources exist with the same source function and user data,
2251 * the first one found will be returned.
2253 * Returns: (transfer none): the source, if one was found, otherwise %NULL
2255 GSource *
2256 g_main_context_find_source_by_funcs_user_data (GMainContext *context,
2257 GSourceFuncs *funcs,
2258 gpointer user_data)
2260 GSourceIter iter;
2261 GSource *source;
2263 g_return_val_if_fail (funcs != NULL, NULL);
2265 if (context == NULL)
2266 context = g_main_context_default ();
2268 LOCK_CONTEXT (context);
2270 g_source_iter_init (&iter, context, FALSE);
2271 while (g_source_iter_next (&iter, &source))
2273 if (!SOURCE_DESTROYED (source) &&
2274 source->source_funcs == funcs &&
2275 source->callback_funcs)
2277 GSourceFunc callback;
2278 gpointer callback_data;
2280 source->callback_funcs->get (source->callback_data, source, &callback, &callback_data);
2282 if (callback_data == user_data)
2283 break;
2286 g_source_iter_clear (&iter);
2288 UNLOCK_CONTEXT (context);
2290 return source;
2294 * g_main_context_find_source_by_user_data:
2295 * @context: a #GMainContext
2296 * @user_data: the user_data for the callback.
2298 * Finds a source with the given user data for the callback. If
2299 * multiple sources exist with the same user data, the first
2300 * one found will be returned.
2302 * Returns: (transfer none): the source, if one was found, otherwise %NULL
2304 GSource *
2305 g_main_context_find_source_by_user_data (GMainContext *context,
2306 gpointer user_data)
2308 GSourceIter iter;
2309 GSource *source;
2311 if (context == NULL)
2312 context = g_main_context_default ();
2314 LOCK_CONTEXT (context);
2316 g_source_iter_init (&iter, context, FALSE);
2317 while (g_source_iter_next (&iter, &source))
2319 if (!SOURCE_DESTROYED (source) &&
2320 source->callback_funcs)
2322 GSourceFunc callback;
2323 gpointer callback_data = NULL;
2325 source->callback_funcs->get (source->callback_data, source, &callback, &callback_data);
2327 if (callback_data == user_data)
2328 break;
2331 g_source_iter_clear (&iter);
2333 UNLOCK_CONTEXT (context);
2335 return source;
2339 * g_source_remove:
2340 * @tag: the ID of the source to remove.
2342 * Removes the source with the given ID from the default main context. You must
2343 * use g_source_destroy() for sources added to a non-default main context.
2345 * The ID of a #GSource is given by g_source_get_id(), or will be
2346 * returned by the functions g_source_attach(), g_idle_add(),
2347 * g_idle_add_full(), g_timeout_add(), g_timeout_add_full(),
2348 * g_child_watch_add(), g_child_watch_add_full(), g_io_add_watch(), and
2349 * g_io_add_watch_full().
2351 * It is a programmer error to attempt to remove a non-existent source.
2353 * More specifically: source IDs can be reissued after a source has been
2354 * destroyed and therefore it is never valid to use this function with a
2355 * source ID which may have already been removed. An example is when
2356 * scheduling an idle to run in another thread with g_idle_add(): the
2357 * idle may already have run and been removed by the time this function
2358 * is called on its (now invalid) source ID. This source ID may have
2359 * been reissued, leading to the operation being performed against the
2360 * wrong source.
2362 * Returns: For historical reasons, this function always returns %TRUE
2364 gboolean
2365 g_source_remove (guint tag)
2367 GSource *source;
2369 g_return_val_if_fail (tag > 0, FALSE);
2371 source = g_main_context_find_source_by_id (NULL, tag);
2372 if (source)
2373 g_source_destroy (source);
2374 else
2375 g_critical ("Source ID %u was not found when attempting to remove it", tag);
2377 return source != NULL;
2381 * g_source_remove_by_user_data:
2382 * @user_data: the user_data for the callback.
2384 * Removes a source from the default main loop context given the user
2385 * data for the callback. If multiple sources exist with the same user
2386 * data, only one will be destroyed.
2388 * Returns: %TRUE if a source was found and removed.
2390 gboolean
2391 g_source_remove_by_user_data (gpointer user_data)
2393 GSource *source;
2395 source = g_main_context_find_source_by_user_data (NULL, user_data);
2396 if (source)
2398 g_source_destroy (source);
2399 return TRUE;
2401 else
2402 return FALSE;
2406 * g_source_remove_by_funcs_user_data:
2407 * @funcs: The @source_funcs passed to g_source_new()
2408 * @user_data: the user data for the callback
2410 * Removes a source from the default main loop context given the
2411 * source functions and user data. If multiple sources exist with the
2412 * same source functions and user data, only one will be destroyed.
2414 * Returns: %TRUE if a source was found and removed.
2416 gboolean
2417 g_source_remove_by_funcs_user_data (GSourceFuncs *funcs,
2418 gpointer user_data)
2420 GSource *source;
2422 g_return_val_if_fail (funcs != NULL, FALSE);
2424 source = g_main_context_find_source_by_funcs_user_data (NULL, funcs, user_data);
2425 if (source)
2427 g_source_destroy (source);
2428 return TRUE;
2430 else
2431 return FALSE;
2435 * g_clear_handle_id: (skip)
2436 * @tag_ptr: (not nullable): a pointer to the handler ID
2437 * @clear_func: (not nullable): the function to call to clear the handler
2439 * Clears a numeric handler, such as a #GSource ID.
2441 * @tag_ptr must be a valid pointer to the variable holding the handler.
2443 * If the ID is zero then this function does nothing.
2444 * Otherwise, clear_func() is called with the ID as a parameter, and the tag is
2445 * set to zero.
2447 * A macro is also included that allows this function to be used without
2448 * pointer casts.
2450 * Since: 2.56
2452 #undef g_clear_handle_id
2453 void
2454 g_clear_handle_id (guint *tag_ptr,
2455 GClearHandleFunc clear_func)
2457 guint _handle_id;
2459 _handle_id = *tag_ptr;
2460 if (_handle_id > 0)
2462 *tag_ptr = 0;
2463 if (clear_func != NULL)
2464 clear_func (_handle_id);
2468 #ifdef G_OS_UNIX
2470 * g_source_add_unix_fd:
2471 * @source: a #GSource
2472 * @fd: the fd to monitor
2473 * @events: an event mask
2475 * Monitors @fd for the IO events in @events.
2477 * The tag returned by this function can be used to remove or modify the
2478 * monitoring of the fd using g_source_remove_unix_fd() or
2479 * g_source_modify_unix_fd().
2481 * It is not necessary to remove the fd before destroying the source; it
2482 * will be cleaned up automatically.
2484 * This API is only intended to be used by implementations of #GSource.
2485 * Do not call this API on a #GSource that you did not create.
2487 * As the name suggests, this function is not available on Windows.
2489 * Returns: (not nullable): an opaque tag
2491 * Since: 2.36
2493 gpointer
2494 g_source_add_unix_fd (GSource *source,
2495 gint fd,
2496 GIOCondition events)
2498 GMainContext *context;
2499 GPollFD *poll_fd;
2501 g_return_val_if_fail (source != NULL, NULL);
2502 g_return_val_if_fail (!SOURCE_DESTROYED (source), NULL);
2504 poll_fd = g_new (GPollFD, 1);
2505 poll_fd->fd = fd;
2506 poll_fd->events = events;
2507 poll_fd->revents = 0;
2509 context = source->context;
2511 if (context)
2512 LOCK_CONTEXT (context);
2514 source->priv->fds = g_slist_prepend (source->priv->fds, poll_fd);
2516 if (context)
2518 if (!SOURCE_BLOCKED (source))
2519 g_main_context_add_poll_unlocked (context, source->priority, poll_fd);
2520 UNLOCK_CONTEXT (context);
2523 return poll_fd;
2527 * g_source_modify_unix_fd:
2528 * @source: a #GSource
2529 * @tag: (not nullable): the tag from g_source_add_unix_fd()
2530 * @new_events: the new event mask to watch
2532 * Updates the event mask to watch for the fd identified by @tag.
2534 * @tag is the tag returned from g_source_add_unix_fd().
2536 * If you want to remove a fd, don't set its event mask to zero.
2537 * Instead, call g_source_remove_unix_fd().
2539 * This API is only intended to be used by implementations of #GSource.
2540 * Do not call this API on a #GSource that you did not create.
2542 * As the name suggests, this function is not available on Windows.
2544 * Since: 2.36
2546 void
2547 g_source_modify_unix_fd (GSource *source,
2548 gpointer tag,
2549 GIOCondition new_events)
2551 GMainContext *context;
2552 GPollFD *poll_fd;
2554 g_return_if_fail (source != NULL);
2555 g_return_if_fail (g_slist_find (source->priv->fds, tag));
2557 context = source->context;
2558 poll_fd = tag;
2560 poll_fd->events = new_events;
2562 if (context)
2563 g_main_context_wakeup (context);
2567 * g_source_remove_unix_fd:
2568 * @source: a #GSource
2569 * @tag: (not nullable): the tag from g_source_add_unix_fd()
2571 * Reverses the effect of a previous call to g_source_add_unix_fd().
2573 * You only need to call this if you want to remove an fd from being
2574 * watched while keeping the same source around. In the normal case you
2575 * will just want to destroy the source.
2577 * This API is only intended to be used by implementations of #GSource.
2578 * Do not call this API on a #GSource that you did not create.
2580 * As the name suggests, this function is not available on Windows.
2582 * Since: 2.36
2584 void
2585 g_source_remove_unix_fd (GSource *source,
2586 gpointer tag)
2588 GMainContext *context;
2589 GPollFD *poll_fd;
2591 g_return_if_fail (source != NULL);
2592 g_return_if_fail (g_slist_find (source->priv->fds, tag));
2594 context = source->context;
2595 poll_fd = tag;
2597 if (context)
2598 LOCK_CONTEXT (context);
2600 source->priv->fds = g_slist_remove (source->priv->fds, poll_fd);
2602 if (context)
2604 if (!SOURCE_BLOCKED (source))
2605 g_main_context_remove_poll_unlocked (context, poll_fd);
2607 UNLOCK_CONTEXT (context);
2610 g_free (poll_fd);
2614 * g_source_query_unix_fd:
2615 * @source: a #GSource
2616 * @tag: (not nullable): the tag from g_source_add_unix_fd()
2618 * Queries the events reported for the fd corresponding to @tag on
2619 * @source during the last poll.
2621 * The return value of this function is only defined when the function
2622 * is called from the check or dispatch functions for @source.
2624 * This API is only intended to be used by implementations of #GSource.
2625 * Do not call this API on a #GSource that you did not create.
2627 * As the name suggests, this function is not available on Windows.
2629 * Returns: the conditions reported on the fd
2631 * Since: 2.36
2633 GIOCondition
2634 g_source_query_unix_fd (GSource *source,
2635 gpointer tag)
2637 GPollFD *poll_fd;
2639 g_return_val_if_fail (source != NULL, 0);
2640 g_return_val_if_fail (g_slist_find (source->priv->fds, tag), 0);
2642 poll_fd = tag;
2644 return poll_fd->revents;
2646 #endif /* G_OS_UNIX */
2649 * g_get_current_time:
2650 * @result: #GTimeVal structure in which to store current time.
2652 * Equivalent to the UNIX gettimeofday() function, but portable.
2654 * You may find g_get_real_time() to be more convenient.
2656 void
2657 g_get_current_time (GTimeVal *result)
2659 #ifndef G_OS_WIN32
2660 struct timeval r;
2662 g_return_if_fail (result != NULL);
2664 /*this is required on alpha, there the timeval structs are int's
2665 not longs and a cast only would fail horribly*/
2666 gettimeofday (&r, NULL);
2667 result->tv_sec = r.tv_sec;
2668 result->tv_usec = r.tv_usec;
2669 #else
2670 FILETIME ft;
2671 guint64 time64;
2673 g_return_if_fail (result != NULL);
2675 GetSystemTimeAsFileTime (&ft);
2676 memmove (&time64, &ft, sizeof (FILETIME));
2678 /* Convert from 100s of nanoseconds since 1601-01-01
2679 * to Unix epoch. Yes, this is Y2038 unsafe.
2681 time64 -= G_GINT64_CONSTANT (116444736000000000);
2682 time64 /= 10;
2684 result->tv_sec = time64 / 1000000;
2685 result->tv_usec = time64 % 1000000;
2686 #endif
2690 * g_get_real_time:
2692 * Queries the system wall-clock time.
2694 * This call is functionally equivalent to g_get_current_time() except
2695 * that the return value is often more convenient than dealing with a
2696 * #GTimeVal.
2698 * You should only use this call if you are actually interested in the real
2699 * wall-clock time. g_get_monotonic_time() is probably more useful for
2700 * measuring intervals.
2702 * Returns: the number of microseconds since January 1, 1970 UTC.
2704 * Since: 2.28
2706 gint64
2707 g_get_real_time (void)
2709 GTimeVal tv;
2711 g_get_current_time (&tv);
2713 return (((gint64) tv.tv_sec) * 1000000) + tv.tv_usec;
2717 * g_get_monotonic_time:
2719 * Queries the system monotonic time.
2721 * The monotonic clock will always increase and doesn't suffer
2722 * discontinuities when the user (or NTP) changes the system time. It
2723 * may or may not continue to tick during times where the machine is
2724 * suspended.
2726 * We try to use the clock that corresponds as closely as possible to
2727 * the passage of time as measured by system calls such as poll() but it
2728 * may not always be possible to do this.
2730 * Returns: the monotonic time, in microseconds
2732 * Since: 2.28
2734 #if defined (G_OS_WIN32)
2735 /* NOTE:
2736 * time_usec = ticks_since_boot * usec_per_sec / ticks_per_sec
2738 * Doing (ticks_since_boot * usec_per_sec) before the division can overflow 64 bits
2739 * (ticks_since_boot / ticks_per_sec) and then multiply would not be accurate enough.
2740 * So for now we calculate (usec_per_sec / ticks_per_sec) and use floating point
2742 static gdouble g_monotonic_usec_per_tick = 0;
2744 void
2745 g_clock_win32_init (void)
2747 LARGE_INTEGER freq;
2749 if (!QueryPerformanceFrequency (&freq) || freq.QuadPart == 0)
2751 /* The documentation says that this should never happen */
2752 g_assert_not_reached ();
2753 return;
2756 g_monotonic_usec_per_tick = (gdouble)G_USEC_PER_SEC / freq.QuadPart;
2759 gint64
2760 g_get_monotonic_time (void)
2762 if (G_LIKELY (g_monotonic_usec_per_tick != 0))
2764 LARGE_INTEGER ticks;
2766 if (QueryPerformanceCounter (&ticks))
2767 return (gint64)(ticks.QuadPart * g_monotonic_usec_per_tick);
2769 g_warning ("QueryPerformanceCounter Failed (%lu)", GetLastError ());
2770 g_monotonic_usec_per_tick = 0;
2773 return 0;
2775 #elif defined(HAVE_MACH_MACH_TIME_H) /* Mac OS */
2776 gint64
2777 g_get_monotonic_time (void)
2779 static mach_timebase_info_data_t timebase_info;
2781 if (timebase_info.denom == 0)
2783 /* This is a fraction that we must use to scale
2784 * mach_absolute_time() by in order to reach nanoseconds.
2786 * We've only ever observed this to be 1/1, but maybe it could be
2787 * 1000/1 if mach time is microseconds already, or 1/1000 if
2788 * picoseconds. Try to deal nicely with that.
2790 mach_timebase_info (&timebase_info);
2792 /* We actually want microseconds... */
2793 if (timebase_info.numer % 1000 == 0)
2794 timebase_info.numer /= 1000;
2795 else
2796 timebase_info.denom *= 1000;
2798 /* We want to make the numer 1 to avoid having to multiply... */
2799 if (timebase_info.denom % timebase_info.numer == 0)
2801 timebase_info.denom /= timebase_info.numer;
2802 timebase_info.numer = 1;
2804 else
2806 /* We could just multiply by timebase_info.numer below, but why
2807 * bother for a case that may never actually exist...
2809 * Plus -- performing the multiplication would risk integer
2810 * overflow. If we ever actually end up in this situation, we
2811 * should more carefully evaluate the correct course of action.
2813 mach_timebase_info (&timebase_info); /* Get a fresh copy for a better message */
2814 g_error ("Got weird mach timebase info of %d/%d. Please file a bug against GLib.",
2815 timebase_info.numer, timebase_info.denom);
2819 return mach_absolute_time () / timebase_info.denom;
2821 #else
2822 gint64
2823 g_get_monotonic_time (void)
2825 struct timespec ts;
2826 gint result;
2828 result = clock_gettime (CLOCK_MONOTONIC, &ts);
2830 if G_UNLIKELY (result != 0)
2831 g_error ("GLib requires working CLOCK_MONOTONIC");
2833 return (((gint64) ts.tv_sec) * 1000000) + (ts.tv_nsec / 1000);
2835 #endif
2837 static void
2838 g_main_dispatch_free (gpointer dispatch)
2840 g_slice_free (GMainDispatch, dispatch);
2843 /* Running the main loop */
2845 static GMainDispatch *
2846 get_dispatch (void)
2848 static GPrivate depth_private = G_PRIVATE_INIT (g_main_dispatch_free);
2849 GMainDispatch *dispatch;
2851 dispatch = g_private_get (&depth_private);
2853 if (!dispatch)
2855 dispatch = g_slice_new0 (GMainDispatch);
2856 g_private_set (&depth_private, dispatch);
2859 return dispatch;
2863 * g_main_depth:
2865 * Returns the depth of the stack of calls to
2866 * g_main_context_dispatch() on any #GMainContext in the current thread.
2867 * That is, when called from the toplevel, it gives 0. When
2868 * called from within a callback from g_main_context_iteration()
2869 * (or g_main_loop_run(), etc.) it returns 1. When called from within
2870 * a callback to a recursive call to g_main_context_iteration(),
2871 * it returns 2. And so forth.
2873 * This function is useful in a situation like the following:
2874 * Imagine an extremely simple "garbage collected" system.
2876 * |[<!-- language="C" -->
2877 * static GList *free_list;
2879 * gpointer
2880 * allocate_memory (gsize size)
2881 * {
2882 * gpointer result = g_malloc (size);
2883 * free_list = g_list_prepend (free_list, result);
2884 * return result;
2887 * void
2888 * free_allocated_memory (void)
2890 * GList *l;
2891 * for (l = free_list; l; l = l->next);
2892 * g_free (l->data);
2893 * g_list_free (free_list);
2894 * free_list = NULL;
2897 * [...]
2899 * while (TRUE);
2901 * g_main_context_iteration (NULL, TRUE);
2902 * free_allocated_memory();
2904 * ]|
2906 * This works from an application, however, if you want to do the same
2907 * thing from a library, it gets more difficult, since you no longer
2908 * control the main loop. You might think you can simply use an idle
2909 * function to make the call to free_allocated_memory(), but that
2910 * doesn't work, since the idle function could be called from a
2911 * recursive callback. This can be fixed by using g_main_depth()
2913 * |[<!-- language="C" -->
2914 * gpointer
2915 * allocate_memory (gsize size)
2916 * {
2917 * FreeListBlock *block = g_new (FreeListBlock, 1);
2918 * block->mem = g_malloc (size);
2919 * block->depth = g_main_depth ();
2920 * free_list = g_list_prepend (free_list, block);
2921 * return block->mem;
2924 * void
2925 * free_allocated_memory (void)
2927 * GList *l;
2929 * int depth = g_main_depth ();
2930 * for (l = free_list; l; );
2932 * GList *next = l->next;
2933 * FreeListBlock *block = l->data;
2934 * if (block->depth > depth)
2936 * g_free (block->mem);
2937 * g_free (block);
2938 * free_list = g_list_delete_link (free_list, l);
2941 * l = next;
2944 * ]|
2946 * There is a temptation to use g_main_depth() to solve
2947 * problems with reentrancy. For instance, while waiting for data
2948 * to be received from the network in response to a menu item,
2949 * the menu item might be selected again. It might seem that
2950 * one could make the menu item's callback return immediately
2951 * and do nothing if g_main_depth() returns a value greater than 1.
2952 * However, this should be avoided since the user then sees selecting
2953 * the menu item do nothing. Furthermore, you'll find yourself adding
2954 * these checks all over your code, since there are doubtless many,
2955 * many things that the user could do. Instead, you can use the
2956 * following techniques:
2958 * 1. Use gtk_widget_set_sensitive() or modal dialogs to prevent
2959 * the user from interacting with elements while the main
2960 * loop is recursing.
2962 * 2. Avoid main loop recursion in situations where you can't handle
2963 * arbitrary callbacks. Instead, structure your code so that you
2964 * simply return to the main loop and then get called again when
2965 * there is more work to do.
2967 * Returns: The main loop recursion level in the current thread
2970 g_main_depth (void)
2972 GMainDispatch *dispatch = get_dispatch ();
2973 return dispatch->depth;
2977 * g_main_current_source:
2979 * Returns the currently firing source for this thread.
2981 * Returns: (transfer none): The currently firing source or %NULL.
2983 * Since: 2.12
2985 GSource *
2986 g_main_current_source (void)
2988 GMainDispatch *dispatch = get_dispatch ();
2989 return dispatch->source;
2993 * g_source_is_destroyed:
2994 * @source: a #GSource
2996 * Returns whether @source has been destroyed.
2998 * This is important when you operate upon your objects
2999 * from within idle handlers, but may have freed the object
3000 * before the dispatch of your idle handler.
3002 * |[<!-- language="C" -->
3003 * static gboolean
3004 * idle_callback (gpointer data)
3006 * SomeWidget *self = data;
3008 * GDK_THREADS_ENTER ();
3009 * // do stuff with self
3010 * self->idle_id = 0;
3011 * GDK_THREADS_LEAVE ();
3013 * return G_SOURCE_REMOVE;
3016 * static void
3017 * some_widget_do_stuff_later (SomeWidget *self)
3019 * self->idle_id = g_idle_add (idle_callback, self);
3022 * static void
3023 * some_widget_finalize (GObject *object)
3025 * SomeWidget *self = SOME_WIDGET (object);
3027 * if (self->idle_id)
3028 * g_source_remove (self->idle_id);
3030 * G_OBJECT_CLASS (parent_class)->finalize (object);
3032 * ]|
3034 * This will fail in a multi-threaded application if the
3035 * widget is destroyed before the idle handler fires due
3036 * to the use after free in the callback. A solution, to
3037 * this particular problem, is to check to if the source
3038 * has already been destroy within the callback.
3040 * |[<!-- language="C" -->
3041 * static gboolean
3042 * idle_callback (gpointer data)
3044 * SomeWidget *self = data;
3046 * GDK_THREADS_ENTER ();
3047 * if (!g_source_is_destroyed (g_main_current_source ()))
3049 * // do stuff with self
3051 * GDK_THREADS_LEAVE ();
3053 * return FALSE;
3055 * ]|
3057 * Calls to this function from a thread other than the one acquired by the
3058 * #GMainContext the #GSource is attached to are typically redundant, as the
3059 * source could be destroyed immediately after this function returns. However,
3060 * once a source is destroyed it cannot be un-destroyed, so this function can be
3061 * used for opportunistic checks from any thread.
3063 * Returns: %TRUE if the source has been destroyed
3065 * Since: 2.12
3067 gboolean
3068 g_source_is_destroyed (GSource *source)
3070 return SOURCE_DESTROYED (source);
3073 /* Temporarily remove all this source's file descriptors from the
3074 * poll(), so that if data comes available for one of the file descriptors
3075 * we don't continually spin in the poll()
3077 /* HOLDS: source->context's lock */
3078 static void
3079 block_source (GSource *source)
3081 GSList *tmp_list;
3083 g_return_if_fail (!SOURCE_BLOCKED (source));
3085 source->flags |= G_SOURCE_BLOCKED;
3087 if (source->context)
3089 tmp_list = source->poll_fds;
3090 while (tmp_list)
3092 g_main_context_remove_poll_unlocked (source->context, tmp_list->data);
3093 tmp_list = tmp_list->next;
3096 for (tmp_list = source->priv->fds; tmp_list; tmp_list = tmp_list->next)
3097 g_main_context_remove_poll_unlocked (source->context, tmp_list->data);
3100 if (source->priv && source->priv->child_sources)
3102 tmp_list = source->priv->child_sources;
3103 while (tmp_list)
3105 block_source (tmp_list->data);
3106 tmp_list = tmp_list->next;
3111 /* HOLDS: source->context's lock */
3112 static void
3113 unblock_source (GSource *source)
3115 GSList *tmp_list;
3117 g_return_if_fail (SOURCE_BLOCKED (source)); /* Source already unblocked */
3118 g_return_if_fail (!SOURCE_DESTROYED (source));
3120 source->flags &= ~G_SOURCE_BLOCKED;
3122 tmp_list = source->poll_fds;
3123 while (tmp_list)
3125 g_main_context_add_poll_unlocked (source->context, source->priority, tmp_list->data);
3126 tmp_list = tmp_list->next;
3129 for (tmp_list = source->priv->fds; tmp_list; tmp_list = tmp_list->next)
3130 g_main_context_add_poll_unlocked (source->context, source->priority, tmp_list->data);
3132 if (source->priv && source->priv->child_sources)
3134 tmp_list = source->priv->child_sources;
3135 while (tmp_list)
3137 unblock_source (tmp_list->data);
3138 tmp_list = tmp_list->next;
3143 /* HOLDS: context's lock */
3144 static void
3145 g_main_dispatch (GMainContext *context)
3147 GMainDispatch *current = get_dispatch ();
3148 guint i;
3150 for (i = 0; i < context->pending_dispatches->len; i++)
3152 GSource *source = context->pending_dispatches->pdata[i];
3154 context->pending_dispatches->pdata[i] = NULL;
3155 g_assert (source);
3157 source->flags &= ~G_SOURCE_READY;
3159 if (!SOURCE_DESTROYED (source))
3161 gboolean was_in_call;
3162 gpointer user_data = NULL;
3163 GSourceFunc callback = NULL;
3164 GSourceCallbackFuncs *cb_funcs;
3165 gpointer cb_data;
3166 gboolean need_destroy;
3168 gboolean (*dispatch) (GSource *,
3169 GSourceFunc,
3170 gpointer);
3171 GSource *prev_source;
3173 dispatch = source->source_funcs->dispatch;
3174 cb_funcs = source->callback_funcs;
3175 cb_data = source->callback_data;
3177 if (cb_funcs)
3178 cb_funcs->ref (cb_data);
3180 if ((source->flags & G_SOURCE_CAN_RECURSE) == 0)
3181 block_source (source);
3183 was_in_call = source->flags & G_HOOK_FLAG_IN_CALL;
3184 source->flags |= G_HOOK_FLAG_IN_CALL;
3186 if (cb_funcs)
3187 cb_funcs->get (cb_data, source, &callback, &user_data);
3189 UNLOCK_CONTEXT (context);
3191 /* These operations are safe because 'current' is thread-local
3192 * and not modified from anywhere but this function.
3194 prev_source = current->source;
3195 current->source = source;
3196 current->depth++;
3198 TRACE (GLIB_MAIN_BEFORE_DISPATCH (g_source_get_name (source), source,
3199 dispatch, callback, user_data));
3200 need_destroy = !(* dispatch) (source, callback, user_data);
3201 TRACE (GLIB_MAIN_AFTER_DISPATCH (g_source_get_name (source), source,
3202 dispatch, need_destroy));
3204 current->source = prev_source;
3205 current->depth--;
3207 if (cb_funcs)
3208 cb_funcs->unref (cb_data);
3210 LOCK_CONTEXT (context);
3212 if (!was_in_call)
3213 source->flags &= ~G_HOOK_FLAG_IN_CALL;
3215 if (SOURCE_BLOCKED (source) && !SOURCE_DESTROYED (source))
3216 unblock_source (source);
3218 /* Note: this depends on the fact that we can't switch
3219 * sources from one main context to another
3221 if (need_destroy && !SOURCE_DESTROYED (source))
3223 g_assert (source->context == context);
3224 g_source_destroy_internal (source, context, TRUE);
3228 SOURCE_UNREF (source, context);
3231 g_ptr_array_set_size (context->pending_dispatches, 0);
3235 * g_main_context_acquire:
3236 * @context: a #GMainContext
3238 * Tries to become the owner of the specified context.
3239 * If some other thread is the owner of the context,
3240 * returns %FALSE immediately. Ownership is properly
3241 * recursive: the owner can require ownership again
3242 * and will release ownership when g_main_context_release()
3243 * is called as many times as g_main_context_acquire().
3245 * You must be the owner of a context before you
3246 * can call g_main_context_prepare(), g_main_context_query(),
3247 * g_main_context_check(), g_main_context_dispatch().
3249 * Returns: %TRUE if the operation succeeded, and
3250 * this thread is now the owner of @context.
3252 gboolean
3253 g_main_context_acquire (GMainContext *context)
3255 gboolean result = FALSE;
3256 GThread *self = G_THREAD_SELF;
3258 if (context == NULL)
3259 context = g_main_context_default ();
3261 LOCK_CONTEXT (context);
3263 if (!context->owner)
3265 context->owner = self;
3266 g_assert (context->owner_count == 0);
3267 TRACE (GLIB_MAIN_CONTEXT_ACQUIRE (context, TRUE /* success */));
3270 if (context->owner == self)
3272 context->owner_count++;
3273 result = TRUE;
3275 else
3277 TRACE (GLIB_MAIN_CONTEXT_ACQUIRE (context, FALSE /* failure */));
3280 UNLOCK_CONTEXT (context);
3282 return result;
3286 * g_main_context_release:
3287 * @context: a #GMainContext
3289 * Releases ownership of a context previously acquired by this thread
3290 * with g_main_context_acquire(). If the context was acquired multiple
3291 * times, the ownership will be released only when g_main_context_release()
3292 * is called as many times as it was acquired.
3294 void
3295 g_main_context_release (GMainContext *context)
3297 if (context == NULL)
3298 context = g_main_context_default ();
3300 LOCK_CONTEXT (context);
3302 context->owner_count--;
3303 if (context->owner_count == 0)
3305 TRACE (GLIB_MAIN_CONTEXT_RELEASE (context));
3307 context->owner = NULL;
3309 if (context->waiters)
3311 GMainWaiter *waiter = context->waiters->data;
3312 gboolean loop_internal_waiter = (waiter->mutex == &context->mutex);
3313 context->waiters = g_slist_delete_link (context->waiters,
3314 context->waiters);
3315 if (!loop_internal_waiter)
3316 g_mutex_lock (waiter->mutex);
3318 g_cond_signal (waiter->cond);
3320 if (!loop_internal_waiter)
3321 g_mutex_unlock (waiter->mutex);
3325 UNLOCK_CONTEXT (context);
3329 * g_main_context_wait:
3330 * @context: a #GMainContext
3331 * @cond: a condition variable
3332 * @mutex: a mutex, currently held
3334 * Tries to become the owner of the specified context,
3335 * as with g_main_context_acquire(). But if another thread
3336 * is the owner, atomically drop @mutex and wait on @cond until
3337 * that owner releases ownership or until @cond is signaled, then
3338 * try again (once) to become the owner.
3340 * Returns: %TRUE if the operation succeeded, and
3341 * this thread is now the owner of @context.
3343 gboolean
3344 g_main_context_wait (GMainContext *context,
3345 GCond *cond,
3346 GMutex *mutex)
3348 gboolean result = FALSE;
3349 GThread *self = G_THREAD_SELF;
3350 gboolean loop_internal_waiter;
3352 if (context == NULL)
3353 context = g_main_context_default ();
3355 if G_UNLIKELY (cond != &context->cond || mutex != &context->mutex)
3357 static gboolean warned;
3359 if (!warned)
3361 g_critical ("WARNING!! g_main_context_wait() will be removed in a future release. "
3362 "If you see this message, please file a bug immediately.");
3363 warned = TRUE;
3367 loop_internal_waiter = (mutex == &context->mutex);
3369 if (!loop_internal_waiter)
3370 LOCK_CONTEXT (context);
3372 if (context->owner && context->owner != self)
3374 GMainWaiter waiter;
3376 waiter.cond = cond;
3377 waiter.mutex = mutex;
3379 context->waiters = g_slist_append (context->waiters, &waiter);
3381 if (!loop_internal_waiter)
3382 UNLOCK_CONTEXT (context);
3383 g_cond_wait (cond, mutex);
3384 if (!loop_internal_waiter)
3385 LOCK_CONTEXT (context);
3387 context->waiters = g_slist_remove (context->waiters, &waiter);
3390 if (!context->owner)
3392 context->owner = self;
3393 g_assert (context->owner_count == 0);
3396 if (context->owner == self)
3398 context->owner_count++;
3399 result = TRUE;
3402 if (!loop_internal_waiter)
3403 UNLOCK_CONTEXT (context);
3405 return result;
3409 * g_main_context_prepare:
3410 * @context: a #GMainContext
3411 * @priority: location to store priority of highest priority
3412 * source already ready.
3414 * Prepares to poll sources within a main loop. The resulting information
3415 * for polling is determined by calling g_main_context_query ().
3417 * You must have successfully acquired the context with
3418 * g_main_context_acquire() before you may call this function.
3420 * Returns: %TRUE if some source is ready to be dispatched
3421 * prior to polling.
3423 gboolean
3424 g_main_context_prepare (GMainContext *context,
3425 gint *priority)
3427 guint i;
3428 gint n_ready = 0;
3429 gint current_priority = G_MAXINT;
3430 GSource *source;
3431 GSourceIter iter;
3433 if (context == NULL)
3434 context = g_main_context_default ();
3436 LOCK_CONTEXT (context);
3438 context->time_is_fresh = FALSE;
3440 if (context->in_check_or_prepare)
3442 g_warning ("g_main_context_prepare() called recursively from within a source's check() or "
3443 "prepare() member.");
3444 UNLOCK_CONTEXT (context);
3445 return FALSE;
3448 TRACE (GLIB_MAIN_CONTEXT_BEFORE_PREPARE (context));
3450 #if 0
3451 /* If recursing, finish up current dispatch, before starting over */
3452 if (context->pending_dispatches)
3454 if (dispatch)
3455 g_main_dispatch (context, &current_time);
3457 UNLOCK_CONTEXT (context);
3458 return TRUE;
3460 #endif
3462 /* If recursing, clear list of pending dispatches */
3464 for (i = 0; i < context->pending_dispatches->len; i++)
3466 if (context->pending_dispatches->pdata[i])
3467 SOURCE_UNREF ((GSource *)context->pending_dispatches->pdata[i], context);
3469 g_ptr_array_set_size (context->pending_dispatches, 0);
3471 /* Prepare all sources */
3473 context->timeout = -1;
3475 g_source_iter_init (&iter, context, TRUE);
3476 while (g_source_iter_next (&iter, &source))
3478 gint source_timeout = -1;
3480 if (SOURCE_DESTROYED (source) || SOURCE_BLOCKED (source))
3481 continue;
3482 if ((n_ready > 0) && (source->priority > current_priority))
3483 break;
3485 if (!(source->flags & G_SOURCE_READY))
3487 gboolean result;
3488 gboolean (* prepare) (GSource *source,
3489 gint *timeout);
3491 prepare = source->source_funcs->prepare;
3493 if (prepare)
3495 context->in_check_or_prepare++;
3496 UNLOCK_CONTEXT (context);
3498 result = (* prepare) (source, &source_timeout);
3499 TRACE (GLIB_MAIN_AFTER_PREPARE (source, prepare, source_timeout));
3501 LOCK_CONTEXT (context);
3502 context->in_check_or_prepare--;
3504 else
3506 source_timeout = -1;
3507 result = FALSE;
3510 if (result == FALSE && source->priv->ready_time != -1)
3512 if (!context->time_is_fresh)
3514 context->time = g_get_monotonic_time ();
3515 context->time_is_fresh = TRUE;
3518 if (source->priv->ready_time <= context->time)
3520 source_timeout = 0;
3521 result = TRUE;
3523 else
3525 gint timeout;
3527 /* rounding down will lead to spinning, so always round up */
3528 timeout = (source->priv->ready_time - context->time + 999) / 1000;
3530 if (source_timeout < 0 || timeout < source_timeout)
3531 source_timeout = timeout;
3535 if (result)
3537 GSource *ready_source = source;
3539 while (ready_source)
3541 ready_source->flags |= G_SOURCE_READY;
3542 ready_source = ready_source->priv->parent_source;
3547 if (source->flags & G_SOURCE_READY)
3549 n_ready++;
3550 current_priority = source->priority;
3551 context->timeout = 0;
3554 if (source_timeout >= 0)
3556 if (context->timeout < 0)
3557 context->timeout = source_timeout;
3558 else
3559 context->timeout = MIN (context->timeout, source_timeout);
3562 g_source_iter_clear (&iter);
3564 TRACE (GLIB_MAIN_CONTEXT_AFTER_PREPARE (context, current_priority, n_ready));
3566 UNLOCK_CONTEXT (context);
3568 if (priority)
3569 *priority = current_priority;
3571 return (n_ready > 0);
3575 * g_main_context_query:
3576 * @context: a #GMainContext
3577 * @max_priority: maximum priority source to check
3578 * @timeout_: (out): location to store timeout to be used in polling
3579 * @fds: (out caller-allocates) (array length=n_fds): location to
3580 * store #GPollFD records that need to be polled.
3581 * @n_fds: (in): length of @fds.
3583 * Determines information necessary to poll this main loop.
3585 * You must have successfully acquired the context with
3586 * g_main_context_acquire() before you may call this function.
3588 * Returns: the number of records actually stored in @fds,
3589 * or, if more than @n_fds records need to be stored, the number
3590 * of records that need to be stored.
3592 gint
3593 g_main_context_query (GMainContext *context,
3594 gint max_priority,
3595 gint *timeout,
3596 GPollFD *fds,
3597 gint n_fds)
3599 gint n_poll;
3600 GPollRec *pollrec, *lastpollrec;
3601 gushort events;
3603 LOCK_CONTEXT (context);
3605 TRACE (GLIB_MAIN_CONTEXT_BEFORE_QUERY (context, max_priority));
3607 n_poll = 0;
3608 lastpollrec = NULL;
3609 for (pollrec = context->poll_records; pollrec; pollrec = pollrec->next)
3611 if (pollrec->priority > max_priority)
3612 continue;
3614 /* In direct contradiction to the Unix98 spec, IRIX runs into
3615 * difficulty if you pass in POLLERR, POLLHUP or POLLNVAL
3616 * flags in the events field of the pollfd while it should
3617 * just ignoring them. So we mask them out here.
3619 events = pollrec->fd->events & ~(G_IO_ERR|G_IO_HUP|G_IO_NVAL);
3621 if (lastpollrec && pollrec->fd->fd == lastpollrec->fd->fd)
3623 if (n_poll - 1 < n_fds)
3624 fds[n_poll - 1].events |= events;
3626 else
3628 if (n_poll < n_fds)
3630 fds[n_poll].fd = pollrec->fd->fd;
3631 fds[n_poll].events = events;
3632 fds[n_poll].revents = 0;
3635 n_poll++;
3638 lastpollrec = pollrec;
3641 context->poll_changed = FALSE;
3643 if (timeout)
3645 *timeout = context->timeout;
3646 if (*timeout != 0)
3647 context->time_is_fresh = FALSE;
3650 TRACE (GLIB_MAIN_CONTEXT_AFTER_QUERY (context, context->timeout,
3651 fds, n_poll));
3653 UNLOCK_CONTEXT (context);
3655 return n_poll;
3659 * g_main_context_check:
3660 * @context: a #GMainContext
3661 * @max_priority: the maximum numerical priority of sources to check
3662 * @fds: (array length=n_fds): array of #GPollFD's that was passed to
3663 * the last call to g_main_context_query()
3664 * @n_fds: return value of g_main_context_query()
3666 * Passes the results of polling back to the main loop.
3668 * You must have successfully acquired the context with
3669 * g_main_context_acquire() before you may call this function.
3671 * Returns: %TRUE if some sources are ready to be dispatched.
3673 gboolean
3674 g_main_context_check (GMainContext *context,
3675 gint max_priority,
3676 GPollFD *fds,
3677 gint n_fds)
3679 GSource *source;
3680 GSourceIter iter;
3681 GPollRec *pollrec;
3682 gint n_ready = 0;
3683 gint i;
3685 LOCK_CONTEXT (context);
3687 if (context->in_check_or_prepare)
3689 g_warning ("g_main_context_check() called recursively from within a source's check() or "
3690 "prepare() member.");
3691 UNLOCK_CONTEXT (context);
3692 return FALSE;
3695 TRACE (GLIB_MAIN_CONTEXT_BEFORE_CHECK (context, max_priority, fds, n_fds));
3697 for (i = 0; i < n_fds; i++)
3699 if (fds[i].fd == context->wake_up_rec.fd)
3701 if (fds[i].revents)
3703 TRACE (GLIB_MAIN_CONTEXT_WAKEUP_ACKNOWLEDGE (context));
3704 g_wakeup_acknowledge (context->wakeup);
3706 break;
3710 /* If the set of poll file descriptors changed, bail out
3711 * and let the main loop rerun
3713 if (context->poll_changed)
3715 TRACE (GLIB_MAIN_CONTEXT_AFTER_CHECK (context, 0));
3717 UNLOCK_CONTEXT (context);
3718 return FALSE;
3721 pollrec = context->poll_records;
3722 i = 0;
3723 while (pollrec && i < n_fds)
3725 while (pollrec && pollrec->fd->fd == fds[i].fd)
3727 if (pollrec->priority <= max_priority)
3729 pollrec->fd->revents =
3730 fds[i].revents & (pollrec->fd->events | G_IO_ERR | G_IO_HUP | G_IO_NVAL);
3732 pollrec = pollrec->next;
3735 i++;
3738 g_source_iter_init (&iter, context, TRUE);
3739 while (g_source_iter_next (&iter, &source))
3741 if (SOURCE_DESTROYED (source) || SOURCE_BLOCKED (source))
3742 continue;
3743 if ((n_ready > 0) && (source->priority > max_priority))
3744 break;
3746 if (!(source->flags & G_SOURCE_READY))
3748 gboolean result;
3749 gboolean (* check) (GSource *source);
3751 check = source->source_funcs->check;
3753 if (check)
3755 /* If the check function is set, call it. */
3756 context->in_check_or_prepare++;
3757 UNLOCK_CONTEXT (context);
3759 result = (* check) (source);
3761 TRACE (GLIB_MAIN_AFTER_CHECK (source, check, result));
3763 LOCK_CONTEXT (context);
3764 context->in_check_or_prepare--;
3766 else
3767 result = FALSE;
3769 if (result == FALSE)
3771 GSList *tmp_list;
3773 /* If not already explicitly flagged ready by ->check()
3774 * (or if we have no check) then we can still be ready if
3775 * any of our fds poll as ready.
3777 for (tmp_list = source->priv->fds; tmp_list; tmp_list = tmp_list->next)
3779 GPollFD *pollfd = tmp_list->data;
3781 if (pollfd->revents)
3783 result = TRUE;
3784 break;
3789 if (result == FALSE && source->priv->ready_time != -1)
3791 if (!context->time_is_fresh)
3793 context->time = g_get_monotonic_time ();
3794 context->time_is_fresh = TRUE;
3797 if (source->priv->ready_time <= context->time)
3798 result = TRUE;
3801 if (result)
3803 GSource *ready_source = source;
3805 while (ready_source)
3807 ready_source->flags |= G_SOURCE_READY;
3808 ready_source = ready_source->priv->parent_source;
3813 if (source->flags & G_SOURCE_READY)
3815 source->ref_count++;
3816 g_ptr_array_add (context->pending_dispatches, source);
3818 n_ready++;
3820 /* never dispatch sources with less priority than the first
3821 * one we choose to dispatch
3823 max_priority = source->priority;
3826 g_source_iter_clear (&iter);
3828 TRACE (GLIB_MAIN_CONTEXT_AFTER_CHECK (context, n_ready));
3830 UNLOCK_CONTEXT (context);
3832 return n_ready > 0;
3836 * g_main_context_dispatch:
3837 * @context: a #GMainContext
3839 * Dispatches all pending sources.
3841 * You must have successfully acquired the context with
3842 * g_main_context_acquire() before you may call this function.
3844 void
3845 g_main_context_dispatch (GMainContext *context)
3847 LOCK_CONTEXT (context);
3849 TRACE (GLIB_MAIN_CONTEXT_BEFORE_DISPATCH (context));
3851 if (context->pending_dispatches->len > 0)
3853 g_main_dispatch (context);
3856 TRACE (GLIB_MAIN_CONTEXT_AFTER_DISPATCH (context));
3858 UNLOCK_CONTEXT (context);
3861 /* HOLDS context lock */
3862 static gboolean
3863 g_main_context_iterate (GMainContext *context,
3864 gboolean block,
3865 gboolean dispatch,
3866 GThread *self)
3868 gint max_priority;
3869 gint timeout;
3870 gboolean some_ready;
3871 gint nfds, allocated_nfds;
3872 GPollFD *fds = NULL;
3874 UNLOCK_CONTEXT (context);
3876 if (!g_main_context_acquire (context))
3878 gboolean got_ownership;
3880 LOCK_CONTEXT (context);
3882 if (!block)
3883 return FALSE;
3885 got_ownership = g_main_context_wait (context,
3886 &context->cond,
3887 &context->mutex);
3889 if (!got_ownership)
3890 return FALSE;
3892 else
3893 LOCK_CONTEXT (context);
3895 if (!context->cached_poll_array)
3897 context->cached_poll_array_size = context->n_poll_records;
3898 context->cached_poll_array = g_new (GPollFD, context->n_poll_records);
3901 allocated_nfds = context->cached_poll_array_size;
3902 fds = context->cached_poll_array;
3904 UNLOCK_CONTEXT (context);
3906 g_main_context_prepare (context, &max_priority);
3908 while ((nfds = g_main_context_query (context, max_priority, &timeout, fds,
3909 allocated_nfds)) > allocated_nfds)
3911 LOCK_CONTEXT (context);
3912 g_free (fds);
3913 context->cached_poll_array_size = allocated_nfds = nfds;
3914 context->cached_poll_array = fds = g_new (GPollFD, nfds);
3915 UNLOCK_CONTEXT (context);
3918 if (!block)
3919 timeout = 0;
3921 g_main_context_poll (context, timeout, max_priority, fds, nfds);
3923 some_ready = g_main_context_check (context, max_priority, fds, nfds);
3925 if (dispatch)
3926 g_main_context_dispatch (context);
3928 g_main_context_release (context);
3930 LOCK_CONTEXT (context);
3932 return some_ready;
3936 * g_main_context_pending:
3937 * @context: (nullable): a #GMainContext (if %NULL, the default context will be used)
3939 * Checks if any sources have pending events for the given context.
3941 * Returns: %TRUE if events are pending.
3943 gboolean
3944 g_main_context_pending (GMainContext *context)
3946 gboolean retval;
3948 if (!context)
3949 context = g_main_context_default();
3951 LOCK_CONTEXT (context);
3952 retval = g_main_context_iterate (context, FALSE, FALSE, G_THREAD_SELF);
3953 UNLOCK_CONTEXT (context);
3955 return retval;
3959 * g_main_context_iteration:
3960 * @context: (nullable): a #GMainContext (if %NULL, the default context will be used)
3961 * @may_block: whether the call may block.
3963 * Runs a single iteration for the given main loop. This involves
3964 * checking to see if any event sources are ready to be processed,
3965 * then if no events sources are ready and @may_block is %TRUE, waiting
3966 * for a source to become ready, then dispatching the highest priority
3967 * events sources that are ready. Otherwise, if @may_block is %FALSE
3968 * sources are not waited to become ready, only those highest priority
3969 * events sources will be dispatched (if any), that are ready at this
3970 * given moment without further waiting.
3972 * Note that even when @may_block is %TRUE, it is still possible for
3973 * g_main_context_iteration() to return %FALSE, since the wait may
3974 * be interrupted for other reasons than an event source becoming ready.
3976 * Returns: %TRUE if events were dispatched.
3978 gboolean
3979 g_main_context_iteration (GMainContext *context, gboolean may_block)
3981 gboolean retval;
3983 if (!context)
3984 context = g_main_context_default();
3986 LOCK_CONTEXT (context);
3987 retval = g_main_context_iterate (context, may_block, TRUE, G_THREAD_SELF);
3988 UNLOCK_CONTEXT (context);
3990 return retval;
3994 * g_main_loop_new:
3995 * @context: (nullable): a #GMainContext (if %NULL, the default context will be used).
3996 * @is_running: set to %TRUE to indicate that the loop is running. This
3997 * is not very important since calling g_main_loop_run() will set this to
3998 * %TRUE anyway.
4000 * Creates a new #GMainLoop structure.
4002 * Returns: a new #GMainLoop.
4004 GMainLoop *
4005 g_main_loop_new (GMainContext *context,
4006 gboolean is_running)
4008 GMainLoop *loop;
4010 if (!context)
4011 context = g_main_context_default();
4013 g_main_context_ref (context);
4015 loop = g_new0 (GMainLoop, 1);
4016 loop->context = context;
4017 loop->is_running = is_running != FALSE;
4018 loop->ref_count = 1;
4020 TRACE (GLIB_MAIN_LOOP_NEW (loop, context));
4022 return loop;
4026 * g_main_loop_ref:
4027 * @loop: a #GMainLoop
4029 * Increases the reference count on a #GMainLoop object by one.
4031 * Returns: @loop
4033 GMainLoop *
4034 g_main_loop_ref (GMainLoop *loop)
4036 g_return_val_if_fail (loop != NULL, NULL);
4037 g_return_val_if_fail (g_atomic_int_get (&loop->ref_count) > 0, NULL);
4039 g_atomic_int_inc (&loop->ref_count);
4041 return loop;
4045 * g_main_loop_unref:
4046 * @loop: a #GMainLoop
4048 * Decreases the reference count on a #GMainLoop object by one. If
4049 * the result is zero, free the loop and free all associated memory.
4051 void
4052 g_main_loop_unref (GMainLoop *loop)
4054 g_return_if_fail (loop != NULL);
4055 g_return_if_fail (g_atomic_int_get (&loop->ref_count) > 0);
4057 if (!g_atomic_int_dec_and_test (&loop->ref_count))
4058 return;
4060 g_main_context_unref (loop->context);
4061 g_free (loop);
4065 * g_main_loop_run:
4066 * @loop: a #GMainLoop
4068 * Runs a main loop until g_main_loop_quit() is called on the loop.
4069 * If this is called for the thread of the loop's #GMainContext,
4070 * it will process events from the loop, otherwise it will
4071 * simply wait.
4073 void
4074 g_main_loop_run (GMainLoop *loop)
4076 GThread *self = G_THREAD_SELF;
4078 g_return_if_fail (loop != NULL);
4079 g_return_if_fail (g_atomic_int_get (&loop->ref_count) > 0);
4081 if (!g_main_context_acquire (loop->context))
4083 gboolean got_ownership = FALSE;
4085 /* Another thread owns this context */
4086 LOCK_CONTEXT (loop->context);
4088 g_atomic_int_inc (&loop->ref_count);
4090 if (!loop->is_running)
4091 loop->is_running = TRUE;
4093 while (loop->is_running && !got_ownership)
4094 got_ownership = g_main_context_wait (loop->context,
4095 &loop->context->cond,
4096 &loop->context->mutex);
4098 if (!loop->is_running)
4100 UNLOCK_CONTEXT (loop->context);
4101 if (got_ownership)
4102 g_main_context_release (loop->context);
4103 g_main_loop_unref (loop);
4104 return;
4107 g_assert (got_ownership);
4109 else
4110 LOCK_CONTEXT (loop->context);
4112 if (loop->context->in_check_or_prepare)
4114 g_warning ("g_main_loop_run(): called recursively from within a source's "
4115 "check() or prepare() member, iteration not possible.");
4116 return;
4119 g_atomic_int_inc (&loop->ref_count);
4120 loop->is_running = TRUE;
4121 while (loop->is_running)
4122 g_main_context_iterate (loop->context, TRUE, TRUE, self);
4124 UNLOCK_CONTEXT (loop->context);
4126 g_main_context_release (loop->context);
4128 g_main_loop_unref (loop);
4132 * g_main_loop_quit:
4133 * @loop: a #GMainLoop
4135 * Stops a #GMainLoop from running. Any calls to g_main_loop_run()
4136 * for the loop will return.
4138 * Note that sources that have already been dispatched when
4139 * g_main_loop_quit() is called will still be executed.
4141 void
4142 g_main_loop_quit (GMainLoop *loop)
4144 g_return_if_fail (loop != NULL);
4145 g_return_if_fail (g_atomic_int_get (&loop->ref_count) > 0);
4147 LOCK_CONTEXT (loop->context);
4148 loop->is_running = FALSE;
4149 g_wakeup_signal (loop->context->wakeup);
4151 g_cond_broadcast (&loop->context->cond);
4153 UNLOCK_CONTEXT (loop->context);
4155 TRACE (GLIB_MAIN_LOOP_QUIT (loop));
4159 * g_main_loop_is_running:
4160 * @loop: a #GMainLoop.
4162 * Checks to see if the main loop is currently being run via g_main_loop_run().
4164 * Returns: %TRUE if the mainloop is currently being run.
4166 gboolean
4167 g_main_loop_is_running (GMainLoop *loop)
4169 g_return_val_if_fail (loop != NULL, FALSE);
4170 g_return_val_if_fail (g_atomic_int_get (&loop->ref_count) > 0, FALSE);
4172 return loop->is_running;
4176 * g_main_loop_get_context:
4177 * @loop: a #GMainLoop.
4179 * Returns the #GMainContext of @loop.
4181 * Returns: (transfer none): the #GMainContext of @loop
4183 GMainContext *
4184 g_main_loop_get_context (GMainLoop *loop)
4186 g_return_val_if_fail (loop != NULL, NULL);
4187 g_return_val_if_fail (g_atomic_int_get (&loop->ref_count) > 0, NULL);
4189 return loop->context;
4192 /* HOLDS: context's lock */
4193 static void
4194 g_main_context_poll (GMainContext *context,
4195 gint timeout,
4196 gint priority,
4197 GPollFD *fds,
4198 gint n_fds)
4200 #ifdef G_MAIN_POLL_DEBUG
4201 GTimer *poll_timer;
4202 GPollRec *pollrec;
4203 gint i;
4204 #endif
4206 GPollFunc poll_func;
4208 if (n_fds || timeout != 0)
4210 int ret, errsv;
4212 #ifdef G_MAIN_POLL_DEBUG
4213 poll_timer = NULL;
4214 if (_g_main_poll_debug)
4216 g_print ("polling context=%p n=%d timeout=%d\n",
4217 context, n_fds, timeout);
4218 poll_timer = g_timer_new ();
4220 #endif
4222 LOCK_CONTEXT (context);
4224 poll_func = context->poll_func;
4226 UNLOCK_CONTEXT (context);
4227 ret = (*poll_func) (fds, n_fds, timeout);
4228 errsv = errno;
4229 if (ret < 0 && errsv != EINTR)
4231 #ifndef G_OS_WIN32
4232 g_warning ("poll(2) failed due to: %s.",
4233 g_strerror (errsv));
4234 #else
4235 /* If g_poll () returns -1, it has already called g_warning() */
4236 #endif
4239 #ifdef G_MAIN_POLL_DEBUG
4240 if (_g_main_poll_debug)
4242 LOCK_CONTEXT (context);
4244 g_print ("g_main_poll(%d) timeout: %d - elapsed %12.10f seconds",
4245 n_fds,
4246 timeout,
4247 g_timer_elapsed (poll_timer, NULL));
4248 g_timer_destroy (poll_timer);
4249 pollrec = context->poll_records;
4251 while (pollrec != NULL)
4253 i = 0;
4254 while (i < n_fds)
4256 if (fds[i].fd == pollrec->fd->fd &&
4257 pollrec->fd->events &&
4258 fds[i].revents)
4260 g_print (" [" G_POLLFD_FORMAT " :", fds[i].fd);
4261 if (fds[i].revents & G_IO_IN)
4262 g_print ("i");
4263 if (fds[i].revents & G_IO_OUT)
4264 g_print ("o");
4265 if (fds[i].revents & G_IO_PRI)
4266 g_print ("p");
4267 if (fds[i].revents & G_IO_ERR)
4268 g_print ("e");
4269 if (fds[i].revents & G_IO_HUP)
4270 g_print ("h");
4271 if (fds[i].revents & G_IO_NVAL)
4272 g_print ("n");
4273 g_print ("]");
4275 i++;
4277 pollrec = pollrec->next;
4279 g_print ("\n");
4281 UNLOCK_CONTEXT (context);
4283 #endif
4284 } /* if (n_fds || timeout != 0) */
4288 * g_main_context_add_poll:
4289 * @context: (nullable): a #GMainContext (or %NULL for the default context)
4290 * @fd: a #GPollFD structure holding information about a file
4291 * descriptor to watch.
4292 * @priority: the priority for this file descriptor which should be
4293 * the same as the priority used for g_source_attach() to ensure that the
4294 * file descriptor is polled whenever the results may be needed.
4296 * Adds a file descriptor to the set of file descriptors polled for
4297 * this context. This will very seldom be used directly. Instead
4298 * a typical event source will use g_source_add_unix_fd() instead.
4300 void
4301 g_main_context_add_poll (GMainContext *context,
4302 GPollFD *fd,
4303 gint priority)
4305 if (!context)
4306 context = g_main_context_default ();
4308 g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
4309 g_return_if_fail (fd);
4311 LOCK_CONTEXT (context);
4312 g_main_context_add_poll_unlocked (context, priority, fd);
4313 UNLOCK_CONTEXT (context);
4316 /* HOLDS: main_loop_lock */
4317 static void
4318 g_main_context_add_poll_unlocked (GMainContext *context,
4319 gint priority,
4320 GPollFD *fd)
4322 GPollRec *prevrec, *nextrec;
4323 GPollRec *newrec = g_slice_new (GPollRec);
4325 /* This file descriptor may be checked before we ever poll */
4326 fd->revents = 0;
4327 newrec->fd = fd;
4328 newrec->priority = priority;
4330 prevrec = NULL;
4331 nextrec = context->poll_records;
4332 while (nextrec)
4334 if (nextrec->fd->fd > fd->fd)
4335 break;
4336 prevrec = nextrec;
4337 nextrec = nextrec->next;
4340 if (prevrec)
4341 prevrec->next = newrec;
4342 else
4343 context->poll_records = newrec;
4345 newrec->prev = prevrec;
4346 newrec->next = nextrec;
4348 if (nextrec)
4349 nextrec->prev = newrec;
4351 context->n_poll_records++;
4353 context->poll_changed = TRUE;
4355 /* Now wake up the main loop if it is waiting in the poll() */
4356 conditional_wakeup (context);
4360 * g_main_context_remove_poll:
4361 * @context:a #GMainContext
4362 * @fd: a #GPollFD descriptor previously added with g_main_context_add_poll()
4364 * Removes file descriptor from the set of file descriptors to be
4365 * polled for a particular context.
4367 void
4368 g_main_context_remove_poll (GMainContext *context,
4369 GPollFD *fd)
4371 if (!context)
4372 context = g_main_context_default ();
4374 g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
4375 g_return_if_fail (fd);
4377 LOCK_CONTEXT (context);
4378 g_main_context_remove_poll_unlocked (context, fd);
4379 UNLOCK_CONTEXT (context);
4382 static void
4383 g_main_context_remove_poll_unlocked (GMainContext *context,
4384 GPollFD *fd)
4386 GPollRec *pollrec, *prevrec, *nextrec;
4388 prevrec = NULL;
4389 pollrec = context->poll_records;
4391 while (pollrec)
4393 nextrec = pollrec->next;
4394 if (pollrec->fd == fd)
4396 if (prevrec != NULL)
4397 prevrec->next = nextrec;
4398 else
4399 context->poll_records = nextrec;
4401 if (nextrec != NULL)
4402 nextrec->prev = prevrec;
4404 g_slice_free (GPollRec, pollrec);
4406 context->n_poll_records--;
4407 break;
4409 prevrec = pollrec;
4410 pollrec = nextrec;
4413 context->poll_changed = TRUE;
4415 /* Now wake up the main loop if it is waiting in the poll() */
4416 conditional_wakeup (context);
4420 * g_source_get_current_time:
4421 * @source: a #GSource
4422 * @timeval: #GTimeVal structure in which to store current time.
4424 * This function ignores @source and is otherwise the same as
4425 * g_get_current_time().
4427 * Deprecated: 2.28: use g_source_get_time() instead
4429 void
4430 g_source_get_current_time (GSource *source,
4431 GTimeVal *timeval)
4433 g_get_current_time (timeval);
4437 * g_source_get_time:
4438 * @source: a #GSource
4440 * Gets the time to be used when checking this source. The advantage of
4441 * calling this function over calling g_get_monotonic_time() directly is
4442 * that when checking multiple sources, GLib can cache a single value
4443 * instead of having to repeatedly get the system monotonic time.
4445 * The time here is the system monotonic time, if available, or some
4446 * other reasonable alternative otherwise. See g_get_monotonic_time().
4448 * Returns: the monotonic time in microseconds
4450 * Since: 2.28
4452 gint64
4453 g_source_get_time (GSource *source)
4455 GMainContext *context;
4456 gint64 result;
4458 g_return_val_if_fail (source->context != NULL, 0);
4460 context = source->context;
4462 LOCK_CONTEXT (context);
4464 if (!context->time_is_fresh)
4466 context->time = g_get_monotonic_time ();
4467 context->time_is_fresh = TRUE;
4470 result = context->time;
4472 UNLOCK_CONTEXT (context);
4474 return result;
4478 * g_main_context_set_poll_func:
4479 * @context: a #GMainContext
4480 * @func: the function to call to poll all file descriptors
4482 * Sets the function to use to handle polling of file descriptors. It
4483 * will be used instead of the poll() system call
4484 * (or GLib's replacement function, which is used where
4485 * poll() isn't available).
4487 * This function could possibly be used to integrate the GLib event
4488 * loop with an external event loop.
4490 void
4491 g_main_context_set_poll_func (GMainContext *context,
4492 GPollFunc func)
4494 if (!context)
4495 context = g_main_context_default ();
4497 g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
4499 LOCK_CONTEXT (context);
4501 if (func)
4502 context->poll_func = func;
4503 else
4504 context->poll_func = g_poll;
4506 UNLOCK_CONTEXT (context);
4510 * g_main_context_get_poll_func:
4511 * @context: a #GMainContext
4513 * Gets the poll function set by g_main_context_set_poll_func().
4515 * Returns: the poll function
4517 GPollFunc
4518 g_main_context_get_poll_func (GMainContext *context)
4520 GPollFunc result;
4522 if (!context)
4523 context = g_main_context_default ();
4525 g_return_val_if_fail (g_atomic_int_get (&context->ref_count) > 0, NULL);
4527 LOCK_CONTEXT (context);
4528 result = context->poll_func;
4529 UNLOCK_CONTEXT (context);
4531 return result;
4535 * g_main_context_wakeup:
4536 * @context: a #GMainContext
4538 * If @context is currently blocking in g_main_context_iteration()
4539 * waiting for a source to become ready, cause it to stop blocking
4540 * and return. Otherwise, cause the next invocation of
4541 * g_main_context_iteration() to return without blocking.
4543 * This API is useful for low-level control over #GMainContext; for
4544 * example, integrating it with main loop implementations such as
4545 * #GMainLoop.
4547 * Another related use for this function is when implementing a main
4548 * loop with a termination condition, computed from multiple threads:
4550 * |[<!-- language="C" -->
4551 * #define NUM_TASKS 10
4552 * static volatile gint tasks_remaining = NUM_TASKS;
4553 * ...
4555 * while (g_atomic_int_get (&tasks_remaining) != 0)
4556 * g_main_context_iteration (NULL, TRUE);
4557 * ]|
4559 * Then in a thread:
4560 * |[<!-- language="C" -->
4561 * perform_work();
4563 * if (g_atomic_int_dec_and_test (&tasks_remaining))
4564 * g_main_context_wakeup (NULL);
4565 * ]|
4567 void
4568 g_main_context_wakeup (GMainContext *context)
4570 if (!context)
4571 context = g_main_context_default ();
4573 g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
4575 TRACE (GLIB_MAIN_CONTEXT_WAKEUP (context));
4577 g_wakeup_signal (context->wakeup);
4581 * g_main_context_is_owner:
4582 * @context: a #GMainContext
4584 * Determines whether this thread holds the (recursive)
4585 * ownership of this #GMainContext. This is useful to
4586 * know before waiting on another thread that may be
4587 * blocking to get ownership of @context.
4589 * Returns: %TRUE if current thread is owner of @context.
4591 * Since: 2.10
4593 gboolean
4594 g_main_context_is_owner (GMainContext *context)
4596 gboolean is_owner;
4598 if (!context)
4599 context = g_main_context_default ();
4601 LOCK_CONTEXT (context);
4602 is_owner = context->owner == G_THREAD_SELF;
4603 UNLOCK_CONTEXT (context);
4605 return is_owner;
4608 /* Timeouts */
4610 static void
4611 g_timeout_set_expiration (GTimeoutSource *timeout_source,
4612 gint64 current_time)
4614 gint64 expiration;
4616 expiration = current_time + (guint64) timeout_source->interval * 1000;
4618 if (timeout_source->seconds)
4620 gint64 remainder;
4621 static gint timer_perturb = -1;
4623 if (timer_perturb == -1)
4626 * we want a per machine/session unique 'random' value; try the dbus
4627 * address first, that has a UUID in it. If there is no dbus, use the
4628 * hostname for hashing.
4630 const char *session_bus_address = g_getenv ("DBUS_SESSION_BUS_ADDRESS");
4631 if (!session_bus_address)
4632 session_bus_address = g_getenv ("HOSTNAME");
4633 if (session_bus_address)
4634 timer_perturb = ABS ((gint) g_str_hash (session_bus_address)) % 1000000;
4635 else
4636 timer_perturb = 0;
4639 /* We want the microseconds part of the timeout to land on the
4640 * 'timer_perturb' mark, but we need to make sure we don't try to
4641 * set the timeout in the past. We do this by ensuring that we
4642 * always only *increase* the expiration time by adding a full
4643 * second in the case that the microsecond portion decreases.
4645 expiration -= timer_perturb;
4647 remainder = expiration % 1000000;
4648 if (remainder >= 1000000/4)
4649 expiration += 1000000;
4651 expiration -= remainder;
4652 expiration += timer_perturb;
4655 g_source_set_ready_time ((GSource *) timeout_source, expiration);
4658 static gboolean
4659 g_timeout_dispatch (GSource *source,
4660 GSourceFunc callback,
4661 gpointer user_data)
4663 GTimeoutSource *timeout_source = (GTimeoutSource *)source;
4664 gboolean again;
4666 if (!callback)
4668 g_warning ("Timeout source dispatched without callback\n"
4669 "You must call g_source_set_callback().");
4670 return FALSE;
4673 again = callback (user_data);
4675 TRACE (GLIB_TIMEOUT_DISPATCH (source, source->context, callback, user_data, again));
4677 if (again)
4678 g_timeout_set_expiration (timeout_source, g_source_get_time (source));
4680 return again;
4684 * g_timeout_source_new:
4685 * @interval: the timeout interval in milliseconds.
4687 * Creates a new timeout source.
4689 * The source will not initially be associated with any #GMainContext
4690 * and must be added to one with g_source_attach() before it will be
4691 * executed.
4693 * The interval given is in terms of monotonic time, not wall clock
4694 * time. See g_get_monotonic_time().
4696 * Returns: the newly-created timeout source
4698 GSource *
4699 g_timeout_source_new (guint interval)
4701 GSource *source = g_source_new (&g_timeout_funcs, sizeof (GTimeoutSource));
4702 GTimeoutSource *timeout_source = (GTimeoutSource *)source;
4704 timeout_source->interval = interval;
4705 g_timeout_set_expiration (timeout_source, g_get_monotonic_time ());
4707 return source;
4711 * g_timeout_source_new_seconds:
4712 * @interval: the timeout interval in seconds
4714 * Creates a new timeout source.
4716 * The source will not initially be associated with any #GMainContext
4717 * and must be added to one with g_source_attach() before it will be
4718 * executed.
4720 * The scheduling granularity/accuracy of this timeout source will be
4721 * in seconds.
4723 * The interval given in terms of monotonic time, not wall clock time.
4724 * See g_get_monotonic_time().
4726 * Returns: the newly-created timeout source
4728 * Since: 2.14
4730 GSource *
4731 g_timeout_source_new_seconds (guint interval)
4733 GSource *source = g_source_new (&g_timeout_funcs, sizeof (GTimeoutSource));
4734 GTimeoutSource *timeout_source = (GTimeoutSource *)source;
4736 timeout_source->interval = 1000 * interval;
4737 timeout_source->seconds = TRUE;
4739 g_timeout_set_expiration (timeout_source, g_get_monotonic_time ());
4741 return source;
4746 * g_timeout_add_full: (rename-to g_timeout_add)
4747 * @priority: the priority of the timeout source. Typically this will be in
4748 * the range between #G_PRIORITY_DEFAULT and #G_PRIORITY_HIGH.
4749 * @interval: the time between calls to the function, in milliseconds
4750 * (1/1000ths of a second)
4751 * @function: function to call
4752 * @data: data to pass to @function
4753 * @notify: (nullable): function to call when the timeout is removed, or %NULL
4755 * Sets a function to be called at regular intervals, with the given
4756 * priority. The function is called repeatedly until it returns
4757 * %FALSE, at which point the timeout is automatically destroyed and
4758 * the function will not be called again. The @notify function is
4759 * called when the timeout is destroyed. The first call to the
4760 * function will be at the end of the first @interval.
4762 * Note that timeout functions may be delayed, due to the processing of other
4763 * event sources. Thus they should not be relied on for precise timing.
4764 * After each call to the timeout function, the time of the next
4765 * timeout is recalculated based on the current time and the given interval
4766 * (it does not try to 'catch up' time lost in delays).
4768 * See [memory management of sources][mainloop-memory-management] for details
4769 * on how to handle the return value and memory management of @data.
4771 * This internally creates a main loop source using g_timeout_source_new()
4772 * and attaches it to the global #GMainContext using g_source_attach(), so
4773 * the callback will be invoked in whichever thread is running that main
4774 * context. You can do these steps manually if you need greater control or to
4775 * use a custom main context.
4777 * The interval given in terms of monotonic time, not wall clock time.
4778 * See g_get_monotonic_time().
4780 * Returns: the ID (greater than 0) of the event source.
4782 guint
4783 g_timeout_add_full (gint priority,
4784 guint interval,
4785 GSourceFunc function,
4786 gpointer data,
4787 GDestroyNotify notify)
4789 GSource *source;
4790 guint id;
4792 g_return_val_if_fail (function != NULL, 0);
4794 source = g_timeout_source_new (interval);
4796 if (priority != G_PRIORITY_DEFAULT)
4797 g_source_set_priority (source, priority);
4799 g_source_set_callback (source, function, data, notify);
4800 id = g_source_attach (source, NULL);
4802 TRACE (GLIB_TIMEOUT_ADD (source, g_main_context_default (), id, priority, interval, function, data));
4804 g_source_unref (source);
4806 return id;
4810 * g_timeout_add:
4811 * @interval: the time between calls to the function, in milliseconds
4812 * (1/1000ths of a second)
4813 * @function: function to call
4814 * @data: data to pass to @function
4816 * Sets a function to be called at regular intervals, with the default
4817 * priority, #G_PRIORITY_DEFAULT. The function is called repeatedly
4818 * until it returns %FALSE, at which point the timeout is automatically
4819 * destroyed and the function will not be called again. The first call
4820 * to the function will be at the end of the first @interval.
4822 * Note that timeout functions may be delayed, due to the processing of other
4823 * event sources. Thus they should not be relied on for precise timing.
4824 * After each call to the timeout function, the time of the next
4825 * timeout is recalculated based on the current time and the given interval
4826 * (it does not try to 'catch up' time lost in delays).
4828 * See [memory management of sources][mainloop-memory-management] for details
4829 * on how to handle the return value and memory management of @data.
4831 * If you want to have a timer in the "seconds" range and do not care
4832 * about the exact time of the first call of the timer, use the
4833 * g_timeout_add_seconds() function; this function allows for more
4834 * optimizations and more efficient system power usage.
4836 * This internally creates a main loop source using g_timeout_source_new()
4837 * and attaches it to the global #GMainContext using g_source_attach(), so
4838 * the callback will be invoked in whichever thread is running that main
4839 * context. You can do these steps manually if you need greater control or to
4840 * use a custom main context.
4842 * The interval given is in terms of monotonic time, not wall clock
4843 * time. See g_get_monotonic_time().
4845 * Returns: the ID (greater than 0) of the event source.
4847 guint
4848 g_timeout_add (guint32 interval,
4849 GSourceFunc function,
4850 gpointer data)
4852 return g_timeout_add_full (G_PRIORITY_DEFAULT,
4853 interval, function, data, NULL);
4857 * g_timeout_add_seconds_full: (rename-to g_timeout_add_seconds)
4858 * @priority: the priority of the timeout source. Typically this will be in
4859 * the range between #G_PRIORITY_DEFAULT and #G_PRIORITY_HIGH.
4860 * @interval: the time between calls to the function, in seconds
4861 * @function: function to call
4862 * @data: data to pass to @function
4863 * @notify: (nullable): function to call when the timeout is removed, or %NULL
4865 * Sets a function to be called at regular intervals, with @priority.
4866 * The function is called repeatedly until it returns %FALSE, at which
4867 * point the timeout is automatically destroyed and the function will
4868 * not be called again.
4870 * Unlike g_timeout_add(), this function operates at whole second granularity.
4871 * The initial starting point of the timer is determined by the implementation
4872 * and the implementation is expected to group multiple timers together so that
4873 * they fire all at the same time.
4874 * To allow this grouping, the @interval to the first timer is rounded
4875 * and can deviate up to one second from the specified interval.
4876 * Subsequent timer iterations will generally run at the specified interval.
4878 * Note that timeout functions may be delayed, due to the processing of other
4879 * event sources. Thus they should not be relied on for precise timing.
4880 * After each call to the timeout function, the time of the next
4881 * timeout is recalculated based on the current time and the given @interval
4883 * See [memory management of sources][mainloop-memory-management] for details
4884 * on how to handle the return value and memory management of @data.
4886 * If you want timing more precise than whole seconds, use g_timeout_add()
4887 * instead.
4889 * The grouping of timers to fire at the same time results in a more power
4890 * and CPU efficient behavior so if your timer is in multiples of seconds
4891 * and you don't require the first timer exactly one second from now, the
4892 * use of g_timeout_add_seconds() is preferred over g_timeout_add().
4894 * This internally creates a main loop source using
4895 * g_timeout_source_new_seconds() and attaches it to the main loop context
4896 * using g_source_attach(). You can do these steps manually if you need
4897 * greater control.
4899 * The interval given is in terms of monotonic time, not wall clock
4900 * time. See g_get_monotonic_time().
4902 * Returns: the ID (greater than 0) of the event source.
4904 * Since: 2.14
4906 guint
4907 g_timeout_add_seconds_full (gint priority,
4908 guint32 interval,
4909 GSourceFunc function,
4910 gpointer data,
4911 GDestroyNotify notify)
4913 GSource *source;
4914 guint id;
4916 g_return_val_if_fail (function != NULL, 0);
4918 source = g_timeout_source_new_seconds (interval);
4920 if (priority != G_PRIORITY_DEFAULT)
4921 g_source_set_priority (source, priority);
4923 g_source_set_callback (source, function, data, notify);
4924 id = g_source_attach (source, NULL);
4925 g_source_unref (source);
4927 return id;
4931 * g_timeout_add_seconds:
4932 * @interval: the time between calls to the function, in seconds
4933 * @function: function to call
4934 * @data: data to pass to @function
4936 * Sets a function to be called at regular intervals with the default
4937 * priority, #G_PRIORITY_DEFAULT. The function is called repeatedly until
4938 * it returns %FALSE, at which point the timeout is automatically destroyed
4939 * and the function will not be called again.
4941 * This internally creates a main loop source using
4942 * g_timeout_source_new_seconds() and attaches it to the main loop context
4943 * using g_source_attach(). You can do these steps manually if you need
4944 * greater control. Also see g_timeout_add_seconds_full().
4946 * Note that the first call of the timer may not be precise for timeouts
4947 * of one second. If you need finer precision and have such a timeout,
4948 * you may want to use g_timeout_add() instead.
4950 * See [memory management of sources][mainloop-memory-management] for details
4951 * on how to handle the return value and memory management of @data.
4953 * The interval given is in terms of monotonic time, not wall clock
4954 * time. See g_get_monotonic_time().
4956 * Returns: the ID (greater than 0) of the event source.
4958 * Since: 2.14
4960 guint
4961 g_timeout_add_seconds (guint interval,
4962 GSourceFunc function,
4963 gpointer data)
4965 g_return_val_if_fail (function != NULL, 0);
4967 return g_timeout_add_seconds_full (G_PRIORITY_DEFAULT, interval, function, data, NULL);
4970 /* Child watch functions */
4972 #ifdef G_OS_WIN32
4974 static gboolean
4975 g_child_watch_prepare (GSource *source,
4976 gint *timeout)
4978 *timeout = -1;
4979 return FALSE;
4982 static gboolean
4983 g_child_watch_check (GSource *source)
4985 GChildWatchSource *child_watch_source;
4986 gboolean child_exited;
4988 child_watch_source = (GChildWatchSource *) source;
4990 child_exited = child_watch_source->poll.revents & G_IO_IN;
4992 if (child_exited)
4994 DWORD child_status;
4997 * Note: We do _not_ check for the special value of STILL_ACTIVE
4998 * since we know that the process has exited and doing so runs into
4999 * problems if the child process "happens to return STILL_ACTIVE(259)"
5000 * as Microsoft's Platform SDK puts it.
5002 if (!GetExitCodeProcess (child_watch_source->pid, &child_status))
5004 gchar *emsg = g_win32_error_message (GetLastError ());
5005 g_warning (G_STRLOC ": GetExitCodeProcess() failed: %s", emsg);
5006 g_free (emsg);
5008 child_watch_source->child_status = -1;
5010 else
5011 child_watch_source->child_status = child_status;
5014 return child_exited;
5017 static void
5018 g_child_watch_finalize (GSource *source)
5022 #else /* G_OS_WIN32 */
5024 static void
5025 wake_source (GSource *source)
5027 GMainContext *context;
5029 /* This should be thread-safe:
5031 * - if the source is currently being added to a context, that
5032 * context will be woken up anyway
5034 * - if the source is currently being destroyed, we simply need not
5035 * to crash:
5037 * - the memory for the source will remain valid until after the
5038 * source finalize function was called (which would remove the
5039 * source from the global list which we are currently holding the
5040 * lock for)
5042 * - the GMainContext will either be NULL or point to a live
5043 * GMainContext
5045 * - the GMainContext will remain valid since we hold the
5046 * main_context_list lock
5048 * Since we are holding a lot of locks here, don't try to enter any
5049 * more GMainContext functions for fear of dealock -- just hit the
5050 * GWakeup and run. Even if that's safe now, it could easily become
5051 * unsafe with some very minor changes in the future, and signal
5052 * handling is not the most well-tested codepath.
5054 G_LOCK(main_context_list);
5055 context = source->context;
5056 if (context)
5057 g_wakeup_signal (context->wakeup);
5058 G_UNLOCK(main_context_list);
5061 static void
5062 dispatch_unix_signals_unlocked (void)
5064 gboolean pending[NSIG];
5065 GSList *node;
5066 gint i;
5068 /* clear this first in case another one arrives while we're processing */
5069 any_unix_signal_pending = FALSE;
5071 /* We atomically test/clear the bit from the global array in case
5072 * other signals arrive while we are dispatching.
5074 * We then can safely use our own array below without worrying about
5075 * races.
5077 for (i = 0; i < NSIG; i++)
5079 /* Be very careful with (the volatile) unix_signal_pending.
5081 * We must ensure that it's not possible that we clear it without
5082 * handling the signal. We therefore must ensure that our pending
5083 * array has a field set (ie: we will do something about the
5084 * signal) before we clear the item in unix_signal_pending.
5086 * Note specifically: we must check _our_ array.
5088 pending[i] = unix_signal_pending[i];
5089 if (pending[i])
5090 unix_signal_pending[i] = FALSE;
5093 /* handle GChildWatchSource instances */
5094 if (pending[SIGCHLD])
5096 /* The only way we can do this is to scan all of the children.
5098 * The docs promise that we will not reap children that we are not
5099 * explicitly watching, so that ties our hands from calling
5100 * waitpid(-1). We also can't use siginfo's si_pid field since if
5101 * multiple SIGCHLD arrive at the same time, one of them can be
5102 * dropped (since a given UNIX signal can only be pending once).
5104 for (node = unix_child_watches; node; node = node->next)
5106 GChildWatchSource *source = node->data;
5108 if (!source->child_exited)
5110 pid_t pid;
5113 g_assert (source->pid > 0);
5115 pid = waitpid (source->pid, &source->child_status, WNOHANG);
5116 if (pid > 0)
5118 source->child_exited = TRUE;
5119 wake_source ((GSource *) source);
5121 else if (pid == -1 && errno == ECHILD)
5123 g_warning ("GChildWatchSource: Exit status of a child process was requested but ECHILD was received by waitpid(). See the documentation of g_child_watch_source_new() for possible causes.");
5124 source->child_exited = TRUE;
5125 source->child_status = 0;
5126 wake_source ((GSource *) source);
5129 while (pid == -1 && errno == EINTR);
5134 /* handle GUnixSignalWatchSource instances */
5135 for (node = unix_signal_watches; node; node = node->next)
5137 GUnixSignalWatchSource *source = node->data;
5139 if (!source->pending)
5141 if (pending[source->signum])
5143 source->pending = TRUE;
5145 wake_source ((GSource *) source);
5152 static void
5153 dispatch_unix_signals (void)
5155 G_LOCK(unix_signal_lock);
5156 dispatch_unix_signals_unlocked ();
5157 G_UNLOCK(unix_signal_lock);
5160 static gboolean
5161 g_child_watch_prepare (GSource *source,
5162 gint *timeout)
5164 GChildWatchSource *child_watch_source;
5166 child_watch_source = (GChildWatchSource *) source;
5168 return child_watch_source->child_exited;
5171 static gboolean
5172 g_child_watch_check (GSource *source)
5174 GChildWatchSource *child_watch_source;
5176 child_watch_source = (GChildWatchSource *) source;
5178 return child_watch_source->child_exited;
5181 static gboolean
5182 g_unix_signal_watch_prepare (GSource *source,
5183 gint *timeout)
5185 GUnixSignalWatchSource *unix_signal_source;
5187 unix_signal_source = (GUnixSignalWatchSource *) source;
5189 return unix_signal_source->pending;
5192 static gboolean
5193 g_unix_signal_watch_check (GSource *source)
5195 GUnixSignalWatchSource *unix_signal_source;
5197 unix_signal_source = (GUnixSignalWatchSource *) source;
5199 return unix_signal_source->pending;
5202 static gboolean
5203 g_unix_signal_watch_dispatch (GSource *source,
5204 GSourceFunc callback,
5205 gpointer user_data)
5207 GUnixSignalWatchSource *unix_signal_source;
5208 gboolean again;
5210 unix_signal_source = (GUnixSignalWatchSource *) source;
5212 if (!callback)
5214 g_warning ("Unix signal source dispatched without callback\n"
5215 "You must call g_source_set_callback().");
5216 return FALSE;
5219 again = (callback) (user_data);
5221 unix_signal_source->pending = FALSE;
5223 return again;
5226 static void
5227 ref_unix_signal_handler_unlocked (int signum)
5229 /* Ensure we have the worker context */
5230 g_get_worker_context ();
5231 unix_signal_refcount[signum]++;
5232 if (unix_signal_refcount[signum] == 1)
5234 struct sigaction action;
5235 action.sa_handler = g_unix_signal_handler;
5236 sigemptyset (&action.sa_mask);
5237 #ifdef SA_RESTART
5238 action.sa_flags = SA_RESTART | SA_NOCLDSTOP;
5239 #else
5240 action.sa_flags = SA_NOCLDSTOP;
5241 #endif
5242 sigaction (signum, &action, NULL);
5246 static void
5247 unref_unix_signal_handler_unlocked (int signum)
5249 unix_signal_refcount[signum]--;
5250 if (unix_signal_refcount[signum] == 0)
5252 struct sigaction action;
5253 memset (&action, 0, sizeof (action));
5254 action.sa_handler = SIG_DFL;
5255 sigemptyset (&action.sa_mask);
5256 sigaction (signum, &action, NULL);
5260 GSource *
5261 _g_main_create_unix_signal_watch (int signum)
5263 GSource *source;
5264 GUnixSignalWatchSource *unix_signal_source;
5266 source = g_source_new (&g_unix_signal_funcs, sizeof (GUnixSignalWatchSource));
5267 unix_signal_source = (GUnixSignalWatchSource *) source;
5269 unix_signal_source->signum = signum;
5270 unix_signal_source->pending = FALSE;
5272 G_LOCK (unix_signal_lock);
5273 ref_unix_signal_handler_unlocked (signum);
5274 unix_signal_watches = g_slist_prepend (unix_signal_watches, unix_signal_source);
5275 dispatch_unix_signals_unlocked ();
5276 G_UNLOCK (unix_signal_lock);
5278 return source;
5281 static void
5282 g_unix_signal_watch_finalize (GSource *source)
5284 GUnixSignalWatchSource *unix_signal_source;
5286 unix_signal_source = (GUnixSignalWatchSource *) source;
5288 G_LOCK (unix_signal_lock);
5289 unref_unix_signal_handler_unlocked (unix_signal_source->signum);
5290 unix_signal_watches = g_slist_remove (unix_signal_watches, source);
5291 G_UNLOCK (unix_signal_lock);
5294 static void
5295 g_child_watch_finalize (GSource *source)
5297 G_LOCK (unix_signal_lock);
5298 unix_child_watches = g_slist_remove (unix_child_watches, source);
5299 unref_unix_signal_handler_unlocked (SIGCHLD);
5300 G_UNLOCK (unix_signal_lock);
5303 #endif /* G_OS_WIN32 */
5305 static gboolean
5306 g_child_watch_dispatch (GSource *source,
5307 GSourceFunc callback,
5308 gpointer user_data)
5310 GChildWatchSource *child_watch_source;
5311 GChildWatchFunc child_watch_callback = (GChildWatchFunc) callback;
5313 child_watch_source = (GChildWatchSource *) source;
5315 if (!callback)
5317 g_warning ("Child watch source dispatched without callback\n"
5318 "You must call g_source_set_callback().");
5319 return FALSE;
5322 (child_watch_callback) (child_watch_source->pid, child_watch_source->child_status, user_data);
5324 /* We never keep a child watch source around as the child is gone */
5325 return FALSE;
5328 #ifndef G_OS_WIN32
5330 static void
5331 g_unix_signal_handler (int signum)
5333 gint saved_errno = errno;
5335 unix_signal_pending[signum] = TRUE;
5336 any_unix_signal_pending = TRUE;
5338 g_wakeup_signal (glib_worker_context->wakeup);
5340 errno = saved_errno;
5343 #endif /* !G_OS_WIN32 */
5346 * g_child_watch_source_new:
5347 * @pid: process to watch. On POSIX the positive pid of a child process. On
5348 * Windows a handle for a process (which doesn't have to be a child).
5350 * Creates a new child_watch source.
5352 * The source will not initially be associated with any #GMainContext
5353 * and must be added to one with g_source_attach() before it will be
5354 * executed.
5356 * Note that child watch sources can only be used in conjunction with
5357 * `g_spawn...` when the %G_SPAWN_DO_NOT_REAP_CHILD flag is used.
5359 * Note that on platforms where #GPid must be explicitly closed
5360 * (see g_spawn_close_pid()) @pid must not be closed while the
5361 * source is still active. Typically, you will want to call
5362 * g_spawn_close_pid() in the callback function for the source.
5364 * On POSIX platforms, the following restrictions apply to this API
5365 * due to limitations in POSIX process interfaces:
5367 * * @pid must be a child of this process
5368 * * @pid must be positive
5369 * * the application must not call `waitpid` with a non-positive
5370 * first argument, for instance in another thread
5371 * * the application must not wait for @pid to exit by any other
5372 * mechanism, including `waitpid(pid, ...)` or a second child-watch
5373 * source for the same @pid
5374 * * the application must not ignore SIGCHILD
5376 * If any of those conditions are not met, this and related APIs will
5377 * not work correctly. This can often be diagnosed via a GLib warning
5378 * stating that `ECHILD` was received by `waitpid`.
5380 * Calling `waitpid` for specific processes other than @pid remains a
5381 * valid thing to do.
5383 * Returns: the newly-created child watch source
5385 * Since: 2.4
5387 GSource *
5388 g_child_watch_source_new (GPid pid)
5390 GSource *source;
5391 GChildWatchSource *child_watch_source;
5393 #ifndef G_OS_WIN32
5394 g_return_val_if_fail (pid > 0, NULL);
5395 #endif
5397 source = g_source_new (&g_child_watch_funcs, sizeof (GChildWatchSource));
5398 child_watch_source = (GChildWatchSource *)source;
5400 child_watch_source->pid = pid;
5402 #ifdef G_OS_WIN32
5403 child_watch_source->poll.fd = (gintptr) pid;
5404 child_watch_source->poll.events = G_IO_IN;
5406 g_source_add_poll (source, &child_watch_source->poll);
5407 #else /* G_OS_WIN32 */
5408 G_LOCK (unix_signal_lock);
5409 ref_unix_signal_handler_unlocked (SIGCHLD);
5410 unix_child_watches = g_slist_prepend (unix_child_watches, child_watch_source);
5411 if (waitpid (pid, &child_watch_source->child_status, WNOHANG) > 0)
5412 child_watch_source->child_exited = TRUE;
5413 G_UNLOCK (unix_signal_lock);
5414 #endif /* G_OS_WIN32 */
5416 return source;
5420 * g_child_watch_add_full: (rename-to g_child_watch_add)
5421 * @priority: the priority of the idle source. Typically this will be in the
5422 * range between #G_PRIORITY_DEFAULT_IDLE and #G_PRIORITY_HIGH_IDLE.
5423 * @pid: process to watch. On POSIX the positive pid of a child process. On
5424 * Windows a handle for a process (which doesn't have to be a child).
5425 * @function: function to call
5426 * @data: data to pass to @function
5427 * @notify: (nullable): function to call when the idle is removed, or %NULL
5429 * Sets a function to be called when the child indicated by @pid
5430 * exits, at the priority @priority.
5432 * If you obtain @pid from g_spawn_async() or g_spawn_async_with_pipes()
5433 * you will need to pass #G_SPAWN_DO_NOT_REAP_CHILD as flag to
5434 * the spawn function for the child watching to work.
5436 * In many programs, you will want to call g_spawn_check_exit_status()
5437 * in the callback to determine whether or not the child exited
5438 * successfully.
5440 * Also, note that on platforms where #GPid must be explicitly closed
5441 * (see g_spawn_close_pid()) @pid must not be closed while the source
5442 * is still active. Typically, you should invoke g_spawn_close_pid()
5443 * in the callback function for the source.
5445 * GLib supports only a single callback per process id.
5446 * On POSIX platforms, the same restrictions mentioned for
5447 * g_child_watch_source_new() apply to this function.
5449 * This internally creates a main loop source using
5450 * g_child_watch_source_new() and attaches it to the main loop context
5451 * using g_source_attach(). You can do these steps manually if you
5452 * need greater control.
5454 * Returns: the ID (greater than 0) of the event source.
5456 * Since: 2.4
5458 guint
5459 g_child_watch_add_full (gint priority,
5460 GPid pid,
5461 GChildWatchFunc function,
5462 gpointer data,
5463 GDestroyNotify notify)
5465 GSource *source;
5466 guint id;
5468 g_return_val_if_fail (function != NULL, 0);
5469 #ifndef G_OS_WIN32
5470 g_return_val_if_fail (pid > 0, 0);
5471 #endif
5473 source = g_child_watch_source_new (pid);
5475 if (priority != G_PRIORITY_DEFAULT)
5476 g_source_set_priority (source, priority);
5478 g_source_set_callback (source, (GSourceFunc) function, data, notify);
5479 id = g_source_attach (source, NULL);
5480 g_source_unref (source);
5482 return id;
5486 * g_child_watch_add:
5487 * @pid: process id to watch. On POSIX the positive pid of a child
5488 * process. On Windows a handle for a process (which doesn't have to be
5489 * a child).
5490 * @function: function to call
5491 * @data: data to pass to @function
5493 * Sets a function to be called when the child indicated by @pid
5494 * exits, at a default priority, #G_PRIORITY_DEFAULT.
5496 * If you obtain @pid from g_spawn_async() or g_spawn_async_with_pipes()
5497 * you will need to pass #G_SPAWN_DO_NOT_REAP_CHILD as flag to
5498 * the spawn function for the child watching to work.
5500 * Note that on platforms where #GPid must be explicitly closed
5501 * (see g_spawn_close_pid()) @pid must not be closed while the
5502 * source is still active. Typically, you will want to call
5503 * g_spawn_close_pid() in the callback function for the source.
5505 * GLib supports only a single callback per process id.
5506 * On POSIX platforms, the same restrictions mentioned for
5507 * g_child_watch_source_new() apply to this function.
5509 * This internally creates a main loop source using
5510 * g_child_watch_source_new() and attaches it to the main loop context
5511 * using g_source_attach(). You can do these steps manually if you
5512 * need greater control.
5514 * Returns: the ID (greater than 0) of the event source.
5516 * Since: 2.4
5518 guint
5519 g_child_watch_add (GPid pid,
5520 GChildWatchFunc function,
5521 gpointer data)
5523 return g_child_watch_add_full (G_PRIORITY_DEFAULT, pid, function, data, NULL);
5527 /* Idle functions */
5529 static gboolean
5530 g_idle_prepare (GSource *source,
5531 gint *timeout)
5533 *timeout = 0;
5535 return TRUE;
5538 static gboolean
5539 g_idle_check (GSource *source)
5541 return TRUE;
5544 static gboolean
5545 g_idle_dispatch (GSource *source,
5546 GSourceFunc callback,
5547 gpointer user_data)
5549 gboolean again;
5551 if (!callback)
5553 g_warning ("Idle source dispatched without callback\n"
5554 "You must call g_source_set_callback().");
5555 return FALSE;
5558 again = callback (user_data);
5560 TRACE (GLIB_IDLE_DISPATCH (source, source->context, callback, user_data, again));
5562 return again;
5566 * g_idle_source_new:
5568 * Creates a new idle source.
5570 * The source will not initially be associated with any #GMainContext
5571 * and must be added to one with g_source_attach() before it will be
5572 * executed. Note that the default priority for idle sources is
5573 * %G_PRIORITY_DEFAULT_IDLE, as compared to other sources which
5574 * have a default priority of %G_PRIORITY_DEFAULT.
5576 * Returns: the newly-created idle source
5578 GSource *
5579 g_idle_source_new (void)
5581 GSource *source;
5583 source = g_source_new (&g_idle_funcs, sizeof (GSource));
5584 g_source_set_priority (source, G_PRIORITY_DEFAULT_IDLE);
5586 return source;
5590 * g_idle_add_full: (rename-to g_idle_add)
5591 * @priority: the priority of the idle source. Typically this will be in the
5592 * range between #G_PRIORITY_DEFAULT_IDLE and #G_PRIORITY_HIGH_IDLE.
5593 * @function: function to call
5594 * @data: data to pass to @function
5595 * @notify: (nullable): function to call when the idle is removed, or %NULL
5597 * Adds a function to be called whenever there are no higher priority
5598 * events pending. If the function returns %FALSE it is automatically
5599 * removed from the list of event sources and will not be called again.
5601 * See [memory management of sources][mainloop-memory-management] for details
5602 * on how to handle the return value and memory management of @data.
5604 * This internally creates a main loop source using g_idle_source_new()
5605 * and attaches it to the global #GMainContext using g_source_attach(), so
5606 * the callback will be invoked in whichever thread is running that main
5607 * context. You can do these steps manually if you need greater control or to
5608 * use a custom main context.
5610 * Returns: the ID (greater than 0) of the event source.
5612 guint
5613 g_idle_add_full (gint priority,
5614 GSourceFunc function,
5615 gpointer data,
5616 GDestroyNotify notify)
5618 GSource *source;
5619 guint id;
5621 g_return_val_if_fail (function != NULL, 0);
5623 source = g_idle_source_new ();
5625 if (priority != G_PRIORITY_DEFAULT_IDLE)
5626 g_source_set_priority (source, priority);
5628 g_source_set_callback (source, function, data, notify);
5629 id = g_source_attach (source, NULL);
5631 TRACE (GLIB_IDLE_ADD (source, g_main_context_default (), id, priority, function, data));
5633 g_source_unref (source);
5635 return id;
5639 * g_idle_add:
5640 * @function: function to call
5641 * @data: data to pass to @function.
5643 * Adds a function to be called whenever there are no higher priority
5644 * events pending to the default main loop. The function is given the
5645 * default idle priority, #G_PRIORITY_DEFAULT_IDLE. If the function
5646 * returns %FALSE it is automatically removed from the list of event
5647 * sources and will not be called again.
5649 * See [memory management of sources][mainloop-memory-management] for details
5650 * on how to handle the return value and memory management of @data.
5652 * This internally creates a main loop source using g_idle_source_new()
5653 * and attaches it to the global #GMainContext using g_source_attach(), so
5654 * the callback will be invoked in whichever thread is running that main
5655 * context. You can do these steps manually if you need greater control or to
5656 * use a custom main context.
5658 * Returns: the ID (greater than 0) of the event source.
5660 guint
5661 g_idle_add (GSourceFunc function,
5662 gpointer data)
5664 return g_idle_add_full (G_PRIORITY_DEFAULT_IDLE, function, data, NULL);
5668 * g_idle_remove_by_data:
5669 * @data: the data for the idle source's callback.
5671 * Removes the idle function with the given data.
5673 * Returns: %TRUE if an idle source was found and removed.
5675 gboolean
5676 g_idle_remove_by_data (gpointer data)
5678 return g_source_remove_by_funcs_user_data (&g_idle_funcs, data);
5682 * g_main_context_invoke:
5683 * @context: (nullable): a #GMainContext, or %NULL
5684 * @function: function to call
5685 * @data: data to pass to @function
5687 * Invokes a function in such a way that @context is owned during the
5688 * invocation of @function.
5690 * If @context is %NULL then the global default main context — as
5691 * returned by g_main_context_default() — is used.
5693 * If @context is owned by the current thread, @function is called
5694 * directly. Otherwise, if @context is the thread-default main context
5695 * of the current thread and g_main_context_acquire() succeeds, then
5696 * @function is called and g_main_context_release() is called
5697 * afterwards.
5699 * In any other case, an idle source is created to call @function and
5700 * that source is attached to @context (presumably to be run in another
5701 * thread). The idle source is attached with #G_PRIORITY_DEFAULT
5702 * priority. If you want a different priority, use
5703 * g_main_context_invoke_full().
5705 * Note that, as with normal idle functions, @function should probably
5706 * return %FALSE. If it returns %TRUE, it will be continuously run in a
5707 * loop (and may prevent this call from returning).
5709 * Since: 2.28
5711 void
5712 g_main_context_invoke (GMainContext *context,
5713 GSourceFunc function,
5714 gpointer data)
5716 g_main_context_invoke_full (context,
5717 G_PRIORITY_DEFAULT,
5718 function, data, NULL);
5722 * g_main_context_invoke_full:
5723 * @context: (nullable): a #GMainContext, or %NULL
5724 * @priority: the priority at which to run @function
5725 * @function: function to call
5726 * @data: data to pass to @function
5727 * @notify: (nullable): a function to call when @data is no longer in use, or %NULL.
5729 * Invokes a function in such a way that @context is owned during the
5730 * invocation of @function.
5732 * This function is the same as g_main_context_invoke() except that it
5733 * lets you specify the priority in case @function ends up being
5734 * scheduled as an idle and also lets you give a #GDestroyNotify for @data.
5736 * @notify should not assume that it is called from any particular
5737 * thread or with any particular context acquired.
5739 * Since: 2.28
5741 void
5742 g_main_context_invoke_full (GMainContext *context,
5743 gint priority,
5744 GSourceFunc function,
5745 gpointer data,
5746 GDestroyNotify notify)
5748 g_return_if_fail (function != NULL);
5750 if (!context)
5751 context = g_main_context_default ();
5753 if (g_main_context_is_owner (context))
5755 while (function (data));
5756 if (notify != NULL)
5757 notify (data);
5760 else
5762 GMainContext *thread_default;
5764 thread_default = g_main_context_get_thread_default ();
5766 if (!thread_default)
5767 thread_default = g_main_context_default ();
5769 if (thread_default == context && g_main_context_acquire (context))
5771 while (function (data));
5773 g_main_context_release (context);
5775 if (notify != NULL)
5776 notify (data);
5778 else
5780 GSource *source;
5782 source = g_idle_source_new ();
5783 g_source_set_priority (source, priority);
5784 g_source_set_callback (source, function, data, notify);
5785 g_source_attach (source, context);
5786 g_source_unref (source);
5791 static gpointer
5792 glib_worker_main (gpointer data)
5794 while (TRUE)
5796 g_main_context_iteration (glib_worker_context, TRUE);
5798 #ifdef G_OS_UNIX
5799 if (any_unix_signal_pending)
5800 dispatch_unix_signals ();
5801 #endif
5804 return NULL; /* worst GCC warning message ever... */
5807 GMainContext *
5808 g_get_worker_context (void)
5810 static gsize initialised;
5812 if (g_once_init_enter (&initialised))
5814 /* mask all signals in the worker thread */
5815 #ifdef G_OS_UNIX
5816 sigset_t prev_mask;
5817 sigset_t all;
5819 sigfillset (&all);
5820 pthread_sigmask (SIG_SETMASK, &all, &prev_mask);
5821 #endif
5822 glib_worker_context = g_main_context_new ();
5823 g_thread_new ("gmain", glib_worker_main, NULL);
5824 #ifdef G_OS_UNIX
5825 pthread_sigmask (SIG_SETMASK, &prev_mask, NULL);
5826 #endif
5827 g_once_init_leave (&initialised, TRUE);
5830 return glib_worker_context;