Merge branch 'fix-gdbus-unix-addresses-test' into 'master'
[glib.git] / glib / gmain.c
blob18148352767c300637a7356ba3a93f542bb4516c
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 * Returns: the ID (greater than 0) for the source
1301 guint
1302 g_source_get_id (GSource *source)
1304 guint result;
1306 g_return_val_if_fail (source != NULL, 0);
1307 g_return_val_if_fail (source->context != NULL, 0);
1309 LOCK_CONTEXT (source->context);
1310 result = source->source_id;
1311 UNLOCK_CONTEXT (source->context);
1313 return result;
1317 * g_source_get_context:
1318 * @source: a #GSource
1320 * Gets the #GMainContext with which the source is associated.
1322 * You can call this on a source that has been destroyed, provided
1323 * that the #GMainContext it was attached to still exists (in which
1324 * case it will return that #GMainContext). In particular, you can
1325 * always call this function on the source returned from
1326 * g_main_current_source(). But calling this function on a source
1327 * whose #GMainContext has been destroyed is an error.
1329 * Returns: (transfer none) (nullable): the #GMainContext with which the
1330 * source is associated, or %NULL if the context has not
1331 * yet been added to a source.
1333 GMainContext *
1334 g_source_get_context (GSource *source)
1336 g_return_val_if_fail (source->context != NULL || !SOURCE_DESTROYED (source), NULL);
1338 return source->context;
1342 * g_source_add_poll:
1343 * @source:a #GSource
1344 * @fd: a #GPollFD structure holding information about a file
1345 * descriptor to watch.
1347 * Adds a file descriptor to the set of file descriptors polled for
1348 * this source. This is usually combined with g_source_new() to add an
1349 * event source. The event source's check function will typically test
1350 * the @revents field in the #GPollFD struct and return %TRUE if events need
1351 * to be processed.
1353 * This API is only intended to be used by implementations of #GSource.
1354 * Do not call this API on a #GSource that you did not create.
1356 * Using this API forces the linear scanning of event sources on each
1357 * main loop iteration. Newly-written event sources should try to use
1358 * g_source_add_unix_fd() instead of this API.
1360 void
1361 g_source_add_poll (GSource *source,
1362 GPollFD *fd)
1364 GMainContext *context;
1366 g_return_if_fail (source != NULL);
1367 g_return_if_fail (fd != NULL);
1368 g_return_if_fail (!SOURCE_DESTROYED (source));
1370 context = source->context;
1372 if (context)
1373 LOCK_CONTEXT (context);
1375 source->poll_fds = g_slist_prepend (source->poll_fds, fd);
1377 if (context)
1379 if (!SOURCE_BLOCKED (source))
1380 g_main_context_add_poll_unlocked (context, source->priority, fd);
1381 UNLOCK_CONTEXT (context);
1386 * g_source_remove_poll:
1387 * @source:a #GSource
1388 * @fd: a #GPollFD structure previously passed to g_source_add_poll().
1390 * Removes a file descriptor from the set of file descriptors polled for
1391 * this source.
1393 * This API is only intended to be used by implementations of #GSource.
1394 * Do not call this API on a #GSource that you did not create.
1396 void
1397 g_source_remove_poll (GSource *source,
1398 GPollFD *fd)
1400 GMainContext *context;
1402 g_return_if_fail (source != NULL);
1403 g_return_if_fail (fd != NULL);
1404 g_return_if_fail (!SOURCE_DESTROYED (source));
1406 context = source->context;
1408 if (context)
1409 LOCK_CONTEXT (context);
1411 source->poll_fds = g_slist_remove (source->poll_fds, fd);
1413 if (context)
1415 if (!SOURCE_BLOCKED (source))
1416 g_main_context_remove_poll_unlocked (context, fd);
1417 UNLOCK_CONTEXT (context);
1422 * g_source_add_child_source:
1423 * @source:a #GSource
1424 * @child_source: a second #GSource that @source should "poll"
1426 * Adds @child_source to @source as a "polled" source; when @source is
1427 * added to a #GMainContext, @child_source will be automatically added
1428 * with the same priority, when @child_source is triggered, it will
1429 * cause @source to dispatch (in addition to calling its own
1430 * callback), and when @source is destroyed, it will destroy
1431 * @child_source as well. (@source will also still be dispatched if
1432 * its own prepare/check functions indicate that it is ready.)
1434 * If you don't need @child_source to do anything on its own when it
1435 * triggers, you can call g_source_set_dummy_callback() on it to set a
1436 * callback that does nothing (except return %TRUE if appropriate).
1438 * @source will hold a reference on @child_source while @child_source
1439 * is attached to it.
1441 * This API is only intended to be used by implementations of #GSource.
1442 * Do not call this API on a #GSource that you did not create.
1444 * Since: 2.28
1446 void
1447 g_source_add_child_source (GSource *source,
1448 GSource *child_source)
1450 GMainContext *context;
1452 g_return_if_fail (source != NULL);
1453 g_return_if_fail (child_source != NULL);
1454 g_return_if_fail (!SOURCE_DESTROYED (source));
1455 g_return_if_fail (!SOURCE_DESTROYED (child_source));
1456 g_return_if_fail (child_source->context == NULL);
1457 g_return_if_fail (child_source->priv->parent_source == NULL);
1459 context = source->context;
1461 if (context)
1462 LOCK_CONTEXT (context);
1464 TRACE (GLIB_SOURCE_ADD_CHILD_SOURCE (source, child_source));
1466 source->priv->child_sources = g_slist_prepend (source->priv->child_sources,
1467 g_source_ref (child_source));
1468 child_source->priv->parent_source = source;
1469 g_source_set_priority_unlocked (child_source, NULL, source->priority);
1470 if (SOURCE_BLOCKED (source))
1471 block_source (child_source);
1473 if (context)
1475 g_source_attach_unlocked (child_source, context, TRUE);
1476 UNLOCK_CONTEXT (context);
1480 static void
1481 g_child_source_remove_internal (GSource *child_source,
1482 GMainContext *context)
1484 GSource *parent_source = child_source->priv->parent_source;
1486 parent_source->priv->child_sources =
1487 g_slist_remove (parent_source->priv->child_sources, child_source);
1488 child_source->priv->parent_source = NULL;
1490 g_source_destroy_internal (child_source, context, TRUE);
1491 g_source_unref_internal (child_source, context, TRUE);
1495 * g_source_remove_child_source:
1496 * @source:a #GSource
1497 * @child_source: a #GSource previously passed to
1498 * g_source_add_child_source().
1500 * Detaches @child_source from @source and destroys it.
1502 * This API is only intended to be used by implementations of #GSource.
1503 * Do not call this API on a #GSource that you did not create.
1505 * Since: 2.28
1507 void
1508 g_source_remove_child_source (GSource *source,
1509 GSource *child_source)
1511 GMainContext *context;
1513 g_return_if_fail (source != NULL);
1514 g_return_if_fail (child_source != NULL);
1515 g_return_if_fail (child_source->priv->parent_source == source);
1516 g_return_if_fail (!SOURCE_DESTROYED (source));
1517 g_return_if_fail (!SOURCE_DESTROYED (child_source));
1519 context = source->context;
1521 if (context)
1522 LOCK_CONTEXT (context);
1524 g_child_source_remove_internal (child_source, context);
1526 if (context)
1527 UNLOCK_CONTEXT (context);
1530 static void
1531 g_source_callback_ref (gpointer cb_data)
1533 GSourceCallback *callback = cb_data;
1535 g_atomic_int_inc (&callback->ref_count);
1538 static void
1539 g_source_callback_unref (gpointer cb_data)
1541 GSourceCallback *callback = cb_data;
1543 if (g_atomic_int_dec_and_test (&callback->ref_count))
1545 if (callback->notify)
1546 callback->notify (callback->data);
1547 g_free (callback);
1551 static void
1552 g_source_callback_get (gpointer cb_data,
1553 GSource *source,
1554 GSourceFunc *func,
1555 gpointer *data)
1557 GSourceCallback *callback = cb_data;
1559 *func = callback->func;
1560 *data = callback->data;
1563 static GSourceCallbackFuncs g_source_callback_funcs = {
1564 g_source_callback_ref,
1565 g_source_callback_unref,
1566 g_source_callback_get,
1570 * g_source_set_callback_indirect:
1571 * @source: the source
1572 * @callback_data: pointer to callback data "object"
1573 * @callback_funcs: functions for reference counting @callback_data
1574 * and getting the callback and data
1576 * Sets the callback function storing the data as a refcounted callback
1577 * "object". This is used internally. Note that calling
1578 * g_source_set_callback_indirect() assumes
1579 * an initial reference count on @callback_data, and thus
1580 * @callback_funcs->unref will eventually be called once more
1581 * than @callback_funcs->ref.
1583 void
1584 g_source_set_callback_indirect (GSource *source,
1585 gpointer callback_data,
1586 GSourceCallbackFuncs *callback_funcs)
1588 GMainContext *context;
1589 gpointer old_cb_data;
1590 GSourceCallbackFuncs *old_cb_funcs;
1592 g_return_if_fail (source != NULL);
1593 g_return_if_fail (callback_funcs != NULL || callback_data == NULL);
1595 context = source->context;
1597 if (context)
1598 LOCK_CONTEXT (context);
1600 if (callback_funcs != &g_source_callback_funcs)
1601 TRACE (GLIB_SOURCE_SET_CALLBACK_INDIRECT (source, callback_data,
1602 callback_funcs->ref,
1603 callback_funcs->unref,
1604 callback_funcs->get));
1606 old_cb_data = source->callback_data;
1607 old_cb_funcs = source->callback_funcs;
1609 source->callback_data = callback_data;
1610 source->callback_funcs = callback_funcs;
1612 if (context)
1613 UNLOCK_CONTEXT (context);
1615 if (old_cb_funcs)
1616 old_cb_funcs->unref (old_cb_data);
1620 * g_source_set_callback:
1621 * @source: the source
1622 * @func: a callback function
1623 * @data: the data to pass to callback function
1624 * @notify: (nullable): a function to call when @data is no longer in use, or %NULL.
1626 * Sets the callback function for a source. The callback for a source is
1627 * called from the source's dispatch function.
1629 * The exact type of @func depends on the type of source; ie. you
1630 * should not count on @func being called with @data as its first
1631 * parameter.
1633 * See [memory management of sources][mainloop-memory-management] for details
1634 * on how to handle memory management of @data.
1636 * Typically, you won't use this function. Instead use functions specific
1637 * to the type of source you are using.
1639 void
1640 g_source_set_callback (GSource *source,
1641 GSourceFunc func,
1642 gpointer data,
1643 GDestroyNotify notify)
1645 GSourceCallback *new_callback;
1647 g_return_if_fail (source != NULL);
1649 TRACE (GLIB_SOURCE_SET_CALLBACK (source, func, data, notify));
1651 new_callback = g_new (GSourceCallback, 1);
1653 new_callback->ref_count = 1;
1654 new_callback->func = func;
1655 new_callback->data = data;
1656 new_callback->notify = notify;
1658 g_source_set_callback_indirect (source, new_callback, &g_source_callback_funcs);
1663 * g_source_set_funcs:
1664 * @source: a #GSource
1665 * @funcs: the new #GSourceFuncs
1667 * Sets the source functions (can be used to override
1668 * default implementations) of an unattached source.
1670 * Since: 2.12
1672 void
1673 g_source_set_funcs (GSource *source,
1674 GSourceFuncs *funcs)
1676 g_return_if_fail (source != NULL);
1677 g_return_if_fail (source->context == NULL);
1678 g_return_if_fail (source->ref_count > 0);
1679 g_return_if_fail (funcs != NULL);
1681 source->source_funcs = funcs;
1684 static void
1685 g_source_set_priority_unlocked (GSource *source,
1686 GMainContext *context,
1687 gint priority)
1689 GSList *tmp_list;
1691 g_return_if_fail (source->priv->parent_source == NULL ||
1692 source->priv->parent_source->priority == priority);
1694 TRACE (GLIB_SOURCE_SET_PRIORITY (source, context, priority));
1696 if (context)
1698 /* Remove the source from the context's source and then
1699 * add it back after so it is sorted in the correct place
1701 source_remove_from_context (source, source->context);
1704 source->priority = priority;
1706 if (context)
1708 source_add_to_context (source, source->context);
1710 if (!SOURCE_BLOCKED (source))
1712 tmp_list = source->poll_fds;
1713 while (tmp_list)
1715 g_main_context_remove_poll_unlocked (context, tmp_list->data);
1716 g_main_context_add_poll_unlocked (context, priority, tmp_list->data);
1718 tmp_list = tmp_list->next;
1721 for (tmp_list = source->priv->fds; tmp_list; tmp_list = tmp_list->next)
1723 g_main_context_remove_poll_unlocked (context, tmp_list->data);
1724 g_main_context_add_poll_unlocked (context, priority, tmp_list->data);
1729 if (source->priv->child_sources)
1731 tmp_list = source->priv->child_sources;
1732 while (tmp_list)
1734 g_source_set_priority_unlocked (tmp_list->data, context, priority);
1735 tmp_list = tmp_list->next;
1741 * g_source_set_priority:
1742 * @source: a #GSource
1743 * @priority: the new priority.
1745 * Sets the priority of a source. While the main loop is being run, a
1746 * source will be dispatched if it is ready to be dispatched and no
1747 * sources at a higher (numerically smaller) priority are ready to be
1748 * dispatched.
1750 * A child source always has the same priority as its parent. It is not
1751 * permitted to change the priority of a source once it has been added
1752 * as a child of another source.
1754 void
1755 g_source_set_priority (GSource *source,
1756 gint priority)
1758 GMainContext *context;
1760 g_return_if_fail (source != NULL);
1761 g_return_if_fail (source->priv->parent_source == NULL);
1763 context = source->context;
1765 if (context)
1766 LOCK_CONTEXT (context);
1767 g_source_set_priority_unlocked (source, context, priority);
1768 if (context)
1769 UNLOCK_CONTEXT (context);
1773 * g_source_get_priority:
1774 * @source: a #GSource
1776 * Gets the priority of a source.
1778 * Returns: the priority of the source
1780 gint
1781 g_source_get_priority (GSource *source)
1783 g_return_val_if_fail (source != NULL, 0);
1785 return source->priority;
1789 * g_source_set_ready_time:
1790 * @source: a #GSource
1791 * @ready_time: the monotonic time at which the source will be ready,
1792 * 0 for "immediately", -1 for "never"
1794 * Sets a #GSource to be dispatched when the given monotonic time is
1795 * reached (or passed). If the monotonic time is in the past (as it
1796 * always will be if @ready_time is 0) then the source will be
1797 * dispatched immediately.
1799 * If @ready_time is -1 then the source is never woken up on the basis
1800 * of the passage of time.
1802 * Dispatching the source does not reset the ready time. You should do
1803 * so yourself, from the source dispatch function.
1805 * Note that if you have a pair of sources where the ready time of one
1806 * suggests that it will be delivered first but the priority for the
1807 * other suggests that it would be delivered first, and the ready time
1808 * for both sources is reached during the same main context iteration,
1809 * then the order of dispatch is undefined.
1811 * It is a no-op to call this function on a #GSource which has already been
1812 * destroyed with g_source_destroy().
1814 * This API is only intended to be used by implementations of #GSource.
1815 * Do not call this API on a #GSource that you did not create.
1817 * Since: 2.36
1819 void
1820 g_source_set_ready_time (GSource *source,
1821 gint64 ready_time)
1823 GMainContext *context;
1825 g_return_if_fail (source != NULL);
1826 /* We deliberately don't check for ref_count > 0 here, because that
1827 * breaks cancellable_source_cancelled() in GCancellable: it has no
1828 * way to find out that the last-unref has happened until the
1829 * finalize() function is called, but that's too late, because the
1830 * ref_count already has already reached 0 before that time.
1831 * However, priv is only poisoned (set to NULL) after finalize(),
1832 * so we can use this as a simple guard against use-after-free.
1833 * See https://bugzilla.gnome.org/show_bug.cgi?id=791754 */
1834 g_return_if_fail (source->priv != NULL);
1836 context = source->context;
1838 if (context)
1839 LOCK_CONTEXT (context);
1841 if (source->priv->ready_time == ready_time)
1843 if (context)
1844 UNLOCK_CONTEXT (context);
1846 return;
1849 source->priv->ready_time = ready_time;
1851 TRACE (GLIB_SOURCE_SET_READY_TIME (source, ready_time));
1853 if (context)
1855 /* Quite likely that we need to change the timeout on the poll */
1856 if (!SOURCE_BLOCKED (source))
1857 g_wakeup_signal (context->wakeup);
1858 UNLOCK_CONTEXT (context);
1863 * g_source_get_ready_time:
1864 * @source: a #GSource
1866 * Gets the "ready time" of @source, as set by
1867 * g_source_set_ready_time().
1869 * Any time before the current monotonic time (including 0) is an
1870 * indication that the source will fire immediately.
1872 * Returns: the monotonic ready time, -1 for "never"
1874 gint64
1875 g_source_get_ready_time (GSource *source)
1877 g_return_val_if_fail (source != NULL, -1);
1879 return source->priv->ready_time;
1883 * g_source_set_can_recurse:
1884 * @source: a #GSource
1885 * @can_recurse: whether recursion is allowed for this source
1887 * Sets whether a source can be called recursively. If @can_recurse is
1888 * %TRUE, then while the source is being dispatched then this source
1889 * will be processed normally. Otherwise, all processing of this
1890 * source is blocked until the dispatch function returns.
1892 void
1893 g_source_set_can_recurse (GSource *source,
1894 gboolean can_recurse)
1896 GMainContext *context;
1898 g_return_if_fail (source != NULL);
1900 context = source->context;
1902 if (context)
1903 LOCK_CONTEXT (context);
1905 if (can_recurse)
1906 source->flags |= G_SOURCE_CAN_RECURSE;
1907 else
1908 source->flags &= ~G_SOURCE_CAN_RECURSE;
1910 if (context)
1911 UNLOCK_CONTEXT (context);
1915 * g_source_get_can_recurse:
1916 * @source: a #GSource
1918 * Checks whether a source is allowed to be called recursively.
1919 * see g_source_set_can_recurse().
1921 * Returns: whether recursion is allowed.
1923 gboolean
1924 g_source_get_can_recurse (GSource *source)
1926 g_return_val_if_fail (source != NULL, FALSE);
1928 return (source->flags & G_SOURCE_CAN_RECURSE) != 0;
1933 * g_source_set_name:
1934 * @source: a #GSource
1935 * @name: debug name for the source
1937 * Sets a name for the source, used in debugging and profiling.
1938 * The name defaults to #NULL.
1940 * The source name should describe in a human-readable way
1941 * what the source does. For example, "X11 event queue"
1942 * or "GTK+ repaint idle handler" or whatever it is.
1944 * It is permitted to call this function multiple times, but is not
1945 * recommended due to the potential performance impact. For example,
1946 * one could change the name in the "check" function of a #GSourceFuncs
1947 * to include details like the event type in the source name.
1949 * Use caution if changing the name while another thread may be
1950 * accessing it with g_source_get_name(); that function does not copy
1951 * the value, and changing the value will free it while the other thread
1952 * may be attempting to use it.
1954 * Since: 2.26
1956 void
1957 g_source_set_name (GSource *source,
1958 const char *name)
1960 GMainContext *context;
1962 g_return_if_fail (source != NULL);
1964 context = source->context;
1966 if (context)
1967 LOCK_CONTEXT (context);
1969 TRACE (GLIB_SOURCE_SET_NAME (source, name));
1971 /* setting back to NULL is allowed, just because it's
1972 * weird if get_name can return NULL but you can't
1973 * set that.
1976 g_free (source->name);
1977 source->name = g_strdup (name);
1979 if (context)
1980 UNLOCK_CONTEXT (context);
1984 * g_source_get_name:
1985 * @source: a #GSource
1987 * Gets a name for the source, used in debugging and profiling. The
1988 * name may be #NULL if it has never been set with g_source_set_name().
1990 * Returns: the name of the source
1992 * Since: 2.26
1994 const char *
1995 g_source_get_name (GSource *source)
1997 g_return_val_if_fail (source != NULL, NULL);
1999 return source->name;
2003 * g_source_set_name_by_id:
2004 * @tag: a #GSource ID
2005 * @name: debug name for the source
2007 * Sets the name of a source using its ID.
2009 * This is a convenience utility to set source names from the return
2010 * value of g_idle_add(), g_timeout_add(), etc.
2012 * It is a programmer error to attempt to set the name of a non-existent
2013 * source.
2015 * More specifically: source IDs can be reissued after a source has been
2016 * destroyed and therefore it is never valid to use this function with a
2017 * source ID which may have already been removed. An example is when
2018 * scheduling an idle to run in another thread with g_idle_add(): the
2019 * idle may already have run and been removed by the time this function
2020 * is called on its (now invalid) source ID. This source ID may have
2021 * been reissued, leading to the operation being performed against the
2022 * wrong source.
2024 * Since: 2.26
2026 void
2027 g_source_set_name_by_id (guint tag,
2028 const char *name)
2030 GSource *source;
2032 g_return_if_fail (tag > 0);
2034 source = g_main_context_find_source_by_id (NULL, tag);
2035 if (source == NULL)
2036 return;
2038 g_source_set_name (source, name);
2043 * g_source_ref:
2044 * @source: a #GSource
2046 * Increases the reference count on a source by one.
2048 * Returns: @source
2050 GSource *
2051 g_source_ref (GSource *source)
2053 GMainContext *context;
2055 g_return_val_if_fail (source != NULL, NULL);
2057 context = source->context;
2059 if (context)
2060 LOCK_CONTEXT (context);
2062 source->ref_count++;
2064 if (context)
2065 UNLOCK_CONTEXT (context);
2067 return source;
2070 /* g_source_unref() but possible to call within context lock
2072 static void
2073 g_source_unref_internal (GSource *source,
2074 GMainContext *context,
2075 gboolean have_lock)
2077 gpointer old_cb_data = NULL;
2078 GSourceCallbackFuncs *old_cb_funcs = NULL;
2080 g_return_if_fail (source != NULL);
2082 if (!have_lock && context)
2083 LOCK_CONTEXT (context);
2085 source->ref_count--;
2086 if (source->ref_count == 0)
2088 TRACE (GLIB_SOURCE_BEFORE_FREE (source, context,
2089 source->source_funcs->finalize));
2091 old_cb_data = source->callback_data;
2092 old_cb_funcs = source->callback_funcs;
2094 source->callback_data = NULL;
2095 source->callback_funcs = NULL;
2097 if (context)
2099 if (!SOURCE_DESTROYED (source))
2100 g_warning (G_STRLOC ": ref_count == 0, but source was still attached to a context!");
2101 source_remove_from_context (source, context);
2103 g_hash_table_remove (context->sources, GUINT_TO_POINTER (source->source_id));
2106 if (source->source_funcs->finalize)
2108 /* Temporarily increase the ref count again so that GSource methods
2109 * can be called from finalize(). */
2110 source->ref_count++;
2111 if (context)
2112 UNLOCK_CONTEXT (context);
2113 source->source_funcs->finalize (source);
2114 if (context)
2115 LOCK_CONTEXT (context);
2116 source->ref_count--;
2119 if (old_cb_funcs)
2121 /* Temporarily increase the ref count again so that GSource methods
2122 * can be called from callback_funcs.unref(). */
2123 source->ref_count++;
2124 if (context)
2125 UNLOCK_CONTEXT (context);
2127 old_cb_funcs->unref (old_cb_data);
2129 if (context)
2130 LOCK_CONTEXT (context);
2131 source->ref_count--;
2134 g_free (source->name);
2135 source->name = NULL;
2137 g_slist_free (source->poll_fds);
2138 source->poll_fds = NULL;
2140 g_slist_free_full (source->priv->fds, g_free);
2142 while (source->priv->child_sources)
2144 GSource *child_source = source->priv->child_sources->data;
2146 source->priv->child_sources =
2147 g_slist_remove (source->priv->child_sources, child_source);
2148 child_source->priv->parent_source = NULL;
2150 g_source_unref_internal (child_source, context, have_lock);
2153 g_slice_free (GSourcePrivate, source->priv);
2154 source->priv = NULL;
2156 g_free (source);
2159 if (!have_lock && context)
2160 UNLOCK_CONTEXT (context);
2164 * g_source_unref:
2165 * @source: a #GSource
2167 * Decreases the reference count of a source by one. If the
2168 * resulting reference count is zero the source and associated
2169 * memory will be destroyed.
2171 void
2172 g_source_unref (GSource *source)
2174 g_return_if_fail (source != NULL);
2176 g_source_unref_internal (source, source->context, FALSE);
2180 * g_main_context_find_source_by_id:
2181 * @context: (nullable): a #GMainContext (if %NULL, the default context will be used)
2182 * @source_id: the source ID, as returned by g_source_get_id().
2184 * Finds a #GSource given a pair of context and ID.
2186 * It is a programmer error to attempt to lookup a non-existent source.
2188 * More specifically: source IDs can be reissued after a source has been
2189 * destroyed and therefore it is never valid to use this function with a
2190 * source ID which may have already been removed. An example is when
2191 * scheduling an idle to run in another thread with g_idle_add(): the
2192 * idle may already have run and been removed by the time this function
2193 * is called on its (now invalid) source ID. This source ID may have
2194 * been reissued, leading to the operation being performed against the
2195 * wrong source.
2197 * Returns: (transfer none): the #GSource
2199 GSource *
2200 g_main_context_find_source_by_id (GMainContext *context,
2201 guint source_id)
2203 GSource *source;
2205 g_return_val_if_fail (source_id > 0, NULL);
2207 if (context == NULL)
2208 context = g_main_context_default ();
2210 LOCK_CONTEXT (context);
2211 source = g_hash_table_lookup (context->sources, GUINT_TO_POINTER (source_id));
2212 UNLOCK_CONTEXT (context);
2214 if (source && SOURCE_DESTROYED (source))
2215 source = NULL;
2217 return source;
2221 * g_main_context_find_source_by_funcs_user_data:
2222 * @context: (nullable): a #GMainContext (if %NULL, the default context will be used).
2223 * @funcs: the @source_funcs passed to g_source_new().
2224 * @user_data: the user data from the callback.
2226 * Finds a source with the given source functions and user data. If
2227 * multiple sources exist with the same source function and user data,
2228 * the first one found will be returned.
2230 * Returns: (transfer none): the source, if one was found, otherwise %NULL
2232 GSource *
2233 g_main_context_find_source_by_funcs_user_data (GMainContext *context,
2234 GSourceFuncs *funcs,
2235 gpointer user_data)
2237 GSourceIter iter;
2238 GSource *source;
2240 g_return_val_if_fail (funcs != NULL, NULL);
2242 if (context == NULL)
2243 context = g_main_context_default ();
2245 LOCK_CONTEXT (context);
2247 g_source_iter_init (&iter, context, FALSE);
2248 while (g_source_iter_next (&iter, &source))
2250 if (!SOURCE_DESTROYED (source) &&
2251 source->source_funcs == funcs &&
2252 source->callback_funcs)
2254 GSourceFunc callback;
2255 gpointer callback_data;
2257 source->callback_funcs->get (source->callback_data, source, &callback, &callback_data);
2259 if (callback_data == user_data)
2260 break;
2263 g_source_iter_clear (&iter);
2265 UNLOCK_CONTEXT (context);
2267 return source;
2271 * g_main_context_find_source_by_user_data:
2272 * @context: a #GMainContext
2273 * @user_data: the user_data for the callback.
2275 * Finds a source with the given user data for the callback. If
2276 * multiple sources exist with the same user data, the first
2277 * one found will be returned.
2279 * Returns: (transfer none): the source, if one was found, otherwise %NULL
2281 GSource *
2282 g_main_context_find_source_by_user_data (GMainContext *context,
2283 gpointer user_data)
2285 GSourceIter iter;
2286 GSource *source;
2288 if (context == NULL)
2289 context = g_main_context_default ();
2291 LOCK_CONTEXT (context);
2293 g_source_iter_init (&iter, context, FALSE);
2294 while (g_source_iter_next (&iter, &source))
2296 if (!SOURCE_DESTROYED (source) &&
2297 source->callback_funcs)
2299 GSourceFunc callback;
2300 gpointer callback_data = NULL;
2302 source->callback_funcs->get (source->callback_data, source, &callback, &callback_data);
2304 if (callback_data == user_data)
2305 break;
2308 g_source_iter_clear (&iter);
2310 UNLOCK_CONTEXT (context);
2312 return source;
2316 * g_source_remove:
2317 * @tag: the ID of the source to remove.
2319 * Removes the source with the given ID from the default main context. You must
2320 * use g_source_destroy() for sources added to a non-default main context.
2322 * The ID of a #GSource is given by g_source_get_id(), or will be
2323 * returned by the functions g_source_attach(), g_idle_add(),
2324 * g_idle_add_full(), g_timeout_add(), g_timeout_add_full(),
2325 * g_child_watch_add(), g_child_watch_add_full(), g_io_add_watch(), and
2326 * g_io_add_watch_full().
2328 * It is a programmer error to attempt to remove a non-existent source.
2330 * More specifically: source IDs can be reissued after a source has been
2331 * destroyed and therefore it is never valid to use this function with a
2332 * source ID which may have already been removed. An example is when
2333 * scheduling an idle to run in another thread with g_idle_add(): the
2334 * idle may already have run and been removed by the time this function
2335 * is called on its (now invalid) source ID. This source ID may have
2336 * been reissued, leading to the operation being performed against the
2337 * wrong source.
2339 * Returns: For historical reasons, this function always returns %TRUE
2341 gboolean
2342 g_source_remove (guint tag)
2344 GSource *source;
2346 g_return_val_if_fail (tag > 0, FALSE);
2348 source = g_main_context_find_source_by_id (NULL, tag);
2349 if (source)
2350 g_source_destroy (source);
2351 else
2352 g_critical ("Source ID %u was not found when attempting to remove it", tag);
2354 return source != NULL;
2358 * g_source_remove_by_user_data:
2359 * @user_data: the user_data for the callback.
2361 * Removes a source from the default main loop context given the user
2362 * data for the callback. If multiple sources exist with the same user
2363 * data, only one will be destroyed.
2365 * Returns: %TRUE if a source was found and removed.
2367 gboolean
2368 g_source_remove_by_user_data (gpointer user_data)
2370 GSource *source;
2372 source = g_main_context_find_source_by_user_data (NULL, user_data);
2373 if (source)
2375 g_source_destroy (source);
2376 return TRUE;
2378 else
2379 return FALSE;
2383 * g_source_remove_by_funcs_user_data:
2384 * @funcs: The @source_funcs passed to g_source_new()
2385 * @user_data: the user data for the callback
2387 * Removes a source from the default main loop context given the
2388 * source functions and user data. If multiple sources exist with the
2389 * same source functions and user data, only one will be destroyed.
2391 * Returns: %TRUE if a source was found and removed.
2393 gboolean
2394 g_source_remove_by_funcs_user_data (GSourceFuncs *funcs,
2395 gpointer user_data)
2397 GSource *source;
2399 g_return_val_if_fail (funcs != NULL, FALSE);
2401 source = g_main_context_find_source_by_funcs_user_data (NULL, funcs, user_data);
2402 if (source)
2404 g_source_destroy (source);
2405 return TRUE;
2407 else
2408 return FALSE;
2412 * g_clear_handle_id: (skip)
2413 * @tag_ptr: (not nullable): a pointer to the handler ID
2414 * @clear_func: (not nullable): the function to call to clear the handler
2416 * Clears a numeric handler, such as a #GSource ID.
2418 * @tag_ptr must be a valid pointer to the variable holding the handler.
2420 * If the ID is zero then this function does nothing.
2421 * Otherwise, clear_func() is called with the ID as a parameter, and the tag is
2422 * set to zero.
2424 * A macro is also included that allows this function to be used without
2425 * pointer casts.
2427 * Since: 2.56
2429 #undef g_clear_handle_id
2430 void
2431 g_clear_handle_id (guint *tag_ptr,
2432 GClearHandleFunc clear_func)
2434 guint _handle_id;
2436 _handle_id = *tag_ptr;
2437 if (_handle_id > 0)
2439 *tag_ptr = 0;
2440 if (clear_func != NULL)
2441 clear_func (_handle_id);
2445 #ifdef G_OS_UNIX
2447 * g_source_add_unix_fd:
2448 * @source: a #GSource
2449 * @fd: the fd to monitor
2450 * @events: an event mask
2452 * Monitors @fd for the IO events in @events.
2454 * The tag returned by this function can be used to remove or modify the
2455 * monitoring of the fd using g_source_remove_unix_fd() or
2456 * g_source_modify_unix_fd().
2458 * It is not necessary to remove the fd before destroying the source; it
2459 * will be cleaned up automatically.
2461 * This API is only intended to be used by implementations of #GSource.
2462 * Do not call this API on a #GSource that you did not create.
2464 * As the name suggests, this function is not available on Windows.
2466 * Returns: (not nullable): an opaque tag
2468 * Since: 2.36
2470 gpointer
2471 g_source_add_unix_fd (GSource *source,
2472 gint fd,
2473 GIOCondition events)
2475 GMainContext *context;
2476 GPollFD *poll_fd;
2478 g_return_val_if_fail (source != NULL, NULL);
2479 g_return_val_if_fail (!SOURCE_DESTROYED (source), NULL);
2481 poll_fd = g_new (GPollFD, 1);
2482 poll_fd->fd = fd;
2483 poll_fd->events = events;
2484 poll_fd->revents = 0;
2486 context = source->context;
2488 if (context)
2489 LOCK_CONTEXT (context);
2491 source->priv->fds = g_slist_prepend (source->priv->fds, poll_fd);
2493 if (context)
2495 if (!SOURCE_BLOCKED (source))
2496 g_main_context_add_poll_unlocked (context, source->priority, poll_fd);
2497 UNLOCK_CONTEXT (context);
2500 return poll_fd;
2504 * g_source_modify_unix_fd:
2505 * @source: a #GSource
2506 * @tag: (not nullable): the tag from g_source_add_unix_fd()
2507 * @new_events: the new event mask to watch
2509 * Updates the event mask to watch for the fd identified by @tag.
2511 * @tag is the tag returned from g_source_add_unix_fd().
2513 * If you want to remove a fd, don't set its event mask to zero.
2514 * Instead, call g_source_remove_unix_fd().
2516 * This API is only intended to be used by implementations of #GSource.
2517 * Do not call this API on a #GSource that you did not create.
2519 * As the name suggests, this function is not available on Windows.
2521 * Since: 2.36
2523 void
2524 g_source_modify_unix_fd (GSource *source,
2525 gpointer tag,
2526 GIOCondition new_events)
2528 GMainContext *context;
2529 GPollFD *poll_fd;
2531 g_return_if_fail (source != NULL);
2532 g_return_if_fail (g_slist_find (source->priv->fds, tag));
2534 context = source->context;
2535 poll_fd = tag;
2537 poll_fd->events = new_events;
2539 if (context)
2540 g_main_context_wakeup (context);
2544 * g_source_remove_unix_fd:
2545 * @source: a #GSource
2546 * @tag: (not nullable): the tag from g_source_add_unix_fd()
2548 * Reverses the effect of a previous call to g_source_add_unix_fd().
2550 * You only need to call this if you want to remove an fd from being
2551 * watched while keeping the same source around. In the normal case you
2552 * will just want to destroy the source.
2554 * This API is only intended to be used by implementations of #GSource.
2555 * Do not call this API on a #GSource that you did not create.
2557 * As the name suggests, this function is not available on Windows.
2559 * Since: 2.36
2561 void
2562 g_source_remove_unix_fd (GSource *source,
2563 gpointer tag)
2565 GMainContext *context;
2566 GPollFD *poll_fd;
2568 g_return_if_fail (source != NULL);
2569 g_return_if_fail (g_slist_find (source->priv->fds, tag));
2571 context = source->context;
2572 poll_fd = tag;
2574 if (context)
2575 LOCK_CONTEXT (context);
2577 source->priv->fds = g_slist_remove (source->priv->fds, poll_fd);
2579 if (context)
2581 if (!SOURCE_BLOCKED (source))
2582 g_main_context_remove_poll_unlocked (context, poll_fd);
2584 UNLOCK_CONTEXT (context);
2587 g_free (poll_fd);
2591 * g_source_query_unix_fd:
2592 * @source: a #GSource
2593 * @tag: (not nullable): the tag from g_source_add_unix_fd()
2595 * Queries the events reported for the fd corresponding to @tag on
2596 * @source during the last poll.
2598 * The return value of this function is only defined when the function
2599 * is called from the check or dispatch functions for @source.
2601 * This API is only intended to be used by implementations of #GSource.
2602 * Do not call this API on a #GSource that you did not create.
2604 * As the name suggests, this function is not available on Windows.
2606 * Returns: the conditions reported on the fd
2608 * Since: 2.36
2610 GIOCondition
2611 g_source_query_unix_fd (GSource *source,
2612 gpointer tag)
2614 GPollFD *poll_fd;
2616 g_return_val_if_fail (source != NULL, 0);
2617 g_return_val_if_fail (g_slist_find (source->priv->fds, tag), 0);
2619 poll_fd = tag;
2621 return poll_fd->revents;
2623 #endif /* G_OS_UNIX */
2626 * g_get_current_time:
2627 * @result: #GTimeVal structure in which to store current time.
2629 * Equivalent to the UNIX gettimeofday() function, but portable.
2631 * You may find g_get_real_time() to be more convenient.
2633 void
2634 g_get_current_time (GTimeVal *result)
2636 #ifndef G_OS_WIN32
2637 struct timeval r;
2639 g_return_if_fail (result != NULL);
2641 /*this is required on alpha, there the timeval structs are int's
2642 not longs and a cast only would fail horribly*/
2643 gettimeofday (&r, NULL);
2644 result->tv_sec = r.tv_sec;
2645 result->tv_usec = r.tv_usec;
2646 #else
2647 FILETIME ft;
2648 guint64 time64;
2650 g_return_if_fail (result != NULL);
2652 GetSystemTimeAsFileTime (&ft);
2653 memmove (&time64, &ft, sizeof (FILETIME));
2655 /* Convert from 100s of nanoseconds since 1601-01-01
2656 * to Unix epoch. Yes, this is Y2038 unsafe.
2658 time64 -= G_GINT64_CONSTANT (116444736000000000);
2659 time64 /= 10;
2661 result->tv_sec = time64 / 1000000;
2662 result->tv_usec = time64 % 1000000;
2663 #endif
2667 * g_get_real_time:
2669 * Queries the system wall-clock time.
2671 * This call is functionally equivalent to g_get_current_time() except
2672 * that the return value is often more convenient than dealing with a
2673 * #GTimeVal.
2675 * You should only use this call if you are actually interested in the real
2676 * wall-clock time. g_get_monotonic_time() is probably more useful for
2677 * measuring intervals.
2679 * Returns: the number of microseconds since January 1, 1970 UTC.
2681 * Since: 2.28
2683 gint64
2684 g_get_real_time (void)
2686 GTimeVal tv;
2688 g_get_current_time (&tv);
2690 return (((gint64) tv.tv_sec) * 1000000) + tv.tv_usec;
2694 * g_get_monotonic_time:
2696 * Queries the system monotonic time.
2698 * The monotonic clock will always increase and doesn't suffer
2699 * discontinuities when the user (or NTP) changes the system time. It
2700 * may or may not continue to tick during times where the machine is
2701 * suspended.
2703 * We try to use the clock that corresponds as closely as possible to
2704 * the passage of time as measured by system calls such as poll() but it
2705 * may not always be possible to do this.
2707 * Returns: the monotonic time, in microseconds
2709 * Since: 2.28
2711 #if defined (G_OS_WIN32)
2712 /* NOTE:
2713 * time_usec = ticks_since_boot * usec_per_sec / ticks_per_sec
2715 * Doing (ticks_since_boot * usec_per_sec) before the division can overflow 64 bits
2716 * (ticks_since_boot / ticks_per_sec) and then multiply would not be accurate enough.
2717 * So for now we calculate (usec_per_sec / ticks_per_sec) and use floating point
2719 static gdouble g_monotonic_usec_per_tick = 0;
2721 void
2722 g_clock_win32_init (void)
2724 LARGE_INTEGER freq;
2726 if (!QueryPerformanceFrequency (&freq) || freq.QuadPart == 0)
2728 /* The documentation says that this should never happen */
2729 g_assert_not_reached ();
2730 return;
2733 g_monotonic_usec_per_tick = (gdouble)G_USEC_PER_SEC / freq.QuadPart;
2736 gint64
2737 g_get_monotonic_time (void)
2739 if (G_LIKELY (g_monotonic_usec_per_tick != 0))
2741 LARGE_INTEGER ticks;
2743 if (QueryPerformanceCounter (&ticks))
2744 return (gint64)(ticks.QuadPart * g_monotonic_usec_per_tick);
2746 g_warning ("QueryPerformanceCounter Failed (%lu)", GetLastError ());
2747 g_monotonic_usec_per_tick = 0;
2750 return 0;
2752 #elif defined(HAVE_MACH_MACH_TIME_H) /* Mac OS */
2753 gint64
2754 g_get_monotonic_time (void)
2756 static mach_timebase_info_data_t timebase_info;
2758 if (timebase_info.denom == 0)
2760 /* This is a fraction that we must use to scale
2761 * mach_absolute_time() by in order to reach nanoseconds.
2763 * We've only ever observed this to be 1/1, but maybe it could be
2764 * 1000/1 if mach time is microseconds already, or 1/1000 if
2765 * picoseconds. Try to deal nicely with that.
2767 mach_timebase_info (&timebase_info);
2769 /* We actually want microseconds... */
2770 if (timebase_info.numer % 1000 == 0)
2771 timebase_info.numer /= 1000;
2772 else
2773 timebase_info.denom *= 1000;
2775 /* We want to make the numer 1 to avoid having to multiply... */
2776 if (timebase_info.denom % timebase_info.numer == 0)
2778 timebase_info.denom /= timebase_info.numer;
2779 timebase_info.numer = 1;
2781 else
2783 /* We could just multiply by timebase_info.numer below, but why
2784 * bother for a case that may never actually exist...
2786 * Plus -- performing the multiplication would risk integer
2787 * overflow. If we ever actually end up in this situation, we
2788 * should more carefully evaluate the correct course of action.
2790 mach_timebase_info (&timebase_info); /* Get a fresh copy for a better message */
2791 g_error ("Got weird mach timebase info of %d/%d. Please file a bug against GLib.",
2792 timebase_info.numer, timebase_info.denom);
2796 return mach_absolute_time () / timebase_info.denom;
2798 #else
2799 gint64
2800 g_get_monotonic_time (void)
2802 struct timespec ts;
2803 gint result;
2805 result = clock_gettime (CLOCK_MONOTONIC, &ts);
2807 if G_UNLIKELY (result != 0)
2808 g_error ("GLib requires working CLOCK_MONOTONIC");
2810 return (((gint64) ts.tv_sec) * 1000000) + (ts.tv_nsec / 1000);
2812 #endif
2814 static void
2815 g_main_dispatch_free (gpointer dispatch)
2817 g_slice_free (GMainDispatch, dispatch);
2820 /* Running the main loop */
2822 static GMainDispatch *
2823 get_dispatch (void)
2825 static GPrivate depth_private = G_PRIVATE_INIT (g_main_dispatch_free);
2826 GMainDispatch *dispatch;
2828 dispatch = g_private_get (&depth_private);
2830 if (!dispatch)
2832 dispatch = g_slice_new0 (GMainDispatch);
2833 g_private_set (&depth_private, dispatch);
2836 return dispatch;
2840 * g_main_depth:
2842 * Returns the depth of the stack of calls to
2843 * g_main_context_dispatch() on any #GMainContext in the current thread.
2844 * That is, when called from the toplevel, it gives 0. When
2845 * called from within a callback from g_main_context_iteration()
2846 * (or g_main_loop_run(), etc.) it returns 1. When called from within
2847 * a callback to a recursive call to g_main_context_iteration(),
2848 * it returns 2. And so forth.
2850 * This function is useful in a situation like the following:
2851 * Imagine an extremely simple "garbage collected" system.
2853 * |[<!-- language="C" -->
2854 * static GList *free_list;
2856 * gpointer
2857 * allocate_memory (gsize size)
2858 * {
2859 * gpointer result = g_malloc (size);
2860 * free_list = g_list_prepend (free_list, result);
2861 * return result;
2864 * void
2865 * free_allocated_memory (void)
2867 * GList *l;
2868 * for (l = free_list; l; l = l->next);
2869 * g_free (l->data);
2870 * g_list_free (free_list);
2871 * free_list = NULL;
2874 * [...]
2876 * while (TRUE);
2878 * g_main_context_iteration (NULL, TRUE);
2879 * free_allocated_memory();
2881 * ]|
2883 * This works from an application, however, if you want to do the same
2884 * thing from a library, it gets more difficult, since you no longer
2885 * control the main loop. You might think you can simply use an idle
2886 * function to make the call to free_allocated_memory(), but that
2887 * doesn't work, since the idle function could be called from a
2888 * recursive callback. This can be fixed by using g_main_depth()
2890 * |[<!-- language="C" -->
2891 * gpointer
2892 * allocate_memory (gsize size)
2893 * {
2894 * FreeListBlock *block = g_new (FreeListBlock, 1);
2895 * block->mem = g_malloc (size);
2896 * block->depth = g_main_depth ();
2897 * free_list = g_list_prepend (free_list, block);
2898 * return block->mem;
2901 * void
2902 * free_allocated_memory (void)
2904 * GList *l;
2906 * int depth = g_main_depth ();
2907 * for (l = free_list; l; );
2909 * GList *next = l->next;
2910 * FreeListBlock *block = l->data;
2911 * if (block->depth > depth)
2913 * g_free (block->mem);
2914 * g_free (block);
2915 * free_list = g_list_delete_link (free_list, l);
2918 * l = next;
2921 * ]|
2923 * There is a temptation to use g_main_depth() to solve
2924 * problems with reentrancy. For instance, while waiting for data
2925 * to be received from the network in response to a menu item,
2926 * the menu item might be selected again. It might seem that
2927 * one could make the menu item's callback return immediately
2928 * and do nothing if g_main_depth() returns a value greater than 1.
2929 * However, this should be avoided since the user then sees selecting
2930 * the menu item do nothing. Furthermore, you'll find yourself adding
2931 * these checks all over your code, since there are doubtless many,
2932 * many things that the user could do. Instead, you can use the
2933 * following techniques:
2935 * 1. Use gtk_widget_set_sensitive() or modal dialogs to prevent
2936 * the user from interacting with elements while the main
2937 * loop is recursing.
2939 * 2. Avoid main loop recursion in situations where you can't handle
2940 * arbitrary callbacks. Instead, structure your code so that you
2941 * simply return to the main loop and then get called again when
2942 * there is more work to do.
2944 * Returns: The main loop recursion level in the current thread
2947 g_main_depth (void)
2949 GMainDispatch *dispatch = get_dispatch ();
2950 return dispatch->depth;
2954 * g_main_current_source:
2956 * Returns the currently firing source for this thread.
2958 * Returns: (transfer none): The currently firing source or %NULL.
2960 * Since: 2.12
2962 GSource *
2963 g_main_current_source (void)
2965 GMainDispatch *dispatch = get_dispatch ();
2966 return dispatch->source;
2970 * g_source_is_destroyed:
2971 * @source: a #GSource
2973 * Returns whether @source has been destroyed.
2975 * This is important when you operate upon your objects
2976 * from within idle handlers, but may have freed the object
2977 * before the dispatch of your idle handler.
2979 * |[<!-- language="C" -->
2980 * static gboolean
2981 * idle_callback (gpointer data)
2983 * SomeWidget *self = data;
2985 * GDK_THREADS_ENTER ();
2986 * // do stuff with self
2987 * self->idle_id = 0;
2988 * GDK_THREADS_LEAVE ();
2990 * return G_SOURCE_REMOVE;
2993 * static void
2994 * some_widget_do_stuff_later (SomeWidget *self)
2996 * self->idle_id = g_idle_add (idle_callback, self);
2999 * static void
3000 * some_widget_finalize (GObject *object)
3002 * SomeWidget *self = SOME_WIDGET (object);
3004 * if (self->idle_id)
3005 * g_source_remove (self->idle_id);
3007 * G_OBJECT_CLASS (parent_class)->finalize (object);
3009 * ]|
3011 * This will fail in a multi-threaded application if the
3012 * widget is destroyed before the idle handler fires due
3013 * to the use after free in the callback. A solution, to
3014 * this particular problem, is to check to if the source
3015 * has already been destroy within the callback.
3017 * |[<!-- language="C" -->
3018 * static gboolean
3019 * idle_callback (gpointer data)
3021 * SomeWidget *self = data;
3023 * GDK_THREADS_ENTER ();
3024 * if (!g_source_is_destroyed (g_main_current_source ()))
3026 * // do stuff with self
3028 * GDK_THREADS_LEAVE ();
3030 * return FALSE;
3032 * ]|
3034 * Calls to this function from a thread other than the one acquired by the
3035 * #GMainContext the #GSource is attached to are typically redundant, as the
3036 * source could be destroyed immediately after this function returns. However,
3037 * once a source is destroyed it cannot be un-destroyed, so this function can be
3038 * used for opportunistic checks from any thread.
3040 * Returns: %TRUE if the source has been destroyed
3042 * Since: 2.12
3044 gboolean
3045 g_source_is_destroyed (GSource *source)
3047 return SOURCE_DESTROYED (source);
3050 /* Temporarily remove all this source's file descriptors from the
3051 * poll(), so that if data comes available for one of the file descriptors
3052 * we don't continually spin in the poll()
3054 /* HOLDS: source->context's lock */
3055 static void
3056 block_source (GSource *source)
3058 GSList *tmp_list;
3060 g_return_if_fail (!SOURCE_BLOCKED (source));
3062 source->flags |= G_SOURCE_BLOCKED;
3064 if (source->context)
3066 tmp_list = source->poll_fds;
3067 while (tmp_list)
3069 g_main_context_remove_poll_unlocked (source->context, tmp_list->data);
3070 tmp_list = tmp_list->next;
3073 for (tmp_list = source->priv->fds; tmp_list; tmp_list = tmp_list->next)
3074 g_main_context_remove_poll_unlocked (source->context, tmp_list->data);
3077 if (source->priv && source->priv->child_sources)
3079 tmp_list = source->priv->child_sources;
3080 while (tmp_list)
3082 block_source (tmp_list->data);
3083 tmp_list = tmp_list->next;
3088 /* HOLDS: source->context's lock */
3089 static void
3090 unblock_source (GSource *source)
3092 GSList *tmp_list;
3094 g_return_if_fail (SOURCE_BLOCKED (source)); /* Source already unblocked */
3095 g_return_if_fail (!SOURCE_DESTROYED (source));
3097 source->flags &= ~G_SOURCE_BLOCKED;
3099 tmp_list = source->poll_fds;
3100 while (tmp_list)
3102 g_main_context_add_poll_unlocked (source->context, source->priority, tmp_list->data);
3103 tmp_list = tmp_list->next;
3106 for (tmp_list = source->priv->fds; tmp_list; tmp_list = tmp_list->next)
3107 g_main_context_add_poll_unlocked (source->context, source->priority, tmp_list->data);
3109 if (source->priv && source->priv->child_sources)
3111 tmp_list = source->priv->child_sources;
3112 while (tmp_list)
3114 unblock_source (tmp_list->data);
3115 tmp_list = tmp_list->next;
3120 /* HOLDS: context's lock */
3121 static void
3122 g_main_dispatch (GMainContext *context)
3124 GMainDispatch *current = get_dispatch ();
3125 guint i;
3127 for (i = 0; i < context->pending_dispatches->len; i++)
3129 GSource *source = context->pending_dispatches->pdata[i];
3131 context->pending_dispatches->pdata[i] = NULL;
3132 g_assert (source);
3134 source->flags &= ~G_SOURCE_READY;
3136 if (!SOURCE_DESTROYED (source))
3138 gboolean was_in_call;
3139 gpointer user_data = NULL;
3140 GSourceFunc callback = NULL;
3141 GSourceCallbackFuncs *cb_funcs;
3142 gpointer cb_data;
3143 gboolean need_destroy;
3145 gboolean (*dispatch) (GSource *,
3146 GSourceFunc,
3147 gpointer);
3148 GSource *prev_source;
3150 dispatch = source->source_funcs->dispatch;
3151 cb_funcs = source->callback_funcs;
3152 cb_data = source->callback_data;
3154 if (cb_funcs)
3155 cb_funcs->ref (cb_data);
3157 if ((source->flags & G_SOURCE_CAN_RECURSE) == 0)
3158 block_source (source);
3160 was_in_call = source->flags & G_HOOK_FLAG_IN_CALL;
3161 source->flags |= G_HOOK_FLAG_IN_CALL;
3163 if (cb_funcs)
3164 cb_funcs->get (cb_data, source, &callback, &user_data);
3166 UNLOCK_CONTEXT (context);
3168 /* These operations are safe because 'current' is thread-local
3169 * and not modified from anywhere but this function.
3171 prev_source = current->source;
3172 current->source = source;
3173 current->depth++;
3175 TRACE (GLIB_MAIN_BEFORE_DISPATCH (g_source_get_name (source), source,
3176 dispatch, callback, user_data));
3177 need_destroy = !(* dispatch) (source, callback, user_data);
3178 TRACE (GLIB_MAIN_AFTER_DISPATCH (g_source_get_name (source), source,
3179 dispatch, need_destroy));
3181 current->source = prev_source;
3182 current->depth--;
3184 if (cb_funcs)
3185 cb_funcs->unref (cb_data);
3187 LOCK_CONTEXT (context);
3189 if (!was_in_call)
3190 source->flags &= ~G_HOOK_FLAG_IN_CALL;
3192 if (SOURCE_BLOCKED (source) && !SOURCE_DESTROYED (source))
3193 unblock_source (source);
3195 /* Note: this depends on the fact that we can't switch
3196 * sources from one main context to another
3198 if (need_destroy && !SOURCE_DESTROYED (source))
3200 g_assert (source->context == context);
3201 g_source_destroy_internal (source, context, TRUE);
3205 SOURCE_UNREF (source, context);
3208 g_ptr_array_set_size (context->pending_dispatches, 0);
3212 * g_main_context_acquire:
3213 * @context: a #GMainContext
3215 * Tries to become the owner of the specified context.
3216 * If some other thread is the owner of the context,
3217 * returns %FALSE immediately. Ownership is properly
3218 * recursive: the owner can require ownership again
3219 * and will release ownership when g_main_context_release()
3220 * is called as many times as g_main_context_acquire().
3222 * You must be the owner of a context before you
3223 * can call g_main_context_prepare(), g_main_context_query(),
3224 * g_main_context_check(), g_main_context_dispatch().
3226 * Returns: %TRUE if the operation succeeded, and
3227 * this thread is now the owner of @context.
3229 gboolean
3230 g_main_context_acquire (GMainContext *context)
3232 gboolean result = FALSE;
3233 GThread *self = G_THREAD_SELF;
3235 if (context == NULL)
3236 context = g_main_context_default ();
3238 LOCK_CONTEXT (context);
3240 if (!context->owner)
3242 context->owner = self;
3243 g_assert (context->owner_count == 0);
3244 TRACE (GLIB_MAIN_CONTEXT_ACQUIRE (context, TRUE /* success */));
3247 if (context->owner == self)
3249 context->owner_count++;
3250 result = TRUE;
3252 else
3254 TRACE (GLIB_MAIN_CONTEXT_ACQUIRE (context, FALSE /* failure */));
3257 UNLOCK_CONTEXT (context);
3259 return result;
3263 * g_main_context_release:
3264 * @context: a #GMainContext
3266 * Releases ownership of a context previously acquired by this thread
3267 * with g_main_context_acquire(). If the context was acquired multiple
3268 * times, the ownership will be released only when g_main_context_release()
3269 * is called as many times as it was acquired.
3271 void
3272 g_main_context_release (GMainContext *context)
3274 if (context == NULL)
3275 context = g_main_context_default ();
3277 LOCK_CONTEXT (context);
3279 context->owner_count--;
3280 if (context->owner_count == 0)
3282 TRACE (GLIB_MAIN_CONTEXT_RELEASE (context));
3284 context->owner = NULL;
3286 if (context->waiters)
3288 GMainWaiter *waiter = context->waiters->data;
3289 gboolean loop_internal_waiter = (waiter->mutex == &context->mutex);
3290 context->waiters = g_slist_delete_link (context->waiters,
3291 context->waiters);
3292 if (!loop_internal_waiter)
3293 g_mutex_lock (waiter->mutex);
3295 g_cond_signal (waiter->cond);
3297 if (!loop_internal_waiter)
3298 g_mutex_unlock (waiter->mutex);
3302 UNLOCK_CONTEXT (context);
3306 * g_main_context_wait:
3307 * @context: a #GMainContext
3308 * @cond: a condition variable
3309 * @mutex: a mutex, currently held
3311 * Tries to become the owner of the specified context,
3312 * as with g_main_context_acquire(). But if another thread
3313 * is the owner, atomically drop @mutex and wait on @cond until
3314 * that owner releases ownership or until @cond is signaled, then
3315 * try again (once) to become the owner.
3317 * Returns: %TRUE if the operation succeeded, and
3318 * this thread is now the owner of @context.
3320 gboolean
3321 g_main_context_wait (GMainContext *context,
3322 GCond *cond,
3323 GMutex *mutex)
3325 gboolean result = FALSE;
3326 GThread *self = G_THREAD_SELF;
3327 gboolean loop_internal_waiter;
3329 if (context == NULL)
3330 context = g_main_context_default ();
3332 if G_UNLIKELY (cond != &context->cond || mutex != &context->mutex)
3334 static gboolean warned;
3336 if (!warned)
3338 g_critical ("WARNING!! g_main_context_wait() will be removed in a future release. "
3339 "If you see this message, please file a bug immediately.");
3340 warned = TRUE;
3344 loop_internal_waiter = (mutex == &context->mutex);
3346 if (!loop_internal_waiter)
3347 LOCK_CONTEXT (context);
3349 if (context->owner && context->owner != self)
3351 GMainWaiter waiter;
3353 waiter.cond = cond;
3354 waiter.mutex = mutex;
3356 context->waiters = g_slist_append (context->waiters, &waiter);
3358 if (!loop_internal_waiter)
3359 UNLOCK_CONTEXT (context);
3360 g_cond_wait (cond, mutex);
3361 if (!loop_internal_waiter)
3362 LOCK_CONTEXT (context);
3364 context->waiters = g_slist_remove (context->waiters, &waiter);
3367 if (!context->owner)
3369 context->owner = self;
3370 g_assert (context->owner_count == 0);
3373 if (context->owner == self)
3375 context->owner_count++;
3376 result = TRUE;
3379 if (!loop_internal_waiter)
3380 UNLOCK_CONTEXT (context);
3382 return result;
3386 * g_main_context_prepare:
3387 * @context: a #GMainContext
3388 * @priority: location to store priority of highest priority
3389 * source already ready.
3391 * Prepares to poll sources within a main loop. The resulting information
3392 * for polling is determined by calling g_main_context_query ().
3394 * You must have successfully acquired the context with
3395 * g_main_context_acquire() before you may call this function.
3397 * Returns: %TRUE if some source is ready to be dispatched
3398 * prior to polling.
3400 gboolean
3401 g_main_context_prepare (GMainContext *context,
3402 gint *priority)
3404 guint i;
3405 gint n_ready = 0;
3406 gint current_priority = G_MAXINT;
3407 GSource *source;
3408 GSourceIter iter;
3410 if (context == NULL)
3411 context = g_main_context_default ();
3413 LOCK_CONTEXT (context);
3415 context->time_is_fresh = FALSE;
3417 if (context->in_check_or_prepare)
3419 g_warning ("g_main_context_prepare() called recursively from within a source's check() or "
3420 "prepare() member.");
3421 UNLOCK_CONTEXT (context);
3422 return FALSE;
3425 TRACE (GLIB_MAIN_CONTEXT_BEFORE_PREPARE (context));
3427 #if 0
3428 /* If recursing, finish up current dispatch, before starting over */
3429 if (context->pending_dispatches)
3431 if (dispatch)
3432 g_main_dispatch (context, &current_time);
3434 UNLOCK_CONTEXT (context);
3435 return TRUE;
3437 #endif
3439 /* If recursing, clear list of pending dispatches */
3441 for (i = 0; i < context->pending_dispatches->len; i++)
3443 if (context->pending_dispatches->pdata[i])
3444 SOURCE_UNREF ((GSource *)context->pending_dispatches->pdata[i], context);
3446 g_ptr_array_set_size (context->pending_dispatches, 0);
3448 /* Prepare all sources */
3450 context->timeout = -1;
3452 g_source_iter_init (&iter, context, TRUE);
3453 while (g_source_iter_next (&iter, &source))
3455 gint source_timeout = -1;
3457 if (SOURCE_DESTROYED (source) || SOURCE_BLOCKED (source))
3458 continue;
3459 if ((n_ready > 0) && (source->priority > current_priority))
3460 break;
3462 if (!(source->flags & G_SOURCE_READY))
3464 gboolean result;
3465 gboolean (* prepare) (GSource *source,
3466 gint *timeout);
3468 prepare = source->source_funcs->prepare;
3470 if (prepare)
3472 context->in_check_or_prepare++;
3473 UNLOCK_CONTEXT (context);
3475 result = (* prepare) (source, &source_timeout);
3476 TRACE (GLIB_MAIN_AFTER_PREPARE (source, prepare, source_timeout));
3478 LOCK_CONTEXT (context);
3479 context->in_check_or_prepare--;
3481 else
3483 source_timeout = -1;
3484 result = FALSE;
3487 if (result == FALSE && source->priv->ready_time != -1)
3489 if (!context->time_is_fresh)
3491 context->time = g_get_monotonic_time ();
3492 context->time_is_fresh = TRUE;
3495 if (source->priv->ready_time <= context->time)
3497 source_timeout = 0;
3498 result = TRUE;
3500 else
3502 gint timeout;
3504 /* rounding down will lead to spinning, so always round up */
3505 timeout = (source->priv->ready_time - context->time + 999) / 1000;
3507 if (source_timeout < 0 || timeout < source_timeout)
3508 source_timeout = timeout;
3512 if (result)
3514 GSource *ready_source = source;
3516 while (ready_source)
3518 ready_source->flags |= G_SOURCE_READY;
3519 ready_source = ready_source->priv->parent_source;
3524 if (source->flags & G_SOURCE_READY)
3526 n_ready++;
3527 current_priority = source->priority;
3528 context->timeout = 0;
3531 if (source_timeout >= 0)
3533 if (context->timeout < 0)
3534 context->timeout = source_timeout;
3535 else
3536 context->timeout = MIN (context->timeout, source_timeout);
3539 g_source_iter_clear (&iter);
3541 TRACE (GLIB_MAIN_CONTEXT_AFTER_PREPARE (context, current_priority, n_ready));
3543 UNLOCK_CONTEXT (context);
3545 if (priority)
3546 *priority = current_priority;
3548 return (n_ready > 0);
3552 * g_main_context_query:
3553 * @context: a #GMainContext
3554 * @max_priority: maximum priority source to check
3555 * @timeout_: (out): location to store timeout to be used in polling
3556 * @fds: (out caller-allocates) (array length=n_fds): location to
3557 * store #GPollFD records that need to be polled.
3558 * @n_fds: (in): length of @fds.
3560 * Determines information necessary to poll this main loop.
3562 * You must have successfully acquired the context with
3563 * g_main_context_acquire() before you may call this function.
3565 * Returns: the number of records actually stored in @fds,
3566 * or, if more than @n_fds records need to be stored, the number
3567 * of records that need to be stored.
3569 gint
3570 g_main_context_query (GMainContext *context,
3571 gint max_priority,
3572 gint *timeout,
3573 GPollFD *fds,
3574 gint n_fds)
3576 gint n_poll;
3577 GPollRec *pollrec, *lastpollrec;
3578 gushort events;
3580 LOCK_CONTEXT (context);
3582 TRACE (GLIB_MAIN_CONTEXT_BEFORE_QUERY (context, max_priority));
3584 n_poll = 0;
3585 lastpollrec = NULL;
3586 for (pollrec = context->poll_records; pollrec; pollrec = pollrec->next)
3588 if (pollrec->priority > max_priority)
3589 continue;
3591 /* In direct contradiction to the Unix98 spec, IRIX runs into
3592 * difficulty if you pass in POLLERR, POLLHUP or POLLNVAL
3593 * flags in the events field of the pollfd while it should
3594 * just ignoring them. So we mask them out here.
3596 events = pollrec->fd->events & ~(G_IO_ERR|G_IO_HUP|G_IO_NVAL);
3598 if (lastpollrec && pollrec->fd->fd == lastpollrec->fd->fd)
3600 if (n_poll - 1 < n_fds)
3601 fds[n_poll - 1].events |= events;
3603 else
3605 if (n_poll < n_fds)
3607 fds[n_poll].fd = pollrec->fd->fd;
3608 fds[n_poll].events = events;
3609 fds[n_poll].revents = 0;
3612 n_poll++;
3615 lastpollrec = pollrec;
3618 context->poll_changed = FALSE;
3620 if (timeout)
3622 *timeout = context->timeout;
3623 if (*timeout != 0)
3624 context->time_is_fresh = FALSE;
3627 TRACE (GLIB_MAIN_CONTEXT_AFTER_QUERY (context, context->timeout,
3628 fds, n_poll));
3630 UNLOCK_CONTEXT (context);
3632 return n_poll;
3636 * g_main_context_check:
3637 * @context: a #GMainContext
3638 * @max_priority: the maximum numerical priority of sources to check
3639 * @fds: (array length=n_fds): array of #GPollFD's that was passed to
3640 * the last call to g_main_context_query()
3641 * @n_fds: return value of g_main_context_query()
3643 * Passes the results of polling back to the main loop.
3645 * You must have successfully acquired the context with
3646 * g_main_context_acquire() before you may call this function.
3648 * Returns: %TRUE if some sources are ready to be dispatched.
3650 gboolean
3651 g_main_context_check (GMainContext *context,
3652 gint max_priority,
3653 GPollFD *fds,
3654 gint n_fds)
3656 GSource *source;
3657 GSourceIter iter;
3658 GPollRec *pollrec;
3659 gint n_ready = 0;
3660 gint i;
3662 LOCK_CONTEXT (context);
3664 if (context->in_check_or_prepare)
3666 g_warning ("g_main_context_check() called recursively from within a source's check() or "
3667 "prepare() member.");
3668 UNLOCK_CONTEXT (context);
3669 return FALSE;
3672 TRACE (GLIB_MAIN_CONTEXT_BEFORE_CHECK (context, max_priority, fds, n_fds));
3674 for (i = 0; i < n_fds; i++)
3676 if (fds[i].fd == context->wake_up_rec.fd)
3678 if (fds[i].revents)
3680 TRACE (GLIB_MAIN_CONTEXT_WAKEUP_ACKNOWLEDGE (context));
3681 g_wakeup_acknowledge (context->wakeup);
3683 break;
3687 /* If the set of poll file descriptors changed, bail out
3688 * and let the main loop rerun
3690 if (context->poll_changed)
3692 TRACE (GLIB_MAIN_CONTEXT_AFTER_CHECK (context, 0));
3694 UNLOCK_CONTEXT (context);
3695 return FALSE;
3698 pollrec = context->poll_records;
3699 i = 0;
3700 while (pollrec && i < n_fds)
3702 while (pollrec && pollrec->fd->fd == fds[i].fd)
3704 if (pollrec->priority <= max_priority)
3706 pollrec->fd->revents =
3707 fds[i].revents & (pollrec->fd->events | G_IO_ERR | G_IO_HUP | G_IO_NVAL);
3709 pollrec = pollrec->next;
3712 i++;
3715 g_source_iter_init (&iter, context, TRUE);
3716 while (g_source_iter_next (&iter, &source))
3718 if (SOURCE_DESTROYED (source) || SOURCE_BLOCKED (source))
3719 continue;
3720 if ((n_ready > 0) && (source->priority > max_priority))
3721 break;
3723 if (!(source->flags & G_SOURCE_READY))
3725 gboolean result;
3726 gboolean (* check) (GSource *source);
3728 check = source->source_funcs->check;
3730 if (check)
3732 /* If the check function is set, call it. */
3733 context->in_check_or_prepare++;
3734 UNLOCK_CONTEXT (context);
3736 result = (* check) (source);
3738 TRACE (GLIB_MAIN_AFTER_CHECK (source, check, result));
3740 LOCK_CONTEXT (context);
3741 context->in_check_or_prepare--;
3743 else
3744 result = FALSE;
3746 if (result == FALSE)
3748 GSList *tmp_list;
3750 /* If not already explicitly flagged ready by ->check()
3751 * (or if we have no check) then we can still be ready if
3752 * any of our fds poll as ready.
3754 for (tmp_list = source->priv->fds; tmp_list; tmp_list = tmp_list->next)
3756 GPollFD *pollfd = tmp_list->data;
3758 if (pollfd->revents)
3760 result = TRUE;
3761 break;
3766 if (result == FALSE && source->priv->ready_time != -1)
3768 if (!context->time_is_fresh)
3770 context->time = g_get_monotonic_time ();
3771 context->time_is_fresh = TRUE;
3774 if (source->priv->ready_time <= context->time)
3775 result = TRUE;
3778 if (result)
3780 GSource *ready_source = source;
3782 while (ready_source)
3784 ready_source->flags |= G_SOURCE_READY;
3785 ready_source = ready_source->priv->parent_source;
3790 if (source->flags & G_SOURCE_READY)
3792 source->ref_count++;
3793 g_ptr_array_add (context->pending_dispatches, source);
3795 n_ready++;
3797 /* never dispatch sources with less priority than the first
3798 * one we choose to dispatch
3800 max_priority = source->priority;
3803 g_source_iter_clear (&iter);
3805 TRACE (GLIB_MAIN_CONTEXT_AFTER_CHECK (context, n_ready));
3807 UNLOCK_CONTEXT (context);
3809 return n_ready > 0;
3813 * g_main_context_dispatch:
3814 * @context: a #GMainContext
3816 * Dispatches all pending sources.
3818 * You must have successfully acquired the context with
3819 * g_main_context_acquire() before you may call this function.
3821 void
3822 g_main_context_dispatch (GMainContext *context)
3824 LOCK_CONTEXT (context);
3826 TRACE (GLIB_MAIN_CONTEXT_BEFORE_DISPATCH (context));
3828 if (context->pending_dispatches->len > 0)
3830 g_main_dispatch (context);
3833 TRACE (GLIB_MAIN_CONTEXT_AFTER_DISPATCH (context));
3835 UNLOCK_CONTEXT (context);
3838 /* HOLDS context lock */
3839 static gboolean
3840 g_main_context_iterate (GMainContext *context,
3841 gboolean block,
3842 gboolean dispatch,
3843 GThread *self)
3845 gint max_priority;
3846 gint timeout;
3847 gboolean some_ready;
3848 gint nfds, allocated_nfds;
3849 GPollFD *fds = NULL;
3851 UNLOCK_CONTEXT (context);
3853 if (!g_main_context_acquire (context))
3855 gboolean got_ownership;
3857 LOCK_CONTEXT (context);
3859 if (!block)
3860 return FALSE;
3862 got_ownership = g_main_context_wait (context,
3863 &context->cond,
3864 &context->mutex);
3866 if (!got_ownership)
3867 return FALSE;
3869 else
3870 LOCK_CONTEXT (context);
3872 if (!context->cached_poll_array)
3874 context->cached_poll_array_size = context->n_poll_records;
3875 context->cached_poll_array = g_new (GPollFD, context->n_poll_records);
3878 allocated_nfds = context->cached_poll_array_size;
3879 fds = context->cached_poll_array;
3881 UNLOCK_CONTEXT (context);
3883 g_main_context_prepare (context, &max_priority);
3885 while ((nfds = g_main_context_query (context, max_priority, &timeout, fds,
3886 allocated_nfds)) > allocated_nfds)
3888 LOCK_CONTEXT (context);
3889 g_free (fds);
3890 context->cached_poll_array_size = allocated_nfds = nfds;
3891 context->cached_poll_array = fds = g_new (GPollFD, nfds);
3892 UNLOCK_CONTEXT (context);
3895 if (!block)
3896 timeout = 0;
3898 g_main_context_poll (context, timeout, max_priority, fds, nfds);
3900 some_ready = g_main_context_check (context, max_priority, fds, nfds);
3902 if (dispatch)
3903 g_main_context_dispatch (context);
3905 g_main_context_release (context);
3907 LOCK_CONTEXT (context);
3909 return some_ready;
3913 * g_main_context_pending:
3914 * @context: (nullable): a #GMainContext (if %NULL, the default context will be used)
3916 * Checks if any sources have pending events for the given context.
3918 * Returns: %TRUE if events are pending.
3920 gboolean
3921 g_main_context_pending (GMainContext *context)
3923 gboolean retval;
3925 if (!context)
3926 context = g_main_context_default();
3928 LOCK_CONTEXT (context);
3929 retval = g_main_context_iterate (context, FALSE, FALSE, G_THREAD_SELF);
3930 UNLOCK_CONTEXT (context);
3932 return retval;
3936 * g_main_context_iteration:
3937 * @context: (nullable): a #GMainContext (if %NULL, the default context will be used)
3938 * @may_block: whether the call may block.
3940 * Runs a single iteration for the given main loop. This involves
3941 * checking to see if any event sources are ready to be processed,
3942 * then if no events sources are ready and @may_block is %TRUE, waiting
3943 * for a source to become ready, then dispatching the highest priority
3944 * events sources that are ready. Otherwise, if @may_block is %FALSE
3945 * sources are not waited to become ready, only those highest priority
3946 * events sources will be dispatched (if any), that are ready at this
3947 * given moment without further waiting.
3949 * Note that even when @may_block is %TRUE, it is still possible for
3950 * g_main_context_iteration() to return %FALSE, since the wait may
3951 * be interrupted for other reasons than an event source becoming ready.
3953 * Returns: %TRUE if events were dispatched.
3955 gboolean
3956 g_main_context_iteration (GMainContext *context, gboolean may_block)
3958 gboolean retval;
3960 if (!context)
3961 context = g_main_context_default();
3963 LOCK_CONTEXT (context);
3964 retval = g_main_context_iterate (context, may_block, TRUE, G_THREAD_SELF);
3965 UNLOCK_CONTEXT (context);
3967 return retval;
3971 * g_main_loop_new:
3972 * @context: (nullable): a #GMainContext (if %NULL, the default context will be used).
3973 * @is_running: set to %TRUE to indicate that the loop is running. This
3974 * is not very important since calling g_main_loop_run() will set this to
3975 * %TRUE anyway.
3977 * Creates a new #GMainLoop structure.
3979 * Returns: a new #GMainLoop.
3981 GMainLoop *
3982 g_main_loop_new (GMainContext *context,
3983 gboolean is_running)
3985 GMainLoop *loop;
3987 if (!context)
3988 context = g_main_context_default();
3990 g_main_context_ref (context);
3992 loop = g_new0 (GMainLoop, 1);
3993 loop->context = context;
3994 loop->is_running = is_running != FALSE;
3995 loop->ref_count = 1;
3997 TRACE (GLIB_MAIN_LOOP_NEW (loop, context));
3999 return loop;
4003 * g_main_loop_ref:
4004 * @loop: a #GMainLoop
4006 * Increases the reference count on a #GMainLoop object by one.
4008 * Returns: @loop
4010 GMainLoop *
4011 g_main_loop_ref (GMainLoop *loop)
4013 g_return_val_if_fail (loop != NULL, NULL);
4014 g_return_val_if_fail (g_atomic_int_get (&loop->ref_count) > 0, NULL);
4016 g_atomic_int_inc (&loop->ref_count);
4018 return loop;
4022 * g_main_loop_unref:
4023 * @loop: a #GMainLoop
4025 * Decreases the reference count on a #GMainLoop object by one. If
4026 * the result is zero, free the loop and free all associated memory.
4028 void
4029 g_main_loop_unref (GMainLoop *loop)
4031 g_return_if_fail (loop != NULL);
4032 g_return_if_fail (g_atomic_int_get (&loop->ref_count) > 0);
4034 if (!g_atomic_int_dec_and_test (&loop->ref_count))
4035 return;
4037 g_main_context_unref (loop->context);
4038 g_free (loop);
4042 * g_main_loop_run:
4043 * @loop: a #GMainLoop
4045 * Runs a main loop until g_main_loop_quit() is called on the loop.
4046 * If this is called for the thread of the loop's #GMainContext,
4047 * it will process events from the loop, otherwise it will
4048 * simply wait.
4050 void
4051 g_main_loop_run (GMainLoop *loop)
4053 GThread *self = G_THREAD_SELF;
4055 g_return_if_fail (loop != NULL);
4056 g_return_if_fail (g_atomic_int_get (&loop->ref_count) > 0);
4058 if (!g_main_context_acquire (loop->context))
4060 gboolean got_ownership = FALSE;
4062 /* Another thread owns this context */
4063 LOCK_CONTEXT (loop->context);
4065 g_atomic_int_inc (&loop->ref_count);
4067 if (!loop->is_running)
4068 loop->is_running = TRUE;
4070 while (loop->is_running && !got_ownership)
4071 got_ownership = g_main_context_wait (loop->context,
4072 &loop->context->cond,
4073 &loop->context->mutex);
4075 if (!loop->is_running)
4077 UNLOCK_CONTEXT (loop->context);
4078 if (got_ownership)
4079 g_main_context_release (loop->context);
4080 g_main_loop_unref (loop);
4081 return;
4084 g_assert (got_ownership);
4086 else
4087 LOCK_CONTEXT (loop->context);
4089 if (loop->context->in_check_or_prepare)
4091 g_warning ("g_main_loop_run(): called recursively from within a source's "
4092 "check() or prepare() member, iteration not possible.");
4093 return;
4096 g_atomic_int_inc (&loop->ref_count);
4097 loop->is_running = TRUE;
4098 while (loop->is_running)
4099 g_main_context_iterate (loop->context, TRUE, TRUE, self);
4101 UNLOCK_CONTEXT (loop->context);
4103 g_main_context_release (loop->context);
4105 g_main_loop_unref (loop);
4109 * g_main_loop_quit:
4110 * @loop: a #GMainLoop
4112 * Stops a #GMainLoop from running. Any calls to g_main_loop_run()
4113 * for the loop will return.
4115 * Note that sources that have already been dispatched when
4116 * g_main_loop_quit() is called will still be executed.
4118 void
4119 g_main_loop_quit (GMainLoop *loop)
4121 g_return_if_fail (loop != NULL);
4122 g_return_if_fail (g_atomic_int_get (&loop->ref_count) > 0);
4124 LOCK_CONTEXT (loop->context);
4125 loop->is_running = FALSE;
4126 g_wakeup_signal (loop->context->wakeup);
4128 g_cond_broadcast (&loop->context->cond);
4130 UNLOCK_CONTEXT (loop->context);
4132 TRACE (GLIB_MAIN_LOOP_QUIT (loop));
4136 * g_main_loop_is_running:
4137 * @loop: a #GMainLoop.
4139 * Checks to see if the main loop is currently being run via g_main_loop_run().
4141 * Returns: %TRUE if the mainloop is currently being run.
4143 gboolean
4144 g_main_loop_is_running (GMainLoop *loop)
4146 g_return_val_if_fail (loop != NULL, FALSE);
4147 g_return_val_if_fail (g_atomic_int_get (&loop->ref_count) > 0, FALSE);
4149 return loop->is_running;
4153 * g_main_loop_get_context:
4154 * @loop: a #GMainLoop.
4156 * Returns the #GMainContext of @loop.
4158 * Returns: (transfer none): the #GMainContext of @loop
4160 GMainContext *
4161 g_main_loop_get_context (GMainLoop *loop)
4163 g_return_val_if_fail (loop != NULL, NULL);
4164 g_return_val_if_fail (g_atomic_int_get (&loop->ref_count) > 0, NULL);
4166 return loop->context;
4169 /* HOLDS: context's lock */
4170 static void
4171 g_main_context_poll (GMainContext *context,
4172 gint timeout,
4173 gint priority,
4174 GPollFD *fds,
4175 gint n_fds)
4177 #ifdef G_MAIN_POLL_DEBUG
4178 GTimer *poll_timer;
4179 GPollRec *pollrec;
4180 gint i;
4181 #endif
4183 GPollFunc poll_func;
4185 if (n_fds || timeout != 0)
4187 int ret, errsv;
4189 #ifdef G_MAIN_POLL_DEBUG
4190 poll_timer = NULL;
4191 if (_g_main_poll_debug)
4193 g_print ("polling context=%p n=%d timeout=%d\n",
4194 context, n_fds, timeout);
4195 poll_timer = g_timer_new ();
4197 #endif
4199 LOCK_CONTEXT (context);
4201 poll_func = context->poll_func;
4203 UNLOCK_CONTEXT (context);
4204 ret = (*poll_func) (fds, n_fds, timeout);
4205 errsv = errno;
4206 if (ret < 0 && errsv != EINTR)
4208 #ifndef G_OS_WIN32
4209 g_warning ("poll(2) failed due to: %s.",
4210 g_strerror (errsv));
4211 #else
4212 /* If g_poll () returns -1, it has already called g_warning() */
4213 #endif
4216 #ifdef G_MAIN_POLL_DEBUG
4217 if (_g_main_poll_debug)
4219 LOCK_CONTEXT (context);
4221 g_print ("g_main_poll(%d) timeout: %d - elapsed %12.10f seconds",
4222 n_fds,
4223 timeout,
4224 g_timer_elapsed (poll_timer, NULL));
4225 g_timer_destroy (poll_timer);
4226 pollrec = context->poll_records;
4228 while (pollrec != NULL)
4230 i = 0;
4231 while (i < n_fds)
4233 if (fds[i].fd == pollrec->fd->fd &&
4234 pollrec->fd->events &&
4235 fds[i].revents)
4237 g_print (" [" G_POLLFD_FORMAT " :", fds[i].fd);
4238 if (fds[i].revents & G_IO_IN)
4239 g_print ("i");
4240 if (fds[i].revents & G_IO_OUT)
4241 g_print ("o");
4242 if (fds[i].revents & G_IO_PRI)
4243 g_print ("p");
4244 if (fds[i].revents & G_IO_ERR)
4245 g_print ("e");
4246 if (fds[i].revents & G_IO_HUP)
4247 g_print ("h");
4248 if (fds[i].revents & G_IO_NVAL)
4249 g_print ("n");
4250 g_print ("]");
4252 i++;
4254 pollrec = pollrec->next;
4256 g_print ("\n");
4258 UNLOCK_CONTEXT (context);
4260 #endif
4261 } /* if (n_fds || timeout != 0) */
4265 * g_main_context_add_poll:
4266 * @context: (nullable): a #GMainContext (or %NULL for the default context)
4267 * @fd: a #GPollFD structure holding information about a file
4268 * descriptor to watch.
4269 * @priority: the priority for this file descriptor which should be
4270 * the same as the priority used for g_source_attach() to ensure that the
4271 * file descriptor is polled whenever the results may be needed.
4273 * Adds a file descriptor to the set of file descriptors polled for
4274 * this context. This will very seldom be used directly. Instead
4275 * a typical event source will use g_source_add_unix_fd() instead.
4277 void
4278 g_main_context_add_poll (GMainContext *context,
4279 GPollFD *fd,
4280 gint priority)
4282 if (!context)
4283 context = g_main_context_default ();
4285 g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
4286 g_return_if_fail (fd);
4288 LOCK_CONTEXT (context);
4289 g_main_context_add_poll_unlocked (context, priority, fd);
4290 UNLOCK_CONTEXT (context);
4293 /* HOLDS: main_loop_lock */
4294 static void
4295 g_main_context_add_poll_unlocked (GMainContext *context,
4296 gint priority,
4297 GPollFD *fd)
4299 GPollRec *prevrec, *nextrec;
4300 GPollRec *newrec = g_slice_new (GPollRec);
4302 /* This file descriptor may be checked before we ever poll */
4303 fd->revents = 0;
4304 newrec->fd = fd;
4305 newrec->priority = priority;
4307 prevrec = NULL;
4308 nextrec = context->poll_records;
4309 while (nextrec)
4311 if (nextrec->fd->fd > fd->fd)
4312 break;
4313 prevrec = nextrec;
4314 nextrec = nextrec->next;
4317 if (prevrec)
4318 prevrec->next = newrec;
4319 else
4320 context->poll_records = newrec;
4322 newrec->prev = prevrec;
4323 newrec->next = nextrec;
4325 if (nextrec)
4326 nextrec->prev = newrec;
4328 context->n_poll_records++;
4330 context->poll_changed = TRUE;
4332 /* Now wake up the main loop if it is waiting in the poll() */
4333 g_wakeup_signal (context->wakeup);
4337 * g_main_context_remove_poll:
4338 * @context:a #GMainContext
4339 * @fd: a #GPollFD descriptor previously added with g_main_context_add_poll()
4341 * Removes file descriptor from the set of file descriptors to be
4342 * polled for a particular context.
4344 void
4345 g_main_context_remove_poll (GMainContext *context,
4346 GPollFD *fd)
4348 if (!context)
4349 context = g_main_context_default ();
4351 g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
4352 g_return_if_fail (fd);
4354 LOCK_CONTEXT (context);
4355 g_main_context_remove_poll_unlocked (context, fd);
4356 UNLOCK_CONTEXT (context);
4359 static void
4360 g_main_context_remove_poll_unlocked (GMainContext *context,
4361 GPollFD *fd)
4363 GPollRec *pollrec, *prevrec, *nextrec;
4365 prevrec = NULL;
4366 pollrec = context->poll_records;
4368 while (pollrec)
4370 nextrec = pollrec->next;
4371 if (pollrec->fd == fd)
4373 if (prevrec != NULL)
4374 prevrec->next = nextrec;
4375 else
4376 context->poll_records = nextrec;
4378 if (nextrec != NULL)
4379 nextrec->prev = prevrec;
4381 g_slice_free (GPollRec, pollrec);
4383 context->n_poll_records--;
4384 break;
4386 prevrec = pollrec;
4387 pollrec = nextrec;
4390 context->poll_changed = TRUE;
4392 /* Now wake up the main loop if it is waiting in the poll() */
4393 g_wakeup_signal (context->wakeup);
4397 * g_source_get_current_time:
4398 * @source: a #GSource
4399 * @timeval: #GTimeVal structure in which to store current time.
4401 * This function ignores @source and is otherwise the same as
4402 * g_get_current_time().
4404 * Deprecated: 2.28: use g_source_get_time() instead
4406 void
4407 g_source_get_current_time (GSource *source,
4408 GTimeVal *timeval)
4410 g_get_current_time (timeval);
4414 * g_source_get_time:
4415 * @source: a #GSource
4417 * Gets the time to be used when checking this source. The advantage of
4418 * calling this function over calling g_get_monotonic_time() directly is
4419 * that when checking multiple sources, GLib can cache a single value
4420 * instead of having to repeatedly get the system monotonic time.
4422 * The time here is the system monotonic time, if available, or some
4423 * other reasonable alternative otherwise. See g_get_monotonic_time().
4425 * Returns: the monotonic time in microseconds
4427 * Since: 2.28
4429 gint64
4430 g_source_get_time (GSource *source)
4432 GMainContext *context;
4433 gint64 result;
4435 g_return_val_if_fail (source->context != NULL, 0);
4437 context = source->context;
4439 LOCK_CONTEXT (context);
4441 if (!context->time_is_fresh)
4443 context->time = g_get_monotonic_time ();
4444 context->time_is_fresh = TRUE;
4447 result = context->time;
4449 UNLOCK_CONTEXT (context);
4451 return result;
4455 * g_main_context_set_poll_func:
4456 * @context: a #GMainContext
4457 * @func: the function to call to poll all file descriptors
4459 * Sets the function to use to handle polling of file descriptors. It
4460 * will be used instead of the poll() system call
4461 * (or GLib's replacement function, which is used where
4462 * poll() isn't available).
4464 * This function could possibly be used to integrate the GLib event
4465 * loop with an external event loop.
4467 void
4468 g_main_context_set_poll_func (GMainContext *context,
4469 GPollFunc func)
4471 if (!context)
4472 context = g_main_context_default ();
4474 g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
4476 LOCK_CONTEXT (context);
4478 if (func)
4479 context->poll_func = func;
4480 else
4481 context->poll_func = g_poll;
4483 UNLOCK_CONTEXT (context);
4487 * g_main_context_get_poll_func:
4488 * @context: a #GMainContext
4490 * Gets the poll function set by g_main_context_set_poll_func().
4492 * Returns: the poll function
4494 GPollFunc
4495 g_main_context_get_poll_func (GMainContext *context)
4497 GPollFunc result;
4499 if (!context)
4500 context = g_main_context_default ();
4502 g_return_val_if_fail (g_atomic_int_get (&context->ref_count) > 0, NULL);
4504 LOCK_CONTEXT (context);
4505 result = context->poll_func;
4506 UNLOCK_CONTEXT (context);
4508 return result;
4512 * g_main_context_wakeup:
4513 * @context: a #GMainContext
4515 * If @context is currently blocking in g_main_context_iteration()
4516 * waiting for a source to become ready, cause it to stop blocking
4517 * and return. Otherwise, cause the next invocation of
4518 * g_main_context_iteration() to return without blocking.
4520 * This API is useful for low-level control over #GMainContext; for
4521 * example, integrating it with main loop implementations such as
4522 * #GMainLoop.
4524 * Another related use for this function is when implementing a main
4525 * loop with a termination condition, computed from multiple threads:
4527 * |[<!-- language="C" -->
4528 * #define NUM_TASKS 10
4529 * static volatile gint tasks_remaining = NUM_TASKS;
4530 * ...
4532 * while (g_atomic_int_get (&tasks_remaining) != 0)
4533 * g_main_context_iteration (NULL, TRUE);
4534 * ]|
4536 * Then in a thread:
4537 * |[<!-- language="C" -->
4538 * perform_work();
4540 * if (g_atomic_int_dec_and_test (&tasks_remaining))
4541 * g_main_context_wakeup (NULL);
4542 * ]|
4544 void
4545 g_main_context_wakeup (GMainContext *context)
4547 if (!context)
4548 context = g_main_context_default ();
4550 g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
4552 TRACE (GLIB_MAIN_CONTEXT_WAKEUP (context));
4554 g_wakeup_signal (context->wakeup);
4558 * g_main_context_is_owner:
4559 * @context: a #GMainContext
4561 * Determines whether this thread holds the (recursive)
4562 * ownership of this #GMainContext. This is useful to
4563 * know before waiting on another thread that may be
4564 * blocking to get ownership of @context.
4566 * Returns: %TRUE if current thread is owner of @context.
4568 * Since: 2.10
4570 gboolean
4571 g_main_context_is_owner (GMainContext *context)
4573 gboolean is_owner;
4575 if (!context)
4576 context = g_main_context_default ();
4578 LOCK_CONTEXT (context);
4579 is_owner = context->owner == G_THREAD_SELF;
4580 UNLOCK_CONTEXT (context);
4582 return is_owner;
4585 /* Timeouts */
4587 static void
4588 g_timeout_set_expiration (GTimeoutSource *timeout_source,
4589 gint64 current_time)
4591 gint64 expiration;
4593 expiration = current_time + (guint64) timeout_source->interval * 1000;
4595 if (timeout_source->seconds)
4597 gint64 remainder;
4598 static gint timer_perturb = -1;
4600 if (timer_perturb == -1)
4603 * we want a per machine/session unique 'random' value; try the dbus
4604 * address first, that has a UUID in it. If there is no dbus, use the
4605 * hostname for hashing.
4607 const char *session_bus_address = g_getenv ("DBUS_SESSION_BUS_ADDRESS");
4608 if (!session_bus_address)
4609 session_bus_address = g_getenv ("HOSTNAME");
4610 if (session_bus_address)
4611 timer_perturb = ABS ((gint) g_str_hash (session_bus_address)) % 1000000;
4612 else
4613 timer_perturb = 0;
4616 /* We want the microseconds part of the timeout to land on the
4617 * 'timer_perturb' mark, but we need to make sure we don't try to
4618 * set the timeout in the past. We do this by ensuring that we
4619 * always only *increase* the expiration time by adding a full
4620 * second in the case that the microsecond portion decreases.
4622 expiration -= timer_perturb;
4624 remainder = expiration % 1000000;
4625 if (remainder >= 1000000/4)
4626 expiration += 1000000;
4628 expiration -= remainder;
4629 expiration += timer_perturb;
4632 g_source_set_ready_time ((GSource *) timeout_source, expiration);
4635 static gboolean
4636 g_timeout_dispatch (GSource *source,
4637 GSourceFunc callback,
4638 gpointer user_data)
4640 GTimeoutSource *timeout_source = (GTimeoutSource *)source;
4641 gboolean again;
4643 if (!callback)
4645 g_warning ("Timeout source dispatched without callback. "
4646 "You must call g_source_set_callback().");
4647 return FALSE;
4650 again = callback (user_data);
4652 TRACE (GLIB_TIMEOUT_DISPATCH (source, source->context, callback, user_data, again));
4654 if (again)
4655 g_timeout_set_expiration (timeout_source, g_source_get_time (source));
4657 return again;
4661 * g_timeout_source_new:
4662 * @interval: the timeout interval in milliseconds.
4664 * Creates a new timeout source.
4666 * The source will not initially be associated with any #GMainContext
4667 * and must be added to one with g_source_attach() before it will be
4668 * executed.
4670 * The interval given is in terms of monotonic time, not wall clock
4671 * time. See g_get_monotonic_time().
4673 * Returns: the newly-created timeout source
4675 GSource *
4676 g_timeout_source_new (guint interval)
4678 GSource *source = g_source_new (&g_timeout_funcs, sizeof (GTimeoutSource));
4679 GTimeoutSource *timeout_source = (GTimeoutSource *)source;
4681 timeout_source->interval = interval;
4682 g_timeout_set_expiration (timeout_source, g_get_monotonic_time ());
4684 return source;
4688 * g_timeout_source_new_seconds:
4689 * @interval: the timeout interval in seconds
4691 * Creates a new timeout source.
4693 * The source will not initially be associated with any #GMainContext
4694 * and must be added to one with g_source_attach() before it will be
4695 * executed.
4697 * The scheduling granularity/accuracy of this timeout source will be
4698 * in seconds.
4700 * The interval given is in terms of monotonic time, not wall clock time.
4701 * See g_get_monotonic_time().
4703 * Returns: the newly-created timeout source
4705 * Since: 2.14
4707 GSource *
4708 g_timeout_source_new_seconds (guint interval)
4710 GSource *source = g_source_new (&g_timeout_funcs, sizeof (GTimeoutSource));
4711 GTimeoutSource *timeout_source = (GTimeoutSource *)source;
4713 timeout_source->interval = 1000 * interval;
4714 timeout_source->seconds = TRUE;
4716 g_timeout_set_expiration (timeout_source, g_get_monotonic_time ());
4718 return source;
4723 * g_timeout_add_full: (rename-to g_timeout_add)
4724 * @priority: the priority of the timeout source. Typically this will be in
4725 * the range between #G_PRIORITY_DEFAULT and #G_PRIORITY_HIGH.
4726 * @interval: the time between calls to the function, in milliseconds
4727 * (1/1000ths of a second)
4728 * @function: function to call
4729 * @data: data to pass to @function
4730 * @notify: (nullable): function to call when the timeout is removed, or %NULL
4732 * Sets a function to be called at regular intervals, with the given
4733 * priority. The function is called repeatedly until it returns
4734 * %FALSE, at which point the timeout is automatically destroyed and
4735 * the function will not be called again. The @notify function is
4736 * called when the timeout is destroyed. The first call to the
4737 * function will be at the end of the first @interval.
4739 * Note that timeout functions may be delayed, due to the processing of other
4740 * event sources. Thus they should not be relied on for precise timing.
4741 * After each call to the timeout function, the time of the next
4742 * timeout is recalculated based on the current time and the given interval
4743 * (it does not try to 'catch up' time lost in delays).
4745 * See [memory management of sources][mainloop-memory-management] for details
4746 * on how to handle the return value and memory management of @data.
4748 * This internally creates a main loop source using g_timeout_source_new()
4749 * and attaches it to the global #GMainContext using g_source_attach(), so
4750 * the callback will be invoked in whichever thread is running that main
4751 * context. You can do these steps manually if you need greater control or to
4752 * use a custom main context.
4754 * The interval given is in terms of monotonic time, not wall clock time.
4755 * See g_get_monotonic_time().
4757 * Returns: the ID (greater than 0) of the event source.
4759 guint
4760 g_timeout_add_full (gint priority,
4761 guint interval,
4762 GSourceFunc function,
4763 gpointer data,
4764 GDestroyNotify notify)
4766 GSource *source;
4767 guint id;
4769 g_return_val_if_fail (function != NULL, 0);
4771 source = g_timeout_source_new (interval);
4773 if (priority != G_PRIORITY_DEFAULT)
4774 g_source_set_priority (source, priority);
4776 g_source_set_callback (source, function, data, notify);
4777 id = g_source_attach (source, NULL);
4779 TRACE (GLIB_TIMEOUT_ADD (source, g_main_context_default (), id, priority, interval, function, data));
4781 g_source_unref (source);
4783 return id;
4787 * g_timeout_add:
4788 * @interval: the time between calls to the function, in milliseconds
4789 * (1/1000ths of a second)
4790 * @function: function to call
4791 * @data: data to pass to @function
4793 * Sets a function to be called at regular intervals, with the default
4794 * priority, #G_PRIORITY_DEFAULT. The function is called repeatedly
4795 * until it returns %FALSE, at which point the timeout is automatically
4796 * destroyed and the function will not be called again. The first call
4797 * to the function will be at the end of the first @interval.
4799 * Note that timeout functions may be delayed, due to the processing of other
4800 * event sources. Thus they should not be relied on for precise timing.
4801 * After each call to the timeout function, the time of the next
4802 * timeout is recalculated based on the current time and the given interval
4803 * (it does not try to 'catch up' time lost in delays).
4805 * See [memory management of sources][mainloop-memory-management] for details
4806 * on how to handle the return value and memory management of @data.
4808 * If you want to have a timer in the "seconds" range and do not care
4809 * about the exact time of the first call of the timer, use the
4810 * g_timeout_add_seconds() function; this function allows for more
4811 * optimizations and more efficient system power usage.
4813 * This internally creates a main loop source using g_timeout_source_new()
4814 * and attaches it to the global #GMainContext using g_source_attach(), so
4815 * the callback will be invoked in whichever thread is running that main
4816 * context. You can do these steps manually if you need greater control or to
4817 * use a custom main context.
4819 * The interval given is in terms of monotonic time, not wall clock
4820 * time. See g_get_monotonic_time().
4822 * Returns: the ID (greater than 0) of the event source.
4824 guint
4825 g_timeout_add (guint32 interval,
4826 GSourceFunc function,
4827 gpointer data)
4829 return g_timeout_add_full (G_PRIORITY_DEFAULT,
4830 interval, function, data, NULL);
4834 * g_timeout_add_seconds_full: (rename-to g_timeout_add_seconds)
4835 * @priority: the priority of the timeout source. Typically this will be in
4836 * the range between #G_PRIORITY_DEFAULT and #G_PRIORITY_HIGH.
4837 * @interval: the time between calls to the function, in seconds
4838 * @function: function to call
4839 * @data: data to pass to @function
4840 * @notify: (nullable): function to call when the timeout is removed, or %NULL
4842 * Sets a function to be called at regular intervals, with @priority.
4843 * The function is called repeatedly until it returns %FALSE, at which
4844 * point the timeout is automatically destroyed and the function will
4845 * not be called again.
4847 * Unlike g_timeout_add(), this function operates at whole second granularity.
4848 * The initial starting point of the timer is determined by the implementation
4849 * and the implementation is expected to group multiple timers together so that
4850 * they fire all at the same time.
4851 * To allow this grouping, the @interval to the first timer is rounded
4852 * and can deviate up to one second from the specified interval.
4853 * Subsequent timer iterations will generally run at the specified interval.
4855 * Note that timeout functions may be delayed, due to the processing of other
4856 * event sources. Thus they should not be relied on for precise timing.
4857 * After each call to the timeout function, the time of the next
4858 * timeout is recalculated based on the current time and the given @interval
4860 * See [memory management of sources][mainloop-memory-management] for details
4861 * on how to handle the return value and memory management of @data.
4863 * If you want timing more precise than whole seconds, use g_timeout_add()
4864 * instead.
4866 * The grouping of timers to fire at the same time results in a more power
4867 * and CPU efficient behavior so if your timer is in multiples of seconds
4868 * and you don't require the first timer exactly one second from now, the
4869 * use of g_timeout_add_seconds() is preferred over g_timeout_add().
4871 * This internally creates a main loop source using
4872 * g_timeout_source_new_seconds() and attaches it to the main loop context
4873 * using g_source_attach(). You can do these steps manually if you need
4874 * greater control.
4876 * The interval given is in terms of monotonic time, not wall clock
4877 * time. See g_get_monotonic_time().
4879 * Returns: the ID (greater than 0) of the event source.
4881 * Since: 2.14
4883 guint
4884 g_timeout_add_seconds_full (gint priority,
4885 guint32 interval,
4886 GSourceFunc function,
4887 gpointer data,
4888 GDestroyNotify notify)
4890 GSource *source;
4891 guint id;
4893 g_return_val_if_fail (function != NULL, 0);
4895 source = g_timeout_source_new_seconds (interval);
4897 if (priority != G_PRIORITY_DEFAULT)
4898 g_source_set_priority (source, priority);
4900 g_source_set_callback (source, function, data, notify);
4901 id = g_source_attach (source, NULL);
4902 g_source_unref (source);
4904 return id;
4908 * g_timeout_add_seconds:
4909 * @interval: the time between calls to the function, in seconds
4910 * @function: function to call
4911 * @data: data to pass to @function
4913 * Sets a function to be called at regular intervals with the default
4914 * priority, #G_PRIORITY_DEFAULT. The function is called repeatedly until
4915 * it returns %FALSE, at which point the timeout is automatically destroyed
4916 * and the function will not be called again.
4918 * This internally creates a main loop source using
4919 * g_timeout_source_new_seconds() and attaches it to the main loop context
4920 * using g_source_attach(). You can do these steps manually if you need
4921 * greater control. Also see g_timeout_add_seconds_full().
4923 * Note that the first call of the timer may not be precise for timeouts
4924 * of one second. If you need finer precision and have such a timeout,
4925 * you may want to use g_timeout_add() instead.
4927 * See [memory management of sources][mainloop-memory-management] for details
4928 * on how to handle the return value and memory management of @data.
4930 * The interval given is in terms of monotonic time, not wall clock
4931 * time. See g_get_monotonic_time().
4933 * Returns: the ID (greater than 0) of the event source.
4935 * Since: 2.14
4937 guint
4938 g_timeout_add_seconds (guint interval,
4939 GSourceFunc function,
4940 gpointer data)
4942 g_return_val_if_fail (function != NULL, 0);
4944 return g_timeout_add_seconds_full (G_PRIORITY_DEFAULT, interval, function, data, NULL);
4947 /* Child watch functions */
4949 #ifdef G_OS_WIN32
4951 static gboolean
4952 g_child_watch_prepare (GSource *source,
4953 gint *timeout)
4955 *timeout = -1;
4956 return FALSE;
4959 static gboolean
4960 g_child_watch_check (GSource *source)
4962 GChildWatchSource *child_watch_source;
4963 gboolean child_exited;
4965 child_watch_source = (GChildWatchSource *) source;
4967 child_exited = child_watch_source->poll.revents & G_IO_IN;
4969 if (child_exited)
4971 DWORD child_status;
4974 * Note: We do _not_ check for the special value of STILL_ACTIVE
4975 * since we know that the process has exited and doing so runs into
4976 * problems if the child process "happens to return STILL_ACTIVE(259)"
4977 * as Microsoft's Platform SDK puts it.
4979 if (!GetExitCodeProcess (child_watch_source->pid, &child_status))
4981 gchar *emsg = g_win32_error_message (GetLastError ());
4982 g_warning (G_STRLOC ": GetExitCodeProcess() failed: %s", emsg);
4983 g_free (emsg);
4985 child_watch_source->child_status = -1;
4987 else
4988 child_watch_source->child_status = child_status;
4991 return child_exited;
4994 static void
4995 g_child_watch_finalize (GSource *source)
4999 #else /* G_OS_WIN32 */
5001 static void
5002 wake_source (GSource *source)
5004 GMainContext *context;
5006 /* This should be thread-safe:
5008 * - if the source is currently being added to a context, that
5009 * context will be woken up anyway
5011 * - if the source is currently being destroyed, we simply need not
5012 * to crash:
5014 * - the memory for the source will remain valid until after the
5015 * source finalize function was called (which would remove the
5016 * source from the global list which we are currently holding the
5017 * lock for)
5019 * - the GMainContext will either be NULL or point to a live
5020 * GMainContext
5022 * - the GMainContext will remain valid since we hold the
5023 * main_context_list lock
5025 * Since we are holding a lot of locks here, don't try to enter any
5026 * more GMainContext functions for fear of dealock -- just hit the
5027 * GWakeup and run. Even if that's safe now, it could easily become
5028 * unsafe with some very minor changes in the future, and signal
5029 * handling is not the most well-tested codepath.
5031 G_LOCK(main_context_list);
5032 context = source->context;
5033 if (context)
5034 g_wakeup_signal (context->wakeup);
5035 G_UNLOCK(main_context_list);
5038 static void
5039 dispatch_unix_signals_unlocked (void)
5041 gboolean pending[NSIG];
5042 GSList *node;
5043 gint i;
5045 /* clear this first in case another one arrives while we're processing */
5046 any_unix_signal_pending = FALSE;
5048 /* We atomically test/clear the bit from the global array in case
5049 * other signals arrive while we are dispatching.
5051 * We then can safely use our own array below without worrying about
5052 * races.
5054 for (i = 0; i < NSIG; i++)
5056 /* Be very careful with (the volatile) unix_signal_pending.
5058 * We must ensure that it's not possible that we clear it without
5059 * handling the signal. We therefore must ensure that our pending
5060 * array has a field set (ie: we will do something about the
5061 * signal) before we clear the item in unix_signal_pending.
5063 * Note specifically: we must check _our_ array.
5065 pending[i] = unix_signal_pending[i];
5066 if (pending[i])
5067 unix_signal_pending[i] = FALSE;
5070 /* handle GChildWatchSource instances */
5071 if (pending[SIGCHLD])
5073 /* The only way we can do this is to scan all of the children.
5075 * The docs promise that we will not reap children that we are not
5076 * explicitly watching, so that ties our hands from calling
5077 * waitpid(-1). We also can't use siginfo's si_pid field since if
5078 * multiple SIGCHLD arrive at the same time, one of them can be
5079 * dropped (since a given UNIX signal can only be pending once).
5081 for (node = unix_child_watches; node; node = node->next)
5083 GChildWatchSource *source = node->data;
5085 if (!source->child_exited)
5087 pid_t pid;
5090 g_assert (source->pid > 0);
5092 pid = waitpid (source->pid, &source->child_status, WNOHANG);
5093 if (pid > 0)
5095 source->child_exited = TRUE;
5096 wake_source ((GSource *) source);
5098 else if (pid == -1 && errno == ECHILD)
5100 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.");
5101 source->child_exited = TRUE;
5102 source->child_status = 0;
5103 wake_source ((GSource *) source);
5106 while (pid == -1 && errno == EINTR);
5111 /* handle GUnixSignalWatchSource instances */
5112 for (node = unix_signal_watches; node; node = node->next)
5114 GUnixSignalWatchSource *source = node->data;
5116 if (!source->pending)
5118 if (pending[source->signum])
5120 source->pending = TRUE;
5122 wake_source ((GSource *) source);
5129 static void
5130 dispatch_unix_signals (void)
5132 G_LOCK(unix_signal_lock);
5133 dispatch_unix_signals_unlocked ();
5134 G_UNLOCK(unix_signal_lock);
5137 static gboolean
5138 g_child_watch_prepare (GSource *source,
5139 gint *timeout)
5141 GChildWatchSource *child_watch_source;
5143 child_watch_source = (GChildWatchSource *) source;
5145 return child_watch_source->child_exited;
5148 static gboolean
5149 g_child_watch_check (GSource *source)
5151 GChildWatchSource *child_watch_source;
5153 child_watch_source = (GChildWatchSource *) source;
5155 return child_watch_source->child_exited;
5158 static gboolean
5159 g_unix_signal_watch_prepare (GSource *source,
5160 gint *timeout)
5162 GUnixSignalWatchSource *unix_signal_source;
5164 unix_signal_source = (GUnixSignalWatchSource *) source;
5166 return unix_signal_source->pending;
5169 static gboolean
5170 g_unix_signal_watch_check (GSource *source)
5172 GUnixSignalWatchSource *unix_signal_source;
5174 unix_signal_source = (GUnixSignalWatchSource *) source;
5176 return unix_signal_source->pending;
5179 static gboolean
5180 g_unix_signal_watch_dispatch (GSource *source,
5181 GSourceFunc callback,
5182 gpointer user_data)
5184 GUnixSignalWatchSource *unix_signal_source;
5185 gboolean again;
5187 unix_signal_source = (GUnixSignalWatchSource *) source;
5189 if (!callback)
5191 g_warning ("Unix signal source dispatched without callback. "
5192 "You must call g_source_set_callback().");
5193 return FALSE;
5196 again = (callback) (user_data);
5198 unix_signal_source->pending = FALSE;
5200 return again;
5203 static void
5204 ref_unix_signal_handler_unlocked (int signum)
5206 /* Ensure we have the worker context */
5207 g_get_worker_context ();
5208 unix_signal_refcount[signum]++;
5209 if (unix_signal_refcount[signum] == 1)
5211 struct sigaction action;
5212 action.sa_handler = g_unix_signal_handler;
5213 sigemptyset (&action.sa_mask);
5214 #ifdef SA_RESTART
5215 action.sa_flags = SA_RESTART | SA_NOCLDSTOP;
5216 #else
5217 action.sa_flags = SA_NOCLDSTOP;
5218 #endif
5219 sigaction (signum, &action, NULL);
5223 static void
5224 unref_unix_signal_handler_unlocked (int signum)
5226 unix_signal_refcount[signum]--;
5227 if (unix_signal_refcount[signum] == 0)
5229 struct sigaction action;
5230 memset (&action, 0, sizeof (action));
5231 action.sa_handler = SIG_DFL;
5232 sigemptyset (&action.sa_mask);
5233 sigaction (signum, &action, NULL);
5237 GSource *
5238 _g_main_create_unix_signal_watch (int signum)
5240 GSource *source;
5241 GUnixSignalWatchSource *unix_signal_source;
5243 source = g_source_new (&g_unix_signal_funcs, sizeof (GUnixSignalWatchSource));
5244 unix_signal_source = (GUnixSignalWatchSource *) source;
5246 unix_signal_source->signum = signum;
5247 unix_signal_source->pending = FALSE;
5249 G_LOCK (unix_signal_lock);
5250 ref_unix_signal_handler_unlocked (signum);
5251 unix_signal_watches = g_slist_prepend (unix_signal_watches, unix_signal_source);
5252 dispatch_unix_signals_unlocked ();
5253 G_UNLOCK (unix_signal_lock);
5255 return source;
5258 static void
5259 g_unix_signal_watch_finalize (GSource *source)
5261 GUnixSignalWatchSource *unix_signal_source;
5263 unix_signal_source = (GUnixSignalWatchSource *) source;
5265 G_LOCK (unix_signal_lock);
5266 unref_unix_signal_handler_unlocked (unix_signal_source->signum);
5267 unix_signal_watches = g_slist_remove (unix_signal_watches, source);
5268 G_UNLOCK (unix_signal_lock);
5271 static void
5272 g_child_watch_finalize (GSource *source)
5274 G_LOCK (unix_signal_lock);
5275 unix_child_watches = g_slist_remove (unix_child_watches, source);
5276 unref_unix_signal_handler_unlocked (SIGCHLD);
5277 G_UNLOCK (unix_signal_lock);
5280 #endif /* G_OS_WIN32 */
5282 static gboolean
5283 g_child_watch_dispatch (GSource *source,
5284 GSourceFunc callback,
5285 gpointer user_data)
5287 GChildWatchSource *child_watch_source;
5288 GChildWatchFunc child_watch_callback = (GChildWatchFunc) callback;
5290 child_watch_source = (GChildWatchSource *) source;
5292 if (!callback)
5294 g_warning ("Child watch source dispatched without callback. "
5295 "You must call g_source_set_callback().");
5296 return FALSE;
5299 (child_watch_callback) (child_watch_source->pid, child_watch_source->child_status, user_data);
5301 /* We never keep a child watch source around as the child is gone */
5302 return FALSE;
5305 #ifndef G_OS_WIN32
5307 static void
5308 g_unix_signal_handler (int signum)
5310 gint saved_errno = errno;
5312 unix_signal_pending[signum] = TRUE;
5313 any_unix_signal_pending = TRUE;
5315 g_wakeup_signal (glib_worker_context->wakeup);
5317 errno = saved_errno;
5320 #endif /* !G_OS_WIN32 */
5323 * g_child_watch_source_new:
5324 * @pid: process to watch. On POSIX the positive pid of a child process. On
5325 * Windows a handle for a process (which doesn't have to be a child).
5327 * Creates a new child_watch source.
5329 * The source will not initially be associated with any #GMainContext
5330 * and must be added to one with g_source_attach() before it will be
5331 * executed.
5333 * Note that child watch sources can only be used in conjunction with
5334 * `g_spawn...` when the %G_SPAWN_DO_NOT_REAP_CHILD flag is used.
5336 * Note that on platforms where #GPid must be explicitly closed
5337 * (see g_spawn_close_pid()) @pid must not be closed while the
5338 * source is still active. Typically, you will want to call
5339 * g_spawn_close_pid() in the callback function for the source.
5341 * On POSIX platforms, the following restrictions apply to this API
5342 * due to limitations in POSIX process interfaces:
5344 * * @pid must be a child of this process
5345 * * @pid must be positive
5346 * * the application must not call `waitpid` with a non-positive
5347 * first argument, for instance in another thread
5348 * * the application must not wait for @pid to exit by any other
5349 * mechanism, including `waitpid(pid, ...)` or a second child-watch
5350 * source for the same @pid
5351 * * the application must not ignore SIGCHILD
5353 * If any of those conditions are not met, this and related APIs will
5354 * not work correctly. This can often be diagnosed via a GLib warning
5355 * stating that `ECHILD` was received by `waitpid`.
5357 * Calling `waitpid` for specific processes other than @pid remains a
5358 * valid thing to do.
5360 * Returns: the newly-created child watch source
5362 * Since: 2.4
5364 GSource *
5365 g_child_watch_source_new (GPid pid)
5367 GSource *source;
5368 GChildWatchSource *child_watch_source;
5370 #ifndef G_OS_WIN32
5371 g_return_val_if_fail (pid > 0, NULL);
5372 #endif
5374 source = g_source_new (&g_child_watch_funcs, sizeof (GChildWatchSource));
5375 child_watch_source = (GChildWatchSource *)source;
5377 child_watch_source->pid = pid;
5379 #ifdef G_OS_WIN32
5380 child_watch_source->poll.fd = (gintptr) pid;
5381 child_watch_source->poll.events = G_IO_IN;
5383 g_source_add_poll (source, &child_watch_source->poll);
5384 #else /* G_OS_WIN32 */
5385 G_LOCK (unix_signal_lock);
5386 ref_unix_signal_handler_unlocked (SIGCHLD);
5387 unix_child_watches = g_slist_prepend (unix_child_watches, child_watch_source);
5388 if (waitpid (pid, &child_watch_source->child_status, WNOHANG) > 0)
5389 child_watch_source->child_exited = TRUE;
5390 G_UNLOCK (unix_signal_lock);
5391 #endif /* G_OS_WIN32 */
5393 return source;
5397 * g_child_watch_add_full: (rename-to g_child_watch_add)
5398 * @priority: the priority of the idle source. Typically this will be in the
5399 * range between #G_PRIORITY_DEFAULT_IDLE and #G_PRIORITY_HIGH_IDLE.
5400 * @pid: process to watch. On POSIX the positive pid of a child process. On
5401 * Windows a handle for a process (which doesn't have to be a child).
5402 * @function: function to call
5403 * @data: data to pass to @function
5404 * @notify: (nullable): function to call when the idle is removed, or %NULL
5406 * Sets a function to be called when the child indicated by @pid
5407 * exits, at the priority @priority.
5409 * If you obtain @pid from g_spawn_async() or g_spawn_async_with_pipes()
5410 * you will need to pass #G_SPAWN_DO_NOT_REAP_CHILD as flag to
5411 * the spawn function for the child watching to work.
5413 * In many programs, you will want to call g_spawn_check_exit_status()
5414 * in the callback to determine whether or not the child exited
5415 * successfully.
5417 * Also, note that on platforms where #GPid must be explicitly closed
5418 * (see g_spawn_close_pid()) @pid must not be closed while the source
5419 * is still active. Typically, you should invoke g_spawn_close_pid()
5420 * in the callback function for the source.
5422 * GLib supports only a single callback per process id.
5423 * On POSIX platforms, the same restrictions mentioned for
5424 * g_child_watch_source_new() apply to this function.
5426 * This internally creates a main loop source using
5427 * g_child_watch_source_new() and attaches it to the main loop context
5428 * using g_source_attach(). You can do these steps manually if you
5429 * need greater control.
5431 * Returns: the ID (greater than 0) of the event source.
5433 * Since: 2.4
5435 guint
5436 g_child_watch_add_full (gint priority,
5437 GPid pid,
5438 GChildWatchFunc function,
5439 gpointer data,
5440 GDestroyNotify notify)
5442 GSource *source;
5443 guint id;
5445 g_return_val_if_fail (function != NULL, 0);
5446 #ifndef G_OS_WIN32
5447 g_return_val_if_fail (pid > 0, 0);
5448 #endif
5450 source = g_child_watch_source_new (pid);
5452 if (priority != G_PRIORITY_DEFAULT)
5453 g_source_set_priority (source, priority);
5455 g_source_set_callback (source, (GSourceFunc) function, data, notify);
5456 id = g_source_attach (source, NULL);
5457 g_source_unref (source);
5459 return id;
5463 * g_child_watch_add:
5464 * @pid: process id to watch. On POSIX the positive pid of a child
5465 * process. On Windows a handle for a process (which doesn't have to be
5466 * a child).
5467 * @function: function to call
5468 * @data: data to pass to @function
5470 * Sets a function to be called when the child indicated by @pid
5471 * exits, at a default priority, #G_PRIORITY_DEFAULT.
5473 * If you obtain @pid from g_spawn_async() or g_spawn_async_with_pipes()
5474 * you will need to pass #G_SPAWN_DO_NOT_REAP_CHILD as flag to
5475 * the spawn function for the child watching to work.
5477 * Note that on platforms where #GPid must be explicitly closed
5478 * (see g_spawn_close_pid()) @pid must not be closed while the
5479 * source is still active. Typically, you will want to call
5480 * g_spawn_close_pid() in the callback function for the source.
5482 * GLib supports only a single callback per process id.
5483 * On POSIX platforms, the same restrictions mentioned for
5484 * g_child_watch_source_new() apply to this function.
5486 * This internally creates a main loop source using
5487 * g_child_watch_source_new() and attaches it to the main loop context
5488 * using g_source_attach(). You can do these steps manually if you
5489 * need greater control.
5491 * Returns: the ID (greater than 0) of the event source.
5493 * Since: 2.4
5495 guint
5496 g_child_watch_add (GPid pid,
5497 GChildWatchFunc function,
5498 gpointer data)
5500 return g_child_watch_add_full (G_PRIORITY_DEFAULT, pid, function, data, NULL);
5504 /* Idle functions */
5506 static gboolean
5507 g_idle_prepare (GSource *source,
5508 gint *timeout)
5510 *timeout = 0;
5512 return TRUE;
5515 static gboolean
5516 g_idle_check (GSource *source)
5518 return TRUE;
5521 static gboolean
5522 g_idle_dispatch (GSource *source,
5523 GSourceFunc callback,
5524 gpointer user_data)
5526 gboolean again;
5528 if (!callback)
5530 g_warning ("Idle source dispatched without callback. "
5531 "You must call g_source_set_callback().");
5532 return FALSE;
5535 again = callback (user_data);
5537 TRACE (GLIB_IDLE_DISPATCH (source, source->context, callback, user_data, again));
5539 return again;
5543 * g_idle_source_new:
5545 * Creates a new idle source.
5547 * The source will not initially be associated with any #GMainContext
5548 * and must be added to one with g_source_attach() before it will be
5549 * executed. Note that the default priority for idle sources is
5550 * %G_PRIORITY_DEFAULT_IDLE, as compared to other sources which
5551 * have a default priority of %G_PRIORITY_DEFAULT.
5553 * Returns: the newly-created idle source
5555 GSource *
5556 g_idle_source_new (void)
5558 GSource *source;
5560 source = g_source_new (&g_idle_funcs, sizeof (GSource));
5561 g_source_set_priority (source, G_PRIORITY_DEFAULT_IDLE);
5563 return source;
5567 * g_idle_add_full: (rename-to g_idle_add)
5568 * @priority: the priority of the idle source. Typically this will be in the
5569 * range between #G_PRIORITY_DEFAULT_IDLE and #G_PRIORITY_HIGH_IDLE.
5570 * @function: function to call
5571 * @data: data to pass to @function
5572 * @notify: (nullable): function to call when the idle is removed, or %NULL
5574 * Adds a function to be called whenever there are no higher priority
5575 * events pending. If the function returns %FALSE it is automatically
5576 * removed from the list of event sources and will not be called again.
5578 * See [memory management of sources][mainloop-memory-management] for details
5579 * on how to handle the return value and memory management of @data.
5581 * This internally creates a main loop source using g_idle_source_new()
5582 * and attaches it to the global #GMainContext using g_source_attach(), so
5583 * the callback will be invoked in whichever thread is running that main
5584 * context. You can do these steps manually if you need greater control or to
5585 * use a custom main context.
5587 * Returns: the ID (greater than 0) of the event source.
5589 guint
5590 g_idle_add_full (gint priority,
5591 GSourceFunc function,
5592 gpointer data,
5593 GDestroyNotify notify)
5595 GSource *source;
5596 guint id;
5598 g_return_val_if_fail (function != NULL, 0);
5600 source = g_idle_source_new ();
5602 if (priority != G_PRIORITY_DEFAULT_IDLE)
5603 g_source_set_priority (source, priority);
5605 g_source_set_callback (source, function, data, notify);
5606 id = g_source_attach (source, NULL);
5608 TRACE (GLIB_IDLE_ADD (source, g_main_context_default (), id, priority, function, data));
5610 g_source_unref (source);
5612 return id;
5616 * g_idle_add:
5617 * @function: function to call
5618 * @data: data to pass to @function.
5620 * Adds a function to be called whenever there are no higher priority
5621 * events pending to the default main loop. The function is given the
5622 * default idle priority, #G_PRIORITY_DEFAULT_IDLE. If the function
5623 * returns %FALSE it is automatically removed from the list of event
5624 * sources and will not be called again.
5626 * See [memory management of sources][mainloop-memory-management] for details
5627 * on how to handle the return value and memory management of @data.
5629 * This internally creates a main loop source using g_idle_source_new()
5630 * and attaches it to the global #GMainContext using g_source_attach(), so
5631 * the callback will be invoked in whichever thread is running that main
5632 * context. You can do these steps manually if you need greater control or to
5633 * use a custom main context.
5635 * Returns: the ID (greater than 0) of the event source.
5637 guint
5638 g_idle_add (GSourceFunc function,
5639 gpointer data)
5641 return g_idle_add_full (G_PRIORITY_DEFAULT_IDLE, function, data, NULL);
5645 * g_idle_remove_by_data:
5646 * @data: the data for the idle source's callback.
5648 * Removes the idle function with the given data.
5650 * Returns: %TRUE if an idle source was found and removed.
5652 gboolean
5653 g_idle_remove_by_data (gpointer data)
5655 return g_source_remove_by_funcs_user_data (&g_idle_funcs, data);
5659 * g_main_context_invoke:
5660 * @context: (nullable): a #GMainContext, or %NULL
5661 * @function: function to call
5662 * @data: data to pass to @function
5664 * Invokes a function in such a way that @context is owned during the
5665 * invocation of @function.
5667 * If @context is %NULL then the global default main context — as
5668 * returned by g_main_context_default() — is used.
5670 * If @context is owned by the current thread, @function is called
5671 * directly. Otherwise, if @context is the thread-default main context
5672 * of the current thread and g_main_context_acquire() succeeds, then
5673 * @function is called and g_main_context_release() is called
5674 * afterwards.
5676 * In any other case, an idle source is created to call @function and
5677 * that source is attached to @context (presumably to be run in another
5678 * thread). The idle source is attached with #G_PRIORITY_DEFAULT
5679 * priority. If you want a different priority, use
5680 * g_main_context_invoke_full().
5682 * Note that, as with normal idle functions, @function should probably
5683 * return %FALSE. If it returns %TRUE, it will be continuously run in a
5684 * loop (and may prevent this call from returning).
5686 * Since: 2.28
5688 void
5689 g_main_context_invoke (GMainContext *context,
5690 GSourceFunc function,
5691 gpointer data)
5693 g_main_context_invoke_full (context,
5694 G_PRIORITY_DEFAULT,
5695 function, data, NULL);
5699 * g_main_context_invoke_full:
5700 * @context: (nullable): a #GMainContext, or %NULL
5701 * @priority: the priority at which to run @function
5702 * @function: function to call
5703 * @data: data to pass to @function
5704 * @notify: (nullable): a function to call when @data is no longer in use, or %NULL.
5706 * Invokes a function in such a way that @context is owned during the
5707 * invocation of @function.
5709 * This function is the same as g_main_context_invoke() except that it
5710 * lets you specify the priority in case @function ends up being
5711 * scheduled as an idle and also lets you give a #GDestroyNotify for @data.
5713 * @notify should not assume that it is called from any particular
5714 * thread or with any particular context acquired.
5716 * Since: 2.28
5718 void
5719 g_main_context_invoke_full (GMainContext *context,
5720 gint priority,
5721 GSourceFunc function,
5722 gpointer data,
5723 GDestroyNotify notify)
5725 g_return_if_fail (function != NULL);
5727 if (!context)
5728 context = g_main_context_default ();
5730 if (g_main_context_is_owner (context))
5732 while (function (data));
5733 if (notify != NULL)
5734 notify (data);
5737 else
5739 GMainContext *thread_default;
5741 thread_default = g_main_context_get_thread_default ();
5743 if (!thread_default)
5744 thread_default = g_main_context_default ();
5746 if (thread_default == context && g_main_context_acquire (context))
5748 while (function (data));
5750 g_main_context_release (context);
5752 if (notify != NULL)
5753 notify (data);
5755 else
5757 GSource *source;
5759 source = g_idle_source_new ();
5760 g_source_set_priority (source, priority);
5761 g_source_set_callback (source, function, data, notify);
5762 g_source_attach (source, context);
5763 g_source_unref (source);
5768 static gpointer
5769 glib_worker_main (gpointer data)
5771 while (TRUE)
5773 g_main_context_iteration (glib_worker_context, TRUE);
5775 #ifdef G_OS_UNIX
5776 if (any_unix_signal_pending)
5777 dispatch_unix_signals ();
5778 #endif
5781 return NULL; /* worst GCC warning message ever... */
5784 GMainContext *
5785 g_get_worker_context (void)
5787 static gsize initialised;
5789 if (g_once_init_enter (&initialised))
5791 /* mask all signals in the worker thread */
5792 #ifdef G_OS_UNIX
5793 sigset_t prev_mask;
5794 sigset_t all;
5796 sigfillset (&all);
5797 pthread_sigmask (SIG_SETMASK, &all, &prev_mask);
5798 #endif
5799 glib_worker_context = g_main_context_new ();
5800 g_thread_new ("gmain", glib_worker_main, NULL);
5801 #ifdef G_OS_UNIX
5802 pthread_sigmask (SIG_SETMASK, &prev_mask, NULL);
5803 #endif
5804 g_once_init_leave (&initialised, TRUE);
5807 return glib_worker_context;