Merge branch 'source-get-id-docs' into 'master'
[glib.git] / glib / gmain.c
blob5f0b05198e23684176ddd8b5fafc5892b2c7d235
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 static guint
1122 g_source_attach_unlocked (GSource *source,
1123 GMainContext *context,
1124 gboolean do_wakeup)
1126 GSList *tmp_list;
1127 guint id;
1129 /* The counter may have wrapped, so we must ensure that we do not
1130 * reuse the source id of an existing source.
1133 id = context->next_id++;
1134 while (id == 0 || g_hash_table_contains (context->sources, GUINT_TO_POINTER (id)));
1136 source->context = context;
1137 source->source_id = id;
1138 source->ref_count++;
1140 g_hash_table_insert (context->sources, GUINT_TO_POINTER (id), source);
1142 source_add_to_context (source, context);
1144 if (!SOURCE_BLOCKED (source))
1146 tmp_list = source->poll_fds;
1147 while (tmp_list)
1149 g_main_context_add_poll_unlocked (context, source->priority, tmp_list->data);
1150 tmp_list = tmp_list->next;
1153 for (tmp_list = source->priv->fds; tmp_list; tmp_list = tmp_list->next)
1154 g_main_context_add_poll_unlocked (context, source->priority, tmp_list->data);
1157 tmp_list = source->priv->child_sources;
1158 while (tmp_list)
1160 g_source_attach_unlocked (tmp_list->data, context, FALSE);
1161 tmp_list = tmp_list->next;
1164 /* If another thread has acquired the context, wake it up since it
1165 * might be in poll() right now.
1167 if (do_wakeup && context->owner && context->owner != G_THREAD_SELF)
1168 g_wakeup_signal (context->wakeup);
1170 return source->source_id;
1174 * g_source_attach:
1175 * @source: a #GSource
1176 * @context: (nullable): a #GMainContext (if %NULL, the default context will be used)
1178 * Adds a #GSource to a @context so that it will be executed within
1179 * that context. Remove it by calling g_source_destroy().
1181 * Returns: the ID (greater than 0) for the source within the
1182 * #GMainContext.
1184 guint
1185 g_source_attach (GSource *source,
1186 GMainContext *context)
1188 guint result = 0;
1190 g_return_val_if_fail (source->context == NULL, 0);
1191 g_return_val_if_fail (!SOURCE_DESTROYED (source), 0);
1193 if (!context)
1194 context = g_main_context_default ();
1196 LOCK_CONTEXT (context);
1198 result = g_source_attach_unlocked (source, context, TRUE);
1200 TRACE (GLIB_MAIN_SOURCE_ATTACH (g_source_get_name (source), source, context,
1201 result));
1203 UNLOCK_CONTEXT (context);
1205 return result;
1208 static void
1209 g_source_destroy_internal (GSource *source,
1210 GMainContext *context,
1211 gboolean have_lock)
1213 TRACE (GLIB_MAIN_SOURCE_DESTROY (g_source_get_name (source), source,
1214 context));
1216 if (!have_lock)
1217 LOCK_CONTEXT (context);
1219 if (!SOURCE_DESTROYED (source))
1221 GSList *tmp_list;
1222 gpointer old_cb_data;
1223 GSourceCallbackFuncs *old_cb_funcs;
1225 source->flags &= ~G_HOOK_FLAG_ACTIVE;
1227 old_cb_data = source->callback_data;
1228 old_cb_funcs = source->callback_funcs;
1230 source->callback_data = NULL;
1231 source->callback_funcs = NULL;
1233 if (old_cb_funcs)
1235 UNLOCK_CONTEXT (context);
1236 old_cb_funcs->unref (old_cb_data);
1237 LOCK_CONTEXT (context);
1240 if (!SOURCE_BLOCKED (source))
1242 tmp_list = source->poll_fds;
1243 while (tmp_list)
1245 g_main_context_remove_poll_unlocked (context, tmp_list->data);
1246 tmp_list = tmp_list->next;
1249 for (tmp_list = source->priv->fds; tmp_list; tmp_list = tmp_list->next)
1250 g_main_context_remove_poll_unlocked (context, tmp_list->data);
1253 while (source->priv->child_sources)
1254 g_child_source_remove_internal (source->priv->child_sources->data, context);
1256 if (source->priv->parent_source)
1257 g_child_source_remove_internal (source, context);
1259 g_source_unref_internal (source, context, TRUE);
1262 if (!have_lock)
1263 UNLOCK_CONTEXT (context);
1267 * g_source_destroy:
1268 * @source: a #GSource
1270 * Removes a source from its #GMainContext, if any, and mark it as
1271 * destroyed. The source cannot be subsequently added to another
1272 * context. It is safe to call this on sources which have already been
1273 * removed from their context.
1275 void
1276 g_source_destroy (GSource *source)
1278 GMainContext *context;
1280 g_return_if_fail (source != NULL);
1282 context = source->context;
1284 if (context)
1285 g_source_destroy_internal (source, context, FALSE);
1286 else
1287 source->flags &= ~G_HOOK_FLAG_ACTIVE;
1291 * g_source_get_id:
1292 * @source: a #GSource
1294 * Returns the numeric ID for a particular source. The ID of a source
1295 * is a positive integer which is unique within a particular main loop
1296 * context. The reverse
1297 * mapping from ID to source is done by g_main_context_find_source_by_id().
1299 * You can only call this function while the source is associated to a
1300 * #GMainContext instance; calling this function before g_source_attach()
1301 * or after g_source_destroy() yields undefined behavior. The ID returned
1302 * is unique within the #GMainContext instance passed to g_source_attach().
1304 * Returns: the ID (greater than 0) for the source
1306 guint
1307 g_source_get_id (GSource *source)
1309 guint result;
1311 g_return_val_if_fail (source != NULL, 0);
1312 g_return_val_if_fail (source->context != NULL, 0);
1314 LOCK_CONTEXT (source->context);
1315 result = source->source_id;
1316 UNLOCK_CONTEXT (source->context);
1318 return result;
1322 * g_source_get_context:
1323 * @source: a #GSource
1325 * Gets the #GMainContext with which the source is associated.
1327 * You can call this on a source that has been destroyed, provided
1328 * that the #GMainContext it was attached to still exists (in which
1329 * case it will return that #GMainContext). In particular, you can
1330 * always call this function on the source returned from
1331 * g_main_current_source(). But calling this function on a source
1332 * whose #GMainContext has been destroyed is an error.
1334 * Returns: (transfer none) (nullable): the #GMainContext with which the
1335 * source is associated, or %NULL if the context has not
1336 * yet been added to a source.
1338 GMainContext *
1339 g_source_get_context (GSource *source)
1341 g_return_val_if_fail (source->context != NULL || !SOURCE_DESTROYED (source), NULL);
1343 return source->context;
1347 * g_source_add_poll:
1348 * @source:a #GSource
1349 * @fd: a #GPollFD structure holding information about a file
1350 * descriptor to watch.
1352 * Adds a file descriptor to the set of file descriptors polled for
1353 * this source. This is usually combined with g_source_new() to add an
1354 * event source. The event source's check function will typically test
1355 * the @revents field in the #GPollFD struct and return %TRUE if events need
1356 * to be processed.
1358 * This API is only intended to be used by implementations of #GSource.
1359 * Do not call this API on a #GSource that you did not create.
1361 * Using this API forces the linear scanning of event sources on each
1362 * main loop iteration. Newly-written event sources should try to use
1363 * g_source_add_unix_fd() instead of this API.
1365 void
1366 g_source_add_poll (GSource *source,
1367 GPollFD *fd)
1369 GMainContext *context;
1371 g_return_if_fail (source != NULL);
1372 g_return_if_fail (fd != NULL);
1373 g_return_if_fail (!SOURCE_DESTROYED (source));
1375 context = source->context;
1377 if (context)
1378 LOCK_CONTEXT (context);
1380 source->poll_fds = g_slist_prepend (source->poll_fds, fd);
1382 if (context)
1384 if (!SOURCE_BLOCKED (source))
1385 g_main_context_add_poll_unlocked (context, source->priority, fd);
1386 UNLOCK_CONTEXT (context);
1391 * g_source_remove_poll:
1392 * @source:a #GSource
1393 * @fd: a #GPollFD structure previously passed to g_source_add_poll().
1395 * Removes a file descriptor from the set of file descriptors polled for
1396 * this source.
1398 * This API is only intended to be used by implementations of #GSource.
1399 * Do not call this API on a #GSource that you did not create.
1401 void
1402 g_source_remove_poll (GSource *source,
1403 GPollFD *fd)
1405 GMainContext *context;
1407 g_return_if_fail (source != NULL);
1408 g_return_if_fail (fd != NULL);
1409 g_return_if_fail (!SOURCE_DESTROYED (source));
1411 context = source->context;
1413 if (context)
1414 LOCK_CONTEXT (context);
1416 source->poll_fds = g_slist_remove (source->poll_fds, fd);
1418 if (context)
1420 if (!SOURCE_BLOCKED (source))
1421 g_main_context_remove_poll_unlocked (context, fd);
1422 UNLOCK_CONTEXT (context);
1427 * g_source_add_child_source:
1428 * @source:a #GSource
1429 * @child_source: a second #GSource that @source should "poll"
1431 * Adds @child_source to @source as a "polled" source; when @source is
1432 * added to a #GMainContext, @child_source will be automatically added
1433 * with the same priority, when @child_source is triggered, it will
1434 * cause @source to dispatch (in addition to calling its own
1435 * callback), and when @source is destroyed, it will destroy
1436 * @child_source as well. (@source will also still be dispatched if
1437 * its own prepare/check functions indicate that it is ready.)
1439 * If you don't need @child_source to do anything on its own when it
1440 * triggers, you can call g_source_set_dummy_callback() on it to set a
1441 * callback that does nothing (except return %TRUE if appropriate).
1443 * @source will hold a reference on @child_source while @child_source
1444 * is attached to it.
1446 * This API is only intended to be used by implementations of #GSource.
1447 * Do not call this API on a #GSource that you did not create.
1449 * Since: 2.28
1451 void
1452 g_source_add_child_source (GSource *source,
1453 GSource *child_source)
1455 GMainContext *context;
1457 g_return_if_fail (source != NULL);
1458 g_return_if_fail (child_source != NULL);
1459 g_return_if_fail (!SOURCE_DESTROYED (source));
1460 g_return_if_fail (!SOURCE_DESTROYED (child_source));
1461 g_return_if_fail (child_source->context == NULL);
1462 g_return_if_fail (child_source->priv->parent_source == NULL);
1464 context = source->context;
1466 if (context)
1467 LOCK_CONTEXT (context);
1469 TRACE (GLIB_SOURCE_ADD_CHILD_SOURCE (source, child_source));
1471 source->priv->child_sources = g_slist_prepend (source->priv->child_sources,
1472 g_source_ref (child_source));
1473 child_source->priv->parent_source = source;
1474 g_source_set_priority_unlocked (child_source, NULL, source->priority);
1475 if (SOURCE_BLOCKED (source))
1476 block_source (child_source);
1478 if (context)
1480 g_source_attach_unlocked (child_source, context, TRUE);
1481 UNLOCK_CONTEXT (context);
1485 static void
1486 g_child_source_remove_internal (GSource *child_source,
1487 GMainContext *context)
1489 GSource *parent_source = child_source->priv->parent_source;
1491 parent_source->priv->child_sources =
1492 g_slist_remove (parent_source->priv->child_sources, child_source);
1493 child_source->priv->parent_source = NULL;
1495 g_source_destroy_internal (child_source, context, TRUE);
1496 g_source_unref_internal (child_source, context, TRUE);
1500 * g_source_remove_child_source:
1501 * @source:a #GSource
1502 * @child_source: a #GSource previously passed to
1503 * g_source_add_child_source().
1505 * Detaches @child_source from @source and destroys it.
1507 * This API is only intended to be used by implementations of #GSource.
1508 * Do not call this API on a #GSource that you did not create.
1510 * Since: 2.28
1512 void
1513 g_source_remove_child_source (GSource *source,
1514 GSource *child_source)
1516 GMainContext *context;
1518 g_return_if_fail (source != NULL);
1519 g_return_if_fail (child_source != NULL);
1520 g_return_if_fail (child_source->priv->parent_source == source);
1521 g_return_if_fail (!SOURCE_DESTROYED (source));
1522 g_return_if_fail (!SOURCE_DESTROYED (child_source));
1524 context = source->context;
1526 if (context)
1527 LOCK_CONTEXT (context);
1529 g_child_source_remove_internal (child_source, context);
1531 if (context)
1532 UNLOCK_CONTEXT (context);
1535 static void
1536 g_source_callback_ref (gpointer cb_data)
1538 GSourceCallback *callback = cb_data;
1540 g_atomic_int_inc (&callback->ref_count);
1543 static void
1544 g_source_callback_unref (gpointer cb_data)
1546 GSourceCallback *callback = cb_data;
1548 if (g_atomic_int_dec_and_test (&callback->ref_count))
1550 if (callback->notify)
1551 callback->notify (callback->data);
1552 g_free (callback);
1556 static void
1557 g_source_callback_get (gpointer cb_data,
1558 GSource *source,
1559 GSourceFunc *func,
1560 gpointer *data)
1562 GSourceCallback *callback = cb_data;
1564 *func = callback->func;
1565 *data = callback->data;
1568 static GSourceCallbackFuncs g_source_callback_funcs = {
1569 g_source_callback_ref,
1570 g_source_callback_unref,
1571 g_source_callback_get,
1575 * g_source_set_callback_indirect:
1576 * @source: the source
1577 * @callback_data: pointer to callback data "object"
1578 * @callback_funcs: functions for reference counting @callback_data
1579 * and getting the callback and data
1581 * Sets the callback function storing the data as a refcounted callback
1582 * "object". This is used internally. Note that calling
1583 * g_source_set_callback_indirect() assumes
1584 * an initial reference count on @callback_data, and thus
1585 * @callback_funcs->unref will eventually be called once more
1586 * than @callback_funcs->ref.
1588 void
1589 g_source_set_callback_indirect (GSource *source,
1590 gpointer callback_data,
1591 GSourceCallbackFuncs *callback_funcs)
1593 GMainContext *context;
1594 gpointer old_cb_data;
1595 GSourceCallbackFuncs *old_cb_funcs;
1597 g_return_if_fail (source != NULL);
1598 g_return_if_fail (callback_funcs != NULL || callback_data == NULL);
1600 context = source->context;
1602 if (context)
1603 LOCK_CONTEXT (context);
1605 if (callback_funcs != &g_source_callback_funcs)
1606 TRACE (GLIB_SOURCE_SET_CALLBACK_INDIRECT (source, callback_data,
1607 callback_funcs->ref,
1608 callback_funcs->unref,
1609 callback_funcs->get));
1611 old_cb_data = source->callback_data;
1612 old_cb_funcs = source->callback_funcs;
1614 source->callback_data = callback_data;
1615 source->callback_funcs = callback_funcs;
1617 if (context)
1618 UNLOCK_CONTEXT (context);
1620 if (old_cb_funcs)
1621 old_cb_funcs->unref (old_cb_data);
1625 * g_source_set_callback:
1626 * @source: the source
1627 * @func: a callback function
1628 * @data: the data to pass to callback function
1629 * @notify: (nullable): a function to call when @data is no longer in use, or %NULL.
1631 * Sets the callback function for a source. The callback for a source is
1632 * called from the source's dispatch function.
1634 * The exact type of @func depends on the type of source; ie. you
1635 * should not count on @func being called with @data as its first
1636 * parameter. Cast @func with G_SOURCE_FUNC() to avoid warnings about
1637 * incompatible function types.
1639 * See [memory management of sources][mainloop-memory-management] for details
1640 * on how to handle memory management of @data.
1642 * Typically, you won't use this function. Instead use functions specific
1643 * to the type of source you are using.
1645 void
1646 g_source_set_callback (GSource *source,
1647 GSourceFunc func,
1648 gpointer data,
1649 GDestroyNotify notify)
1651 GSourceCallback *new_callback;
1653 g_return_if_fail (source != NULL);
1655 TRACE (GLIB_SOURCE_SET_CALLBACK (source, func, data, notify));
1657 new_callback = g_new (GSourceCallback, 1);
1659 new_callback->ref_count = 1;
1660 new_callback->func = func;
1661 new_callback->data = data;
1662 new_callback->notify = notify;
1664 g_source_set_callback_indirect (source, new_callback, &g_source_callback_funcs);
1669 * g_source_set_funcs:
1670 * @source: a #GSource
1671 * @funcs: the new #GSourceFuncs
1673 * Sets the source functions (can be used to override
1674 * default implementations) of an unattached source.
1676 * Since: 2.12
1678 void
1679 g_source_set_funcs (GSource *source,
1680 GSourceFuncs *funcs)
1682 g_return_if_fail (source != NULL);
1683 g_return_if_fail (source->context == NULL);
1684 g_return_if_fail (source->ref_count > 0);
1685 g_return_if_fail (funcs != NULL);
1687 source->source_funcs = funcs;
1690 static void
1691 g_source_set_priority_unlocked (GSource *source,
1692 GMainContext *context,
1693 gint priority)
1695 GSList *tmp_list;
1697 g_return_if_fail (source->priv->parent_source == NULL ||
1698 source->priv->parent_source->priority == priority);
1700 TRACE (GLIB_SOURCE_SET_PRIORITY (source, context, priority));
1702 if (context)
1704 /* Remove the source from the context's source and then
1705 * add it back after so it is sorted in the correct place
1707 source_remove_from_context (source, source->context);
1710 source->priority = priority;
1712 if (context)
1714 source_add_to_context (source, source->context);
1716 if (!SOURCE_BLOCKED (source))
1718 tmp_list = source->poll_fds;
1719 while (tmp_list)
1721 g_main_context_remove_poll_unlocked (context, tmp_list->data);
1722 g_main_context_add_poll_unlocked (context, priority, tmp_list->data);
1724 tmp_list = tmp_list->next;
1727 for (tmp_list = source->priv->fds; tmp_list; tmp_list = tmp_list->next)
1729 g_main_context_remove_poll_unlocked (context, tmp_list->data);
1730 g_main_context_add_poll_unlocked (context, priority, tmp_list->data);
1735 if (source->priv->child_sources)
1737 tmp_list = source->priv->child_sources;
1738 while (tmp_list)
1740 g_source_set_priority_unlocked (tmp_list->data, context, priority);
1741 tmp_list = tmp_list->next;
1747 * g_source_set_priority:
1748 * @source: a #GSource
1749 * @priority: the new priority.
1751 * Sets the priority of a source. While the main loop is being run, a
1752 * source will be dispatched if it is ready to be dispatched and no
1753 * sources at a higher (numerically smaller) priority are ready to be
1754 * dispatched.
1756 * A child source always has the same priority as its parent. It is not
1757 * permitted to change the priority of a source once it has been added
1758 * as a child of another source.
1760 void
1761 g_source_set_priority (GSource *source,
1762 gint priority)
1764 GMainContext *context;
1766 g_return_if_fail (source != NULL);
1767 g_return_if_fail (source->priv->parent_source == NULL);
1769 context = source->context;
1771 if (context)
1772 LOCK_CONTEXT (context);
1773 g_source_set_priority_unlocked (source, context, priority);
1774 if (context)
1775 UNLOCK_CONTEXT (context);
1779 * g_source_get_priority:
1780 * @source: a #GSource
1782 * Gets the priority of a source.
1784 * Returns: the priority of the source
1786 gint
1787 g_source_get_priority (GSource *source)
1789 g_return_val_if_fail (source != NULL, 0);
1791 return source->priority;
1795 * g_source_set_ready_time:
1796 * @source: a #GSource
1797 * @ready_time: the monotonic time at which the source will be ready,
1798 * 0 for "immediately", -1 for "never"
1800 * Sets a #GSource to be dispatched when the given monotonic time is
1801 * reached (or passed). If the monotonic time is in the past (as it
1802 * always will be if @ready_time is 0) then the source will be
1803 * dispatched immediately.
1805 * If @ready_time is -1 then the source is never woken up on the basis
1806 * of the passage of time.
1808 * Dispatching the source does not reset the ready time. You should do
1809 * so yourself, from the source dispatch function.
1811 * Note that if you have a pair of sources where the ready time of one
1812 * suggests that it will be delivered first but the priority for the
1813 * other suggests that it would be delivered first, and the ready time
1814 * for both sources is reached during the same main context iteration,
1815 * then the order of dispatch is undefined.
1817 * It is a no-op to call this function on a #GSource which has already been
1818 * destroyed with g_source_destroy().
1820 * This API is only intended to be used by implementations of #GSource.
1821 * Do not call this API on a #GSource that you did not create.
1823 * Since: 2.36
1825 void
1826 g_source_set_ready_time (GSource *source,
1827 gint64 ready_time)
1829 GMainContext *context;
1831 g_return_if_fail (source != NULL);
1832 /* We deliberately don't check for ref_count > 0 here, because that
1833 * breaks cancellable_source_cancelled() in GCancellable: it has no
1834 * way to find out that the last-unref has happened until the
1835 * finalize() function is called, but that's too late, because the
1836 * ref_count already has already reached 0 before that time.
1837 * However, priv is only poisoned (set to NULL) after finalize(),
1838 * so we can use this as a simple guard against use-after-free.
1839 * See https://bugzilla.gnome.org/show_bug.cgi?id=791754 */
1840 g_return_if_fail (source->priv != NULL);
1842 context = source->context;
1844 if (context)
1845 LOCK_CONTEXT (context);
1847 if (source->priv->ready_time == ready_time)
1849 if (context)
1850 UNLOCK_CONTEXT (context);
1852 return;
1855 source->priv->ready_time = ready_time;
1857 TRACE (GLIB_SOURCE_SET_READY_TIME (source, ready_time));
1859 if (context)
1861 /* Quite likely that we need to change the timeout on the poll */
1862 if (!SOURCE_BLOCKED (source))
1863 g_wakeup_signal (context->wakeup);
1864 UNLOCK_CONTEXT (context);
1869 * g_source_get_ready_time:
1870 * @source: a #GSource
1872 * Gets the "ready time" of @source, as set by
1873 * g_source_set_ready_time().
1875 * Any time before the current monotonic time (including 0) is an
1876 * indication that the source will fire immediately.
1878 * Returns: the monotonic ready time, -1 for "never"
1880 gint64
1881 g_source_get_ready_time (GSource *source)
1883 g_return_val_if_fail (source != NULL, -1);
1885 return source->priv->ready_time;
1889 * g_source_set_can_recurse:
1890 * @source: a #GSource
1891 * @can_recurse: whether recursion is allowed for this source
1893 * Sets whether a source can be called recursively. If @can_recurse is
1894 * %TRUE, then while the source is being dispatched then this source
1895 * will be processed normally. Otherwise, all processing of this
1896 * source is blocked until the dispatch function returns.
1898 void
1899 g_source_set_can_recurse (GSource *source,
1900 gboolean can_recurse)
1902 GMainContext *context;
1904 g_return_if_fail (source != NULL);
1906 context = source->context;
1908 if (context)
1909 LOCK_CONTEXT (context);
1911 if (can_recurse)
1912 source->flags |= G_SOURCE_CAN_RECURSE;
1913 else
1914 source->flags &= ~G_SOURCE_CAN_RECURSE;
1916 if (context)
1917 UNLOCK_CONTEXT (context);
1921 * g_source_get_can_recurse:
1922 * @source: a #GSource
1924 * Checks whether a source is allowed to be called recursively.
1925 * see g_source_set_can_recurse().
1927 * Returns: whether recursion is allowed.
1929 gboolean
1930 g_source_get_can_recurse (GSource *source)
1932 g_return_val_if_fail (source != NULL, FALSE);
1934 return (source->flags & G_SOURCE_CAN_RECURSE) != 0;
1939 * g_source_set_name:
1940 * @source: a #GSource
1941 * @name: debug name for the source
1943 * Sets a name for the source, used in debugging and profiling.
1944 * The name defaults to #NULL.
1946 * The source name should describe in a human-readable way
1947 * what the source does. For example, "X11 event queue"
1948 * or "GTK+ repaint idle handler" or whatever it is.
1950 * It is permitted to call this function multiple times, but is not
1951 * recommended due to the potential performance impact. For example,
1952 * one could change the name in the "check" function of a #GSourceFuncs
1953 * to include details like the event type in the source name.
1955 * Use caution if changing the name while another thread may be
1956 * accessing it with g_source_get_name(); that function does not copy
1957 * the value, and changing the value will free it while the other thread
1958 * may be attempting to use it.
1960 * Since: 2.26
1962 void
1963 g_source_set_name (GSource *source,
1964 const char *name)
1966 GMainContext *context;
1968 g_return_if_fail (source != NULL);
1970 context = source->context;
1972 if (context)
1973 LOCK_CONTEXT (context);
1975 TRACE (GLIB_SOURCE_SET_NAME (source, name));
1977 /* setting back to NULL is allowed, just because it's
1978 * weird if get_name can return NULL but you can't
1979 * set that.
1982 g_free (source->name);
1983 source->name = g_strdup (name);
1985 if (context)
1986 UNLOCK_CONTEXT (context);
1990 * g_source_get_name:
1991 * @source: a #GSource
1993 * Gets a name for the source, used in debugging and profiling. The
1994 * name may be #NULL if it has never been set with g_source_set_name().
1996 * Returns: the name of the source
1998 * Since: 2.26
2000 const char *
2001 g_source_get_name (GSource *source)
2003 g_return_val_if_fail (source != NULL, NULL);
2005 return source->name;
2009 * g_source_set_name_by_id:
2010 * @tag: a #GSource ID
2011 * @name: debug name for the source
2013 * Sets the name of a source using its ID.
2015 * This is a convenience utility to set source names from the return
2016 * value of g_idle_add(), g_timeout_add(), etc.
2018 * It is a programmer error to attempt to set the name of a non-existent
2019 * source.
2021 * More specifically: source IDs can be reissued after a source has been
2022 * destroyed and therefore it is never valid to use this function with a
2023 * source ID which may have already been removed. An example is when
2024 * scheduling an idle to run in another thread with g_idle_add(): the
2025 * idle may already have run and been removed by the time this function
2026 * is called on its (now invalid) source ID. This source ID may have
2027 * been reissued, leading to the operation being performed against the
2028 * wrong source.
2030 * Since: 2.26
2032 void
2033 g_source_set_name_by_id (guint tag,
2034 const char *name)
2036 GSource *source;
2038 g_return_if_fail (tag > 0);
2040 source = g_main_context_find_source_by_id (NULL, tag);
2041 if (source == NULL)
2042 return;
2044 g_source_set_name (source, name);
2049 * g_source_ref:
2050 * @source: a #GSource
2052 * Increases the reference count on a source by one.
2054 * Returns: @source
2056 GSource *
2057 g_source_ref (GSource *source)
2059 GMainContext *context;
2061 g_return_val_if_fail (source != NULL, NULL);
2063 context = source->context;
2065 if (context)
2066 LOCK_CONTEXT (context);
2068 source->ref_count++;
2070 if (context)
2071 UNLOCK_CONTEXT (context);
2073 return source;
2076 /* g_source_unref() but possible to call within context lock
2078 static void
2079 g_source_unref_internal (GSource *source,
2080 GMainContext *context,
2081 gboolean have_lock)
2083 gpointer old_cb_data = NULL;
2084 GSourceCallbackFuncs *old_cb_funcs = NULL;
2086 g_return_if_fail (source != NULL);
2088 if (!have_lock && context)
2089 LOCK_CONTEXT (context);
2091 source->ref_count--;
2092 if (source->ref_count == 0)
2094 TRACE (GLIB_SOURCE_BEFORE_FREE (source, context,
2095 source->source_funcs->finalize));
2097 old_cb_data = source->callback_data;
2098 old_cb_funcs = source->callback_funcs;
2100 source->callback_data = NULL;
2101 source->callback_funcs = NULL;
2103 if (context)
2105 if (!SOURCE_DESTROYED (source))
2106 g_warning (G_STRLOC ": ref_count == 0, but source was still attached to a context!");
2107 source_remove_from_context (source, context);
2109 g_hash_table_remove (context->sources, GUINT_TO_POINTER (source->source_id));
2112 if (source->source_funcs->finalize)
2114 /* Temporarily increase the ref count again so that GSource methods
2115 * can be called from finalize(). */
2116 source->ref_count++;
2117 if (context)
2118 UNLOCK_CONTEXT (context);
2119 source->source_funcs->finalize (source);
2120 if (context)
2121 LOCK_CONTEXT (context);
2122 source->ref_count--;
2125 if (old_cb_funcs)
2127 /* Temporarily increase the ref count again so that GSource methods
2128 * can be called from callback_funcs.unref(). */
2129 source->ref_count++;
2130 if (context)
2131 UNLOCK_CONTEXT (context);
2133 old_cb_funcs->unref (old_cb_data);
2135 if (context)
2136 LOCK_CONTEXT (context);
2137 source->ref_count--;
2140 g_free (source->name);
2141 source->name = NULL;
2143 g_slist_free (source->poll_fds);
2144 source->poll_fds = NULL;
2146 g_slist_free_full (source->priv->fds, g_free);
2148 while (source->priv->child_sources)
2150 GSource *child_source = source->priv->child_sources->data;
2152 source->priv->child_sources =
2153 g_slist_remove (source->priv->child_sources, child_source);
2154 child_source->priv->parent_source = NULL;
2156 g_source_unref_internal (child_source, context, have_lock);
2159 g_slice_free (GSourcePrivate, source->priv);
2160 source->priv = NULL;
2162 g_free (source);
2165 if (!have_lock && context)
2166 UNLOCK_CONTEXT (context);
2170 * g_source_unref:
2171 * @source: a #GSource
2173 * Decreases the reference count of a source by one. If the
2174 * resulting reference count is zero the source and associated
2175 * memory will be destroyed.
2177 void
2178 g_source_unref (GSource *source)
2180 g_return_if_fail (source != NULL);
2182 g_source_unref_internal (source, source->context, FALSE);
2186 * g_main_context_find_source_by_id:
2187 * @context: (nullable): a #GMainContext (if %NULL, the default context will be used)
2188 * @source_id: the source ID, as returned by g_source_get_id().
2190 * Finds a #GSource given a pair of context and ID.
2192 * It is a programmer error to attempt to lookup a non-existent source.
2194 * More specifically: source IDs can be reissued after a source has been
2195 * destroyed and therefore it is never valid to use this function with a
2196 * source ID which may have already been removed. An example is when
2197 * scheduling an idle to run in another thread with g_idle_add(): the
2198 * idle may already have run and been removed by the time this function
2199 * is called on its (now invalid) source ID. This source ID may have
2200 * been reissued, leading to the operation being performed against the
2201 * wrong source.
2203 * Returns: (transfer none): the #GSource
2205 GSource *
2206 g_main_context_find_source_by_id (GMainContext *context,
2207 guint source_id)
2209 GSource *source;
2211 g_return_val_if_fail (source_id > 0, NULL);
2213 if (context == NULL)
2214 context = g_main_context_default ();
2216 LOCK_CONTEXT (context);
2217 source = g_hash_table_lookup (context->sources, GUINT_TO_POINTER (source_id));
2218 UNLOCK_CONTEXT (context);
2220 if (source && SOURCE_DESTROYED (source))
2221 source = NULL;
2223 return source;
2227 * g_main_context_find_source_by_funcs_user_data:
2228 * @context: (nullable): a #GMainContext (if %NULL, the default context will be used).
2229 * @funcs: the @source_funcs passed to g_source_new().
2230 * @user_data: the user data from the callback.
2232 * Finds a source with the given source functions and user data. If
2233 * multiple sources exist with the same source function and user data,
2234 * the first one found will be returned.
2236 * Returns: (transfer none): the source, if one was found, otherwise %NULL
2238 GSource *
2239 g_main_context_find_source_by_funcs_user_data (GMainContext *context,
2240 GSourceFuncs *funcs,
2241 gpointer user_data)
2243 GSourceIter iter;
2244 GSource *source;
2246 g_return_val_if_fail (funcs != NULL, NULL);
2248 if (context == NULL)
2249 context = g_main_context_default ();
2251 LOCK_CONTEXT (context);
2253 g_source_iter_init (&iter, context, FALSE);
2254 while (g_source_iter_next (&iter, &source))
2256 if (!SOURCE_DESTROYED (source) &&
2257 source->source_funcs == funcs &&
2258 source->callback_funcs)
2260 GSourceFunc callback;
2261 gpointer callback_data;
2263 source->callback_funcs->get (source->callback_data, source, &callback, &callback_data);
2265 if (callback_data == user_data)
2266 break;
2269 g_source_iter_clear (&iter);
2271 UNLOCK_CONTEXT (context);
2273 return source;
2277 * g_main_context_find_source_by_user_data:
2278 * @context: a #GMainContext
2279 * @user_data: the user_data for the callback.
2281 * Finds a source with the given user data for the callback. If
2282 * multiple sources exist with the same user data, the first
2283 * one found will be returned.
2285 * Returns: (transfer none): the source, if one was found, otherwise %NULL
2287 GSource *
2288 g_main_context_find_source_by_user_data (GMainContext *context,
2289 gpointer user_data)
2291 GSourceIter iter;
2292 GSource *source;
2294 if (context == NULL)
2295 context = g_main_context_default ();
2297 LOCK_CONTEXT (context);
2299 g_source_iter_init (&iter, context, FALSE);
2300 while (g_source_iter_next (&iter, &source))
2302 if (!SOURCE_DESTROYED (source) &&
2303 source->callback_funcs)
2305 GSourceFunc callback;
2306 gpointer callback_data = NULL;
2308 source->callback_funcs->get (source->callback_data, source, &callback, &callback_data);
2310 if (callback_data == user_data)
2311 break;
2314 g_source_iter_clear (&iter);
2316 UNLOCK_CONTEXT (context);
2318 return source;
2322 * g_source_remove:
2323 * @tag: the ID of the source to remove.
2325 * Removes the source with the given ID from the default main context. You must
2326 * use g_source_destroy() for sources added to a non-default main context.
2328 * The ID of a #GSource is given by g_source_get_id(), or will be
2329 * returned by the functions g_source_attach(), g_idle_add(),
2330 * g_idle_add_full(), g_timeout_add(), g_timeout_add_full(),
2331 * g_child_watch_add(), g_child_watch_add_full(), g_io_add_watch(), and
2332 * g_io_add_watch_full().
2334 * It is a programmer error to attempt to remove a non-existent source.
2336 * More specifically: source IDs can be reissued after a source has been
2337 * destroyed and therefore it is never valid to use this function with a
2338 * source ID which may have already been removed. An example is when
2339 * scheduling an idle to run in another thread with g_idle_add(): the
2340 * idle may already have run and been removed by the time this function
2341 * is called on its (now invalid) source ID. This source ID may have
2342 * been reissued, leading to the operation being performed against the
2343 * wrong source.
2345 * Returns: For historical reasons, this function always returns %TRUE
2347 gboolean
2348 g_source_remove (guint tag)
2350 GSource *source;
2352 g_return_val_if_fail (tag > 0, FALSE);
2354 source = g_main_context_find_source_by_id (NULL, tag);
2355 if (source)
2356 g_source_destroy (source);
2357 else
2358 g_critical ("Source ID %u was not found when attempting to remove it", tag);
2360 return source != NULL;
2364 * g_source_remove_by_user_data:
2365 * @user_data: the user_data for the callback.
2367 * Removes a source from the default main loop context given the user
2368 * data for the callback. If multiple sources exist with the same user
2369 * data, only one will be destroyed.
2371 * Returns: %TRUE if a source was found and removed.
2373 gboolean
2374 g_source_remove_by_user_data (gpointer user_data)
2376 GSource *source;
2378 source = g_main_context_find_source_by_user_data (NULL, user_data);
2379 if (source)
2381 g_source_destroy (source);
2382 return TRUE;
2384 else
2385 return FALSE;
2389 * g_source_remove_by_funcs_user_data:
2390 * @funcs: The @source_funcs passed to g_source_new()
2391 * @user_data: the user data for the callback
2393 * Removes a source from the default main loop context given the
2394 * source functions and user data. If multiple sources exist with the
2395 * same source functions and user data, only one will be destroyed.
2397 * Returns: %TRUE if a source was found and removed.
2399 gboolean
2400 g_source_remove_by_funcs_user_data (GSourceFuncs *funcs,
2401 gpointer user_data)
2403 GSource *source;
2405 g_return_val_if_fail (funcs != NULL, FALSE);
2407 source = g_main_context_find_source_by_funcs_user_data (NULL, funcs, user_data);
2408 if (source)
2410 g_source_destroy (source);
2411 return TRUE;
2413 else
2414 return FALSE;
2418 * g_clear_handle_id: (skip)
2419 * @tag_ptr: (not nullable): a pointer to the handler ID
2420 * @clear_func: (not nullable): the function to call to clear the handler
2422 * Clears a numeric handler, such as a #GSource ID.
2424 * @tag_ptr must be a valid pointer to the variable holding the handler.
2426 * If the ID is zero then this function does nothing.
2427 * Otherwise, clear_func() is called with the ID as a parameter, and the tag is
2428 * set to zero.
2430 * A macro is also included that allows this function to be used without
2431 * pointer casts.
2433 * Since: 2.56
2435 #undef g_clear_handle_id
2436 void
2437 g_clear_handle_id (guint *tag_ptr,
2438 GClearHandleFunc clear_func)
2440 guint _handle_id;
2442 _handle_id = *tag_ptr;
2443 if (_handle_id > 0)
2445 *tag_ptr = 0;
2446 clear_func (_handle_id);
2450 #ifdef G_OS_UNIX
2452 * g_source_add_unix_fd:
2453 * @source: a #GSource
2454 * @fd: the fd to monitor
2455 * @events: an event mask
2457 * Monitors @fd for the IO events in @events.
2459 * The tag returned by this function can be used to remove or modify the
2460 * monitoring of the fd using g_source_remove_unix_fd() or
2461 * g_source_modify_unix_fd().
2463 * It is not necessary to remove the fd before destroying the source; it
2464 * will be cleaned up automatically.
2466 * This API is only intended to be used by implementations of #GSource.
2467 * Do not call this API on a #GSource that you did not create.
2469 * As the name suggests, this function is not available on Windows.
2471 * Returns: (not nullable): an opaque tag
2473 * Since: 2.36
2475 gpointer
2476 g_source_add_unix_fd (GSource *source,
2477 gint fd,
2478 GIOCondition events)
2480 GMainContext *context;
2481 GPollFD *poll_fd;
2483 g_return_val_if_fail (source != NULL, NULL);
2484 g_return_val_if_fail (!SOURCE_DESTROYED (source), NULL);
2486 poll_fd = g_new (GPollFD, 1);
2487 poll_fd->fd = fd;
2488 poll_fd->events = events;
2489 poll_fd->revents = 0;
2491 context = source->context;
2493 if (context)
2494 LOCK_CONTEXT (context);
2496 source->priv->fds = g_slist_prepend (source->priv->fds, poll_fd);
2498 if (context)
2500 if (!SOURCE_BLOCKED (source))
2501 g_main_context_add_poll_unlocked (context, source->priority, poll_fd);
2502 UNLOCK_CONTEXT (context);
2505 return poll_fd;
2509 * g_source_modify_unix_fd:
2510 * @source: a #GSource
2511 * @tag: (not nullable): the tag from g_source_add_unix_fd()
2512 * @new_events: the new event mask to watch
2514 * Updates the event mask to watch for the fd identified by @tag.
2516 * @tag is the tag returned from g_source_add_unix_fd().
2518 * If you want to remove a fd, don't set its event mask to zero.
2519 * Instead, call g_source_remove_unix_fd().
2521 * This API is only intended to be used by implementations of #GSource.
2522 * Do not call this API on a #GSource that you did not create.
2524 * As the name suggests, this function is not available on Windows.
2526 * Since: 2.36
2528 void
2529 g_source_modify_unix_fd (GSource *source,
2530 gpointer tag,
2531 GIOCondition new_events)
2533 GMainContext *context;
2534 GPollFD *poll_fd;
2536 g_return_if_fail (source != NULL);
2537 g_return_if_fail (g_slist_find (source->priv->fds, tag));
2539 context = source->context;
2540 poll_fd = tag;
2542 poll_fd->events = new_events;
2544 if (context)
2545 g_main_context_wakeup (context);
2549 * g_source_remove_unix_fd:
2550 * @source: a #GSource
2551 * @tag: (not nullable): the tag from g_source_add_unix_fd()
2553 * Reverses the effect of a previous call to g_source_add_unix_fd().
2555 * You only need to call this if you want to remove an fd from being
2556 * watched while keeping the same source around. In the normal case you
2557 * will just want to destroy the source.
2559 * This API is only intended to be used by implementations of #GSource.
2560 * Do not call this API on a #GSource that you did not create.
2562 * As the name suggests, this function is not available on Windows.
2564 * Since: 2.36
2566 void
2567 g_source_remove_unix_fd (GSource *source,
2568 gpointer tag)
2570 GMainContext *context;
2571 GPollFD *poll_fd;
2573 g_return_if_fail (source != NULL);
2574 g_return_if_fail (g_slist_find (source->priv->fds, tag));
2576 context = source->context;
2577 poll_fd = tag;
2579 if (context)
2580 LOCK_CONTEXT (context);
2582 source->priv->fds = g_slist_remove (source->priv->fds, poll_fd);
2584 if (context)
2586 if (!SOURCE_BLOCKED (source))
2587 g_main_context_remove_poll_unlocked (context, poll_fd);
2589 UNLOCK_CONTEXT (context);
2592 g_free (poll_fd);
2596 * g_source_query_unix_fd:
2597 * @source: a #GSource
2598 * @tag: (not nullable): the tag from g_source_add_unix_fd()
2600 * Queries the events reported for the fd corresponding to @tag on
2601 * @source during the last poll.
2603 * The return value of this function is only defined when the function
2604 * is called from the check or dispatch functions for @source.
2606 * This API is only intended to be used by implementations of #GSource.
2607 * Do not call this API on a #GSource that you did not create.
2609 * As the name suggests, this function is not available on Windows.
2611 * Returns: the conditions reported on the fd
2613 * Since: 2.36
2615 GIOCondition
2616 g_source_query_unix_fd (GSource *source,
2617 gpointer tag)
2619 GPollFD *poll_fd;
2621 g_return_val_if_fail (source != NULL, 0);
2622 g_return_val_if_fail (g_slist_find (source->priv->fds, tag), 0);
2624 poll_fd = tag;
2626 return poll_fd->revents;
2628 #endif /* G_OS_UNIX */
2631 * g_get_current_time:
2632 * @result: #GTimeVal structure in which to store current time.
2634 * Equivalent to the UNIX gettimeofday() function, but portable.
2636 * You may find g_get_real_time() to be more convenient.
2638 void
2639 g_get_current_time (GTimeVal *result)
2641 #ifndef G_OS_WIN32
2642 struct timeval r;
2644 g_return_if_fail (result != NULL);
2646 /*this is required on alpha, there the timeval structs are int's
2647 not longs and a cast only would fail horribly*/
2648 gettimeofday (&r, NULL);
2649 result->tv_sec = r.tv_sec;
2650 result->tv_usec = r.tv_usec;
2651 #else
2652 FILETIME ft;
2653 guint64 time64;
2655 g_return_if_fail (result != NULL);
2657 GetSystemTimeAsFileTime (&ft);
2658 memmove (&time64, &ft, sizeof (FILETIME));
2660 /* Convert from 100s of nanoseconds since 1601-01-01
2661 * to Unix epoch. Yes, this is Y2038 unsafe.
2663 time64 -= G_GINT64_CONSTANT (116444736000000000);
2664 time64 /= 10;
2666 result->tv_sec = time64 / 1000000;
2667 result->tv_usec = time64 % 1000000;
2668 #endif
2672 * g_get_real_time:
2674 * Queries the system wall-clock time.
2676 * This call is functionally equivalent to g_get_current_time() except
2677 * that the return value is often more convenient than dealing with a
2678 * #GTimeVal.
2680 * You should only use this call if you are actually interested in the real
2681 * wall-clock time. g_get_monotonic_time() is probably more useful for
2682 * measuring intervals.
2684 * Returns: the number of microseconds since January 1, 1970 UTC.
2686 * Since: 2.28
2688 gint64
2689 g_get_real_time (void)
2691 GTimeVal tv;
2693 g_get_current_time (&tv);
2695 return (((gint64) tv.tv_sec) * 1000000) + tv.tv_usec;
2699 * g_get_monotonic_time:
2701 * Queries the system monotonic time.
2703 * The monotonic clock will always increase and doesn't suffer
2704 * discontinuities when the user (or NTP) changes the system time. It
2705 * may or may not continue to tick during times where the machine is
2706 * suspended.
2708 * We try to use the clock that corresponds as closely as possible to
2709 * the passage of time as measured by system calls such as poll() but it
2710 * may not always be possible to do this.
2712 * Returns: the monotonic time, in microseconds
2714 * Since: 2.28
2716 #if defined (G_OS_WIN32)
2717 /* NOTE:
2718 * time_usec = ticks_since_boot * usec_per_sec / ticks_per_sec
2720 * Doing (ticks_since_boot * usec_per_sec) before the division can overflow 64 bits
2721 * (ticks_since_boot / ticks_per_sec) and then multiply would not be accurate enough.
2722 * So for now we calculate (usec_per_sec / ticks_per_sec) and use floating point
2724 static gdouble g_monotonic_usec_per_tick = 0;
2726 void
2727 g_clock_win32_init (void)
2729 LARGE_INTEGER freq;
2731 if (!QueryPerformanceFrequency (&freq) || freq.QuadPart == 0)
2733 /* The documentation says that this should never happen */
2734 g_assert_not_reached ();
2735 return;
2738 g_monotonic_usec_per_tick = (gdouble)G_USEC_PER_SEC / freq.QuadPart;
2741 gint64
2742 g_get_monotonic_time (void)
2744 if (G_LIKELY (g_monotonic_usec_per_tick != 0))
2746 LARGE_INTEGER ticks;
2748 if (QueryPerformanceCounter (&ticks))
2749 return (gint64)(ticks.QuadPart * g_monotonic_usec_per_tick);
2751 g_warning ("QueryPerformanceCounter Failed (%lu)", GetLastError ());
2752 g_monotonic_usec_per_tick = 0;
2755 return 0;
2757 #elif defined(HAVE_MACH_MACH_TIME_H) /* Mac OS */
2758 gint64
2759 g_get_monotonic_time (void)
2761 static mach_timebase_info_data_t timebase_info;
2763 if (timebase_info.denom == 0)
2765 /* This is a fraction that we must use to scale
2766 * mach_absolute_time() by in order to reach nanoseconds.
2768 * We've only ever observed this to be 1/1, but maybe it could be
2769 * 1000/1 if mach time is microseconds already, or 1/1000 if
2770 * picoseconds. Try to deal nicely with that.
2772 mach_timebase_info (&timebase_info);
2774 /* We actually want microseconds... */
2775 if (timebase_info.numer % 1000 == 0)
2776 timebase_info.numer /= 1000;
2777 else
2778 timebase_info.denom *= 1000;
2780 /* We want to make the numer 1 to avoid having to multiply... */
2781 if (timebase_info.denom % timebase_info.numer == 0)
2783 timebase_info.denom /= timebase_info.numer;
2784 timebase_info.numer = 1;
2786 else
2788 /* We could just multiply by timebase_info.numer below, but why
2789 * bother for a case that may never actually exist...
2791 * Plus -- performing the multiplication would risk integer
2792 * overflow. If we ever actually end up in this situation, we
2793 * should more carefully evaluate the correct course of action.
2795 mach_timebase_info (&timebase_info); /* Get a fresh copy for a better message */
2796 g_error ("Got weird mach timebase info of %d/%d. Please file a bug against GLib.",
2797 timebase_info.numer, timebase_info.denom);
2801 return mach_absolute_time () / timebase_info.denom;
2803 #else
2804 gint64
2805 g_get_monotonic_time (void)
2807 struct timespec ts;
2808 gint result;
2810 result = clock_gettime (CLOCK_MONOTONIC, &ts);
2812 if G_UNLIKELY (result != 0)
2813 g_error ("GLib requires working CLOCK_MONOTONIC");
2815 return (((gint64) ts.tv_sec) * 1000000) + (ts.tv_nsec / 1000);
2817 #endif
2819 static void
2820 g_main_dispatch_free (gpointer dispatch)
2822 g_slice_free (GMainDispatch, dispatch);
2825 /* Running the main loop */
2827 static GMainDispatch *
2828 get_dispatch (void)
2830 static GPrivate depth_private = G_PRIVATE_INIT (g_main_dispatch_free);
2831 GMainDispatch *dispatch;
2833 dispatch = g_private_get (&depth_private);
2835 if (!dispatch)
2837 dispatch = g_slice_new0 (GMainDispatch);
2838 g_private_set (&depth_private, dispatch);
2841 return dispatch;
2845 * g_main_depth:
2847 * Returns the depth of the stack of calls to
2848 * g_main_context_dispatch() on any #GMainContext in the current thread.
2849 * That is, when called from the toplevel, it gives 0. When
2850 * called from within a callback from g_main_context_iteration()
2851 * (or g_main_loop_run(), etc.) it returns 1. When called from within
2852 * a callback to a recursive call to g_main_context_iteration(),
2853 * it returns 2. And so forth.
2855 * This function is useful in a situation like the following:
2856 * Imagine an extremely simple "garbage collected" system.
2858 * |[<!-- language="C" -->
2859 * static GList *free_list;
2861 * gpointer
2862 * allocate_memory (gsize size)
2863 * {
2864 * gpointer result = g_malloc (size);
2865 * free_list = g_list_prepend (free_list, result);
2866 * return result;
2869 * void
2870 * free_allocated_memory (void)
2872 * GList *l;
2873 * for (l = free_list; l; l = l->next);
2874 * g_free (l->data);
2875 * g_list_free (free_list);
2876 * free_list = NULL;
2879 * [...]
2881 * while (TRUE);
2883 * g_main_context_iteration (NULL, TRUE);
2884 * free_allocated_memory();
2886 * ]|
2888 * This works from an application, however, if you want to do the same
2889 * thing from a library, it gets more difficult, since you no longer
2890 * control the main loop. You might think you can simply use an idle
2891 * function to make the call to free_allocated_memory(), but that
2892 * doesn't work, since the idle function could be called from a
2893 * recursive callback. This can be fixed by using g_main_depth()
2895 * |[<!-- language="C" -->
2896 * gpointer
2897 * allocate_memory (gsize size)
2898 * {
2899 * FreeListBlock *block = g_new (FreeListBlock, 1);
2900 * block->mem = g_malloc (size);
2901 * block->depth = g_main_depth ();
2902 * free_list = g_list_prepend (free_list, block);
2903 * return block->mem;
2906 * void
2907 * free_allocated_memory (void)
2909 * GList *l;
2911 * int depth = g_main_depth ();
2912 * for (l = free_list; l; );
2914 * GList *next = l->next;
2915 * FreeListBlock *block = l->data;
2916 * if (block->depth > depth)
2918 * g_free (block->mem);
2919 * g_free (block);
2920 * free_list = g_list_delete_link (free_list, l);
2923 * l = next;
2926 * ]|
2928 * There is a temptation to use g_main_depth() to solve
2929 * problems with reentrancy. For instance, while waiting for data
2930 * to be received from the network in response to a menu item,
2931 * the menu item might be selected again. It might seem that
2932 * one could make the menu item's callback return immediately
2933 * and do nothing if g_main_depth() returns a value greater than 1.
2934 * However, this should be avoided since the user then sees selecting
2935 * the menu item do nothing. Furthermore, you'll find yourself adding
2936 * these checks all over your code, since there are doubtless many,
2937 * many things that the user could do. Instead, you can use the
2938 * following techniques:
2940 * 1. Use gtk_widget_set_sensitive() or modal dialogs to prevent
2941 * the user from interacting with elements while the main
2942 * loop is recursing.
2944 * 2. Avoid main loop recursion in situations where you can't handle
2945 * arbitrary callbacks. Instead, structure your code so that you
2946 * simply return to the main loop and then get called again when
2947 * there is more work to do.
2949 * Returns: The main loop recursion level in the current thread
2952 g_main_depth (void)
2954 GMainDispatch *dispatch = get_dispatch ();
2955 return dispatch->depth;
2959 * g_main_current_source:
2961 * Returns the currently firing source for this thread.
2963 * Returns: (transfer none): The currently firing source or %NULL.
2965 * Since: 2.12
2967 GSource *
2968 g_main_current_source (void)
2970 GMainDispatch *dispatch = get_dispatch ();
2971 return dispatch->source;
2975 * g_source_is_destroyed:
2976 * @source: a #GSource
2978 * Returns whether @source has been destroyed.
2980 * This is important when you operate upon your objects
2981 * from within idle handlers, but may have freed the object
2982 * before the dispatch of your idle handler.
2984 * |[<!-- language="C" -->
2985 * static gboolean
2986 * idle_callback (gpointer data)
2988 * SomeWidget *self = data;
2990 * GDK_THREADS_ENTER ();
2991 * // do stuff with self
2992 * self->idle_id = 0;
2993 * GDK_THREADS_LEAVE ();
2995 * return G_SOURCE_REMOVE;
2998 * static void
2999 * some_widget_do_stuff_later (SomeWidget *self)
3001 * self->idle_id = g_idle_add (idle_callback, self);
3004 * static void
3005 * some_widget_finalize (GObject *object)
3007 * SomeWidget *self = SOME_WIDGET (object);
3009 * if (self->idle_id)
3010 * g_source_remove (self->idle_id);
3012 * G_OBJECT_CLASS (parent_class)->finalize (object);
3014 * ]|
3016 * This will fail in a multi-threaded application if the
3017 * widget is destroyed before the idle handler fires due
3018 * to the use after free in the callback. A solution, to
3019 * this particular problem, is to check to if the source
3020 * has already been destroy within the callback.
3022 * |[<!-- language="C" -->
3023 * static gboolean
3024 * idle_callback (gpointer data)
3026 * SomeWidget *self = data;
3028 * GDK_THREADS_ENTER ();
3029 * if (!g_source_is_destroyed (g_main_current_source ()))
3031 * // do stuff with self
3033 * GDK_THREADS_LEAVE ();
3035 * return FALSE;
3037 * ]|
3039 * Calls to this function from a thread other than the one acquired by the
3040 * #GMainContext the #GSource is attached to are typically redundant, as the
3041 * source could be destroyed immediately after this function returns. However,
3042 * once a source is destroyed it cannot be un-destroyed, so this function can be
3043 * used for opportunistic checks from any thread.
3045 * Returns: %TRUE if the source has been destroyed
3047 * Since: 2.12
3049 gboolean
3050 g_source_is_destroyed (GSource *source)
3052 return SOURCE_DESTROYED (source);
3055 /* Temporarily remove all this source's file descriptors from the
3056 * poll(), so that if data comes available for one of the file descriptors
3057 * we don't continually spin in the poll()
3059 /* HOLDS: source->context's lock */
3060 static void
3061 block_source (GSource *source)
3063 GSList *tmp_list;
3065 g_return_if_fail (!SOURCE_BLOCKED (source));
3067 source->flags |= G_SOURCE_BLOCKED;
3069 if (source->context)
3071 tmp_list = source->poll_fds;
3072 while (tmp_list)
3074 g_main_context_remove_poll_unlocked (source->context, tmp_list->data);
3075 tmp_list = tmp_list->next;
3078 for (tmp_list = source->priv->fds; tmp_list; tmp_list = tmp_list->next)
3079 g_main_context_remove_poll_unlocked (source->context, tmp_list->data);
3082 if (source->priv && source->priv->child_sources)
3084 tmp_list = source->priv->child_sources;
3085 while (tmp_list)
3087 block_source (tmp_list->data);
3088 tmp_list = tmp_list->next;
3093 /* HOLDS: source->context's lock */
3094 static void
3095 unblock_source (GSource *source)
3097 GSList *tmp_list;
3099 g_return_if_fail (SOURCE_BLOCKED (source)); /* Source already unblocked */
3100 g_return_if_fail (!SOURCE_DESTROYED (source));
3102 source->flags &= ~G_SOURCE_BLOCKED;
3104 tmp_list = source->poll_fds;
3105 while (tmp_list)
3107 g_main_context_add_poll_unlocked (source->context, source->priority, tmp_list->data);
3108 tmp_list = tmp_list->next;
3111 for (tmp_list = source->priv->fds; tmp_list; tmp_list = tmp_list->next)
3112 g_main_context_add_poll_unlocked (source->context, source->priority, tmp_list->data);
3114 if (source->priv && source->priv->child_sources)
3116 tmp_list = source->priv->child_sources;
3117 while (tmp_list)
3119 unblock_source (tmp_list->data);
3120 tmp_list = tmp_list->next;
3125 /* HOLDS: context's lock */
3126 static void
3127 g_main_dispatch (GMainContext *context)
3129 GMainDispatch *current = get_dispatch ();
3130 guint i;
3132 for (i = 0; i < context->pending_dispatches->len; i++)
3134 GSource *source = context->pending_dispatches->pdata[i];
3136 context->pending_dispatches->pdata[i] = NULL;
3137 g_assert (source);
3139 source->flags &= ~G_SOURCE_READY;
3141 if (!SOURCE_DESTROYED (source))
3143 gboolean was_in_call;
3144 gpointer user_data = NULL;
3145 GSourceFunc callback = NULL;
3146 GSourceCallbackFuncs *cb_funcs;
3147 gpointer cb_data;
3148 gboolean need_destroy;
3150 gboolean (*dispatch) (GSource *,
3151 GSourceFunc,
3152 gpointer);
3153 GSource *prev_source;
3155 dispatch = source->source_funcs->dispatch;
3156 cb_funcs = source->callback_funcs;
3157 cb_data = source->callback_data;
3159 if (cb_funcs)
3160 cb_funcs->ref (cb_data);
3162 if ((source->flags & G_SOURCE_CAN_RECURSE) == 0)
3163 block_source (source);
3165 was_in_call = source->flags & G_HOOK_FLAG_IN_CALL;
3166 source->flags |= G_HOOK_FLAG_IN_CALL;
3168 if (cb_funcs)
3169 cb_funcs->get (cb_data, source, &callback, &user_data);
3171 UNLOCK_CONTEXT (context);
3173 /* These operations are safe because 'current' is thread-local
3174 * and not modified from anywhere but this function.
3176 prev_source = current->source;
3177 current->source = source;
3178 current->depth++;
3180 TRACE (GLIB_MAIN_BEFORE_DISPATCH (g_source_get_name (source), source,
3181 dispatch, callback, user_data));
3182 need_destroy = !(* dispatch) (source, callback, user_data);
3183 TRACE (GLIB_MAIN_AFTER_DISPATCH (g_source_get_name (source), source,
3184 dispatch, need_destroy));
3186 current->source = prev_source;
3187 current->depth--;
3189 if (cb_funcs)
3190 cb_funcs->unref (cb_data);
3192 LOCK_CONTEXT (context);
3194 if (!was_in_call)
3195 source->flags &= ~G_HOOK_FLAG_IN_CALL;
3197 if (SOURCE_BLOCKED (source) && !SOURCE_DESTROYED (source))
3198 unblock_source (source);
3200 /* Note: this depends on the fact that we can't switch
3201 * sources from one main context to another
3203 if (need_destroy && !SOURCE_DESTROYED (source))
3205 g_assert (source->context == context);
3206 g_source_destroy_internal (source, context, TRUE);
3210 SOURCE_UNREF (source, context);
3213 g_ptr_array_set_size (context->pending_dispatches, 0);
3217 * g_main_context_acquire:
3218 * @context: a #GMainContext
3220 * Tries to become the owner of the specified context.
3221 * If some other thread is the owner of the context,
3222 * returns %FALSE immediately. Ownership is properly
3223 * recursive: the owner can require ownership again
3224 * and will release ownership when g_main_context_release()
3225 * is called as many times as g_main_context_acquire().
3227 * You must be the owner of a context before you
3228 * can call g_main_context_prepare(), g_main_context_query(),
3229 * g_main_context_check(), g_main_context_dispatch().
3231 * Returns: %TRUE if the operation succeeded, and
3232 * this thread is now the owner of @context.
3234 gboolean
3235 g_main_context_acquire (GMainContext *context)
3237 gboolean result = FALSE;
3238 GThread *self = G_THREAD_SELF;
3240 if (context == NULL)
3241 context = g_main_context_default ();
3243 LOCK_CONTEXT (context);
3245 if (!context->owner)
3247 context->owner = self;
3248 g_assert (context->owner_count == 0);
3249 TRACE (GLIB_MAIN_CONTEXT_ACQUIRE (context, TRUE /* success */));
3252 if (context->owner == self)
3254 context->owner_count++;
3255 result = TRUE;
3257 else
3259 TRACE (GLIB_MAIN_CONTEXT_ACQUIRE (context, FALSE /* failure */));
3262 UNLOCK_CONTEXT (context);
3264 return result;
3268 * g_main_context_release:
3269 * @context: a #GMainContext
3271 * Releases ownership of a context previously acquired by this thread
3272 * with g_main_context_acquire(). If the context was acquired multiple
3273 * times, the ownership will be released only when g_main_context_release()
3274 * is called as many times as it was acquired.
3276 void
3277 g_main_context_release (GMainContext *context)
3279 if (context == NULL)
3280 context = g_main_context_default ();
3282 LOCK_CONTEXT (context);
3284 context->owner_count--;
3285 if (context->owner_count == 0)
3287 TRACE (GLIB_MAIN_CONTEXT_RELEASE (context));
3289 context->owner = NULL;
3291 if (context->waiters)
3293 GMainWaiter *waiter = context->waiters->data;
3294 gboolean loop_internal_waiter = (waiter->mutex == &context->mutex);
3295 context->waiters = g_slist_delete_link (context->waiters,
3296 context->waiters);
3297 if (!loop_internal_waiter)
3298 g_mutex_lock (waiter->mutex);
3300 g_cond_signal (waiter->cond);
3302 if (!loop_internal_waiter)
3303 g_mutex_unlock (waiter->mutex);
3307 UNLOCK_CONTEXT (context);
3311 * g_main_context_wait:
3312 * @context: a #GMainContext
3313 * @cond: a condition variable
3314 * @mutex: a mutex, currently held
3316 * Tries to become the owner of the specified context,
3317 * as with g_main_context_acquire(). But if another thread
3318 * is the owner, atomically drop @mutex and wait on @cond until
3319 * that owner releases ownership or until @cond is signaled, then
3320 * try again (once) to become the owner.
3322 * Returns: %TRUE if the operation succeeded, and
3323 * this thread is now the owner of @context.
3325 gboolean
3326 g_main_context_wait (GMainContext *context,
3327 GCond *cond,
3328 GMutex *mutex)
3330 gboolean result = FALSE;
3331 GThread *self = G_THREAD_SELF;
3332 gboolean loop_internal_waiter;
3334 if (context == NULL)
3335 context = g_main_context_default ();
3337 if G_UNLIKELY (cond != &context->cond || mutex != &context->mutex)
3339 static gboolean warned;
3341 if (!warned)
3343 g_critical ("WARNING!! g_main_context_wait() will be removed in a future release. "
3344 "If you see this message, please file a bug immediately.");
3345 warned = TRUE;
3349 loop_internal_waiter = (mutex == &context->mutex);
3351 if (!loop_internal_waiter)
3352 LOCK_CONTEXT (context);
3354 if (context->owner && context->owner != self)
3356 GMainWaiter waiter;
3358 waiter.cond = cond;
3359 waiter.mutex = mutex;
3361 context->waiters = g_slist_append (context->waiters, &waiter);
3363 if (!loop_internal_waiter)
3364 UNLOCK_CONTEXT (context);
3365 g_cond_wait (cond, mutex);
3366 if (!loop_internal_waiter)
3367 LOCK_CONTEXT (context);
3369 context->waiters = g_slist_remove (context->waiters, &waiter);
3372 if (!context->owner)
3374 context->owner = self;
3375 g_assert (context->owner_count == 0);
3378 if (context->owner == self)
3380 context->owner_count++;
3381 result = TRUE;
3384 if (!loop_internal_waiter)
3385 UNLOCK_CONTEXT (context);
3387 return result;
3391 * g_main_context_prepare:
3392 * @context: a #GMainContext
3393 * @priority: location to store priority of highest priority
3394 * source already ready.
3396 * Prepares to poll sources within a main loop. The resulting information
3397 * for polling is determined by calling g_main_context_query ().
3399 * You must have successfully acquired the context with
3400 * g_main_context_acquire() before you may call this function.
3402 * Returns: %TRUE if some source is ready to be dispatched
3403 * prior to polling.
3405 gboolean
3406 g_main_context_prepare (GMainContext *context,
3407 gint *priority)
3409 guint i;
3410 gint n_ready = 0;
3411 gint current_priority = G_MAXINT;
3412 GSource *source;
3413 GSourceIter iter;
3415 if (context == NULL)
3416 context = g_main_context_default ();
3418 LOCK_CONTEXT (context);
3420 context->time_is_fresh = FALSE;
3422 if (context->in_check_or_prepare)
3424 g_warning ("g_main_context_prepare() called recursively from within a source's check() or "
3425 "prepare() member.");
3426 UNLOCK_CONTEXT (context);
3427 return FALSE;
3430 TRACE (GLIB_MAIN_CONTEXT_BEFORE_PREPARE (context));
3432 #if 0
3433 /* If recursing, finish up current dispatch, before starting over */
3434 if (context->pending_dispatches)
3436 if (dispatch)
3437 g_main_dispatch (context, &current_time);
3439 UNLOCK_CONTEXT (context);
3440 return TRUE;
3442 #endif
3444 /* If recursing, clear list of pending dispatches */
3446 for (i = 0; i < context->pending_dispatches->len; i++)
3448 if (context->pending_dispatches->pdata[i])
3449 SOURCE_UNREF ((GSource *)context->pending_dispatches->pdata[i], context);
3451 g_ptr_array_set_size (context->pending_dispatches, 0);
3453 /* Prepare all sources */
3455 context->timeout = -1;
3457 g_source_iter_init (&iter, context, TRUE);
3458 while (g_source_iter_next (&iter, &source))
3460 gint source_timeout = -1;
3462 if (SOURCE_DESTROYED (source) || SOURCE_BLOCKED (source))
3463 continue;
3464 if ((n_ready > 0) && (source->priority > current_priority))
3465 break;
3467 if (!(source->flags & G_SOURCE_READY))
3469 gboolean result;
3470 gboolean (* prepare) (GSource *source,
3471 gint *timeout);
3473 prepare = source->source_funcs->prepare;
3475 if (prepare)
3477 context->in_check_or_prepare++;
3478 UNLOCK_CONTEXT (context);
3480 result = (* prepare) (source, &source_timeout);
3481 TRACE (GLIB_MAIN_AFTER_PREPARE (source, prepare, source_timeout));
3483 LOCK_CONTEXT (context);
3484 context->in_check_or_prepare--;
3486 else
3488 source_timeout = -1;
3489 result = FALSE;
3492 if (result == FALSE && source->priv->ready_time != -1)
3494 if (!context->time_is_fresh)
3496 context->time = g_get_monotonic_time ();
3497 context->time_is_fresh = TRUE;
3500 if (source->priv->ready_time <= context->time)
3502 source_timeout = 0;
3503 result = TRUE;
3505 else
3507 gint timeout;
3509 /* rounding down will lead to spinning, so always round up */
3510 timeout = (source->priv->ready_time - context->time + 999) / 1000;
3512 if (source_timeout < 0 || timeout < source_timeout)
3513 source_timeout = timeout;
3517 if (result)
3519 GSource *ready_source = source;
3521 while (ready_source)
3523 ready_source->flags |= G_SOURCE_READY;
3524 ready_source = ready_source->priv->parent_source;
3529 if (source->flags & G_SOURCE_READY)
3531 n_ready++;
3532 current_priority = source->priority;
3533 context->timeout = 0;
3536 if (source_timeout >= 0)
3538 if (context->timeout < 0)
3539 context->timeout = source_timeout;
3540 else
3541 context->timeout = MIN (context->timeout, source_timeout);
3544 g_source_iter_clear (&iter);
3546 TRACE (GLIB_MAIN_CONTEXT_AFTER_PREPARE (context, current_priority, n_ready));
3548 UNLOCK_CONTEXT (context);
3550 if (priority)
3551 *priority = current_priority;
3553 return (n_ready > 0);
3557 * g_main_context_query:
3558 * @context: a #GMainContext
3559 * @max_priority: maximum priority source to check
3560 * @timeout_: (out): location to store timeout to be used in polling
3561 * @fds: (out caller-allocates) (array length=n_fds): location to
3562 * store #GPollFD records that need to be polled.
3563 * @n_fds: (in): length of @fds.
3565 * Determines information necessary to poll this main loop.
3567 * You must have successfully acquired the context with
3568 * g_main_context_acquire() before you may call this function.
3570 * Returns: the number of records actually stored in @fds,
3571 * or, if more than @n_fds records need to be stored, the number
3572 * of records that need to be stored.
3574 gint
3575 g_main_context_query (GMainContext *context,
3576 gint max_priority,
3577 gint *timeout,
3578 GPollFD *fds,
3579 gint n_fds)
3581 gint n_poll;
3582 GPollRec *pollrec, *lastpollrec;
3583 gushort events;
3585 LOCK_CONTEXT (context);
3587 TRACE (GLIB_MAIN_CONTEXT_BEFORE_QUERY (context, max_priority));
3589 n_poll = 0;
3590 lastpollrec = NULL;
3591 for (pollrec = context->poll_records; pollrec; pollrec = pollrec->next)
3593 if (pollrec->priority > max_priority)
3594 continue;
3596 /* In direct contradiction to the Unix98 spec, IRIX runs into
3597 * difficulty if you pass in POLLERR, POLLHUP or POLLNVAL
3598 * flags in the events field of the pollfd while it should
3599 * just ignoring them. So we mask them out here.
3601 events = pollrec->fd->events & ~(G_IO_ERR|G_IO_HUP|G_IO_NVAL);
3603 if (lastpollrec && pollrec->fd->fd == lastpollrec->fd->fd)
3605 if (n_poll - 1 < n_fds)
3606 fds[n_poll - 1].events |= events;
3608 else
3610 if (n_poll < n_fds)
3612 fds[n_poll].fd = pollrec->fd->fd;
3613 fds[n_poll].events = events;
3614 fds[n_poll].revents = 0;
3617 n_poll++;
3620 lastpollrec = pollrec;
3623 context->poll_changed = FALSE;
3625 if (timeout)
3627 *timeout = context->timeout;
3628 if (*timeout != 0)
3629 context->time_is_fresh = FALSE;
3632 TRACE (GLIB_MAIN_CONTEXT_AFTER_QUERY (context, context->timeout,
3633 fds, n_poll));
3635 UNLOCK_CONTEXT (context);
3637 return n_poll;
3641 * g_main_context_check:
3642 * @context: a #GMainContext
3643 * @max_priority: the maximum numerical priority of sources to check
3644 * @fds: (array length=n_fds): array of #GPollFD's that was passed to
3645 * the last call to g_main_context_query()
3646 * @n_fds: return value of g_main_context_query()
3648 * Passes the results of polling back to the main loop.
3650 * You must have successfully acquired the context with
3651 * g_main_context_acquire() before you may call this function.
3653 * Returns: %TRUE if some sources are ready to be dispatched.
3655 gboolean
3656 g_main_context_check (GMainContext *context,
3657 gint max_priority,
3658 GPollFD *fds,
3659 gint n_fds)
3661 GSource *source;
3662 GSourceIter iter;
3663 GPollRec *pollrec;
3664 gint n_ready = 0;
3665 gint i;
3667 LOCK_CONTEXT (context);
3669 if (context->in_check_or_prepare)
3671 g_warning ("g_main_context_check() called recursively from within a source's check() or "
3672 "prepare() member.");
3673 UNLOCK_CONTEXT (context);
3674 return FALSE;
3677 TRACE (GLIB_MAIN_CONTEXT_BEFORE_CHECK (context, max_priority, fds, n_fds));
3679 for (i = 0; i < n_fds; i++)
3681 if (fds[i].fd == context->wake_up_rec.fd)
3683 if (fds[i].revents)
3685 TRACE (GLIB_MAIN_CONTEXT_WAKEUP_ACKNOWLEDGE (context));
3686 g_wakeup_acknowledge (context->wakeup);
3688 break;
3692 /* If the set of poll file descriptors changed, bail out
3693 * and let the main loop rerun
3695 if (context->poll_changed)
3697 TRACE (GLIB_MAIN_CONTEXT_AFTER_CHECK (context, 0));
3699 UNLOCK_CONTEXT (context);
3700 return FALSE;
3703 pollrec = context->poll_records;
3704 i = 0;
3705 while (pollrec && i < n_fds)
3707 while (pollrec && pollrec->fd->fd == fds[i].fd)
3709 if (pollrec->priority <= max_priority)
3711 pollrec->fd->revents =
3712 fds[i].revents & (pollrec->fd->events | G_IO_ERR | G_IO_HUP | G_IO_NVAL);
3714 pollrec = pollrec->next;
3717 i++;
3720 g_source_iter_init (&iter, context, TRUE);
3721 while (g_source_iter_next (&iter, &source))
3723 if (SOURCE_DESTROYED (source) || SOURCE_BLOCKED (source))
3724 continue;
3725 if ((n_ready > 0) && (source->priority > max_priority))
3726 break;
3728 if (!(source->flags & G_SOURCE_READY))
3730 gboolean result;
3731 gboolean (* check) (GSource *source);
3733 check = source->source_funcs->check;
3735 if (check)
3737 /* If the check function is set, call it. */
3738 context->in_check_or_prepare++;
3739 UNLOCK_CONTEXT (context);
3741 result = (* check) (source);
3743 TRACE (GLIB_MAIN_AFTER_CHECK (source, check, result));
3745 LOCK_CONTEXT (context);
3746 context->in_check_or_prepare--;
3748 else
3749 result = FALSE;
3751 if (result == FALSE)
3753 GSList *tmp_list;
3755 /* If not already explicitly flagged ready by ->check()
3756 * (or if we have no check) then we can still be ready if
3757 * any of our fds poll as ready.
3759 for (tmp_list = source->priv->fds; tmp_list; tmp_list = tmp_list->next)
3761 GPollFD *pollfd = tmp_list->data;
3763 if (pollfd->revents)
3765 result = TRUE;
3766 break;
3771 if (result == FALSE && source->priv->ready_time != -1)
3773 if (!context->time_is_fresh)
3775 context->time = g_get_monotonic_time ();
3776 context->time_is_fresh = TRUE;
3779 if (source->priv->ready_time <= context->time)
3780 result = TRUE;
3783 if (result)
3785 GSource *ready_source = source;
3787 while (ready_source)
3789 ready_source->flags |= G_SOURCE_READY;
3790 ready_source = ready_source->priv->parent_source;
3795 if (source->flags & G_SOURCE_READY)
3797 source->ref_count++;
3798 g_ptr_array_add (context->pending_dispatches, source);
3800 n_ready++;
3802 /* never dispatch sources with less priority than the first
3803 * one we choose to dispatch
3805 max_priority = source->priority;
3808 g_source_iter_clear (&iter);
3810 TRACE (GLIB_MAIN_CONTEXT_AFTER_CHECK (context, n_ready));
3812 UNLOCK_CONTEXT (context);
3814 return n_ready > 0;
3818 * g_main_context_dispatch:
3819 * @context: a #GMainContext
3821 * Dispatches all pending sources.
3823 * You must have successfully acquired the context with
3824 * g_main_context_acquire() before you may call this function.
3826 void
3827 g_main_context_dispatch (GMainContext *context)
3829 LOCK_CONTEXT (context);
3831 TRACE (GLIB_MAIN_CONTEXT_BEFORE_DISPATCH (context));
3833 if (context->pending_dispatches->len > 0)
3835 g_main_dispatch (context);
3838 TRACE (GLIB_MAIN_CONTEXT_AFTER_DISPATCH (context));
3840 UNLOCK_CONTEXT (context);
3843 /* HOLDS context lock */
3844 static gboolean
3845 g_main_context_iterate (GMainContext *context,
3846 gboolean block,
3847 gboolean dispatch,
3848 GThread *self)
3850 gint max_priority;
3851 gint timeout;
3852 gboolean some_ready;
3853 gint nfds, allocated_nfds;
3854 GPollFD *fds = NULL;
3856 UNLOCK_CONTEXT (context);
3858 if (!g_main_context_acquire (context))
3860 gboolean got_ownership;
3862 LOCK_CONTEXT (context);
3864 if (!block)
3865 return FALSE;
3867 got_ownership = g_main_context_wait (context,
3868 &context->cond,
3869 &context->mutex);
3871 if (!got_ownership)
3872 return FALSE;
3874 else
3875 LOCK_CONTEXT (context);
3877 if (!context->cached_poll_array)
3879 context->cached_poll_array_size = context->n_poll_records;
3880 context->cached_poll_array = g_new (GPollFD, context->n_poll_records);
3883 allocated_nfds = context->cached_poll_array_size;
3884 fds = context->cached_poll_array;
3886 UNLOCK_CONTEXT (context);
3888 g_main_context_prepare (context, &max_priority);
3890 while ((nfds = g_main_context_query (context, max_priority, &timeout, fds,
3891 allocated_nfds)) > allocated_nfds)
3893 LOCK_CONTEXT (context);
3894 g_free (fds);
3895 context->cached_poll_array_size = allocated_nfds = nfds;
3896 context->cached_poll_array = fds = g_new (GPollFD, nfds);
3897 UNLOCK_CONTEXT (context);
3900 if (!block)
3901 timeout = 0;
3903 g_main_context_poll (context, timeout, max_priority, fds, nfds);
3905 some_ready = g_main_context_check (context, max_priority, fds, nfds);
3907 if (dispatch)
3908 g_main_context_dispatch (context);
3910 g_main_context_release (context);
3912 LOCK_CONTEXT (context);
3914 return some_ready;
3918 * g_main_context_pending:
3919 * @context: (nullable): a #GMainContext (if %NULL, the default context will be used)
3921 * Checks if any sources have pending events for the given context.
3923 * Returns: %TRUE if events are pending.
3925 gboolean
3926 g_main_context_pending (GMainContext *context)
3928 gboolean retval;
3930 if (!context)
3931 context = g_main_context_default();
3933 LOCK_CONTEXT (context);
3934 retval = g_main_context_iterate (context, FALSE, FALSE, G_THREAD_SELF);
3935 UNLOCK_CONTEXT (context);
3937 return retval;
3941 * g_main_context_iteration:
3942 * @context: (nullable): a #GMainContext (if %NULL, the default context will be used)
3943 * @may_block: whether the call may block.
3945 * Runs a single iteration for the given main loop. This involves
3946 * checking to see if any event sources are ready to be processed,
3947 * then if no events sources are ready and @may_block is %TRUE, waiting
3948 * for a source to become ready, then dispatching the highest priority
3949 * events sources that are ready. Otherwise, if @may_block is %FALSE
3950 * sources are not waited to become ready, only those highest priority
3951 * events sources will be dispatched (if any), that are ready at this
3952 * given moment without further waiting.
3954 * Note that even when @may_block is %TRUE, it is still possible for
3955 * g_main_context_iteration() to return %FALSE, since the wait may
3956 * be interrupted for other reasons than an event source becoming ready.
3958 * Returns: %TRUE if events were dispatched.
3960 gboolean
3961 g_main_context_iteration (GMainContext *context, gboolean may_block)
3963 gboolean retval;
3965 if (!context)
3966 context = g_main_context_default();
3968 LOCK_CONTEXT (context);
3969 retval = g_main_context_iterate (context, may_block, TRUE, G_THREAD_SELF);
3970 UNLOCK_CONTEXT (context);
3972 return retval;
3976 * g_main_loop_new:
3977 * @context: (nullable): a #GMainContext (if %NULL, the default context will be used).
3978 * @is_running: set to %TRUE to indicate that the loop is running. This
3979 * is not very important since calling g_main_loop_run() will set this to
3980 * %TRUE anyway.
3982 * Creates a new #GMainLoop structure.
3984 * Returns: a new #GMainLoop.
3986 GMainLoop *
3987 g_main_loop_new (GMainContext *context,
3988 gboolean is_running)
3990 GMainLoop *loop;
3992 if (!context)
3993 context = g_main_context_default();
3995 g_main_context_ref (context);
3997 loop = g_new0 (GMainLoop, 1);
3998 loop->context = context;
3999 loop->is_running = is_running != FALSE;
4000 loop->ref_count = 1;
4002 TRACE (GLIB_MAIN_LOOP_NEW (loop, context));
4004 return loop;
4008 * g_main_loop_ref:
4009 * @loop: a #GMainLoop
4011 * Increases the reference count on a #GMainLoop object by one.
4013 * Returns: @loop
4015 GMainLoop *
4016 g_main_loop_ref (GMainLoop *loop)
4018 g_return_val_if_fail (loop != NULL, NULL);
4019 g_return_val_if_fail (g_atomic_int_get (&loop->ref_count) > 0, NULL);
4021 g_atomic_int_inc (&loop->ref_count);
4023 return loop;
4027 * g_main_loop_unref:
4028 * @loop: a #GMainLoop
4030 * Decreases the reference count on a #GMainLoop object by one. If
4031 * the result is zero, free the loop and free all associated memory.
4033 void
4034 g_main_loop_unref (GMainLoop *loop)
4036 g_return_if_fail (loop != NULL);
4037 g_return_if_fail (g_atomic_int_get (&loop->ref_count) > 0);
4039 if (!g_atomic_int_dec_and_test (&loop->ref_count))
4040 return;
4042 g_main_context_unref (loop->context);
4043 g_free (loop);
4047 * g_main_loop_run:
4048 * @loop: a #GMainLoop
4050 * Runs a main loop until g_main_loop_quit() is called on the loop.
4051 * If this is called for the thread of the loop's #GMainContext,
4052 * it will process events from the loop, otherwise it will
4053 * simply wait.
4055 void
4056 g_main_loop_run (GMainLoop *loop)
4058 GThread *self = G_THREAD_SELF;
4060 g_return_if_fail (loop != NULL);
4061 g_return_if_fail (g_atomic_int_get (&loop->ref_count) > 0);
4063 if (!g_main_context_acquire (loop->context))
4065 gboolean got_ownership = FALSE;
4067 /* Another thread owns this context */
4068 LOCK_CONTEXT (loop->context);
4070 g_atomic_int_inc (&loop->ref_count);
4072 if (!loop->is_running)
4073 loop->is_running = TRUE;
4075 while (loop->is_running && !got_ownership)
4076 got_ownership = g_main_context_wait (loop->context,
4077 &loop->context->cond,
4078 &loop->context->mutex);
4080 if (!loop->is_running)
4082 UNLOCK_CONTEXT (loop->context);
4083 if (got_ownership)
4084 g_main_context_release (loop->context);
4085 g_main_loop_unref (loop);
4086 return;
4089 g_assert (got_ownership);
4091 else
4092 LOCK_CONTEXT (loop->context);
4094 if (loop->context->in_check_or_prepare)
4096 g_warning ("g_main_loop_run(): called recursively from within a source's "
4097 "check() or prepare() member, iteration not possible.");
4098 return;
4101 g_atomic_int_inc (&loop->ref_count);
4102 loop->is_running = TRUE;
4103 while (loop->is_running)
4104 g_main_context_iterate (loop->context, TRUE, TRUE, self);
4106 UNLOCK_CONTEXT (loop->context);
4108 g_main_context_release (loop->context);
4110 g_main_loop_unref (loop);
4114 * g_main_loop_quit:
4115 * @loop: a #GMainLoop
4117 * Stops a #GMainLoop from running. Any calls to g_main_loop_run()
4118 * for the loop will return.
4120 * Note that sources that have already been dispatched when
4121 * g_main_loop_quit() is called will still be executed.
4123 void
4124 g_main_loop_quit (GMainLoop *loop)
4126 g_return_if_fail (loop != NULL);
4127 g_return_if_fail (g_atomic_int_get (&loop->ref_count) > 0);
4129 LOCK_CONTEXT (loop->context);
4130 loop->is_running = FALSE;
4131 g_wakeup_signal (loop->context->wakeup);
4133 g_cond_broadcast (&loop->context->cond);
4135 UNLOCK_CONTEXT (loop->context);
4137 TRACE (GLIB_MAIN_LOOP_QUIT (loop));
4141 * g_main_loop_is_running:
4142 * @loop: a #GMainLoop.
4144 * Checks to see if the main loop is currently being run via g_main_loop_run().
4146 * Returns: %TRUE if the mainloop is currently being run.
4148 gboolean
4149 g_main_loop_is_running (GMainLoop *loop)
4151 g_return_val_if_fail (loop != NULL, FALSE);
4152 g_return_val_if_fail (g_atomic_int_get (&loop->ref_count) > 0, FALSE);
4154 return loop->is_running;
4158 * g_main_loop_get_context:
4159 * @loop: a #GMainLoop.
4161 * Returns the #GMainContext of @loop.
4163 * Returns: (transfer none): the #GMainContext of @loop
4165 GMainContext *
4166 g_main_loop_get_context (GMainLoop *loop)
4168 g_return_val_if_fail (loop != NULL, NULL);
4169 g_return_val_if_fail (g_atomic_int_get (&loop->ref_count) > 0, NULL);
4171 return loop->context;
4174 /* HOLDS: context's lock */
4175 static void
4176 g_main_context_poll (GMainContext *context,
4177 gint timeout,
4178 gint priority,
4179 GPollFD *fds,
4180 gint n_fds)
4182 #ifdef G_MAIN_POLL_DEBUG
4183 GTimer *poll_timer;
4184 GPollRec *pollrec;
4185 gint i;
4186 #endif
4188 GPollFunc poll_func;
4190 if (n_fds || timeout != 0)
4192 int ret, errsv;
4194 #ifdef G_MAIN_POLL_DEBUG
4195 poll_timer = NULL;
4196 if (_g_main_poll_debug)
4198 g_print ("polling context=%p n=%d timeout=%d\n",
4199 context, n_fds, timeout);
4200 poll_timer = g_timer_new ();
4202 #endif
4204 LOCK_CONTEXT (context);
4206 poll_func = context->poll_func;
4208 UNLOCK_CONTEXT (context);
4209 ret = (*poll_func) (fds, n_fds, timeout);
4210 errsv = errno;
4211 if (ret < 0 && errsv != EINTR)
4213 #ifndef G_OS_WIN32
4214 g_warning ("poll(2) failed due to: %s.",
4215 g_strerror (errsv));
4216 #else
4217 /* If g_poll () returns -1, it has already called g_warning() */
4218 #endif
4221 #ifdef G_MAIN_POLL_DEBUG
4222 if (_g_main_poll_debug)
4224 LOCK_CONTEXT (context);
4226 g_print ("g_main_poll(%d) timeout: %d - elapsed %12.10f seconds",
4227 n_fds,
4228 timeout,
4229 g_timer_elapsed (poll_timer, NULL));
4230 g_timer_destroy (poll_timer);
4231 pollrec = context->poll_records;
4233 while (pollrec != NULL)
4235 i = 0;
4236 while (i < n_fds)
4238 if (fds[i].fd == pollrec->fd->fd &&
4239 pollrec->fd->events &&
4240 fds[i].revents)
4242 g_print (" [" G_POLLFD_FORMAT " :", fds[i].fd);
4243 if (fds[i].revents & G_IO_IN)
4244 g_print ("i");
4245 if (fds[i].revents & G_IO_OUT)
4246 g_print ("o");
4247 if (fds[i].revents & G_IO_PRI)
4248 g_print ("p");
4249 if (fds[i].revents & G_IO_ERR)
4250 g_print ("e");
4251 if (fds[i].revents & G_IO_HUP)
4252 g_print ("h");
4253 if (fds[i].revents & G_IO_NVAL)
4254 g_print ("n");
4255 g_print ("]");
4257 i++;
4259 pollrec = pollrec->next;
4261 g_print ("\n");
4263 UNLOCK_CONTEXT (context);
4265 #endif
4266 } /* if (n_fds || timeout != 0) */
4270 * g_main_context_add_poll:
4271 * @context: (nullable): a #GMainContext (or %NULL for the default context)
4272 * @fd: a #GPollFD structure holding information about a file
4273 * descriptor to watch.
4274 * @priority: the priority for this file descriptor which should be
4275 * the same as the priority used for g_source_attach() to ensure that the
4276 * file descriptor is polled whenever the results may be needed.
4278 * Adds a file descriptor to the set of file descriptors polled for
4279 * this context. This will very seldom be used directly. Instead
4280 * a typical event source will use g_source_add_unix_fd() instead.
4282 void
4283 g_main_context_add_poll (GMainContext *context,
4284 GPollFD *fd,
4285 gint priority)
4287 if (!context)
4288 context = g_main_context_default ();
4290 g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
4291 g_return_if_fail (fd);
4293 LOCK_CONTEXT (context);
4294 g_main_context_add_poll_unlocked (context, priority, fd);
4295 UNLOCK_CONTEXT (context);
4298 /* HOLDS: main_loop_lock */
4299 static void
4300 g_main_context_add_poll_unlocked (GMainContext *context,
4301 gint priority,
4302 GPollFD *fd)
4304 GPollRec *prevrec, *nextrec;
4305 GPollRec *newrec = g_slice_new (GPollRec);
4307 /* This file descriptor may be checked before we ever poll */
4308 fd->revents = 0;
4309 newrec->fd = fd;
4310 newrec->priority = priority;
4312 prevrec = NULL;
4313 nextrec = context->poll_records;
4314 while (nextrec)
4316 if (nextrec->fd->fd > fd->fd)
4317 break;
4318 prevrec = nextrec;
4319 nextrec = nextrec->next;
4322 if (prevrec)
4323 prevrec->next = newrec;
4324 else
4325 context->poll_records = newrec;
4327 newrec->prev = prevrec;
4328 newrec->next = nextrec;
4330 if (nextrec)
4331 nextrec->prev = newrec;
4333 context->n_poll_records++;
4335 context->poll_changed = TRUE;
4337 /* Now wake up the main loop if it is waiting in the poll() */
4338 g_wakeup_signal (context->wakeup);
4342 * g_main_context_remove_poll:
4343 * @context:a #GMainContext
4344 * @fd: a #GPollFD descriptor previously added with g_main_context_add_poll()
4346 * Removes file descriptor from the set of file descriptors to be
4347 * polled for a particular context.
4349 void
4350 g_main_context_remove_poll (GMainContext *context,
4351 GPollFD *fd)
4353 if (!context)
4354 context = g_main_context_default ();
4356 g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
4357 g_return_if_fail (fd);
4359 LOCK_CONTEXT (context);
4360 g_main_context_remove_poll_unlocked (context, fd);
4361 UNLOCK_CONTEXT (context);
4364 static void
4365 g_main_context_remove_poll_unlocked (GMainContext *context,
4366 GPollFD *fd)
4368 GPollRec *pollrec, *prevrec, *nextrec;
4370 prevrec = NULL;
4371 pollrec = context->poll_records;
4373 while (pollrec)
4375 nextrec = pollrec->next;
4376 if (pollrec->fd == fd)
4378 if (prevrec != NULL)
4379 prevrec->next = nextrec;
4380 else
4381 context->poll_records = nextrec;
4383 if (nextrec != NULL)
4384 nextrec->prev = prevrec;
4386 g_slice_free (GPollRec, pollrec);
4388 context->n_poll_records--;
4389 break;
4391 prevrec = pollrec;
4392 pollrec = nextrec;
4395 context->poll_changed = TRUE;
4397 /* Now wake up the main loop if it is waiting in the poll() */
4398 g_wakeup_signal (context->wakeup);
4402 * g_source_get_current_time:
4403 * @source: a #GSource
4404 * @timeval: #GTimeVal structure in which to store current time.
4406 * This function ignores @source and is otherwise the same as
4407 * g_get_current_time().
4409 * Deprecated: 2.28: use g_source_get_time() instead
4411 void
4412 g_source_get_current_time (GSource *source,
4413 GTimeVal *timeval)
4415 g_get_current_time (timeval);
4419 * g_source_get_time:
4420 * @source: a #GSource
4422 * Gets the time to be used when checking this source. The advantage of
4423 * calling this function over calling g_get_monotonic_time() directly is
4424 * that when checking multiple sources, GLib can cache a single value
4425 * instead of having to repeatedly get the system monotonic time.
4427 * The time here is the system monotonic time, if available, or some
4428 * other reasonable alternative otherwise. See g_get_monotonic_time().
4430 * Returns: the monotonic time in microseconds
4432 * Since: 2.28
4434 gint64
4435 g_source_get_time (GSource *source)
4437 GMainContext *context;
4438 gint64 result;
4440 g_return_val_if_fail (source->context != NULL, 0);
4442 context = source->context;
4444 LOCK_CONTEXT (context);
4446 if (!context->time_is_fresh)
4448 context->time = g_get_monotonic_time ();
4449 context->time_is_fresh = TRUE;
4452 result = context->time;
4454 UNLOCK_CONTEXT (context);
4456 return result;
4460 * g_main_context_set_poll_func:
4461 * @context: a #GMainContext
4462 * @func: the function to call to poll all file descriptors
4464 * Sets the function to use to handle polling of file descriptors. It
4465 * will be used instead of the poll() system call
4466 * (or GLib's replacement function, which is used where
4467 * poll() isn't available).
4469 * This function could possibly be used to integrate the GLib event
4470 * loop with an external event loop.
4472 void
4473 g_main_context_set_poll_func (GMainContext *context,
4474 GPollFunc func)
4476 if (!context)
4477 context = g_main_context_default ();
4479 g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
4481 LOCK_CONTEXT (context);
4483 if (func)
4484 context->poll_func = func;
4485 else
4486 context->poll_func = g_poll;
4488 UNLOCK_CONTEXT (context);
4492 * g_main_context_get_poll_func:
4493 * @context: a #GMainContext
4495 * Gets the poll function set by g_main_context_set_poll_func().
4497 * Returns: the poll function
4499 GPollFunc
4500 g_main_context_get_poll_func (GMainContext *context)
4502 GPollFunc result;
4504 if (!context)
4505 context = g_main_context_default ();
4507 g_return_val_if_fail (g_atomic_int_get (&context->ref_count) > 0, NULL);
4509 LOCK_CONTEXT (context);
4510 result = context->poll_func;
4511 UNLOCK_CONTEXT (context);
4513 return result;
4517 * g_main_context_wakeup:
4518 * @context: a #GMainContext
4520 * If @context is currently blocking in g_main_context_iteration()
4521 * waiting for a source to become ready, cause it to stop blocking
4522 * and return. Otherwise, cause the next invocation of
4523 * g_main_context_iteration() to return without blocking.
4525 * This API is useful for low-level control over #GMainContext; for
4526 * example, integrating it with main loop implementations such as
4527 * #GMainLoop.
4529 * Another related use for this function is when implementing a main
4530 * loop with a termination condition, computed from multiple threads:
4532 * |[<!-- language="C" -->
4533 * #define NUM_TASKS 10
4534 * static volatile gint tasks_remaining = NUM_TASKS;
4535 * ...
4537 * while (g_atomic_int_get (&tasks_remaining) != 0)
4538 * g_main_context_iteration (NULL, TRUE);
4539 * ]|
4541 * Then in a thread:
4542 * |[<!-- language="C" -->
4543 * perform_work();
4545 * if (g_atomic_int_dec_and_test (&tasks_remaining))
4546 * g_main_context_wakeup (NULL);
4547 * ]|
4549 void
4550 g_main_context_wakeup (GMainContext *context)
4552 if (!context)
4553 context = g_main_context_default ();
4555 g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
4557 TRACE (GLIB_MAIN_CONTEXT_WAKEUP (context));
4559 g_wakeup_signal (context->wakeup);
4563 * g_main_context_is_owner:
4564 * @context: a #GMainContext
4566 * Determines whether this thread holds the (recursive)
4567 * ownership of this #GMainContext. This is useful to
4568 * know before waiting on another thread that may be
4569 * blocking to get ownership of @context.
4571 * Returns: %TRUE if current thread is owner of @context.
4573 * Since: 2.10
4575 gboolean
4576 g_main_context_is_owner (GMainContext *context)
4578 gboolean is_owner;
4580 if (!context)
4581 context = g_main_context_default ();
4583 LOCK_CONTEXT (context);
4584 is_owner = context->owner == G_THREAD_SELF;
4585 UNLOCK_CONTEXT (context);
4587 return is_owner;
4590 /* Timeouts */
4592 static void
4593 g_timeout_set_expiration (GTimeoutSource *timeout_source,
4594 gint64 current_time)
4596 gint64 expiration;
4598 expiration = current_time + (guint64) timeout_source->interval * 1000;
4600 if (timeout_source->seconds)
4602 gint64 remainder;
4603 static gint timer_perturb = -1;
4605 if (timer_perturb == -1)
4608 * we want a per machine/session unique 'random' value; try the dbus
4609 * address first, that has a UUID in it. If there is no dbus, use the
4610 * hostname for hashing.
4612 const char *session_bus_address = g_getenv ("DBUS_SESSION_BUS_ADDRESS");
4613 if (!session_bus_address)
4614 session_bus_address = g_getenv ("HOSTNAME");
4615 if (session_bus_address)
4616 timer_perturb = ABS ((gint) g_str_hash (session_bus_address)) % 1000000;
4617 else
4618 timer_perturb = 0;
4621 /* We want the microseconds part of the timeout to land on the
4622 * 'timer_perturb' mark, but we need to make sure we don't try to
4623 * set the timeout in the past. We do this by ensuring that we
4624 * always only *increase* the expiration time by adding a full
4625 * second in the case that the microsecond portion decreases.
4627 expiration -= timer_perturb;
4629 remainder = expiration % 1000000;
4630 if (remainder >= 1000000/4)
4631 expiration += 1000000;
4633 expiration -= remainder;
4634 expiration += timer_perturb;
4637 g_source_set_ready_time ((GSource *) timeout_source, expiration);
4640 static gboolean
4641 g_timeout_dispatch (GSource *source,
4642 GSourceFunc callback,
4643 gpointer user_data)
4645 GTimeoutSource *timeout_source = (GTimeoutSource *)source;
4646 gboolean again;
4648 if (!callback)
4650 g_warning ("Timeout source dispatched without callback. "
4651 "You must call g_source_set_callback().");
4652 return FALSE;
4655 again = callback (user_data);
4657 TRACE (GLIB_TIMEOUT_DISPATCH (source, source->context, callback, user_data, again));
4659 if (again)
4660 g_timeout_set_expiration (timeout_source, g_source_get_time (source));
4662 return again;
4666 * g_timeout_source_new:
4667 * @interval: the timeout interval in milliseconds.
4669 * Creates a new timeout source.
4671 * The source will not initially be associated with any #GMainContext
4672 * and must be added to one with g_source_attach() before it will be
4673 * executed.
4675 * The interval given is in terms of monotonic time, not wall clock
4676 * time. See g_get_monotonic_time().
4678 * Returns: the newly-created timeout source
4680 GSource *
4681 g_timeout_source_new (guint interval)
4683 GSource *source = g_source_new (&g_timeout_funcs, sizeof (GTimeoutSource));
4684 GTimeoutSource *timeout_source = (GTimeoutSource *)source;
4686 timeout_source->interval = interval;
4687 g_timeout_set_expiration (timeout_source, g_get_monotonic_time ());
4689 return source;
4693 * g_timeout_source_new_seconds:
4694 * @interval: the timeout interval in seconds
4696 * Creates a new timeout source.
4698 * The source will not initially be associated with any #GMainContext
4699 * and must be added to one with g_source_attach() before it will be
4700 * executed.
4702 * The scheduling granularity/accuracy of this timeout source will be
4703 * in seconds.
4705 * The interval given is in terms of monotonic time, not wall clock time.
4706 * See g_get_monotonic_time().
4708 * Returns: the newly-created timeout source
4710 * Since: 2.14
4712 GSource *
4713 g_timeout_source_new_seconds (guint interval)
4715 GSource *source = g_source_new (&g_timeout_funcs, sizeof (GTimeoutSource));
4716 GTimeoutSource *timeout_source = (GTimeoutSource *)source;
4718 timeout_source->interval = 1000 * interval;
4719 timeout_source->seconds = TRUE;
4721 g_timeout_set_expiration (timeout_source, g_get_monotonic_time ());
4723 return source;
4728 * g_timeout_add_full: (rename-to g_timeout_add)
4729 * @priority: the priority of the timeout source. Typically this will be in
4730 * the range between #G_PRIORITY_DEFAULT and #G_PRIORITY_HIGH.
4731 * @interval: the time between calls to the function, in milliseconds
4732 * (1/1000ths of a second)
4733 * @function: function to call
4734 * @data: data to pass to @function
4735 * @notify: (nullable): function to call when the timeout is removed, or %NULL
4737 * Sets a function to be called at regular intervals, with the given
4738 * priority. The function is called repeatedly until it returns
4739 * %FALSE, at which point the timeout is automatically destroyed and
4740 * the function will not be called again. The @notify function is
4741 * called when the timeout is destroyed. The first call to the
4742 * function will be at the end of the first @interval.
4744 * Note that timeout functions may be delayed, due to the processing of other
4745 * event sources. Thus they should not be relied on for precise timing.
4746 * After each call to the timeout function, the time of the next
4747 * timeout is recalculated based on the current time and the given interval
4748 * (it does not try to 'catch up' time lost in delays).
4750 * See [memory management of sources][mainloop-memory-management] for details
4751 * on how to handle the return value and memory management of @data.
4753 * This internally creates a main loop source using g_timeout_source_new()
4754 * and attaches it to the global #GMainContext using g_source_attach(), so
4755 * the callback will be invoked in whichever thread is running that main
4756 * context. You can do these steps manually if you need greater control or to
4757 * use a custom main context.
4759 * The interval given is in terms of monotonic time, not wall clock time.
4760 * See g_get_monotonic_time().
4762 * Returns: the ID (greater than 0) of the event source.
4764 guint
4765 g_timeout_add_full (gint priority,
4766 guint interval,
4767 GSourceFunc function,
4768 gpointer data,
4769 GDestroyNotify notify)
4771 GSource *source;
4772 guint id;
4774 g_return_val_if_fail (function != NULL, 0);
4776 source = g_timeout_source_new (interval);
4778 if (priority != G_PRIORITY_DEFAULT)
4779 g_source_set_priority (source, priority);
4781 g_source_set_callback (source, function, data, notify);
4782 id = g_source_attach (source, NULL);
4784 TRACE (GLIB_TIMEOUT_ADD (source, g_main_context_default (), id, priority, interval, function, data));
4786 g_source_unref (source);
4788 return id;
4792 * g_timeout_add:
4793 * @interval: the time between calls to the function, in milliseconds
4794 * (1/1000ths of a second)
4795 * @function: function to call
4796 * @data: data to pass to @function
4798 * Sets a function to be called at regular intervals, with the default
4799 * priority, #G_PRIORITY_DEFAULT. The function is called repeatedly
4800 * until it returns %FALSE, at which point the timeout is automatically
4801 * destroyed and the function will not be called again. The first call
4802 * to the function will be at the end of the first @interval.
4804 * Note that timeout functions may be delayed, due to the processing of other
4805 * event sources. Thus they should not be relied on for precise timing.
4806 * After each call to the timeout function, the time of the next
4807 * timeout is recalculated based on the current time and the given interval
4808 * (it does not try to 'catch up' time lost in delays).
4810 * See [memory management of sources][mainloop-memory-management] for details
4811 * on how to handle the return value and memory management of @data.
4813 * If you want to have a timer in the "seconds" range and do not care
4814 * about the exact time of the first call of the timer, use the
4815 * g_timeout_add_seconds() function; this function allows for more
4816 * optimizations and more efficient system power usage.
4818 * This internally creates a main loop source using g_timeout_source_new()
4819 * and attaches it to the global #GMainContext using g_source_attach(), so
4820 * the callback will be invoked in whichever thread is running that main
4821 * context. You can do these steps manually if you need greater control or to
4822 * use a custom main context.
4824 * The interval given is in terms of monotonic time, not wall clock
4825 * time. See g_get_monotonic_time().
4827 * Returns: the ID (greater than 0) of the event source.
4829 guint
4830 g_timeout_add (guint32 interval,
4831 GSourceFunc function,
4832 gpointer data)
4834 return g_timeout_add_full (G_PRIORITY_DEFAULT,
4835 interval, function, data, NULL);
4839 * g_timeout_add_seconds_full: (rename-to g_timeout_add_seconds)
4840 * @priority: the priority of the timeout source. Typically this will be in
4841 * the range between #G_PRIORITY_DEFAULT and #G_PRIORITY_HIGH.
4842 * @interval: the time between calls to the function, in seconds
4843 * @function: function to call
4844 * @data: data to pass to @function
4845 * @notify: (nullable): function to call when the timeout is removed, or %NULL
4847 * Sets a function to be called at regular intervals, with @priority.
4848 * The function is called repeatedly until it returns %FALSE, at which
4849 * point the timeout is automatically destroyed and the function will
4850 * not be called again.
4852 * Unlike g_timeout_add(), this function operates at whole second granularity.
4853 * The initial starting point of the timer is determined by the implementation
4854 * and the implementation is expected to group multiple timers together so that
4855 * they fire all at the same time.
4856 * To allow this grouping, the @interval to the first timer is rounded
4857 * and can deviate up to one second from the specified interval.
4858 * Subsequent timer iterations will generally run at the specified interval.
4860 * Note that timeout functions may be delayed, due to the processing of other
4861 * event sources. Thus they should not be relied on for precise timing.
4862 * After each call to the timeout function, the time of the next
4863 * timeout is recalculated based on the current time and the given @interval
4865 * See [memory management of sources][mainloop-memory-management] for details
4866 * on how to handle the return value and memory management of @data.
4868 * If you want timing more precise than whole seconds, use g_timeout_add()
4869 * instead.
4871 * The grouping of timers to fire at the same time results in a more power
4872 * and CPU efficient behavior so if your timer is in multiples of seconds
4873 * and you don't require the first timer exactly one second from now, the
4874 * use of g_timeout_add_seconds() is preferred over g_timeout_add().
4876 * This internally creates a main loop source using
4877 * g_timeout_source_new_seconds() and attaches it to the main loop context
4878 * using g_source_attach(). You can do these steps manually if you need
4879 * greater control.
4881 * The interval given is in terms of monotonic time, not wall clock
4882 * time. See g_get_monotonic_time().
4884 * Returns: the ID (greater than 0) of the event source.
4886 * Since: 2.14
4888 guint
4889 g_timeout_add_seconds_full (gint priority,
4890 guint32 interval,
4891 GSourceFunc function,
4892 gpointer data,
4893 GDestroyNotify notify)
4895 GSource *source;
4896 guint id;
4898 g_return_val_if_fail (function != NULL, 0);
4900 source = g_timeout_source_new_seconds (interval);
4902 if (priority != G_PRIORITY_DEFAULT)
4903 g_source_set_priority (source, priority);
4905 g_source_set_callback (source, function, data, notify);
4906 id = g_source_attach (source, NULL);
4907 g_source_unref (source);
4909 return id;
4913 * g_timeout_add_seconds:
4914 * @interval: the time between calls to the function, in seconds
4915 * @function: function to call
4916 * @data: data to pass to @function
4918 * Sets a function to be called at regular intervals with the default
4919 * priority, #G_PRIORITY_DEFAULT. The function is called repeatedly until
4920 * it returns %FALSE, at which point the timeout is automatically destroyed
4921 * and the function will not be called again.
4923 * This internally creates a main loop source using
4924 * g_timeout_source_new_seconds() and attaches it to the main loop context
4925 * using g_source_attach(). You can do these steps manually if you need
4926 * greater control. Also see g_timeout_add_seconds_full().
4928 * Note that the first call of the timer may not be precise for timeouts
4929 * of one second. If you need finer precision and have such a timeout,
4930 * you may want to use g_timeout_add() instead.
4932 * See [memory management of sources][mainloop-memory-management] for details
4933 * on how to handle the return value and memory management of @data.
4935 * The interval given is in terms of monotonic time, not wall clock
4936 * time. See g_get_monotonic_time().
4938 * Returns: the ID (greater than 0) of the event source.
4940 * Since: 2.14
4942 guint
4943 g_timeout_add_seconds (guint interval,
4944 GSourceFunc function,
4945 gpointer data)
4947 g_return_val_if_fail (function != NULL, 0);
4949 return g_timeout_add_seconds_full (G_PRIORITY_DEFAULT, interval, function, data, NULL);
4952 /* Child watch functions */
4954 #ifdef G_OS_WIN32
4956 static gboolean
4957 g_child_watch_prepare (GSource *source,
4958 gint *timeout)
4960 *timeout = -1;
4961 return FALSE;
4964 static gboolean
4965 g_child_watch_check (GSource *source)
4967 GChildWatchSource *child_watch_source;
4968 gboolean child_exited;
4970 child_watch_source = (GChildWatchSource *) source;
4972 child_exited = child_watch_source->poll.revents & G_IO_IN;
4974 if (child_exited)
4976 DWORD child_status;
4979 * Note: We do _not_ check for the special value of STILL_ACTIVE
4980 * since we know that the process has exited and doing so runs into
4981 * problems if the child process "happens to return STILL_ACTIVE(259)"
4982 * as Microsoft's Platform SDK puts it.
4984 if (!GetExitCodeProcess (child_watch_source->pid, &child_status))
4986 gchar *emsg = g_win32_error_message (GetLastError ());
4987 g_warning (G_STRLOC ": GetExitCodeProcess() failed: %s", emsg);
4988 g_free (emsg);
4990 child_watch_source->child_status = -1;
4992 else
4993 child_watch_source->child_status = child_status;
4996 return child_exited;
4999 static void
5000 g_child_watch_finalize (GSource *source)
5004 #else /* G_OS_WIN32 */
5006 static void
5007 wake_source (GSource *source)
5009 GMainContext *context;
5011 /* This should be thread-safe:
5013 * - if the source is currently being added to a context, that
5014 * context will be woken up anyway
5016 * - if the source is currently being destroyed, we simply need not
5017 * to crash:
5019 * - the memory for the source will remain valid until after the
5020 * source finalize function was called (which would remove the
5021 * source from the global list which we are currently holding the
5022 * lock for)
5024 * - the GMainContext will either be NULL or point to a live
5025 * GMainContext
5027 * - the GMainContext will remain valid since we hold the
5028 * main_context_list lock
5030 * Since we are holding a lot of locks here, don't try to enter any
5031 * more GMainContext functions for fear of dealock -- just hit the
5032 * GWakeup and run. Even if that's safe now, it could easily become
5033 * unsafe with some very minor changes in the future, and signal
5034 * handling is not the most well-tested codepath.
5036 G_LOCK(main_context_list);
5037 context = source->context;
5038 if (context)
5039 g_wakeup_signal (context->wakeup);
5040 G_UNLOCK(main_context_list);
5043 static void
5044 dispatch_unix_signals_unlocked (void)
5046 gboolean pending[NSIG];
5047 GSList *node;
5048 gint i;
5050 /* clear this first in case another one arrives while we're processing */
5051 any_unix_signal_pending = FALSE;
5053 /* We atomically test/clear the bit from the global array in case
5054 * other signals arrive while we are dispatching.
5056 * We then can safely use our own array below without worrying about
5057 * races.
5059 for (i = 0; i < NSIG; i++)
5061 /* Be very careful with (the volatile) unix_signal_pending.
5063 * We must ensure that it's not possible that we clear it without
5064 * handling the signal. We therefore must ensure that our pending
5065 * array has a field set (ie: we will do something about the
5066 * signal) before we clear the item in unix_signal_pending.
5068 * Note specifically: we must check _our_ array.
5070 pending[i] = unix_signal_pending[i];
5071 if (pending[i])
5072 unix_signal_pending[i] = FALSE;
5075 /* handle GChildWatchSource instances */
5076 if (pending[SIGCHLD])
5078 /* The only way we can do this is to scan all of the children.
5080 * The docs promise that we will not reap children that we are not
5081 * explicitly watching, so that ties our hands from calling
5082 * waitpid(-1). We also can't use siginfo's si_pid field since if
5083 * multiple SIGCHLD arrive at the same time, one of them can be
5084 * dropped (since a given UNIX signal can only be pending once).
5086 for (node = unix_child_watches; node; node = node->next)
5088 GChildWatchSource *source = node->data;
5090 if (!source->child_exited)
5092 pid_t pid;
5095 g_assert (source->pid > 0);
5097 pid = waitpid (source->pid, &source->child_status, WNOHANG);
5098 if (pid > 0)
5100 source->child_exited = TRUE;
5101 wake_source ((GSource *) source);
5103 else if (pid == -1 && errno == ECHILD)
5105 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.");
5106 source->child_exited = TRUE;
5107 source->child_status = 0;
5108 wake_source ((GSource *) source);
5111 while (pid == -1 && errno == EINTR);
5116 /* handle GUnixSignalWatchSource instances */
5117 for (node = unix_signal_watches; node; node = node->next)
5119 GUnixSignalWatchSource *source = node->data;
5121 if (!source->pending)
5123 if (pending[source->signum])
5125 source->pending = TRUE;
5127 wake_source ((GSource *) source);
5134 static void
5135 dispatch_unix_signals (void)
5137 G_LOCK(unix_signal_lock);
5138 dispatch_unix_signals_unlocked ();
5139 G_UNLOCK(unix_signal_lock);
5142 static gboolean
5143 g_child_watch_prepare (GSource *source,
5144 gint *timeout)
5146 GChildWatchSource *child_watch_source;
5148 child_watch_source = (GChildWatchSource *) source;
5150 return child_watch_source->child_exited;
5153 static gboolean
5154 g_child_watch_check (GSource *source)
5156 GChildWatchSource *child_watch_source;
5158 child_watch_source = (GChildWatchSource *) source;
5160 return child_watch_source->child_exited;
5163 static gboolean
5164 g_unix_signal_watch_prepare (GSource *source,
5165 gint *timeout)
5167 GUnixSignalWatchSource *unix_signal_source;
5169 unix_signal_source = (GUnixSignalWatchSource *) source;
5171 return unix_signal_source->pending;
5174 static gboolean
5175 g_unix_signal_watch_check (GSource *source)
5177 GUnixSignalWatchSource *unix_signal_source;
5179 unix_signal_source = (GUnixSignalWatchSource *) source;
5181 return unix_signal_source->pending;
5184 static gboolean
5185 g_unix_signal_watch_dispatch (GSource *source,
5186 GSourceFunc callback,
5187 gpointer user_data)
5189 GUnixSignalWatchSource *unix_signal_source;
5190 gboolean again;
5192 unix_signal_source = (GUnixSignalWatchSource *) source;
5194 if (!callback)
5196 g_warning ("Unix signal source dispatched without callback. "
5197 "You must call g_source_set_callback().");
5198 return FALSE;
5201 again = (callback) (user_data);
5203 unix_signal_source->pending = FALSE;
5205 return again;
5208 static void
5209 ref_unix_signal_handler_unlocked (int signum)
5211 /* Ensure we have the worker context */
5212 g_get_worker_context ();
5213 unix_signal_refcount[signum]++;
5214 if (unix_signal_refcount[signum] == 1)
5216 struct sigaction action;
5217 action.sa_handler = g_unix_signal_handler;
5218 sigemptyset (&action.sa_mask);
5219 #ifdef SA_RESTART
5220 action.sa_flags = SA_RESTART | SA_NOCLDSTOP;
5221 #else
5222 action.sa_flags = SA_NOCLDSTOP;
5223 #endif
5224 sigaction (signum, &action, NULL);
5228 static void
5229 unref_unix_signal_handler_unlocked (int signum)
5231 unix_signal_refcount[signum]--;
5232 if (unix_signal_refcount[signum] == 0)
5234 struct sigaction action;
5235 memset (&action, 0, sizeof (action));
5236 action.sa_handler = SIG_DFL;
5237 sigemptyset (&action.sa_mask);
5238 sigaction (signum, &action, NULL);
5242 GSource *
5243 _g_main_create_unix_signal_watch (int signum)
5245 GSource *source;
5246 GUnixSignalWatchSource *unix_signal_source;
5248 source = g_source_new (&g_unix_signal_funcs, sizeof (GUnixSignalWatchSource));
5249 unix_signal_source = (GUnixSignalWatchSource *) source;
5251 unix_signal_source->signum = signum;
5252 unix_signal_source->pending = FALSE;
5254 G_LOCK (unix_signal_lock);
5255 ref_unix_signal_handler_unlocked (signum);
5256 unix_signal_watches = g_slist_prepend (unix_signal_watches, unix_signal_source);
5257 dispatch_unix_signals_unlocked ();
5258 G_UNLOCK (unix_signal_lock);
5260 return source;
5263 static void
5264 g_unix_signal_watch_finalize (GSource *source)
5266 GUnixSignalWatchSource *unix_signal_source;
5268 unix_signal_source = (GUnixSignalWatchSource *) source;
5270 G_LOCK (unix_signal_lock);
5271 unref_unix_signal_handler_unlocked (unix_signal_source->signum);
5272 unix_signal_watches = g_slist_remove (unix_signal_watches, source);
5273 G_UNLOCK (unix_signal_lock);
5276 static void
5277 g_child_watch_finalize (GSource *source)
5279 G_LOCK (unix_signal_lock);
5280 unix_child_watches = g_slist_remove (unix_child_watches, source);
5281 unref_unix_signal_handler_unlocked (SIGCHLD);
5282 G_UNLOCK (unix_signal_lock);
5285 #endif /* G_OS_WIN32 */
5287 static gboolean
5288 g_child_watch_dispatch (GSource *source,
5289 GSourceFunc callback,
5290 gpointer user_data)
5292 GChildWatchSource *child_watch_source;
5293 GChildWatchFunc child_watch_callback = (GChildWatchFunc) callback;
5295 child_watch_source = (GChildWatchSource *) source;
5297 if (!callback)
5299 g_warning ("Child watch source dispatched without callback. "
5300 "You must call g_source_set_callback().");
5301 return FALSE;
5304 (child_watch_callback) (child_watch_source->pid, child_watch_source->child_status, user_data);
5306 /* We never keep a child watch source around as the child is gone */
5307 return FALSE;
5310 #ifndef G_OS_WIN32
5312 static void
5313 g_unix_signal_handler (int signum)
5315 gint saved_errno = errno;
5317 unix_signal_pending[signum] = TRUE;
5318 any_unix_signal_pending = TRUE;
5320 g_wakeup_signal (glib_worker_context->wakeup);
5322 errno = saved_errno;
5325 #endif /* !G_OS_WIN32 */
5328 * g_child_watch_source_new:
5329 * @pid: process to watch. On POSIX the positive pid of a child process. On
5330 * Windows a handle for a process (which doesn't have to be a child).
5332 * Creates a new child_watch source.
5334 * The source will not initially be associated with any #GMainContext
5335 * and must be added to one with g_source_attach() before it will be
5336 * executed.
5338 * Note that child watch sources can only be used in conjunction with
5339 * `g_spawn...` when the %G_SPAWN_DO_NOT_REAP_CHILD flag is used.
5341 * Note that on platforms where #GPid must be explicitly closed
5342 * (see g_spawn_close_pid()) @pid must not be closed while the
5343 * source is still active. Typically, you will want to call
5344 * g_spawn_close_pid() in the callback function for the source.
5346 * On POSIX platforms, the following restrictions apply to this API
5347 * due to limitations in POSIX process interfaces:
5349 * * @pid must be a child of this process
5350 * * @pid must be positive
5351 * * the application must not call `waitpid` with a non-positive
5352 * first argument, for instance in another thread
5353 * * the application must not wait for @pid to exit by any other
5354 * mechanism, including `waitpid(pid, ...)` or a second child-watch
5355 * source for the same @pid
5356 * * the application must not ignore SIGCHILD
5358 * If any of those conditions are not met, this and related APIs will
5359 * not work correctly. This can often be diagnosed via a GLib warning
5360 * stating that `ECHILD` was received by `waitpid`.
5362 * Calling `waitpid` for specific processes other than @pid remains a
5363 * valid thing to do.
5365 * Returns: the newly-created child watch source
5367 * Since: 2.4
5369 GSource *
5370 g_child_watch_source_new (GPid pid)
5372 GSource *source;
5373 GChildWatchSource *child_watch_source;
5375 #ifndef G_OS_WIN32
5376 g_return_val_if_fail (pid > 0, NULL);
5377 #endif
5379 source = g_source_new (&g_child_watch_funcs, sizeof (GChildWatchSource));
5380 child_watch_source = (GChildWatchSource *)source;
5382 child_watch_source->pid = pid;
5384 #ifdef G_OS_WIN32
5385 child_watch_source->poll.fd = (gintptr) pid;
5386 child_watch_source->poll.events = G_IO_IN;
5388 g_source_add_poll (source, &child_watch_source->poll);
5389 #else /* G_OS_WIN32 */
5390 G_LOCK (unix_signal_lock);
5391 ref_unix_signal_handler_unlocked (SIGCHLD);
5392 unix_child_watches = g_slist_prepend (unix_child_watches, child_watch_source);
5393 if (waitpid (pid, &child_watch_source->child_status, WNOHANG) > 0)
5394 child_watch_source->child_exited = TRUE;
5395 G_UNLOCK (unix_signal_lock);
5396 #endif /* G_OS_WIN32 */
5398 return source;
5402 * g_child_watch_add_full: (rename-to g_child_watch_add)
5403 * @priority: the priority of the idle source. Typically this will be in the
5404 * range between #G_PRIORITY_DEFAULT_IDLE and #G_PRIORITY_HIGH_IDLE.
5405 * @pid: process to watch. On POSIX the positive pid of a child process. On
5406 * Windows a handle for a process (which doesn't have to be a child).
5407 * @function: function to call
5408 * @data: data to pass to @function
5409 * @notify: (nullable): function to call when the idle is removed, or %NULL
5411 * Sets a function to be called when the child indicated by @pid
5412 * exits, at the priority @priority.
5414 * If you obtain @pid from g_spawn_async() or g_spawn_async_with_pipes()
5415 * you will need to pass #G_SPAWN_DO_NOT_REAP_CHILD as flag to
5416 * the spawn function for the child watching to work.
5418 * In many programs, you will want to call g_spawn_check_exit_status()
5419 * in the callback to determine whether or not the child exited
5420 * successfully.
5422 * Also, note that on platforms where #GPid must be explicitly closed
5423 * (see g_spawn_close_pid()) @pid must not be closed while the source
5424 * is still active. Typically, you should invoke g_spawn_close_pid()
5425 * in the callback function for the source.
5427 * GLib supports only a single callback per process id.
5428 * On POSIX platforms, the same restrictions mentioned for
5429 * g_child_watch_source_new() apply to this function.
5431 * This internally creates a main loop source using
5432 * g_child_watch_source_new() and attaches it to the main loop context
5433 * using g_source_attach(). You can do these steps manually if you
5434 * need greater control.
5436 * Returns: the ID (greater than 0) of the event source.
5438 * Since: 2.4
5440 guint
5441 g_child_watch_add_full (gint priority,
5442 GPid pid,
5443 GChildWatchFunc function,
5444 gpointer data,
5445 GDestroyNotify notify)
5447 GSource *source;
5448 guint id;
5450 g_return_val_if_fail (function != NULL, 0);
5451 #ifndef G_OS_WIN32
5452 g_return_val_if_fail (pid > 0, 0);
5453 #endif
5455 source = g_child_watch_source_new (pid);
5457 if (priority != G_PRIORITY_DEFAULT)
5458 g_source_set_priority (source, priority);
5460 g_source_set_callback (source, (GSourceFunc) function, data, notify);
5461 id = g_source_attach (source, NULL);
5462 g_source_unref (source);
5464 return id;
5468 * g_child_watch_add:
5469 * @pid: process id to watch. On POSIX the positive pid of a child
5470 * process. On Windows a handle for a process (which doesn't have to be
5471 * a child).
5472 * @function: function to call
5473 * @data: data to pass to @function
5475 * Sets a function to be called when the child indicated by @pid
5476 * exits, at a default priority, #G_PRIORITY_DEFAULT.
5478 * If you obtain @pid from g_spawn_async() or g_spawn_async_with_pipes()
5479 * you will need to pass #G_SPAWN_DO_NOT_REAP_CHILD as flag to
5480 * the spawn function for the child watching to work.
5482 * Note that on platforms where #GPid must be explicitly closed
5483 * (see g_spawn_close_pid()) @pid must not be closed while the
5484 * source is still active. Typically, you will want to call
5485 * g_spawn_close_pid() in the callback function for the source.
5487 * GLib supports only a single callback per process id.
5488 * On POSIX platforms, the same restrictions mentioned for
5489 * g_child_watch_source_new() apply to this function.
5491 * This internally creates a main loop source using
5492 * g_child_watch_source_new() and attaches it to the main loop context
5493 * using g_source_attach(). You can do these steps manually if you
5494 * need greater control.
5496 * Returns: the ID (greater than 0) of the event source.
5498 * Since: 2.4
5500 guint
5501 g_child_watch_add (GPid pid,
5502 GChildWatchFunc function,
5503 gpointer data)
5505 return g_child_watch_add_full (G_PRIORITY_DEFAULT, pid, function, data, NULL);
5509 /* Idle functions */
5511 static gboolean
5512 g_idle_prepare (GSource *source,
5513 gint *timeout)
5515 *timeout = 0;
5517 return TRUE;
5520 static gboolean
5521 g_idle_check (GSource *source)
5523 return TRUE;
5526 static gboolean
5527 g_idle_dispatch (GSource *source,
5528 GSourceFunc callback,
5529 gpointer user_data)
5531 gboolean again;
5533 if (!callback)
5535 g_warning ("Idle source dispatched without callback. "
5536 "You must call g_source_set_callback().");
5537 return FALSE;
5540 again = callback (user_data);
5542 TRACE (GLIB_IDLE_DISPATCH (source, source->context, callback, user_data, again));
5544 return again;
5548 * g_idle_source_new:
5550 * Creates a new idle source.
5552 * The source will not initially be associated with any #GMainContext
5553 * and must be added to one with g_source_attach() before it will be
5554 * executed. Note that the default priority for idle sources is
5555 * %G_PRIORITY_DEFAULT_IDLE, as compared to other sources which
5556 * have a default priority of %G_PRIORITY_DEFAULT.
5558 * Returns: the newly-created idle source
5560 GSource *
5561 g_idle_source_new (void)
5563 GSource *source;
5565 source = g_source_new (&g_idle_funcs, sizeof (GSource));
5566 g_source_set_priority (source, G_PRIORITY_DEFAULT_IDLE);
5568 return source;
5572 * g_idle_add_full: (rename-to g_idle_add)
5573 * @priority: the priority of the idle source. Typically this will be in the
5574 * range between #G_PRIORITY_DEFAULT_IDLE and #G_PRIORITY_HIGH_IDLE.
5575 * @function: function to call
5576 * @data: data to pass to @function
5577 * @notify: (nullable): function to call when the idle is removed, or %NULL
5579 * Adds a function to be called whenever there are no higher priority
5580 * events pending. If the function returns %FALSE it is automatically
5581 * removed from the list of event sources and will not be called again.
5583 * See [memory management of sources][mainloop-memory-management] for details
5584 * on how to handle the return value and memory management of @data.
5586 * This internally creates a main loop source using g_idle_source_new()
5587 * and attaches it to the global #GMainContext using g_source_attach(), so
5588 * the callback will be invoked in whichever thread is running that main
5589 * context. You can do these steps manually if you need greater control or to
5590 * use a custom main context.
5592 * Returns: the ID (greater than 0) of the event source.
5594 guint
5595 g_idle_add_full (gint priority,
5596 GSourceFunc function,
5597 gpointer data,
5598 GDestroyNotify notify)
5600 GSource *source;
5601 guint id;
5603 g_return_val_if_fail (function != NULL, 0);
5605 source = g_idle_source_new ();
5607 if (priority != G_PRIORITY_DEFAULT_IDLE)
5608 g_source_set_priority (source, priority);
5610 g_source_set_callback (source, function, data, notify);
5611 id = g_source_attach (source, NULL);
5613 TRACE (GLIB_IDLE_ADD (source, g_main_context_default (), id, priority, function, data));
5615 g_source_unref (source);
5617 return id;
5621 * g_idle_add:
5622 * @function: function to call
5623 * @data: data to pass to @function.
5625 * Adds a function to be called whenever there are no higher priority
5626 * events pending to the default main loop. The function is given the
5627 * default idle priority, #G_PRIORITY_DEFAULT_IDLE. If the function
5628 * returns %FALSE it is automatically removed from the list of event
5629 * sources and will not be called again.
5631 * See [memory management of sources][mainloop-memory-management] for details
5632 * on how to handle the return value and memory management of @data.
5634 * This internally creates a main loop source using g_idle_source_new()
5635 * and attaches it to the global #GMainContext using g_source_attach(), so
5636 * the callback will be invoked in whichever thread is running that main
5637 * context. You can do these steps manually if you need greater control or to
5638 * use a custom main context.
5640 * Returns: the ID (greater than 0) of the event source.
5642 guint
5643 g_idle_add (GSourceFunc function,
5644 gpointer data)
5646 return g_idle_add_full (G_PRIORITY_DEFAULT_IDLE, function, data, NULL);
5650 * g_idle_remove_by_data:
5651 * @data: the data for the idle source's callback.
5653 * Removes the idle function with the given data.
5655 * Returns: %TRUE if an idle source was found and removed.
5657 gboolean
5658 g_idle_remove_by_data (gpointer data)
5660 return g_source_remove_by_funcs_user_data (&g_idle_funcs, data);
5664 * g_main_context_invoke:
5665 * @context: (nullable): a #GMainContext, or %NULL
5666 * @function: function to call
5667 * @data: data to pass to @function
5669 * Invokes a function in such a way that @context is owned during the
5670 * invocation of @function.
5672 * If @context is %NULL then the global default main context — as
5673 * returned by g_main_context_default() — is used.
5675 * If @context is owned by the current thread, @function is called
5676 * directly. Otherwise, if @context is the thread-default main context
5677 * of the current thread and g_main_context_acquire() succeeds, then
5678 * @function is called and g_main_context_release() is called
5679 * afterwards.
5681 * In any other case, an idle source is created to call @function and
5682 * that source is attached to @context (presumably to be run in another
5683 * thread). The idle source is attached with #G_PRIORITY_DEFAULT
5684 * priority. If you want a different priority, use
5685 * g_main_context_invoke_full().
5687 * Note that, as with normal idle functions, @function should probably
5688 * return %FALSE. If it returns %TRUE, it will be continuously run in a
5689 * loop (and may prevent this call from returning).
5691 * Since: 2.28
5693 void
5694 g_main_context_invoke (GMainContext *context,
5695 GSourceFunc function,
5696 gpointer data)
5698 g_main_context_invoke_full (context,
5699 G_PRIORITY_DEFAULT,
5700 function, data, NULL);
5704 * g_main_context_invoke_full:
5705 * @context: (nullable): a #GMainContext, or %NULL
5706 * @priority: the priority at which to run @function
5707 * @function: function to call
5708 * @data: data to pass to @function
5709 * @notify: (nullable): a function to call when @data is no longer in use, or %NULL.
5711 * Invokes a function in such a way that @context is owned during the
5712 * invocation of @function.
5714 * This function is the same as g_main_context_invoke() except that it
5715 * lets you specify the priority in case @function ends up being
5716 * scheduled as an idle and also lets you give a #GDestroyNotify for @data.
5718 * @notify should not assume that it is called from any particular
5719 * thread or with any particular context acquired.
5721 * Since: 2.28
5723 void
5724 g_main_context_invoke_full (GMainContext *context,
5725 gint priority,
5726 GSourceFunc function,
5727 gpointer data,
5728 GDestroyNotify notify)
5730 g_return_if_fail (function != NULL);
5732 if (!context)
5733 context = g_main_context_default ();
5735 if (g_main_context_is_owner (context))
5737 while (function (data));
5738 if (notify != NULL)
5739 notify (data);
5742 else
5744 GMainContext *thread_default;
5746 thread_default = g_main_context_get_thread_default ();
5748 if (!thread_default)
5749 thread_default = g_main_context_default ();
5751 if (thread_default == context && g_main_context_acquire (context))
5753 while (function (data));
5755 g_main_context_release (context);
5757 if (notify != NULL)
5758 notify (data);
5760 else
5762 GSource *source;
5764 source = g_idle_source_new ();
5765 g_source_set_priority (source, priority);
5766 g_source_set_callback (source, function, data, notify);
5767 g_source_attach (source, context);
5768 g_source_unref (source);
5773 static gpointer
5774 glib_worker_main (gpointer data)
5776 while (TRUE)
5778 g_main_context_iteration (glib_worker_context, TRUE);
5780 #ifdef G_OS_UNIX
5781 if (any_unix_signal_pending)
5782 dispatch_unix_signals ();
5783 #endif
5786 return NULL; /* worst GCC warning message ever... */
5789 GMainContext *
5790 g_get_worker_context (void)
5792 static gsize initialised;
5794 if (g_once_init_enter (&initialised))
5796 /* mask all signals in the worker thread */
5797 #ifdef G_OS_UNIX
5798 sigset_t prev_mask;
5799 sigset_t all;
5801 sigfillset (&all);
5802 pthread_sigmask (SIG_SETMASK, &all, &prev_mask);
5803 #endif
5804 glib_worker_context = g_main_context_new ();
5805 g_thread_new ("gmain", glib_worker_main, NULL);
5806 #ifdef G_OS_UNIX
5807 pthread_sigmask (SIG_SETMASK, &prev_mask, NULL);
5808 #endif
5809 g_once_init_leave (&initialised, TRUE);
5812 return glib_worker_context;