Revert "gmain: only signal GWakeup right before or during a blocking poll"
[glib.git] / glib / gmain.c
blob1fde50f88acc021b5cc5eb9f2377952e17738a79
1 /* GLIB - Library of useful routines for C programming
2 * Copyright (C) 1995-1997 Peter Mattis, Spencer Kimball and Josh MacDonald
4 * gmain.c: Main loop abstraction, timeouts, and idle functions
5 * Copyright 1998 Owen Taylor
7 * This library is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU Lesser General Public
9 * License as published by the Free Software Foundation; either
10 * version 2.1 of the License, or (at your option) any later version.
12 * This library is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 * Lesser General Public License for more details.
17 * You should have received a copy of the GNU Lesser General Public
18 * License along with this library; if not, see <http://www.gnu.org/licenses/>.
22 * Modified by the GLib Team and others 1997-2000. See the AUTHORS
23 * file for a list of people on the GLib Team. See the ChangeLog
24 * files for a list of changes. These files are distributed with
25 * GLib at ftp://ftp.gtk.org/pub/gtk/.
29 * MT safe
32 #include "config.h"
33 #include "glibconfig.h"
34 #include "glib_trace.h"
36 /* Uncomment the next line (and the corresponding line in gpoll.c) to
37 * enable debugging printouts if the environment variable
38 * G_MAIN_POLL_DEBUG is set to some value.
40 /* #define G_MAIN_POLL_DEBUG */
42 #ifdef _WIN32
43 /* Always enable debugging printout on Windows, as it is more often
44 * needed there...
46 #define G_MAIN_POLL_DEBUG
47 #endif
49 #ifdef G_OS_UNIX
50 #include "glib-unix.h"
51 #include <pthread.h>
52 #ifdef HAVE_EVENTFD
53 #include <sys/eventfd.h>
54 #endif
55 #endif
57 #include <signal.h>
58 #include <sys/types.h>
59 #include <time.h>
60 #include <stdlib.h>
61 #ifdef HAVE_SYS_TIME_H
62 #include <sys/time.h>
63 #endif /* HAVE_SYS_TIME_H */
64 #ifdef G_OS_UNIX
65 #include <unistd.h>
66 #endif /* G_OS_UNIX */
67 #include <errno.h>
68 #include <string.h>
70 #ifdef G_OS_WIN32
71 #define STRICT
72 #include <windows.h>
73 #endif /* G_OS_WIN32 */
75 #ifdef HAVE_MACH_MACH_TIME_H
76 #include <mach/mach_time.h>
77 #endif
79 #include "glib_trace.h"
81 #include "gmain.h"
83 #include "garray.h"
84 #include "giochannel.h"
85 #include "ghash.h"
86 #include "ghook.h"
87 #include "gqueue.h"
88 #include "gstrfuncs.h"
89 #include "gtestutils.h"
91 #ifdef G_OS_WIN32
92 #include "gwin32.h"
93 #endif
95 #ifdef G_MAIN_POLL_DEBUG
96 #include "gtimer.h"
97 #endif
99 #include "gwakeup.h"
100 #include "gmain-internal.h"
101 #include "glib-init.h"
102 #include "glib-private.h"
105 * SECTION:main
106 * @title: The Main Event Loop
107 * @short_description: manages all available sources of events
109 * The main event loop manages all the available sources of events for
110 * GLib and GTK+ applications. These events can come from any number of
111 * different types of sources such as file descriptors (plain files,
112 * pipes or sockets) and timeouts. New types of event sources can also
113 * be added using g_source_attach().
115 * To allow multiple independent sets of sources to be handled in
116 * different threads, each source is associated with a #GMainContext.
117 * A GMainContext can only be running in a single thread, but
118 * sources can be added to it and removed from it from other threads.
120 * Each event source is assigned a priority. The default priority,
121 * #G_PRIORITY_DEFAULT, is 0. Values less than 0 denote higher priorities.
122 * Values greater than 0 denote lower priorities. Events from high priority
123 * sources are always processed before events from lower priority sources.
125 * Idle functions can also be added, and assigned a priority. These will
126 * be run whenever no events with a higher priority are ready to be processed.
128 * The #GMainLoop data type represents a main event loop. A GMainLoop is
129 * created with g_main_loop_new(). After adding the initial event sources,
130 * g_main_loop_run() is called. This continuously checks for new events from
131 * each of the event sources and dispatches them. Finally, the processing of
132 * an event from one of the sources leads to a call to g_main_loop_quit() to
133 * exit the main loop, and g_main_loop_run() returns.
135 * It is possible to create new instances of #GMainLoop recursively.
136 * This is often used in GTK+ applications when showing modal dialog
137 * boxes. Note that event sources are associated with a particular
138 * #GMainContext, and will be checked and dispatched for all main
139 * loops associated with that GMainContext.
141 * GTK+ contains wrappers of some of these functions, e.g. gtk_main(),
142 * gtk_main_quit() and gtk_events_pending().
144 * ## Creating new source types
146 * One of the unusual features of the #GMainLoop functionality
147 * is that new types of event source can be created and used in
148 * addition to the builtin type of event source. A new event source
149 * type is used for handling GDK events. A new source type is created
150 * by "deriving" from the #GSource structure. The derived type of
151 * source is represented by a structure that has the #GSource structure
152 * as a first element, and other elements specific to the new source
153 * type. To create an instance of the new source type, call
154 * g_source_new() passing in the size of the derived structure and
155 * a table of functions. These #GSourceFuncs determine the behavior of
156 * the new source type.
158 * New source types basically interact with the main context
159 * in two ways. Their prepare function in #GSourceFuncs can set a timeout
160 * to determine the maximum amount of time that the main loop will sleep
161 * before checking the source again. In addition, or as well, the source
162 * can add file descriptors to the set that the main context checks using
163 * g_source_add_poll().
165 * ## Customizing the main loop iteration
167 * Single iterations of a #GMainContext can be run with
168 * g_main_context_iteration(). In some cases, more detailed control
169 * of exactly how the details of the main loop work is desired, for
170 * instance, when integrating the #GMainLoop with an external main loop.
171 * In such cases, you can call the component functions of
172 * g_main_context_iteration() directly. These functions are
173 * g_main_context_prepare(), g_main_context_query(),
174 * g_main_context_check() and g_main_context_dispatch().
176 * ## State of a Main Context # {#mainloop-states}
178 * The operation of these functions can best be seen in terms
179 * of a state diagram, as shown in this image.
181 * ![](mainloop-states.gif)
183 * On UNIX, the GLib mainloop is incompatible with fork(). Any program
184 * using the mainloop must either exec() or exit() from the child
185 * without returning to the mainloop.
187 * ## Memory management of sources # {#mainloop-memory-management}
189 * There are two options for memory management of the user data passed to a
190 * #GSource to be passed to its callback on invocation. This data is provided
191 * in calls to g_timeout_add(), g_timeout_add_full(), g_idle_add(), etc. and
192 * more generally, using g_source_set_callback(). This data is typically an
193 * object which ‘owns’ the timeout or idle callback, such as a widget or a
194 * network protocol implementation. In many cases, it is an error for the
195 * callback to be invoked after this owning object has been destroyed, as that
196 * results in use of freed memory.
198 * The first, and preferred, option is to store the source ID returned by
199 * functions such as g_timeout_add() or g_source_attach(), and explicitly
200 * remove that source from the main context using g_source_remove() when the
201 * owning object is finalized. This ensures that the callback can only be
202 * invoked while the object is still alive.
204 * The second option is to hold a strong reference to the object in the
205 * callback, and to release it in the callback’s #GDestroyNotify. This ensures
206 * that the object is kept alive until after the source is finalized, which is
207 * guaranteed to be after it is invoked for the final time. The #GDestroyNotify
208 * is another callback passed to the ‘full’ variants of #GSource functions (for
209 * example, g_timeout_add_full()). It is called when the source is finalized,
210 * and is designed for releasing references like this.
212 * One important caveat of this second approach is that it will keep the object
213 * alive indefinitely if the main loop is stopped before the #GSource is
214 * invoked, which may be undesirable.
217 /* Types */
219 typedef struct _GTimeoutSource GTimeoutSource;
220 typedef struct _GChildWatchSource GChildWatchSource;
221 typedef struct _GUnixSignalWatchSource GUnixSignalWatchSource;
222 typedef struct _GPollRec GPollRec;
223 typedef struct _GSourceCallback GSourceCallback;
225 typedef enum
227 G_SOURCE_READY = 1 << G_HOOK_FLAG_USER_SHIFT,
228 G_SOURCE_CAN_RECURSE = 1 << (G_HOOK_FLAG_USER_SHIFT + 1),
229 G_SOURCE_BLOCKED = 1 << (G_HOOK_FLAG_USER_SHIFT + 2)
230 } GSourceFlags;
232 typedef struct _GSourceList GSourceList;
234 struct _GSourceList
236 GSource *head, *tail;
237 gint priority;
240 typedef struct _GMainWaiter GMainWaiter;
242 struct _GMainWaiter
244 GCond *cond;
245 GMutex *mutex;
248 typedef struct _GMainDispatch GMainDispatch;
250 struct _GMainDispatch
252 gint depth;
253 GSource *source;
256 #ifdef G_MAIN_POLL_DEBUG
257 gboolean _g_main_poll_debug = FALSE;
258 #endif
260 struct _GMainContext
262 /* The following lock is used for both the list of sources
263 * and the list of poll records
265 GMutex mutex;
266 GCond cond;
267 GThread *owner;
268 guint owner_count;
269 GSList *waiters;
271 volatile gint ref_count;
273 GHashTable *sources; /* guint -> GSource */
275 GPtrArray *pending_dispatches;
276 gint timeout; /* Timeout for current iteration */
278 guint next_id;
279 GList *source_lists;
280 gint in_check_or_prepare;
282 GPollRec *poll_records;
283 guint n_poll_records;
284 GPollFD *cached_poll_array;
285 guint cached_poll_array_size;
287 GWakeup *wakeup;
289 GPollFD wake_up_rec;
291 /* Flag indicating whether the set of fd's changed during a poll */
292 gboolean poll_changed;
294 GPollFunc poll_func;
296 gint64 time;
297 gboolean time_is_fresh;
300 struct _GSourceCallback
302 volatile gint ref_count;
303 GSourceFunc func;
304 gpointer data;
305 GDestroyNotify notify;
308 struct _GMainLoop
310 GMainContext *context;
311 gboolean is_running;
312 volatile gint ref_count;
315 struct _GTimeoutSource
317 GSource source;
318 guint interval;
319 gboolean seconds;
322 struct _GChildWatchSource
324 GSource source;
325 GPid pid;
326 gint child_status;
327 #ifdef G_OS_WIN32
328 GPollFD poll;
329 #else /* G_OS_WIN32 */
330 gboolean child_exited;
331 #endif /* G_OS_WIN32 */
334 struct _GUnixSignalWatchSource
336 GSource source;
337 int signum;
338 gboolean pending;
341 struct _GPollRec
343 GPollFD *fd;
344 GPollRec *prev;
345 GPollRec *next;
346 gint priority;
349 struct _GSourcePrivate
351 GSList *child_sources;
352 GSource *parent_source;
354 gint64 ready_time;
356 /* This is currently only used on UNIX, but we always declare it (and
357 * let it remain empty on Windows) to avoid #ifdef all over the place.
359 GSList *fds;
362 typedef struct _GSourceIter
364 GMainContext *context;
365 gboolean may_modify;
366 GList *current_list;
367 GSource *source;
368 } GSourceIter;
370 #define LOCK_CONTEXT(context) g_mutex_lock (&context->mutex)
371 #define UNLOCK_CONTEXT(context) g_mutex_unlock (&context->mutex)
372 #define G_THREAD_SELF g_thread_self ()
374 #define SOURCE_DESTROYED(source) (((source)->flags & G_HOOK_FLAG_ACTIVE) == 0)
375 #define SOURCE_BLOCKED(source) (((source)->flags & G_SOURCE_BLOCKED) != 0)
377 #define SOURCE_UNREF(source, context) \
378 G_STMT_START { \
379 if ((source)->ref_count > 1) \
380 (source)->ref_count--; \
381 else \
382 g_source_unref_internal ((source), (context), TRUE); \
383 } G_STMT_END
386 /* Forward declarations */
388 static void g_source_unref_internal (GSource *source,
389 GMainContext *context,
390 gboolean have_lock);
391 static void g_source_destroy_internal (GSource *source,
392 GMainContext *context,
393 gboolean have_lock);
394 static void g_source_set_priority_unlocked (GSource *source,
395 GMainContext *context,
396 gint priority);
397 static void g_child_source_remove_internal (GSource *child_source,
398 GMainContext *context);
400 static void g_main_context_poll (GMainContext *context,
401 gint timeout,
402 gint priority,
403 GPollFD *fds,
404 gint n_fds);
405 static void g_main_context_add_poll_unlocked (GMainContext *context,
406 gint priority,
407 GPollFD *fd);
408 static void g_main_context_remove_poll_unlocked (GMainContext *context,
409 GPollFD *fd);
411 static void g_source_iter_init (GSourceIter *iter,
412 GMainContext *context,
413 gboolean may_modify);
414 static gboolean g_source_iter_next (GSourceIter *iter,
415 GSource **source);
416 static void g_source_iter_clear (GSourceIter *iter);
418 static gboolean g_timeout_dispatch (GSource *source,
419 GSourceFunc callback,
420 gpointer user_data);
421 static gboolean g_child_watch_prepare (GSource *source,
422 gint *timeout);
423 static gboolean g_child_watch_check (GSource *source);
424 static gboolean g_child_watch_dispatch (GSource *source,
425 GSourceFunc callback,
426 gpointer user_data);
427 static void g_child_watch_finalize (GSource *source);
428 #ifdef G_OS_UNIX
429 static void g_unix_signal_handler (int signum);
430 static gboolean g_unix_signal_watch_prepare (GSource *source,
431 gint *timeout);
432 static gboolean g_unix_signal_watch_check (GSource *source);
433 static gboolean g_unix_signal_watch_dispatch (GSource *source,
434 GSourceFunc callback,
435 gpointer user_data);
436 static void g_unix_signal_watch_finalize (GSource *source);
437 #endif
438 static gboolean g_idle_prepare (GSource *source,
439 gint *timeout);
440 static gboolean g_idle_check (GSource *source);
441 static gboolean g_idle_dispatch (GSource *source,
442 GSourceFunc callback,
443 gpointer user_data);
445 static void block_source (GSource *source);
447 static GMainContext *glib_worker_context;
449 G_LOCK_DEFINE_STATIC (main_loop);
450 static GMainContext *default_main_context;
452 #ifndef G_OS_WIN32
455 /* UNIX signals work by marking one of these variables then waking the
456 * worker context to check on them and dispatch accordingly.
458 #ifdef HAVE_SIG_ATOMIC_T
459 static volatile sig_atomic_t unix_signal_pending[NSIG];
460 static volatile sig_atomic_t any_unix_signal_pending;
461 #else
462 static volatile int unix_signal_pending[NSIG];
463 static volatile int any_unix_signal_pending;
464 #endif
465 static volatile guint unix_signal_refcount[NSIG];
467 /* Guards all the data below */
468 G_LOCK_DEFINE_STATIC (unix_signal_lock);
469 static GSList *unix_signal_watches;
470 static GSList *unix_child_watches;
472 GSourceFuncs g_unix_signal_funcs =
474 g_unix_signal_watch_prepare,
475 g_unix_signal_watch_check,
476 g_unix_signal_watch_dispatch,
477 g_unix_signal_watch_finalize
479 #endif /* !G_OS_WIN32 */
480 G_LOCK_DEFINE_STATIC (main_context_list);
481 static GSList *main_context_list = NULL;
483 GSourceFuncs g_timeout_funcs =
485 NULL, /* prepare */
486 NULL, /* check */
487 g_timeout_dispatch,
488 NULL
491 GSourceFuncs g_child_watch_funcs =
493 g_child_watch_prepare,
494 g_child_watch_check,
495 g_child_watch_dispatch,
496 g_child_watch_finalize
499 GSourceFuncs g_idle_funcs =
501 g_idle_prepare,
502 g_idle_check,
503 g_idle_dispatch,
504 NULL
508 * g_main_context_ref:
509 * @context: a #GMainContext
511 * Increases the reference count on a #GMainContext object by one.
513 * Returns: the @context that was passed in (since 2.6)
515 GMainContext *
516 g_main_context_ref (GMainContext *context)
518 g_return_val_if_fail (context != NULL, NULL);
519 g_return_val_if_fail (g_atomic_int_get (&context->ref_count) > 0, NULL);
521 g_atomic_int_inc (&context->ref_count);
523 return context;
526 static inline void
527 poll_rec_list_free (GMainContext *context,
528 GPollRec *list)
530 g_slice_free_chain (GPollRec, list, next);
534 * g_main_context_unref:
535 * @context: a #GMainContext
537 * Decreases the reference count on a #GMainContext object by one. If
538 * the result is zero, free the context and free all associated memory.
540 void
541 g_main_context_unref (GMainContext *context)
543 GSourceIter iter;
544 GSource *source;
545 GList *sl_iter;
546 GSourceList *list;
547 guint i;
549 g_return_if_fail (context != NULL);
550 g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
552 if (!g_atomic_int_dec_and_test (&context->ref_count))
553 return;
555 G_LOCK (main_context_list);
556 main_context_list = g_slist_remove (main_context_list, context);
557 G_UNLOCK (main_context_list);
559 /* Free pending dispatches */
560 for (i = 0; i < context->pending_dispatches->len; i++)
561 g_source_unref_internal (context->pending_dispatches->pdata[i], context, FALSE);
563 /* g_source_iter_next() assumes the context is locked. */
564 LOCK_CONTEXT (context);
565 g_source_iter_init (&iter, context, TRUE);
566 while (g_source_iter_next (&iter, &source))
568 source->context = NULL;
569 g_source_destroy_internal (source, context, TRUE);
571 UNLOCK_CONTEXT (context);
573 for (sl_iter = context->source_lists; sl_iter; sl_iter = sl_iter->next)
575 list = sl_iter->data;
576 g_slice_free (GSourceList, list);
578 g_list_free (context->source_lists);
580 g_hash_table_destroy (context->sources);
582 g_mutex_clear (&context->mutex);
584 g_ptr_array_free (context->pending_dispatches, TRUE);
585 g_free (context->cached_poll_array);
587 poll_rec_list_free (context, context->poll_records);
589 g_wakeup_free (context->wakeup);
590 g_cond_clear (&context->cond);
592 g_free (context);
595 /* Helper function used by mainloop/overflow test.
597 GMainContext *
598 g_main_context_new_with_next_id (guint next_id)
600 GMainContext *ret = g_main_context_new ();
602 ret->next_id = next_id;
604 return ret;
608 * g_main_context_new:
610 * Creates a new #GMainContext structure.
612 * Returns: the new #GMainContext
614 GMainContext *
615 g_main_context_new (void)
617 static gsize initialised;
618 GMainContext *context;
620 if (g_once_init_enter (&initialised))
622 #ifdef G_MAIN_POLL_DEBUG
623 if (getenv ("G_MAIN_POLL_DEBUG") != NULL)
624 _g_main_poll_debug = TRUE;
625 #endif
627 g_once_init_leave (&initialised, TRUE);
630 context = g_new0 (GMainContext, 1);
632 TRACE (GLIB_MAIN_CONTEXT_NEW (context));
634 g_mutex_init (&context->mutex);
635 g_cond_init (&context->cond);
637 context->sources = g_hash_table_new (NULL, NULL);
638 context->owner = NULL;
639 context->waiters = NULL;
641 context->ref_count = 1;
643 context->next_id = 1;
645 context->source_lists = NULL;
647 context->poll_func = g_poll;
649 context->cached_poll_array = NULL;
650 context->cached_poll_array_size = 0;
652 context->pending_dispatches = g_ptr_array_new ();
654 context->time_is_fresh = FALSE;
656 context->wakeup = g_wakeup_new ();
657 g_wakeup_get_pollfd (context->wakeup, &context->wake_up_rec);
658 g_main_context_add_poll_unlocked (context, 0, &context->wake_up_rec);
660 G_LOCK (main_context_list);
661 main_context_list = g_slist_append (main_context_list, context);
663 #ifdef G_MAIN_POLL_DEBUG
664 if (_g_main_poll_debug)
665 g_print ("created context=%p\n", context);
666 #endif
668 G_UNLOCK (main_context_list);
670 return context;
674 * g_main_context_default:
676 * Returns the global default main context. This is the main context
677 * used for main loop functions when a main loop is not explicitly
678 * specified, and corresponds to the "main" main loop. See also
679 * g_main_context_get_thread_default().
681 * Returns: (transfer none): the global default main context.
683 GMainContext *
684 g_main_context_default (void)
686 /* Slow, but safe */
688 G_LOCK (main_loop);
690 if (!default_main_context)
692 default_main_context = g_main_context_new ();
694 TRACE (GLIB_MAIN_CONTEXT_DEFAULT (default_main_context));
696 #ifdef G_MAIN_POLL_DEBUG
697 if (_g_main_poll_debug)
698 g_print ("default context=%p\n", default_main_context);
699 #endif
702 G_UNLOCK (main_loop);
704 return default_main_context;
707 static void
708 free_context (gpointer data)
710 GMainContext *context = data;
712 TRACE (GLIB_MAIN_CONTEXT_FREE (context));
714 g_main_context_release (context);
715 if (context)
716 g_main_context_unref (context);
719 static void
720 free_context_stack (gpointer data)
722 g_queue_free_full((GQueue *) data, (GDestroyNotify) free_context);
725 static GPrivate thread_context_stack = G_PRIVATE_INIT (free_context_stack);
728 * g_main_context_push_thread_default:
729 * @context: (nullable): a #GMainContext, or %NULL for the global default context
731 * Acquires @context and sets it as the thread-default context for the
732 * current thread. This will cause certain asynchronous operations
733 * (such as most [gio][gio]-based I/O) which are
734 * started in this thread to run under @context and deliver their
735 * results to its main loop, rather than running under the global
736 * default context in the main thread. Note that calling this function
737 * changes the context returned by g_main_context_get_thread_default(),
738 * not the one returned by g_main_context_default(), so it does not affect
739 * the context used by functions like g_idle_add().
741 * Normally you would call this function shortly after creating a new
742 * thread, passing it a #GMainContext which will be run by a
743 * #GMainLoop in that thread, to set a new default context for all
744 * async operations in that thread. In this case you may not need to
745 * ever call g_main_context_pop_thread_default(), assuming you want the
746 * new #GMainContext to be the default for the whole lifecycle of the
747 * thread.
749 * If you don't have control over how the new thread was created (e.g.
750 * in the new thread isn't newly created, or if the thread life
751 * cycle is managed by a #GThreadPool), it is always suggested to wrap
752 * the logic that needs to use the new #GMainContext inside a
753 * g_main_context_push_thread_default() / g_main_context_pop_thread_default()
754 * pair, otherwise threads that are re-used will end up never explicitly
755 * releasing the #GMainContext reference they hold.
757 * In some cases you may want to schedule a single operation in a
758 * non-default context, or temporarily use a non-default context in
759 * the main thread. In that case, you can wrap the call to the
760 * asynchronous operation inside a
761 * g_main_context_push_thread_default() /
762 * g_main_context_pop_thread_default() pair, but it is up to you to
763 * ensure that no other asynchronous operations accidentally get
764 * started while the non-default context is active.
766 * Beware that libraries that predate this function may not correctly
767 * handle being used from a thread with a thread-default context. Eg,
768 * see g_file_supports_thread_contexts().
770 * Since: 2.22
772 void
773 g_main_context_push_thread_default (GMainContext *context)
775 GQueue *stack;
776 gboolean acquired_context;
778 acquired_context = g_main_context_acquire (context);
779 g_return_if_fail (acquired_context);
781 if (context == g_main_context_default ())
782 context = NULL;
783 else if (context)
784 g_main_context_ref (context);
786 stack = g_private_get (&thread_context_stack);
787 if (!stack)
789 stack = g_queue_new ();
790 g_private_set (&thread_context_stack, stack);
793 g_queue_push_head (stack, context);
795 TRACE (GLIB_MAIN_CONTEXT_PUSH_THREAD_DEFAULT (context));
799 * g_main_context_pop_thread_default:
800 * @context: (nullable): a #GMainContext object, or %NULL
802 * Pops @context off the thread-default context stack (verifying that
803 * it was on the top of the stack).
805 * Since: 2.22
807 void
808 g_main_context_pop_thread_default (GMainContext *context)
810 GQueue *stack;
812 if (context == g_main_context_default ())
813 context = NULL;
815 stack = g_private_get (&thread_context_stack);
817 g_return_if_fail (stack != NULL);
818 g_return_if_fail (g_queue_peek_head (stack) == context);
820 TRACE (GLIB_MAIN_CONTEXT_POP_THREAD_DEFAULT (context));
822 g_queue_pop_head (stack);
824 g_main_context_release (context);
825 if (context)
826 g_main_context_unref (context);
830 * g_main_context_get_thread_default:
832 * Gets the thread-default #GMainContext for this thread. Asynchronous
833 * operations that want to be able to be run in contexts other than
834 * the default one should call this method or
835 * g_main_context_ref_thread_default() to get a #GMainContext to add
836 * their #GSources to. (Note that even in single-threaded
837 * programs applications may sometimes want to temporarily push a
838 * non-default context, so it is not safe to assume that this will
839 * always return %NULL if you are running in the default thread.)
841 * If you need to hold a reference on the context, use
842 * g_main_context_ref_thread_default() instead.
844 * Returns: (transfer none): the thread-default #GMainContext, or
845 * %NULL if the thread-default context is the global default context.
847 * Since: 2.22
849 GMainContext *
850 g_main_context_get_thread_default (void)
852 GQueue *stack;
854 stack = g_private_get (&thread_context_stack);
855 if (stack)
856 return g_queue_peek_head (stack);
857 else
858 return NULL;
862 * g_main_context_ref_thread_default:
864 * Gets the thread-default #GMainContext for this thread, as with
865 * g_main_context_get_thread_default(), but also adds a reference to
866 * it with g_main_context_ref(). In addition, unlike
867 * g_main_context_get_thread_default(), if the thread-default context
868 * is the global default context, this will return that #GMainContext
869 * (with a ref added to it) rather than returning %NULL.
871 * Returns: (transfer full): the thread-default #GMainContext. Unref
872 * with g_main_context_unref() when you are done with it.
874 * Since: 2.32
876 GMainContext *
877 g_main_context_ref_thread_default (void)
879 GMainContext *context;
881 context = g_main_context_get_thread_default ();
882 if (!context)
883 context = g_main_context_default ();
884 return g_main_context_ref (context);
887 /* Hooks for adding to the main loop */
890 * g_source_new:
891 * @source_funcs: structure containing functions that implement
892 * the sources behavior.
893 * @struct_size: size of the #GSource structure to create.
895 * Creates a new #GSource structure. The size is specified to
896 * allow creating structures derived from #GSource that contain
897 * additional data. The size passed in must be at least
898 * `sizeof (GSource)`.
900 * The source will not initially be associated with any #GMainContext
901 * and must be added to one with g_source_attach() before it will be
902 * executed.
904 * Returns: the newly-created #GSource.
906 GSource *
907 g_source_new (GSourceFuncs *source_funcs,
908 guint struct_size)
910 GSource *source;
912 g_return_val_if_fail (source_funcs != NULL, NULL);
913 g_return_val_if_fail (struct_size >= sizeof (GSource), NULL);
915 source = (GSource*) g_malloc0 (struct_size);
916 source->priv = g_slice_new0 (GSourcePrivate);
917 source->source_funcs = source_funcs;
918 source->ref_count = 1;
920 source->priority = G_PRIORITY_DEFAULT;
922 source->flags = G_HOOK_FLAG_ACTIVE;
924 source->priv->ready_time = -1;
926 /* NULL/0 initialization for all other fields */
928 TRACE (GLIB_SOURCE_NEW (source, source_funcs->prepare, source_funcs->check,
929 source_funcs->dispatch, source_funcs->finalize,
930 struct_size));
932 return source;
935 /* Holds context's lock */
936 static void
937 g_source_iter_init (GSourceIter *iter,
938 GMainContext *context,
939 gboolean may_modify)
941 iter->context = context;
942 iter->current_list = NULL;
943 iter->source = NULL;
944 iter->may_modify = may_modify;
947 /* Holds context's lock */
948 static gboolean
949 g_source_iter_next (GSourceIter *iter, GSource **source)
951 GSource *next_source;
953 if (iter->source)
954 next_source = iter->source->next;
955 else
956 next_source = NULL;
958 if (!next_source)
960 if (iter->current_list)
961 iter->current_list = iter->current_list->next;
962 else
963 iter->current_list = iter->context->source_lists;
965 if (iter->current_list)
967 GSourceList *source_list = iter->current_list->data;
969 next_source = source_list->head;
973 /* Note: unreffing iter->source could potentially cause its
974 * GSourceList to be removed from source_lists (if iter->source is
975 * the only source in its list, and it is destroyed), so we have to
976 * keep it reffed until after we advance iter->current_list, above.
979 if (iter->source && iter->may_modify)
980 SOURCE_UNREF (iter->source, iter->context);
981 iter->source = next_source;
982 if (iter->source && iter->may_modify)
983 iter->source->ref_count++;
985 *source = iter->source;
986 return *source != NULL;
989 /* Holds context's lock. Only necessary to call if you broke out of
990 * the g_source_iter_next() loop early.
992 static void
993 g_source_iter_clear (GSourceIter *iter)
995 if (iter->source && iter->may_modify)
997 SOURCE_UNREF (iter->source, iter->context);
998 iter->source = NULL;
1002 /* Holds context's lock
1004 static GSourceList *
1005 find_source_list_for_priority (GMainContext *context,
1006 gint priority,
1007 gboolean create)
1009 GList *iter, *last;
1010 GSourceList *source_list;
1012 last = NULL;
1013 for (iter = context->source_lists; iter != NULL; last = iter, iter = iter->next)
1015 source_list = iter->data;
1017 if (source_list->priority == priority)
1018 return source_list;
1020 if (source_list->priority > priority)
1022 if (!create)
1023 return NULL;
1025 source_list = g_slice_new0 (GSourceList);
1026 source_list->priority = priority;
1027 context->source_lists = g_list_insert_before (context->source_lists,
1028 iter,
1029 source_list);
1030 return source_list;
1034 if (!create)
1035 return NULL;
1037 source_list = g_slice_new0 (GSourceList);
1038 source_list->priority = priority;
1040 if (!last)
1041 context->source_lists = g_list_append (NULL, source_list);
1042 else
1044 /* This just appends source_list to the end of
1045 * context->source_lists without having to walk the list again.
1047 last = g_list_append (last, source_list);
1049 return source_list;
1052 /* Holds context's lock
1054 static void
1055 source_add_to_context (GSource *source,
1056 GMainContext *context)
1058 GSourceList *source_list;
1059 GSource *prev, *next;
1061 source_list = find_source_list_for_priority (context, source->priority, TRUE);
1063 if (source->priv->parent_source)
1065 g_assert (source_list->head != NULL);
1067 /* Put the source immediately before its parent */
1068 prev = source->priv->parent_source->prev;
1069 next = source->priv->parent_source;
1071 else
1073 prev = source_list->tail;
1074 next = NULL;
1077 source->next = next;
1078 if (next)
1079 next->prev = source;
1080 else
1081 source_list->tail = source;
1083 source->prev = prev;
1084 if (prev)
1085 prev->next = source;
1086 else
1087 source_list->head = source;
1090 /* Holds context's lock
1092 static void
1093 source_remove_from_context (GSource *source,
1094 GMainContext *context)
1096 GSourceList *source_list;
1098 source_list = find_source_list_for_priority (context, source->priority, FALSE);
1099 g_return_if_fail (source_list != NULL);
1101 if (source->prev)
1102 source->prev->next = source->next;
1103 else
1104 source_list->head = source->next;
1106 if (source->next)
1107 source->next->prev = source->prev;
1108 else
1109 source_list->tail = source->prev;
1111 source->prev = NULL;
1112 source->next = NULL;
1114 if (source_list->head == NULL)
1116 context->source_lists = g_list_remove (context->source_lists, source_list);
1117 g_slice_free (GSourceList, source_list);
1121 /* See https://bugzilla.gnome.org/show_bug.cgi?id=761102 for
1122 * the introduction of this.
1124 * The main optimization is to avoid waking up the main
1125 * context if a change is made by the current owner.
1127 static void
1128 conditional_wakeup (GMainContext *context)
1130 /* We want to signal wakeups in two cases:
1131 * 1 When the context is owned by another thread
1132 * 2 When the context owner is NULL (two subcases)
1133 * 2a Possible if the context has never been acquired
1134 * 2b Or if the context has no current owner
1136 * At least case 2a) is necessary to ensure backwards compatibility with
1137 * qemu's use of GMainContext.
1138 * https://bugzilla.gnome.org/show_bug.cgi?id=761102#c14
1140 if (context->owner != G_THREAD_SELF)
1141 g_wakeup_signal (context->wakeup);
1144 static guint
1145 g_source_attach_unlocked (GSource *source,
1146 GMainContext *context,
1147 gboolean do_wakeup)
1149 GSList *tmp_list;
1150 guint id;
1152 /* The counter may have wrapped, so we must ensure that we do not
1153 * reuse the source id of an existing source.
1156 id = context->next_id++;
1157 while (id == 0 || g_hash_table_contains (context->sources, GUINT_TO_POINTER (id)));
1159 source->context = context;
1160 source->source_id = id;
1161 source->ref_count++;
1163 g_hash_table_insert (context->sources, GUINT_TO_POINTER (id), source);
1165 source_add_to_context (source, context);
1167 if (!SOURCE_BLOCKED (source))
1169 tmp_list = source->poll_fds;
1170 while (tmp_list)
1172 g_main_context_add_poll_unlocked (context, source->priority, tmp_list->data);
1173 tmp_list = tmp_list->next;
1176 for (tmp_list = source->priv->fds; tmp_list; tmp_list = tmp_list->next)
1177 g_main_context_add_poll_unlocked (context, source->priority, tmp_list->data);
1180 tmp_list = source->priv->child_sources;
1181 while (tmp_list)
1183 g_source_attach_unlocked (tmp_list->data, context, FALSE);
1184 tmp_list = tmp_list->next;
1187 /* If another thread has acquired the context, wake it up since it
1188 * might be in poll() right now.
1190 if (do_wakeup)
1191 conditional_wakeup (context);
1193 return source->source_id;
1197 * g_source_attach:
1198 * @source: a #GSource
1199 * @context: (nullable): a #GMainContext (if %NULL, the default context will be used)
1201 * Adds a #GSource to a @context so that it will be executed within
1202 * that context. Remove it by calling g_source_destroy().
1204 * Returns: the ID (greater than 0) for the source within the
1205 * #GMainContext.
1207 guint
1208 g_source_attach (GSource *source,
1209 GMainContext *context)
1211 guint result = 0;
1213 g_return_val_if_fail (source->context == NULL, 0);
1214 g_return_val_if_fail (!SOURCE_DESTROYED (source), 0);
1216 if (!context)
1217 context = g_main_context_default ();
1219 LOCK_CONTEXT (context);
1221 result = g_source_attach_unlocked (source, context, TRUE);
1223 TRACE (GLIB_MAIN_SOURCE_ATTACH (g_source_get_name (source), source, context,
1224 result));
1226 UNLOCK_CONTEXT (context);
1228 return result;
1231 static void
1232 g_source_destroy_internal (GSource *source,
1233 GMainContext *context,
1234 gboolean have_lock)
1236 TRACE (GLIB_MAIN_SOURCE_DESTROY (g_source_get_name (source), source,
1237 context));
1239 if (!have_lock)
1240 LOCK_CONTEXT (context);
1242 if (!SOURCE_DESTROYED (source))
1244 GSList *tmp_list;
1245 gpointer old_cb_data;
1246 GSourceCallbackFuncs *old_cb_funcs;
1248 source->flags &= ~G_HOOK_FLAG_ACTIVE;
1250 old_cb_data = source->callback_data;
1251 old_cb_funcs = source->callback_funcs;
1253 source->callback_data = NULL;
1254 source->callback_funcs = NULL;
1256 if (old_cb_funcs)
1258 UNLOCK_CONTEXT (context);
1259 old_cb_funcs->unref (old_cb_data);
1260 LOCK_CONTEXT (context);
1263 if (!SOURCE_BLOCKED (source))
1265 tmp_list = source->poll_fds;
1266 while (tmp_list)
1268 g_main_context_remove_poll_unlocked (context, tmp_list->data);
1269 tmp_list = tmp_list->next;
1272 for (tmp_list = source->priv->fds; tmp_list; tmp_list = tmp_list->next)
1273 g_main_context_remove_poll_unlocked (context, tmp_list->data);
1276 while (source->priv->child_sources)
1277 g_child_source_remove_internal (source->priv->child_sources->data, context);
1279 if (source->priv->parent_source)
1280 g_child_source_remove_internal (source, context);
1282 g_source_unref_internal (source, context, TRUE);
1285 if (!have_lock)
1286 UNLOCK_CONTEXT (context);
1290 * g_source_destroy:
1291 * @source: a #GSource
1293 * Removes a source from its #GMainContext, if any, and mark it as
1294 * destroyed. The source cannot be subsequently added to another
1295 * context. It is safe to call this on sources which have already been
1296 * removed from their context.
1298 void
1299 g_source_destroy (GSource *source)
1301 GMainContext *context;
1303 g_return_if_fail (source != NULL);
1305 context = source->context;
1307 if (context)
1308 g_source_destroy_internal (source, context, FALSE);
1309 else
1310 source->flags &= ~G_HOOK_FLAG_ACTIVE;
1314 * g_source_get_id:
1315 * @source: a #GSource
1317 * Returns the numeric ID for a particular source. The ID of a source
1318 * is a positive integer which is unique within a particular main loop
1319 * context. The reverse
1320 * mapping from ID to source is done by g_main_context_find_source_by_id().
1322 * Returns: the ID (greater than 0) for the source
1324 guint
1325 g_source_get_id (GSource *source)
1327 guint result;
1329 g_return_val_if_fail (source != NULL, 0);
1330 g_return_val_if_fail (source->context != NULL, 0);
1332 LOCK_CONTEXT (source->context);
1333 result = source->source_id;
1334 UNLOCK_CONTEXT (source->context);
1336 return result;
1340 * g_source_get_context:
1341 * @source: a #GSource
1343 * Gets the #GMainContext with which the source is associated.
1345 * You can call this on a source that has been destroyed, provided
1346 * that the #GMainContext it was attached to still exists (in which
1347 * case it will return that #GMainContext). In particular, you can
1348 * always call this function on the source returned from
1349 * g_main_current_source(). But calling this function on a source
1350 * whose #GMainContext has been destroyed is an error.
1352 * Returns: (transfer none) (nullable): the #GMainContext with which the
1353 * source is associated, or %NULL if the context has not
1354 * yet been added to a source.
1356 GMainContext *
1357 g_source_get_context (GSource *source)
1359 g_return_val_if_fail (source->context != NULL || !SOURCE_DESTROYED (source), NULL);
1361 return source->context;
1365 * g_source_add_poll:
1366 * @source:a #GSource
1367 * @fd: a #GPollFD structure holding information about a file
1368 * descriptor to watch.
1370 * Adds a file descriptor to the set of file descriptors polled for
1371 * this source. This is usually combined with g_source_new() to add an
1372 * event source. The event source's check function will typically test
1373 * the @revents field in the #GPollFD struct and return %TRUE if events need
1374 * to be processed.
1376 * This API is only intended to be used by implementations of #GSource.
1377 * Do not call this API on a #GSource that you did not create.
1379 * Using this API forces the linear scanning of event sources on each
1380 * main loop iteration. Newly-written event sources should try to use
1381 * g_source_add_unix_fd() instead of this API.
1383 void
1384 g_source_add_poll (GSource *source,
1385 GPollFD *fd)
1387 GMainContext *context;
1389 g_return_if_fail (source != NULL);
1390 g_return_if_fail (fd != NULL);
1391 g_return_if_fail (!SOURCE_DESTROYED (source));
1393 context = source->context;
1395 if (context)
1396 LOCK_CONTEXT (context);
1398 source->poll_fds = g_slist_prepend (source->poll_fds, fd);
1400 if (context)
1402 if (!SOURCE_BLOCKED (source))
1403 g_main_context_add_poll_unlocked (context, source->priority, fd);
1404 UNLOCK_CONTEXT (context);
1409 * g_source_remove_poll:
1410 * @source:a #GSource
1411 * @fd: a #GPollFD structure previously passed to g_source_add_poll().
1413 * Removes a file descriptor from the set of file descriptors polled for
1414 * this source.
1416 * This API is only intended to be used by implementations of #GSource.
1417 * Do not call this API on a #GSource that you did not create.
1419 void
1420 g_source_remove_poll (GSource *source,
1421 GPollFD *fd)
1423 GMainContext *context;
1425 g_return_if_fail (source != NULL);
1426 g_return_if_fail (fd != NULL);
1427 g_return_if_fail (!SOURCE_DESTROYED (source));
1429 context = source->context;
1431 if (context)
1432 LOCK_CONTEXT (context);
1434 source->poll_fds = g_slist_remove (source->poll_fds, fd);
1436 if (context)
1438 if (!SOURCE_BLOCKED (source))
1439 g_main_context_remove_poll_unlocked (context, fd);
1440 UNLOCK_CONTEXT (context);
1445 * g_source_add_child_source:
1446 * @source:a #GSource
1447 * @child_source: a second #GSource that @source should "poll"
1449 * Adds @child_source to @source as a "polled" source; when @source is
1450 * added to a #GMainContext, @child_source will be automatically added
1451 * with the same priority, when @child_source is triggered, it will
1452 * cause @source to dispatch (in addition to calling its own
1453 * callback), and when @source is destroyed, it will destroy
1454 * @child_source as well. (@source will also still be dispatched if
1455 * its own prepare/check functions indicate that it is ready.)
1457 * If you don't need @child_source to do anything on its own when it
1458 * triggers, you can call g_source_set_dummy_callback() on it to set a
1459 * callback that does nothing (except return %TRUE if appropriate).
1461 * @source will hold a reference on @child_source while @child_source
1462 * is attached to it.
1464 * This API is only intended to be used by implementations of #GSource.
1465 * Do not call this API on a #GSource that you did not create.
1467 * Since: 2.28
1469 void
1470 g_source_add_child_source (GSource *source,
1471 GSource *child_source)
1473 GMainContext *context;
1475 g_return_if_fail (source != NULL);
1476 g_return_if_fail (child_source != NULL);
1477 g_return_if_fail (!SOURCE_DESTROYED (source));
1478 g_return_if_fail (!SOURCE_DESTROYED (child_source));
1479 g_return_if_fail (child_source->context == NULL);
1480 g_return_if_fail (child_source->priv->parent_source == NULL);
1482 context = source->context;
1484 if (context)
1485 LOCK_CONTEXT (context);
1487 TRACE (GLIB_SOURCE_ADD_CHILD_SOURCE (source, child_source));
1489 source->priv->child_sources = g_slist_prepend (source->priv->child_sources,
1490 g_source_ref (child_source));
1491 child_source->priv->parent_source = source;
1492 g_source_set_priority_unlocked (child_source, NULL, source->priority);
1493 if (SOURCE_BLOCKED (source))
1494 block_source (child_source);
1496 if (context)
1498 g_source_attach_unlocked (child_source, context, TRUE);
1499 UNLOCK_CONTEXT (context);
1503 static void
1504 g_child_source_remove_internal (GSource *child_source,
1505 GMainContext *context)
1507 GSource *parent_source = child_source->priv->parent_source;
1509 parent_source->priv->child_sources =
1510 g_slist_remove (parent_source->priv->child_sources, child_source);
1511 child_source->priv->parent_source = NULL;
1513 g_source_destroy_internal (child_source, context, TRUE);
1514 g_source_unref_internal (child_source, context, TRUE);
1518 * g_source_remove_child_source:
1519 * @source:a #GSource
1520 * @child_source: a #GSource previously passed to
1521 * g_source_add_child_source().
1523 * Detaches @child_source from @source and destroys it.
1525 * This API is only intended to be used by implementations of #GSource.
1526 * Do not call this API on a #GSource that you did not create.
1528 * Since: 2.28
1530 void
1531 g_source_remove_child_source (GSource *source,
1532 GSource *child_source)
1534 GMainContext *context;
1536 g_return_if_fail (source != NULL);
1537 g_return_if_fail (child_source != NULL);
1538 g_return_if_fail (child_source->priv->parent_source == source);
1539 g_return_if_fail (!SOURCE_DESTROYED (source));
1540 g_return_if_fail (!SOURCE_DESTROYED (child_source));
1542 context = source->context;
1544 if (context)
1545 LOCK_CONTEXT (context);
1547 g_child_source_remove_internal (child_source, context);
1549 if (context)
1550 UNLOCK_CONTEXT (context);
1553 static void
1554 g_source_callback_ref (gpointer cb_data)
1556 GSourceCallback *callback = cb_data;
1558 g_atomic_int_inc (&callback->ref_count);
1561 static void
1562 g_source_callback_unref (gpointer cb_data)
1564 GSourceCallback *callback = cb_data;
1566 if (g_atomic_int_dec_and_test (&callback->ref_count))
1568 if (callback->notify)
1569 callback->notify (callback->data);
1570 g_free (callback);
1574 static void
1575 g_source_callback_get (gpointer cb_data,
1576 GSource *source,
1577 GSourceFunc *func,
1578 gpointer *data)
1580 GSourceCallback *callback = cb_data;
1582 *func = callback->func;
1583 *data = callback->data;
1586 static GSourceCallbackFuncs g_source_callback_funcs = {
1587 g_source_callback_ref,
1588 g_source_callback_unref,
1589 g_source_callback_get,
1593 * g_source_set_callback_indirect:
1594 * @source: the source
1595 * @callback_data: pointer to callback data "object"
1596 * @callback_funcs: functions for reference counting @callback_data
1597 * and getting the callback and data
1599 * Sets the callback function storing the data as a refcounted callback
1600 * "object". This is used internally. Note that calling
1601 * g_source_set_callback_indirect() assumes
1602 * an initial reference count on @callback_data, and thus
1603 * @callback_funcs->unref will eventually be called once more
1604 * than @callback_funcs->ref.
1606 void
1607 g_source_set_callback_indirect (GSource *source,
1608 gpointer callback_data,
1609 GSourceCallbackFuncs *callback_funcs)
1611 GMainContext *context;
1612 gpointer old_cb_data;
1613 GSourceCallbackFuncs *old_cb_funcs;
1615 g_return_if_fail (source != NULL);
1616 g_return_if_fail (callback_funcs != NULL || callback_data == NULL);
1618 context = source->context;
1620 if (context)
1621 LOCK_CONTEXT (context);
1623 if (callback_funcs != &g_source_callback_funcs)
1624 TRACE (GLIB_SOURCE_SET_CALLBACK_INDIRECT (source, callback_data,
1625 callback_funcs->ref,
1626 callback_funcs->unref,
1627 callback_funcs->get));
1629 old_cb_data = source->callback_data;
1630 old_cb_funcs = source->callback_funcs;
1632 source->callback_data = callback_data;
1633 source->callback_funcs = callback_funcs;
1635 if (context)
1636 UNLOCK_CONTEXT (context);
1638 if (old_cb_funcs)
1639 old_cb_funcs->unref (old_cb_data);
1643 * g_source_set_callback:
1644 * @source: the source
1645 * @func: a callback function
1646 * @data: the data to pass to callback function
1647 * @notify: (nullable): a function to call when @data is no longer in use, or %NULL.
1649 * Sets the callback function for a source. The callback for a source is
1650 * called from the source's dispatch function.
1652 * The exact type of @func depends on the type of source; ie. you
1653 * should not count on @func being called with @data as its first
1654 * parameter.
1656 * See [memory management of sources][mainloop-memory-management] for details
1657 * on how to handle memory management of @data.
1659 * Typically, you won't use this function. Instead use functions specific
1660 * to the type of source you are using.
1662 void
1663 g_source_set_callback (GSource *source,
1664 GSourceFunc func,
1665 gpointer data,
1666 GDestroyNotify notify)
1668 GSourceCallback *new_callback;
1670 g_return_if_fail (source != NULL);
1672 TRACE (GLIB_SOURCE_SET_CALLBACK (source, func, data, notify));
1674 new_callback = g_new (GSourceCallback, 1);
1676 new_callback->ref_count = 1;
1677 new_callback->func = func;
1678 new_callback->data = data;
1679 new_callback->notify = notify;
1681 g_source_set_callback_indirect (source, new_callback, &g_source_callback_funcs);
1686 * g_source_set_funcs:
1687 * @source: a #GSource
1688 * @funcs: the new #GSourceFuncs
1690 * Sets the source functions (can be used to override
1691 * default implementations) of an unattached source.
1693 * Since: 2.12
1695 void
1696 g_source_set_funcs (GSource *source,
1697 GSourceFuncs *funcs)
1699 g_return_if_fail (source != NULL);
1700 g_return_if_fail (source->context == NULL);
1701 g_return_if_fail (source->ref_count > 0);
1702 g_return_if_fail (funcs != NULL);
1704 source->source_funcs = funcs;
1707 static void
1708 g_source_set_priority_unlocked (GSource *source,
1709 GMainContext *context,
1710 gint priority)
1712 GSList *tmp_list;
1714 g_return_if_fail (source->priv->parent_source == NULL ||
1715 source->priv->parent_source->priority == priority);
1717 TRACE (GLIB_SOURCE_SET_PRIORITY (source, context, priority));
1719 if (context)
1721 /* Remove the source from the context's source and then
1722 * add it back after so it is sorted in the correct place
1724 source_remove_from_context (source, source->context);
1727 source->priority = priority;
1729 if (context)
1731 source_add_to_context (source, source->context);
1733 if (!SOURCE_BLOCKED (source))
1735 tmp_list = source->poll_fds;
1736 while (tmp_list)
1738 g_main_context_remove_poll_unlocked (context, tmp_list->data);
1739 g_main_context_add_poll_unlocked (context, priority, tmp_list->data);
1741 tmp_list = tmp_list->next;
1744 for (tmp_list = source->priv->fds; tmp_list; tmp_list = tmp_list->next)
1746 g_main_context_remove_poll_unlocked (context, tmp_list->data);
1747 g_main_context_add_poll_unlocked (context, priority, tmp_list->data);
1752 if (source->priv->child_sources)
1754 tmp_list = source->priv->child_sources;
1755 while (tmp_list)
1757 g_source_set_priority_unlocked (tmp_list->data, context, priority);
1758 tmp_list = tmp_list->next;
1764 * g_source_set_priority:
1765 * @source: a #GSource
1766 * @priority: the new priority.
1768 * Sets the priority of a source. While the main loop is being run, a
1769 * source will be dispatched if it is ready to be dispatched and no
1770 * sources at a higher (numerically smaller) priority are ready to be
1771 * dispatched.
1773 * A child source always has the same priority as its parent. It is not
1774 * permitted to change the priority of a source once it has been added
1775 * as a child of another source.
1777 void
1778 g_source_set_priority (GSource *source,
1779 gint priority)
1781 GMainContext *context;
1783 g_return_if_fail (source != NULL);
1784 g_return_if_fail (source->priv->parent_source == NULL);
1786 context = source->context;
1788 if (context)
1789 LOCK_CONTEXT (context);
1790 g_source_set_priority_unlocked (source, context, priority);
1791 if (context)
1792 UNLOCK_CONTEXT (context);
1796 * g_source_get_priority:
1797 * @source: a #GSource
1799 * Gets the priority of a source.
1801 * Returns: the priority of the source
1803 gint
1804 g_source_get_priority (GSource *source)
1806 g_return_val_if_fail (source != NULL, 0);
1808 return source->priority;
1812 * g_source_set_ready_time:
1813 * @source: a #GSource
1814 * @ready_time: the monotonic time at which the source will be ready,
1815 * 0 for "immediately", -1 for "never"
1817 * Sets a #GSource to be dispatched when the given monotonic time is
1818 * reached (or passed). If the monotonic time is in the past (as it
1819 * always will be if @ready_time is 0) then the source will be
1820 * dispatched immediately.
1822 * If @ready_time is -1 then the source is never woken up on the basis
1823 * of the passage of time.
1825 * Dispatching the source does not reset the ready time. You should do
1826 * so yourself, from the source dispatch function.
1828 * Note that if you have a pair of sources where the ready time of one
1829 * suggests that it will be delivered first but the priority for the
1830 * other suggests that it would be delivered first, and the ready time
1831 * for both sources is reached during the same main context iteration,
1832 * then the order of dispatch is undefined.
1834 * It is a no-op to call this function on a #GSource which has already been
1835 * destroyed with g_source_destroy().
1837 * This API is only intended to be used by implementations of #GSource.
1838 * Do not call this API on a #GSource that you did not create.
1840 * Since: 2.36
1842 void
1843 g_source_set_ready_time (GSource *source,
1844 gint64 ready_time)
1846 GMainContext *context;
1848 g_return_if_fail (source != NULL);
1849 g_return_if_fail (source->ref_count > 0);
1851 if (source->priv->ready_time == ready_time)
1852 return;
1854 context = source->context;
1856 if (context)
1857 LOCK_CONTEXT (context);
1859 source->priv->ready_time = ready_time;
1861 TRACE (GLIB_SOURCE_SET_READY_TIME (source, ready_time));
1863 if (context)
1865 /* Quite likely that we need to change the timeout on the poll */
1866 if (!SOURCE_BLOCKED (source))
1867 conditional_wakeup (context);
1868 UNLOCK_CONTEXT (context);
1873 * g_source_get_ready_time:
1874 * @source: a #GSource
1876 * Gets the "ready time" of @source, as set by
1877 * g_source_set_ready_time().
1879 * Any time before the current monotonic time (including 0) is an
1880 * indication that the source will fire immediately.
1882 * Returns: the monotonic ready time, -1 for "never"
1884 gint64
1885 g_source_get_ready_time (GSource *source)
1887 g_return_val_if_fail (source != NULL, -1);
1889 return source->priv->ready_time;
1893 * g_source_set_can_recurse:
1894 * @source: a #GSource
1895 * @can_recurse: whether recursion is allowed for this source
1897 * Sets whether a source can be called recursively. If @can_recurse is
1898 * %TRUE, then while the source is being dispatched then this source
1899 * will be processed normally. Otherwise, all processing of this
1900 * source is blocked until the dispatch function returns.
1902 void
1903 g_source_set_can_recurse (GSource *source,
1904 gboolean can_recurse)
1906 GMainContext *context;
1908 g_return_if_fail (source != NULL);
1910 context = source->context;
1912 if (context)
1913 LOCK_CONTEXT (context);
1915 if (can_recurse)
1916 source->flags |= G_SOURCE_CAN_RECURSE;
1917 else
1918 source->flags &= ~G_SOURCE_CAN_RECURSE;
1920 if (context)
1921 UNLOCK_CONTEXT (context);
1925 * g_source_get_can_recurse:
1926 * @source: a #GSource
1928 * Checks whether a source is allowed to be called recursively.
1929 * see g_source_set_can_recurse().
1931 * Returns: whether recursion is allowed.
1933 gboolean
1934 g_source_get_can_recurse (GSource *source)
1936 g_return_val_if_fail (source != NULL, FALSE);
1938 return (source->flags & G_SOURCE_CAN_RECURSE) != 0;
1943 * g_source_set_name:
1944 * @source: a #GSource
1945 * @name: debug name for the source
1947 * Sets a name for the source, used in debugging and profiling.
1948 * The name defaults to #NULL.
1950 * The source name should describe in a human-readable way
1951 * what the source does. For example, "X11 event queue"
1952 * or "GTK+ repaint idle handler" or whatever it is.
1954 * It is permitted to call this function multiple times, but is not
1955 * recommended due to the potential performance impact. For example,
1956 * one could change the name in the "check" function of a #GSourceFuncs
1957 * to include details like the event type in the source name.
1959 * Use caution if changing the name while another thread may be
1960 * accessing it with g_source_get_name(); that function does not copy
1961 * the value, and changing the value will free it while the other thread
1962 * may be attempting to use it.
1964 * Since: 2.26
1966 void
1967 g_source_set_name (GSource *source,
1968 const char *name)
1970 GMainContext *context;
1972 g_return_if_fail (source != NULL);
1974 context = source->context;
1976 if (context)
1977 LOCK_CONTEXT (context);
1979 TRACE (GLIB_SOURCE_SET_NAME (source, name));
1981 /* setting back to NULL is allowed, just because it's
1982 * weird if get_name can return NULL but you can't
1983 * set that.
1986 g_free (source->name);
1987 source->name = g_strdup (name);
1989 if (context)
1990 UNLOCK_CONTEXT (context);
1994 * g_source_get_name:
1995 * @source: a #GSource
1997 * Gets a name for the source, used in debugging and profiling. The
1998 * name may be #NULL if it has never been set with g_source_set_name().
2000 * Returns: the name of the source
2002 * Since: 2.26
2004 const char *
2005 g_source_get_name (GSource *source)
2007 g_return_val_if_fail (source != NULL, NULL);
2009 return source->name;
2013 * g_source_set_name_by_id:
2014 * @tag: a #GSource ID
2015 * @name: debug name for the source
2017 * Sets the name of a source using its ID.
2019 * This is a convenience utility to set source names from the return
2020 * value of g_idle_add(), g_timeout_add(), etc.
2022 * It is a programmer error to attempt to set the name of a non-existent
2023 * source.
2025 * More specifically: source IDs can be reissued after a source has been
2026 * destroyed and therefore it is never valid to use this function with a
2027 * source ID which may have already been removed. An example is when
2028 * scheduling an idle to run in another thread with g_idle_add(): the
2029 * idle may already have run and been removed by the time this function
2030 * is called on its (now invalid) source ID. This source ID may have
2031 * been reissued, leading to the operation being performed against the
2032 * wrong source.
2034 * Since: 2.26
2036 void
2037 g_source_set_name_by_id (guint tag,
2038 const char *name)
2040 GSource *source;
2042 g_return_if_fail (tag > 0);
2044 source = g_main_context_find_source_by_id (NULL, tag);
2045 if (source == NULL)
2046 return;
2048 g_source_set_name (source, name);
2053 * g_source_ref:
2054 * @source: a #GSource
2056 * Increases the reference count on a source by one.
2058 * Returns: @source
2060 GSource *
2061 g_source_ref (GSource *source)
2063 GMainContext *context;
2065 g_return_val_if_fail (source != NULL, NULL);
2067 context = source->context;
2069 if (context)
2070 LOCK_CONTEXT (context);
2072 source->ref_count++;
2074 if (context)
2075 UNLOCK_CONTEXT (context);
2077 return source;
2080 /* g_source_unref() but possible to call within context lock
2082 static void
2083 g_source_unref_internal (GSource *source,
2084 GMainContext *context,
2085 gboolean have_lock)
2087 gpointer old_cb_data = NULL;
2088 GSourceCallbackFuncs *old_cb_funcs = NULL;
2090 g_return_if_fail (source != NULL);
2092 if (!have_lock && context)
2093 LOCK_CONTEXT (context);
2095 source->ref_count--;
2096 if (source->ref_count == 0)
2098 TRACE (GLIB_SOURCE_BEFORE_FREE (source, context,
2099 source->source_funcs->finalize));
2101 old_cb_data = source->callback_data;
2102 old_cb_funcs = source->callback_funcs;
2104 source->callback_data = NULL;
2105 source->callback_funcs = NULL;
2107 if (context)
2109 if (!SOURCE_DESTROYED (source))
2110 g_warning (G_STRLOC ": ref_count == 0, but source was still attached to a context!");
2111 source_remove_from_context (source, context);
2113 g_hash_table_remove (context->sources, GUINT_TO_POINTER (source->source_id));
2116 if (source->source_funcs->finalize)
2118 /* Temporarily increase the ref count again so that GSource methods
2119 * can be called from finalize(). */
2120 source->ref_count++;
2121 if (context)
2122 UNLOCK_CONTEXT (context);
2123 source->source_funcs->finalize (source);
2124 if (context)
2125 LOCK_CONTEXT (context);
2126 source->ref_count--;
2129 if (old_cb_funcs)
2131 /* Temporarily increase the ref count again so that GSource methods
2132 * can be called from callback_funcs.unref(). */
2133 source->ref_count++;
2134 if (context)
2135 UNLOCK_CONTEXT (context);
2137 old_cb_funcs->unref (old_cb_data);
2139 if (context)
2140 LOCK_CONTEXT (context);
2141 source->ref_count--;
2144 g_free (source->name);
2145 source->name = NULL;
2147 g_slist_free (source->poll_fds);
2148 source->poll_fds = NULL;
2150 g_slist_free_full (source->priv->fds, g_free);
2152 while (source->priv->child_sources)
2154 GSource *child_source = source->priv->child_sources->data;
2156 source->priv->child_sources =
2157 g_slist_remove (source->priv->child_sources, child_source);
2158 child_source->priv->parent_source = NULL;
2160 g_source_unref_internal (child_source, context, have_lock);
2163 g_slice_free (GSourcePrivate, source->priv);
2164 source->priv = NULL;
2166 g_free (source);
2169 if (!have_lock && context)
2170 UNLOCK_CONTEXT (context);
2174 * g_source_unref:
2175 * @source: a #GSource
2177 * Decreases the reference count of a source by one. If the
2178 * resulting reference count is zero the source and associated
2179 * memory will be destroyed.
2181 void
2182 g_source_unref (GSource *source)
2184 g_return_if_fail (source != NULL);
2186 g_source_unref_internal (source, source->context, FALSE);
2190 * g_main_context_find_source_by_id:
2191 * @context: (nullable): a #GMainContext (if %NULL, the default context will be used)
2192 * @source_id: the source ID, as returned by g_source_get_id().
2194 * Finds a #GSource given a pair of context and ID.
2196 * It is a programmer error to attempt to lookup a non-existent source.
2198 * More specifically: source IDs can be reissued after a source has been
2199 * destroyed and therefore it is never valid to use this function with a
2200 * source ID which may have already been removed. An example is when
2201 * scheduling an idle to run in another thread with g_idle_add(): the
2202 * idle may already have run and been removed by the time this function
2203 * is called on its (now invalid) source ID. This source ID may have
2204 * been reissued, leading to the operation being performed against the
2205 * wrong source.
2207 * Returns: (transfer none): the #GSource
2209 GSource *
2210 g_main_context_find_source_by_id (GMainContext *context,
2211 guint source_id)
2213 GSource *source;
2215 g_return_val_if_fail (source_id > 0, NULL);
2217 if (context == NULL)
2218 context = g_main_context_default ();
2220 LOCK_CONTEXT (context);
2221 source = g_hash_table_lookup (context->sources, GUINT_TO_POINTER (source_id));
2222 UNLOCK_CONTEXT (context);
2224 if (source && SOURCE_DESTROYED (source))
2225 source = NULL;
2227 return source;
2231 * g_main_context_find_source_by_funcs_user_data:
2232 * @context: (nullable): a #GMainContext (if %NULL, the default context will be used).
2233 * @funcs: the @source_funcs passed to g_source_new().
2234 * @user_data: the user data from the callback.
2236 * Finds a source with the given source functions and user data. If
2237 * multiple sources exist with the same source function and user data,
2238 * the first one found will be returned.
2240 * Returns: (transfer none): the source, if one was found, otherwise %NULL
2242 GSource *
2243 g_main_context_find_source_by_funcs_user_data (GMainContext *context,
2244 GSourceFuncs *funcs,
2245 gpointer user_data)
2247 GSourceIter iter;
2248 GSource *source;
2250 g_return_val_if_fail (funcs != NULL, NULL);
2252 if (context == NULL)
2253 context = g_main_context_default ();
2255 LOCK_CONTEXT (context);
2257 g_source_iter_init (&iter, context, FALSE);
2258 while (g_source_iter_next (&iter, &source))
2260 if (!SOURCE_DESTROYED (source) &&
2261 source->source_funcs == funcs &&
2262 source->callback_funcs)
2264 GSourceFunc callback;
2265 gpointer callback_data;
2267 source->callback_funcs->get (source->callback_data, source, &callback, &callback_data);
2269 if (callback_data == user_data)
2270 break;
2273 g_source_iter_clear (&iter);
2275 UNLOCK_CONTEXT (context);
2277 return source;
2281 * g_main_context_find_source_by_user_data:
2282 * @context: a #GMainContext
2283 * @user_data: the user_data for the callback.
2285 * Finds a source with the given user data for the callback. If
2286 * multiple sources exist with the same user data, the first
2287 * one found will be returned.
2289 * Returns: (transfer none): the source, if one was found, otherwise %NULL
2291 GSource *
2292 g_main_context_find_source_by_user_data (GMainContext *context,
2293 gpointer user_data)
2295 GSourceIter iter;
2296 GSource *source;
2298 if (context == NULL)
2299 context = g_main_context_default ();
2301 LOCK_CONTEXT (context);
2303 g_source_iter_init (&iter, context, FALSE);
2304 while (g_source_iter_next (&iter, &source))
2306 if (!SOURCE_DESTROYED (source) &&
2307 source->callback_funcs)
2309 GSourceFunc callback;
2310 gpointer callback_data = NULL;
2312 source->callback_funcs->get (source->callback_data, source, &callback, &callback_data);
2314 if (callback_data == user_data)
2315 break;
2318 g_source_iter_clear (&iter);
2320 UNLOCK_CONTEXT (context);
2322 return source;
2326 * g_source_remove:
2327 * @tag: the ID of the source to remove.
2329 * Removes the source with the given ID from the default main context. You must
2330 * use g_source_destroy() for sources added to a non-default main context.
2332 * The ID of a #GSource is given by g_source_get_id(), or will be
2333 * returned by the functions g_source_attach(), g_idle_add(),
2334 * g_idle_add_full(), g_timeout_add(), g_timeout_add_full(),
2335 * g_child_watch_add(), g_child_watch_add_full(), g_io_add_watch(), and
2336 * g_io_add_watch_full().
2338 * It is a programmer error to attempt to remove a non-existent source.
2340 * More specifically: source IDs can be reissued after a source has been
2341 * destroyed and therefore it is never valid to use this function with a
2342 * source ID which may have already been removed. An example is when
2343 * scheduling an idle to run in another thread with g_idle_add(): the
2344 * idle may already have run and been removed by the time this function
2345 * is called on its (now invalid) source ID. This source ID may have
2346 * been reissued, leading to the operation being performed against the
2347 * wrong source.
2349 * Returns: For historical reasons, this function always returns %TRUE
2351 gboolean
2352 g_source_remove (guint tag)
2354 GSource *source;
2356 g_return_val_if_fail (tag > 0, FALSE);
2358 source = g_main_context_find_source_by_id (NULL, tag);
2359 if (source)
2360 g_source_destroy (source);
2361 else
2362 g_critical ("Source ID %u was not found when attempting to remove it", tag);
2364 return source != NULL;
2368 * g_source_remove_by_user_data:
2369 * @user_data: the user_data for the callback.
2371 * Removes a source from the default main loop context given the user
2372 * data for the callback. If multiple sources exist with the same user
2373 * data, only one will be destroyed.
2375 * Returns: %TRUE if a source was found and removed.
2377 gboolean
2378 g_source_remove_by_user_data (gpointer user_data)
2380 GSource *source;
2382 source = g_main_context_find_source_by_user_data (NULL, user_data);
2383 if (source)
2385 g_source_destroy (source);
2386 return TRUE;
2388 else
2389 return FALSE;
2393 * g_source_remove_by_funcs_user_data:
2394 * @funcs: The @source_funcs passed to g_source_new()
2395 * @user_data: the user data for the callback
2397 * Removes a source from the default main loop context given the
2398 * source functions and user data. If multiple sources exist with the
2399 * same source functions and user data, only one will be destroyed.
2401 * Returns: %TRUE if a source was found and removed.
2403 gboolean
2404 g_source_remove_by_funcs_user_data (GSourceFuncs *funcs,
2405 gpointer user_data)
2407 GSource *source;
2409 g_return_val_if_fail (funcs != NULL, FALSE);
2411 source = g_main_context_find_source_by_funcs_user_data (NULL, funcs, user_data);
2412 if (source)
2414 g_source_destroy (source);
2415 return TRUE;
2417 else
2418 return FALSE;
2422 * g_clear_handle_id: (skip)
2423 * @tag_ptr: (not nullable): a pointer to the handler ID
2424 * @clear_func: (not nullable): the function to call to clear the handler
2426 * Clears a numeric handler, such as a #GSource ID.
2428 * @tag_ptr must be a valid pointer to the variable holding the handler.
2430 * If the ID is zero then this function does nothing.
2431 * Otherwise, clear_func() is called with the ID as a parameter, and the tag is
2432 * set to zero.
2434 * A macro is also included that allows this function to be used without
2435 * pointer casts.
2437 * Since: 2.56
2439 #undef g_clear_handle_id
2440 void
2441 g_clear_handle_id (guint *tag_ptr,
2442 GClearHandleFunc clear_func)
2444 guint _handle_id;
2446 _handle_id = *tag_ptr;
2447 if (_handle_id > 0)
2449 *tag_ptr = 0;
2450 if (clear_func != NULL)
2451 clear_func (_handle_id);
2455 #ifdef G_OS_UNIX
2457 * g_source_add_unix_fd:
2458 * @source: a #GSource
2459 * @fd: the fd to monitor
2460 * @events: an event mask
2462 * Monitors @fd for the IO events in @events.
2464 * The tag returned by this function can be used to remove or modify the
2465 * monitoring of the fd using g_source_remove_unix_fd() or
2466 * g_source_modify_unix_fd().
2468 * It is not necessary to remove the fd before destroying the source; it
2469 * will be cleaned up automatically.
2471 * This API is only intended to be used by implementations of #GSource.
2472 * Do not call this API on a #GSource that you did not create.
2474 * As the name suggests, this function is not available on Windows.
2476 * Returns: (not nullable): an opaque tag
2478 * Since: 2.36
2480 gpointer
2481 g_source_add_unix_fd (GSource *source,
2482 gint fd,
2483 GIOCondition events)
2485 GMainContext *context;
2486 GPollFD *poll_fd;
2488 g_return_val_if_fail (source != NULL, NULL);
2489 g_return_val_if_fail (!SOURCE_DESTROYED (source), NULL);
2491 poll_fd = g_new (GPollFD, 1);
2492 poll_fd->fd = fd;
2493 poll_fd->events = events;
2494 poll_fd->revents = 0;
2496 context = source->context;
2498 if (context)
2499 LOCK_CONTEXT (context);
2501 source->priv->fds = g_slist_prepend (source->priv->fds, poll_fd);
2503 if (context)
2505 if (!SOURCE_BLOCKED (source))
2506 g_main_context_add_poll_unlocked (context, source->priority, poll_fd);
2507 UNLOCK_CONTEXT (context);
2510 return poll_fd;
2514 * g_source_modify_unix_fd:
2515 * @source: a #GSource
2516 * @tag: (not nullable): the tag from g_source_add_unix_fd()
2517 * @new_events: the new event mask to watch
2519 * Updates the event mask to watch for the fd identified by @tag.
2521 * @tag is the tag returned from g_source_add_unix_fd().
2523 * If you want to remove a fd, don't set its event mask to zero.
2524 * Instead, call g_source_remove_unix_fd().
2526 * This API is only intended to be used by implementations of #GSource.
2527 * Do not call this API on a #GSource that you did not create.
2529 * As the name suggests, this function is not available on Windows.
2531 * Since: 2.36
2533 void
2534 g_source_modify_unix_fd (GSource *source,
2535 gpointer tag,
2536 GIOCondition new_events)
2538 GMainContext *context;
2539 GPollFD *poll_fd;
2541 g_return_if_fail (source != NULL);
2542 g_return_if_fail (g_slist_find (source->priv->fds, tag));
2544 context = source->context;
2545 poll_fd = tag;
2547 poll_fd->events = new_events;
2549 if (context)
2550 g_main_context_wakeup (context);
2554 * g_source_remove_unix_fd:
2555 * @source: a #GSource
2556 * @tag: (not nullable): the tag from g_source_add_unix_fd()
2558 * Reverses the effect of a previous call to g_source_add_unix_fd().
2560 * You only need to call this if you want to remove an fd from being
2561 * watched while keeping the same source around. In the normal case you
2562 * will just want to destroy the source.
2564 * This API is only intended to be used by implementations of #GSource.
2565 * Do not call this API on a #GSource that you did not create.
2567 * As the name suggests, this function is not available on Windows.
2569 * Since: 2.36
2571 void
2572 g_source_remove_unix_fd (GSource *source,
2573 gpointer tag)
2575 GMainContext *context;
2576 GPollFD *poll_fd;
2578 g_return_if_fail (source != NULL);
2579 g_return_if_fail (g_slist_find (source->priv->fds, tag));
2581 context = source->context;
2582 poll_fd = tag;
2584 if (context)
2585 LOCK_CONTEXT (context);
2587 source->priv->fds = g_slist_remove (source->priv->fds, poll_fd);
2589 if (context)
2591 if (!SOURCE_BLOCKED (source))
2592 g_main_context_remove_poll_unlocked (context, poll_fd);
2594 UNLOCK_CONTEXT (context);
2597 g_free (poll_fd);
2601 * g_source_query_unix_fd:
2602 * @source: a #GSource
2603 * @tag: (not nullable): the tag from g_source_add_unix_fd()
2605 * Queries the events reported for the fd corresponding to @tag on
2606 * @source during the last poll.
2608 * The return value of this function is only defined when the function
2609 * is called from the check or dispatch functions for @source.
2611 * This API is only intended to be used by implementations of #GSource.
2612 * Do not call this API on a #GSource that you did not create.
2614 * As the name suggests, this function is not available on Windows.
2616 * Returns: the conditions reported on the fd
2618 * Since: 2.36
2620 GIOCondition
2621 g_source_query_unix_fd (GSource *source,
2622 gpointer tag)
2624 GPollFD *poll_fd;
2626 g_return_val_if_fail (source != NULL, 0);
2627 g_return_val_if_fail (g_slist_find (source->priv->fds, tag), 0);
2629 poll_fd = tag;
2631 return poll_fd->revents;
2633 #endif /* G_OS_UNIX */
2636 * g_get_current_time:
2637 * @result: #GTimeVal structure in which to store current time.
2639 * Equivalent to the UNIX gettimeofday() function, but portable.
2641 * You may find g_get_real_time() to be more convenient.
2643 void
2644 g_get_current_time (GTimeVal *result)
2646 #ifndef G_OS_WIN32
2647 struct timeval r;
2649 g_return_if_fail (result != NULL);
2651 /*this is required on alpha, there the timeval structs are int's
2652 not longs and a cast only would fail horribly*/
2653 gettimeofday (&r, NULL);
2654 result->tv_sec = r.tv_sec;
2655 result->tv_usec = r.tv_usec;
2656 #else
2657 FILETIME ft;
2658 guint64 time64;
2660 g_return_if_fail (result != NULL);
2662 GetSystemTimeAsFileTime (&ft);
2663 memmove (&time64, &ft, sizeof (FILETIME));
2665 /* Convert from 100s of nanoseconds since 1601-01-01
2666 * to Unix epoch. Yes, this is Y2038 unsafe.
2668 time64 -= G_GINT64_CONSTANT (116444736000000000);
2669 time64 /= 10;
2671 result->tv_sec = time64 / 1000000;
2672 result->tv_usec = time64 % 1000000;
2673 #endif
2677 * g_get_real_time:
2679 * Queries the system wall-clock time.
2681 * This call is functionally equivalent to g_get_current_time() except
2682 * that the return value is often more convenient than dealing with a
2683 * #GTimeVal.
2685 * You should only use this call if you are actually interested in the real
2686 * wall-clock time. g_get_monotonic_time() is probably more useful for
2687 * measuring intervals.
2689 * Returns: the number of microseconds since January 1, 1970 UTC.
2691 * Since: 2.28
2693 gint64
2694 g_get_real_time (void)
2696 GTimeVal tv;
2698 g_get_current_time (&tv);
2700 return (((gint64) tv.tv_sec) * 1000000) + tv.tv_usec;
2704 * g_get_monotonic_time:
2706 * Queries the system monotonic time.
2708 * The monotonic clock will always increase and doesn't suffer
2709 * discontinuities when the user (or NTP) changes the system time. It
2710 * may or may not continue to tick during times where the machine is
2711 * suspended.
2713 * We try to use the clock that corresponds as closely as possible to
2714 * the passage of time as measured by system calls such as poll() but it
2715 * may not always be possible to do this.
2717 * Returns: the monotonic time, in microseconds
2719 * Since: 2.28
2721 #if defined (G_OS_WIN32)
2722 /* NOTE:
2723 * time_usec = ticks_since_boot * usec_per_sec / ticks_per_sec
2725 * Doing (ticks_since_boot * usec_per_sec) before the division can overflow 64 bits
2726 * (ticks_since_boot / ticks_per_sec) and then multiply would not be accurate enough.
2727 * So for now we calculate (usec_per_sec / ticks_per_sec) and use floating point
2729 static gdouble g_monotonic_usec_per_tick = 0;
2731 void
2732 g_clock_win32_init (void)
2734 LARGE_INTEGER freq;
2736 if (!QueryPerformanceFrequency (&freq) || freq.QuadPart == 0)
2738 /* The documentation says that this should never happen */
2739 g_assert_not_reached ();
2740 return;
2743 g_monotonic_usec_per_tick = (gdouble)G_USEC_PER_SEC / freq.QuadPart;
2746 gint64
2747 g_get_monotonic_time (void)
2749 if (G_LIKELY (g_monotonic_usec_per_tick != 0))
2751 LARGE_INTEGER ticks;
2753 if (QueryPerformanceCounter (&ticks))
2754 return (gint64)(ticks.QuadPart * g_monotonic_usec_per_tick);
2756 g_warning ("QueryPerformanceCounter Failed (%lu)", GetLastError ());
2757 g_monotonic_usec_per_tick = 0;
2760 return 0;
2762 #elif defined(HAVE_MACH_MACH_TIME_H) /* Mac OS */
2763 gint64
2764 g_get_monotonic_time (void)
2766 static mach_timebase_info_data_t timebase_info;
2768 if (timebase_info.denom == 0)
2770 /* This is a fraction that we must use to scale
2771 * mach_absolute_time() by in order to reach nanoseconds.
2773 * We've only ever observed this to be 1/1, but maybe it could be
2774 * 1000/1 if mach time is microseconds already, or 1/1000 if
2775 * picoseconds. Try to deal nicely with that.
2777 mach_timebase_info (&timebase_info);
2779 /* We actually want microseconds... */
2780 if (timebase_info.numer % 1000 == 0)
2781 timebase_info.numer /= 1000;
2782 else
2783 timebase_info.denom *= 1000;
2785 /* We want to make the numer 1 to avoid having to multiply... */
2786 if (timebase_info.denom % timebase_info.numer == 0)
2788 timebase_info.denom /= timebase_info.numer;
2789 timebase_info.numer = 1;
2791 else
2793 /* We could just multiply by timebase_info.numer below, but why
2794 * bother for a case that may never actually exist...
2796 * Plus -- performing the multiplication would risk integer
2797 * overflow. If we ever actually end up in this situation, we
2798 * should more carefully evaluate the correct course of action.
2800 mach_timebase_info (&timebase_info); /* Get a fresh copy for a better message */
2801 g_error ("Got weird mach timebase info of %d/%d. Please file a bug against GLib.",
2802 timebase_info.numer, timebase_info.denom);
2806 return mach_absolute_time () / timebase_info.denom;
2808 #else
2809 gint64
2810 g_get_monotonic_time (void)
2812 struct timespec ts;
2813 gint result;
2815 result = clock_gettime (CLOCK_MONOTONIC, &ts);
2817 if G_UNLIKELY (result != 0)
2818 g_error ("GLib requires working CLOCK_MONOTONIC");
2820 return (((gint64) ts.tv_sec) * 1000000) + (ts.tv_nsec / 1000);
2822 #endif
2824 static void
2825 g_main_dispatch_free (gpointer dispatch)
2827 g_slice_free (GMainDispatch, dispatch);
2830 /* Running the main loop */
2832 static GMainDispatch *
2833 get_dispatch (void)
2835 static GPrivate depth_private = G_PRIVATE_INIT (g_main_dispatch_free);
2836 GMainDispatch *dispatch;
2838 dispatch = g_private_get (&depth_private);
2840 if (!dispatch)
2842 dispatch = g_slice_new0 (GMainDispatch);
2843 g_private_set (&depth_private, dispatch);
2846 return dispatch;
2850 * g_main_depth:
2852 * Returns the depth of the stack of calls to
2853 * g_main_context_dispatch() on any #GMainContext in the current thread.
2854 * That is, when called from the toplevel, it gives 0. When
2855 * called from within a callback from g_main_context_iteration()
2856 * (or g_main_loop_run(), etc.) it returns 1. When called from within
2857 * a callback to a recursive call to g_main_context_iteration(),
2858 * it returns 2. And so forth.
2860 * This function is useful in a situation like the following:
2861 * Imagine an extremely simple "garbage collected" system.
2863 * |[<!-- language="C" -->
2864 * static GList *free_list;
2866 * gpointer
2867 * allocate_memory (gsize size)
2868 * {
2869 * gpointer result = g_malloc (size);
2870 * free_list = g_list_prepend (free_list, result);
2871 * return result;
2874 * void
2875 * free_allocated_memory (void)
2877 * GList *l;
2878 * for (l = free_list; l; l = l->next);
2879 * g_free (l->data);
2880 * g_list_free (free_list);
2881 * free_list = NULL;
2884 * [...]
2886 * while (TRUE);
2888 * g_main_context_iteration (NULL, TRUE);
2889 * free_allocated_memory();
2891 * ]|
2893 * This works from an application, however, if you want to do the same
2894 * thing from a library, it gets more difficult, since you no longer
2895 * control the main loop. You might think you can simply use an idle
2896 * function to make the call to free_allocated_memory(), but that
2897 * doesn't work, since the idle function could be called from a
2898 * recursive callback. This can be fixed by using g_main_depth()
2900 * |[<!-- language="C" -->
2901 * gpointer
2902 * allocate_memory (gsize size)
2903 * {
2904 * FreeListBlock *block = g_new (FreeListBlock, 1);
2905 * block->mem = g_malloc (size);
2906 * block->depth = g_main_depth ();
2907 * free_list = g_list_prepend (free_list, block);
2908 * return block->mem;
2911 * void
2912 * free_allocated_memory (void)
2914 * GList *l;
2916 * int depth = g_main_depth ();
2917 * for (l = free_list; l; );
2919 * GList *next = l->next;
2920 * FreeListBlock *block = l->data;
2921 * if (block->depth > depth)
2923 * g_free (block->mem);
2924 * g_free (block);
2925 * free_list = g_list_delete_link (free_list, l);
2928 * l = next;
2931 * ]|
2933 * There is a temptation to use g_main_depth() to solve
2934 * problems with reentrancy. For instance, while waiting for data
2935 * to be received from the network in response to a menu item,
2936 * the menu item might be selected again. It might seem that
2937 * one could make the menu item's callback return immediately
2938 * and do nothing if g_main_depth() returns a value greater than 1.
2939 * However, this should be avoided since the user then sees selecting
2940 * the menu item do nothing. Furthermore, you'll find yourself adding
2941 * these checks all over your code, since there are doubtless many,
2942 * many things that the user could do. Instead, you can use the
2943 * following techniques:
2945 * 1. Use gtk_widget_set_sensitive() or modal dialogs to prevent
2946 * the user from interacting with elements while the main
2947 * loop is recursing.
2949 * 2. Avoid main loop recursion in situations where you can't handle
2950 * arbitrary callbacks. Instead, structure your code so that you
2951 * simply return to the main loop and then get called again when
2952 * there is more work to do.
2954 * Returns: The main loop recursion level in the current thread
2957 g_main_depth (void)
2959 GMainDispatch *dispatch = get_dispatch ();
2960 return dispatch->depth;
2964 * g_main_current_source:
2966 * Returns the currently firing source for this thread.
2968 * Returns: (transfer none): The currently firing source or %NULL.
2970 * Since: 2.12
2972 GSource *
2973 g_main_current_source (void)
2975 GMainDispatch *dispatch = get_dispatch ();
2976 return dispatch->source;
2980 * g_source_is_destroyed:
2981 * @source: a #GSource
2983 * Returns whether @source has been destroyed.
2985 * This is important when you operate upon your objects
2986 * from within idle handlers, but may have freed the object
2987 * before the dispatch of your idle handler.
2989 * |[<!-- language="C" -->
2990 * static gboolean
2991 * idle_callback (gpointer data)
2993 * SomeWidget *self = data;
2995 * GDK_THREADS_ENTER ();
2996 * // do stuff with self
2997 * self->idle_id = 0;
2998 * GDK_THREADS_LEAVE ();
3000 * return G_SOURCE_REMOVE;
3003 * static void
3004 * some_widget_do_stuff_later (SomeWidget *self)
3006 * self->idle_id = g_idle_add (idle_callback, self);
3009 * static void
3010 * some_widget_finalize (GObject *object)
3012 * SomeWidget *self = SOME_WIDGET (object);
3014 * if (self->idle_id)
3015 * g_source_remove (self->idle_id);
3017 * G_OBJECT_CLASS (parent_class)->finalize (object);
3019 * ]|
3021 * This will fail in a multi-threaded application if the
3022 * widget is destroyed before the idle handler fires due
3023 * to the use after free in the callback. A solution, to
3024 * this particular problem, is to check to if the source
3025 * has already been destroy within the callback.
3027 * |[<!-- language="C" -->
3028 * static gboolean
3029 * idle_callback (gpointer data)
3031 * SomeWidget *self = data;
3033 * GDK_THREADS_ENTER ();
3034 * if (!g_source_is_destroyed (g_main_current_source ()))
3036 * // do stuff with self
3038 * GDK_THREADS_LEAVE ();
3040 * return FALSE;
3042 * ]|
3044 * Calls to this function from a thread other than the one acquired by the
3045 * #GMainContext the #GSource is attached to are typically redundant, as the
3046 * source could be destroyed immediately after this function returns. However,
3047 * once a source is destroyed it cannot be un-destroyed, so this function can be
3048 * used for opportunistic checks from any thread.
3050 * Returns: %TRUE if the source has been destroyed
3052 * Since: 2.12
3054 gboolean
3055 g_source_is_destroyed (GSource *source)
3057 return SOURCE_DESTROYED (source);
3060 /* Temporarily remove all this source's file descriptors from the
3061 * poll(), so that if data comes available for one of the file descriptors
3062 * we don't continually spin in the poll()
3064 /* HOLDS: source->context's lock */
3065 static void
3066 block_source (GSource *source)
3068 GSList *tmp_list;
3070 g_return_if_fail (!SOURCE_BLOCKED (source));
3072 source->flags |= G_SOURCE_BLOCKED;
3074 if (source->context)
3076 tmp_list = source->poll_fds;
3077 while (tmp_list)
3079 g_main_context_remove_poll_unlocked (source->context, tmp_list->data);
3080 tmp_list = tmp_list->next;
3083 for (tmp_list = source->priv->fds; tmp_list; tmp_list = tmp_list->next)
3084 g_main_context_remove_poll_unlocked (source->context, tmp_list->data);
3087 if (source->priv && source->priv->child_sources)
3089 tmp_list = source->priv->child_sources;
3090 while (tmp_list)
3092 block_source (tmp_list->data);
3093 tmp_list = tmp_list->next;
3098 /* HOLDS: source->context's lock */
3099 static void
3100 unblock_source (GSource *source)
3102 GSList *tmp_list;
3104 g_return_if_fail (SOURCE_BLOCKED (source)); /* Source already unblocked */
3105 g_return_if_fail (!SOURCE_DESTROYED (source));
3107 source->flags &= ~G_SOURCE_BLOCKED;
3109 tmp_list = source->poll_fds;
3110 while (tmp_list)
3112 g_main_context_add_poll_unlocked (source->context, source->priority, tmp_list->data);
3113 tmp_list = tmp_list->next;
3116 for (tmp_list = source->priv->fds; tmp_list; tmp_list = tmp_list->next)
3117 g_main_context_add_poll_unlocked (source->context, source->priority, tmp_list->data);
3119 if (source->priv && source->priv->child_sources)
3121 tmp_list = source->priv->child_sources;
3122 while (tmp_list)
3124 unblock_source (tmp_list->data);
3125 tmp_list = tmp_list->next;
3130 /* HOLDS: context's lock */
3131 static void
3132 g_main_dispatch (GMainContext *context)
3134 GMainDispatch *current = get_dispatch ();
3135 guint i;
3137 for (i = 0; i < context->pending_dispatches->len; i++)
3139 GSource *source = context->pending_dispatches->pdata[i];
3141 context->pending_dispatches->pdata[i] = NULL;
3142 g_assert (source);
3144 source->flags &= ~G_SOURCE_READY;
3146 if (!SOURCE_DESTROYED (source))
3148 gboolean was_in_call;
3149 gpointer user_data = NULL;
3150 GSourceFunc callback = NULL;
3151 GSourceCallbackFuncs *cb_funcs;
3152 gpointer cb_data;
3153 gboolean need_destroy;
3155 gboolean (*dispatch) (GSource *,
3156 GSourceFunc,
3157 gpointer);
3158 GSource *prev_source;
3160 dispatch = source->source_funcs->dispatch;
3161 cb_funcs = source->callback_funcs;
3162 cb_data = source->callback_data;
3164 if (cb_funcs)
3165 cb_funcs->ref (cb_data);
3167 if ((source->flags & G_SOURCE_CAN_RECURSE) == 0)
3168 block_source (source);
3170 was_in_call = source->flags & G_HOOK_FLAG_IN_CALL;
3171 source->flags |= G_HOOK_FLAG_IN_CALL;
3173 if (cb_funcs)
3174 cb_funcs->get (cb_data, source, &callback, &user_data);
3176 UNLOCK_CONTEXT (context);
3178 /* These operations are safe because 'current' is thread-local
3179 * and not modified from anywhere but this function.
3181 prev_source = current->source;
3182 current->source = source;
3183 current->depth++;
3185 TRACE (GLIB_MAIN_BEFORE_DISPATCH (g_source_get_name (source), source,
3186 dispatch, callback, user_data));
3187 need_destroy = !(* dispatch) (source, callback, user_data);
3188 TRACE (GLIB_MAIN_AFTER_DISPATCH (g_source_get_name (source), source,
3189 dispatch, need_destroy));
3191 current->source = prev_source;
3192 current->depth--;
3194 if (cb_funcs)
3195 cb_funcs->unref (cb_data);
3197 LOCK_CONTEXT (context);
3199 if (!was_in_call)
3200 source->flags &= ~G_HOOK_FLAG_IN_CALL;
3202 if (SOURCE_BLOCKED (source) && !SOURCE_DESTROYED (source))
3203 unblock_source (source);
3205 /* Note: this depends on the fact that we can't switch
3206 * sources from one main context to another
3208 if (need_destroy && !SOURCE_DESTROYED (source))
3210 g_assert (source->context == context);
3211 g_source_destroy_internal (source, context, TRUE);
3215 SOURCE_UNREF (source, context);
3218 g_ptr_array_set_size (context->pending_dispatches, 0);
3222 * g_main_context_acquire:
3223 * @context: a #GMainContext
3225 * Tries to become the owner of the specified context.
3226 * If some other thread is the owner of the context,
3227 * returns %FALSE immediately. Ownership is properly
3228 * recursive: the owner can require ownership again
3229 * and will release ownership when g_main_context_release()
3230 * is called as many times as g_main_context_acquire().
3232 * You must be the owner of a context before you
3233 * can call g_main_context_prepare(), g_main_context_query(),
3234 * g_main_context_check(), g_main_context_dispatch().
3236 * Returns: %TRUE if the operation succeeded, and
3237 * this thread is now the owner of @context.
3239 gboolean
3240 g_main_context_acquire (GMainContext *context)
3242 gboolean result = FALSE;
3243 GThread *self = G_THREAD_SELF;
3245 if (context == NULL)
3246 context = g_main_context_default ();
3248 LOCK_CONTEXT (context);
3250 if (!context->owner)
3252 context->owner = self;
3253 g_assert (context->owner_count == 0);
3254 TRACE (GLIB_MAIN_CONTEXT_ACQUIRE (context, TRUE /* success */));
3257 if (context->owner == self)
3259 context->owner_count++;
3260 result = TRUE;
3262 else
3264 TRACE (GLIB_MAIN_CONTEXT_ACQUIRE (context, FALSE /* failure */));
3267 UNLOCK_CONTEXT (context);
3269 return result;
3273 * g_main_context_release:
3274 * @context: a #GMainContext
3276 * Releases ownership of a context previously acquired by this thread
3277 * with g_main_context_acquire(). If the context was acquired multiple
3278 * times, the ownership will be released only when g_main_context_release()
3279 * is called as many times as it was acquired.
3281 void
3282 g_main_context_release (GMainContext *context)
3284 if (context == NULL)
3285 context = g_main_context_default ();
3287 LOCK_CONTEXT (context);
3289 context->owner_count--;
3290 if (context->owner_count == 0)
3292 TRACE (GLIB_MAIN_CONTEXT_RELEASE (context));
3294 context->owner = NULL;
3296 if (context->waiters)
3298 GMainWaiter *waiter = context->waiters->data;
3299 gboolean loop_internal_waiter = (waiter->mutex == &context->mutex);
3300 context->waiters = g_slist_delete_link (context->waiters,
3301 context->waiters);
3302 if (!loop_internal_waiter)
3303 g_mutex_lock (waiter->mutex);
3305 g_cond_signal (waiter->cond);
3307 if (!loop_internal_waiter)
3308 g_mutex_unlock (waiter->mutex);
3312 UNLOCK_CONTEXT (context);
3316 * g_main_context_wait:
3317 * @context: a #GMainContext
3318 * @cond: a condition variable
3319 * @mutex: a mutex, currently held
3321 * Tries to become the owner of the specified context,
3322 * as with g_main_context_acquire(). But if another thread
3323 * is the owner, atomically drop @mutex and wait on @cond until
3324 * that owner releases ownership or until @cond is signaled, then
3325 * try again (once) to become the owner.
3327 * Returns: %TRUE if the operation succeeded, and
3328 * this thread is now the owner of @context.
3330 gboolean
3331 g_main_context_wait (GMainContext *context,
3332 GCond *cond,
3333 GMutex *mutex)
3335 gboolean result = FALSE;
3336 GThread *self = G_THREAD_SELF;
3337 gboolean loop_internal_waiter;
3339 if (context == NULL)
3340 context = g_main_context_default ();
3342 if G_UNLIKELY (cond != &context->cond || mutex != &context->mutex)
3344 static gboolean warned;
3346 if (!warned)
3348 g_critical ("WARNING!! g_main_context_wait() will be removed in a future release. "
3349 "If you see this message, please file a bug immediately.");
3350 warned = TRUE;
3354 loop_internal_waiter = (mutex == &context->mutex);
3356 if (!loop_internal_waiter)
3357 LOCK_CONTEXT (context);
3359 if (context->owner && context->owner != self)
3361 GMainWaiter waiter;
3363 waiter.cond = cond;
3364 waiter.mutex = mutex;
3366 context->waiters = g_slist_append (context->waiters, &waiter);
3368 if (!loop_internal_waiter)
3369 UNLOCK_CONTEXT (context);
3370 g_cond_wait (cond, mutex);
3371 if (!loop_internal_waiter)
3372 LOCK_CONTEXT (context);
3374 context->waiters = g_slist_remove (context->waiters, &waiter);
3377 if (!context->owner)
3379 context->owner = self;
3380 g_assert (context->owner_count == 0);
3383 if (context->owner == self)
3385 context->owner_count++;
3386 result = TRUE;
3389 if (!loop_internal_waiter)
3390 UNLOCK_CONTEXT (context);
3392 return result;
3396 * g_main_context_prepare:
3397 * @context: a #GMainContext
3398 * @priority: location to store priority of highest priority
3399 * source already ready.
3401 * Prepares to poll sources within a main loop. The resulting information
3402 * for polling is determined by calling g_main_context_query ().
3404 * You must have successfully acquired the context with
3405 * g_main_context_acquire() before you may call this function.
3407 * Returns: %TRUE if some source is ready to be dispatched
3408 * prior to polling.
3410 gboolean
3411 g_main_context_prepare (GMainContext *context,
3412 gint *priority)
3414 guint i;
3415 gint n_ready = 0;
3416 gint current_priority = G_MAXINT;
3417 GSource *source;
3418 GSourceIter iter;
3420 if (context == NULL)
3421 context = g_main_context_default ();
3423 LOCK_CONTEXT (context);
3425 context->time_is_fresh = FALSE;
3427 if (context->in_check_or_prepare)
3429 g_warning ("g_main_context_prepare() called recursively from within a source's check() or "
3430 "prepare() member.");
3431 UNLOCK_CONTEXT (context);
3432 return FALSE;
3435 TRACE (GLIB_MAIN_CONTEXT_BEFORE_PREPARE (context));
3437 #if 0
3438 /* If recursing, finish up current dispatch, before starting over */
3439 if (context->pending_dispatches)
3441 if (dispatch)
3442 g_main_dispatch (context, &current_time);
3444 UNLOCK_CONTEXT (context);
3445 return TRUE;
3447 #endif
3449 /* If recursing, clear list of pending dispatches */
3451 for (i = 0; i < context->pending_dispatches->len; i++)
3453 if (context->pending_dispatches->pdata[i])
3454 SOURCE_UNREF ((GSource *)context->pending_dispatches->pdata[i], context);
3456 g_ptr_array_set_size (context->pending_dispatches, 0);
3458 /* Prepare all sources */
3460 context->timeout = -1;
3462 g_source_iter_init (&iter, context, TRUE);
3463 while (g_source_iter_next (&iter, &source))
3465 gint source_timeout = -1;
3467 if (SOURCE_DESTROYED (source) || SOURCE_BLOCKED (source))
3468 continue;
3469 if ((n_ready > 0) && (source->priority > current_priority))
3470 break;
3472 if (!(source->flags & G_SOURCE_READY))
3474 gboolean result;
3475 gboolean (* prepare) (GSource *source,
3476 gint *timeout);
3478 prepare = source->source_funcs->prepare;
3480 if (prepare)
3482 context->in_check_or_prepare++;
3483 UNLOCK_CONTEXT (context);
3485 result = (* prepare) (source, &source_timeout);
3486 TRACE (GLIB_MAIN_AFTER_PREPARE (source, prepare, source_timeout));
3488 LOCK_CONTEXT (context);
3489 context->in_check_or_prepare--;
3491 else
3493 source_timeout = -1;
3494 result = FALSE;
3497 if (result == FALSE && source->priv->ready_time != -1)
3499 if (!context->time_is_fresh)
3501 context->time = g_get_monotonic_time ();
3502 context->time_is_fresh = TRUE;
3505 if (source->priv->ready_time <= context->time)
3507 source_timeout = 0;
3508 result = TRUE;
3510 else
3512 gint timeout;
3514 /* rounding down will lead to spinning, so always round up */
3515 timeout = (source->priv->ready_time - context->time + 999) / 1000;
3517 if (source_timeout < 0 || timeout < source_timeout)
3518 source_timeout = timeout;
3522 if (result)
3524 GSource *ready_source = source;
3526 while (ready_source)
3528 ready_source->flags |= G_SOURCE_READY;
3529 ready_source = ready_source->priv->parent_source;
3534 if (source->flags & G_SOURCE_READY)
3536 n_ready++;
3537 current_priority = source->priority;
3538 context->timeout = 0;
3541 if (source_timeout >= 0)
3543 if (context->timeout < 0)
3544 context->timeout = source_timeout;
3545 else
3546 context->timeout = MIN (context->timeout, source_timeout);
3549 g_source_iter_clear (&iter);
3551 TRACE (GLIB_MAIN_CONTEXT_AFTER_PREPARE (context, current_priority, n_ready));
3553 UNLOCK_CONTEXT (context);
3555 if (priority)
3556 *priority = current_priority;
3558 return (n_ready > 0);
3562 * g_main_context_query:
3563 * @context: a #GMainContext
3564 * @max_priority: maximum priority source to check
3565 * @timeout_: (out): location to store timeout to be used in polling
3566 * @fds: (out caller-allocates) (array length=n_fds): location to
3567 * store #GPollFD records that need to be polled.
3568 * @n_fds: (in): length of @fds.
3570 * Determines information necessary to poll this main loop.
3572 * You must have successfully acquired the context with
3573 * g_main_context_acquire() before you may call this function.
3575 * Returns: the number of records actually stored in @fds,
3576 * or, if more than @n_fds records need to be stored, the number
3577 * of records that need to be stored.
3579 gint
3580 g_main_context_query (GMainContext *context,
3581 gint max_priority,
3582 gint *timeout,
3583 GPollFD *fds,
3584 gint n_fds)
3586 gint n_poll;
3587 GPollRec *pollrec, *lastpollrec;
3588 gushort events;
3590 LOCK_CONTEXT (context);
3592 TRACE (GLIB_MAIN_CONTEXT_BEFORE_QUERY (context, max_priority));
3594 n_poll = 0;
3595 lastpollrec = NULL;
3596 for (pollrec = context->poll_records; pollrec; pollrec = pollrec->next)
3598 if (pollrec->priority > max_priority)
3599 continue;
3601 /* In direct contradiction to the Unix98 spec, IRIX runs into
3602 * difficulty if you pass in POLLERR, POLLHUP or POLLNVAL
3603 * flags in the events field of the pollfd while it should
3604 * just ignoring them. So we mask them out here.
3606 events = pollrec->fd->events & ~(G_IO_ERR|G_IO_HUP|G_IO_NVAL);
3608 if (lastpollrec && pollrec->fd->fd == lastpollrec->fd->fd)
3610 if (n_poll - 1 < n_fds)
3611 fds[n_poll - 1].events |= events;
3613 else
3615 if (n_poll < n_fds)
3617 fds[n_poll].fd = pollrec->fd->fd;
3618 fds[n_poll].events = events;
3619 fds[n_poll].revents = 0;
3622 n_poll++;
3625 lastpollrec = pollrec;
3628 context->poll_changed = FALSE;
3630 if (timeout)
3632 *timeout = context->timeout;
3633 if (*timeout != 0)
3634 context->time_is_fresh = FALSE;
3637 TRACE (GLIB_MAIN_CONTEXT_AFTER_QUERY (context, context->timeout,
3638 fds, n_poll));
3640 UNLOCK_CONTEXT (context);
3642 return n_poll;
3646 * g_main_context_check:
3647 * @context: a #GMainContext
3648 * @max_priority: the maximum numerical priority of sources to check
3649 * @fds: (array length=n_fds): array of #GPollFD's that was passed to
3650 * the last call to g_main_context_query()
3651 * @n_fds: return value of g_main_context_query()
3653 * Passes the results of polling back to the main loop.
3655 * You must have successfully acquired the context with
3656 * g_main_context_acquire() before you may call this function.
3658 * Returns: %TRUE if some sources are ready to be dispatched.
3660 gboolean
3661 g_main_context_check (GMainContext *context,
3662 gint max_priority,
3663 GPollFD *fds,
3664 gint n_fds)
3666 GSource *source;
3667 GSourceIter iter;
3668 GPollRec *pollrec;
3669 gint n_ready = 0;
3670 gint i;
3672 LOCK_CONTEXT (context);
3674 if (context->in_check_or_prepare)
3676 g_warning ("g_main_context_check() called recursively from within a source's check() or "
3677 "prepare() member.");
3678 UNLOCK_CONTEXT (context);
3679 return FALSE;
3682 TRACE (GLIB_MAIN_CONTEXT_BEFORE_CHECK (context, max_priority, fds, n_fds));
3684 for (i = 0; i < n_fds; i++)
3686 if (fds[i].fd == context->wake_up_rec.fd)
3688 if (fds[i].revents)
3690 TRACE (GLIB_MAIN_CONTEXT_WAKEUP_ACKNOWLEDGE (context));
3691 g_wakeup_acknowledge (context->wakeup);
3693 break;
3697 /* If the set of poll file descriptors changed, bail out
3698 * and let the main loop rerun
3700 if (context->poll_changed)
3702 TRACE (GLIB_MAIN_CONTEXT_AFTER_CHECK (context, 0));
3704 UNLOCK_CONTEXT (context);
3705 return FALSE;
3708 pollrec = context->poll_records;
3709 i = 0;
3710 while (pollrec && i < n_fds)
3712 while (pollrec && pollrec->fd->fd == fds[i].fd)
3714 if (pollrec->priority <= max_priority)
3716 pollrec->fd->revents =
3717 fds[i].revents & (pollrec->fd->events | G_IO_ERR | G_IO_HUP | G_IO_NVAL);
3719 pollrec = pollrec->next;
3722 i++;
3725 g_source_iter_init (&iter, context, TRUE);
3726 while (g_source_iter_next (&iter, &source))
3728 if (SOURCE_DESTROYED (source) || SOURCE_BLOCKED (source))
3729 continue;
3730 if ((n_ready > 0) && (source->priority > max_priority))
3731 break;
3733 if (!(source->flags & G_SOURCE_READY))
3735 gboolean result;
3736 gboolean (* check) (GSource *source);
3738 check = source->source_funcs->check;
3740 if (check)
3742 /* If the check function is set, call it. */
3743 context->in_check_or_prepare++;
3744 UNLOCK_CONTEXT (context);
3746 result = (* check) (source);
3748 TRACE (GLIB_MAIN_AFTER_CHECK (source, check, result));
3750 LOCK_CONTEXT (context);
3751 context->in_check_or_prepare--;
3753 else
3754 result = FALSE;
3756 if (result == FALSE)
3758 GSList *tmp_list;
3760 /* If not already explicitly flagged ready by ->check()
3761 * (or if we have no check) then we can still be ready if
3762 * any of our fds poll as ready.
3764 for (tmp_list = source->priv->fds; tmp_list; tmp_list = tmp_list->next)
3766 GPollFD *pollfd = tmp_list->data;
3768 if (pollfd->revents)
3770 result = TRUE;
3771 break;
3776 if (result == FALSE && source->priv->ready_time != -1)
3778 if (!context->time_is_fresh)
3780 context->time = g_get_monotonic_time ();
3781 context->time_is_fresh = TRUE;
3784 if (source->priv->ready_time <= context->time)
3785 result = TRUE;
3788 if (result)
3790 GSource *ready_source = source;
3792 while (ready_source)
3794 ready_source->flags |= G_SOURCE_READY;
3795 ready_source = ready_source->priv->parent_source;
3800 if (source->flags & G_SOURCE_READY)
3802 source->ref_count++;
3803 g_ptr_array_add (context->pending_dispatches, source);
3805 n_ready++;
3807 /* never dispatch sources with less priority than the first
3808 * one we choose to dispatch
3810 max_priority = source->priority;
3813 g_source_iter_clear (&iter);
3815 TRACE (GLIB_MAIN_CONTEXT_AFTER_CHECK (context, n_ready));
3817 UNLOCK_CONTEXT (context);
3819 return n_ready > 0;
3823 * g_main_context_dispatch:
3824 * @context: a #GMainContext
3826 * Dispatches all pending sources.
3828 * You must have successfully acquired the context with
3829 * g_main_context_acquire() before you may call this function.
3831 void
3832 g_main_context_dispatch (GMainContext *context)
3834 LOCK_CONTEXT (context);
3836 TRACE (GLIB_MAIN_CONTEXT_BEFORE_DISPATCH (context));
3838 if (context->pending_dispatches->len > 0)
3840 g_main_dispatch (context);
3843 TRACE (GLIB_MAIN_CONTEXT_AFTER_DISPATCH (context));
3845 UNLOCK_CONTEXT (context);
3848 /* HOLDS context lock */
3849 static gboolean
3850 g_main_context_iterate (GMainContext *context,
3851 gboolean block,
3852 gboolean dispatch,
3853 GThread *self)
3855 gint max_priority;
3856 gint timeout;
3857 gboolean some_ready;
3858 gint nfds, allocated_nfds;
3859 GPollFD *fds = NULL;
3861 UNLOCK_CONTEXT (context);
3863 if (!g_main_context_acquire (context))
3865 gboolean got_ownership;
3867 LOCK_CONTEXT (context);
3869 if (!block)
3870 return FALSE;
3872 got_ownership = g_main_context_wait (context,
3873 &context->cond,
3874 &context->mutex);
3876 if (!got_ownership)
3877 return FALSE;
3879 else
3880 LOCK_CONTEXT (context);
3882 if (!context->cached_poll_array)
3884 context->cached_poll_array_size = context->n_poll_records;
3885 context->cached_poll_array = g_new (GPollFD, context->n_poll_records);
3888 allocated_nfds = context->cached_poll_array_size;
3889 fds = context->cached_poll_array;
3891 UNLOCK_CONTEXT (context);
3893 g_main_context_prepare (context, &max_priority);
3895 while ((nfds = g_main_context_query (context, max_priority, &timeout, fds,
3896 allocated_nfds)) > allocated_nfds)
3898 LOCK_CONTEXT (context);
3899 g_free (fds);
3900 context->cached_poll_array_size = allocated_nfds = nfds;
3901 context->cached_poll_array = fds = g_new (GPollFD, nfds);
3902 UNLOCK_CONTEXT (context);
3905 if (!block)
3906 timeout = 0;
3908 g_main_context_poll (context, timeout, max_priority, fds, nfds);
3910 some_ready = g_main_context_check (context, max_priority, fds, nfds);
3912 if (dispatch)
3913 g_main_context_dispatch (context);
3915 g_main_context_release (context);
3917 LOCK_CONTEXT (context);
3919 return some_ready;
3923 * g_main_context_pending:
3924 * @context: (nullable): a #GMainContext (if %NULL, the default context will be used)
3926 * Checks if any sources have pending events for the given context.
3928 * Returns: %TRUE if events are pending.
3930 gboolean
3931 g_main_context_pending (GMainContext *context)
3933 gboolean retval;
3935 if (!context)
3936 context = g_main_context_default();
3938 LOCK_CONTEXT (context);
3939 retval = g_main_context_iterate (context, FALSE, FALSE, G_THREAD_SELF);
3940 UNLOCK_CONTEXT (context);
3942 return retval;
3946 * g_main_context_iteration:
3947 * @context: (nullable): a #GMainContext (if %NULL, the default context will be used)
3948 * @may_block: whether the call may block.
3950 * Runs a single iteration for the given main loop. This involves
3951 * checking to see if any event sources are ready to be processed,
3952 * then if no events sources are ready and @may_block is %TRUE, waiting
3953 * for a source to become ready, then dispatching the highest priority
3954 * events sources that are ready. Otherwise, if @may_block is %FALSE
3955 * sources are not waited to become ready, only those highest priority
3956 * events sources will be dispatched (if any), that are ready at this
3957 * given moment without further waiting.
3959 * Note that even when @may_block is %TRUE, it is still possible for
3960 * g_main_context_iteration() to return %FALSE, since the wait may
3961 * be interrupted for other reasons than an event source becoming ready.
3963 * Returns: %TRUE if events were dispatched.
3965 gboolean
3966 g_main_context_iteration (GMainContext *context, gboolean may_block)
3968 gboolean retval;
3970 if (!context)
3971 context = g_main_context_default();
3973 LOCK_CONTEXT (context);
3974 retval = g_main_context_iterate (context, may_block, TRUE, G_THREAD_SELF);
3975 UNLOCK_CONTEXT (context);
3977 return retval;
3981 * g_main_loop_new:
3982 * @context: (nullable): a #GMainContext (if %NULL, the default context will be used).
3983 * @is_running: set to %TRUE to indicate that the loop is running. This
3984 * is not very important since calling g_main_loop_run() will set this to
3985 * %TRUE anyway.
3987 * Creates a new #GMainLoop structure.
3989 * Returns: a new #GMainLoop.
3991 GMainLoop *
3992 g_main_loop_new (GMainContext *context,
3993 gboolean is_running)
3995 GMainLoop *loop;
3997 if (!context)
3998 context = g_main_context_default();
4000 g_main_context_ref (context);
4002 loop = g_new0 (GMainLoop, 1);
4003 loop->context = context;
4004 loop->is_running = is_running != FALSE;
4005 loop->ref_count = 1;
4007 TRACE (GLIB_MAIN_LOOP_NEW (loop, context));
4009 return loop;
4013 * g_main_loop_ref:
4014 * @loop: a #GMainLoop
4016 * Increases the reference count on a #GMainLoop object by one.
4018 * Returns: @loop
4020 GMainLoop *
4021 g_main_loop_ref (GMainLoop *loop)
4023 g_return_val_if_fail (loop != NULL, NULL);
4024 g_return_val_if_fail (g_atomic_int_get (&loop->ref_count) > 0, NULL);
4026 g_atomic_int_inc (&loop->ref_count);
4028 return loop;
4032 * g_main_loop_unref:
4033 * @loop: a #GMainLoop
4035 * Decreases the reference count on a #GMainLoop object by one. If
4036 * the result is zero, free the loop and free all associated memory.
4038 void
4039 g_main_loop_unref (GMainLoop *loop)
4041 g_return_if_fail (loop != NULL);
4042 g_return_if_fail (g_atomic_int_get (&loop->ref_count) > 0);
4044 if (!g_atomic_int_dec_and_test (&loop->ref_count))
4045 return;
4047 g_main_context_unref (loop->context);
4048 g_free (loop);
4052 * g_main_loop_run:
4053 * @loop: a #GMainLoop
4055 * Runs a main loop until g_main_loop_quit() is called on the loop.
4056 * If this is called for the thread of the loop's #GMainContext,
4057 * it will process events from the loop, otherwise it will
4058 * simply wait.
4060 void
4061 g_main_loop_run (GMainLoop *loop)
4063 GThread *self = G_THREAD_SELF;
4065 g_return_if_fail (loop != NULL);
4066 g_return_if_fail (g_atomic_int_get (&loop->ref_count) > 0);
4068 if (!g_main_context_acquire (loop->context))
4070 gboolean got_ownership = FALSE;
4072 /* Another thread owns this context */
4073 LOCK_CONTEXT (loop->context);
4075 g_atomic_int_inc (&loop->ref_count);
4077 if (!loop->is_running)
4078 loop->is_running = TRUE;
4080 while (loop->is_running && !got_ownership)
4081 got_ownership = g_main_context_wait (loop->context,
4082 &loop->context->cond,
4083 &loop->context->mutex);
4085 if (!loop->is_running)
4087 UNLOCK_CONTEXT (loop->context);
4088 if (got_ownership)
4089 g_main_context_release (loop->context);
4090 g_main_loop_unref (loop);
4091 return;
4094 g_assert (got_ownership);
4096 else
4097 LOCK_CONTEXT (loop->context);
4099 if (loop->context->in_check_or_prepare)
4101 g_warning ("g_main_loop_run(): called recursively from within a source's "
4102 "check() or prepare() member, iteration not possible.");
4103 return;
4106 g_atomic_int_inc (&loop->ref_count);
4107 loop->is_running = TRUE;
4108 while (loop->is_running)
4109 g_main_context_iterate (loop->context, TRUE, TRUE, self);
4111 UNLOCK_CONTEXT (loop->context);
4113 g_main_context_release (loop->context);
4115 g_main_loop_unref (loop);
4119 * g_main_loop_quit:
4120 * @loop: a #GMainLoop
4122 * Stops a #GMainLoop from running. Any calls to g_main_loop_run()
4123 * for the loop will return.
4125 * Note that sources that have already been dispatched when
4126 * g_main_loop_quit() is called will still be executed.
4128 void
4129 g_main_loop_quit (GMainLoop *loop)
4131 g_return_if_fail (loop != NULL);
4132 g_return_if_fail (g_atomic_int_get (&loop->ref_count) > 0);
4134 LOCK_CONTEXT (loop->context);
4135 loop->is_running = FALSE;
4136 g_wakeup_signal (loop->context->wakeup);
4138 g_cond_broadcast (&loop->context->cond);
4140 UNLOCK_CONTEXT (loop->context);
4142 TRACE (GLIB_MAIN_LOOP_QUIT (loop));
4146 * g_main_loop_is_running:
4147 * @loop: a #GMainLoop.
4149 * Checks to see if the main loop is currently being run via g_main_loop_run().
4151 * Returns: %TRUE if the mainloop is currently being run.
4153 gboolean
4154 g_main_loop_is_running (GMainLoop *loop)
4156 g_return_val_if_fail (loop != NULL, FALSE);
4157 g_return_val_if_fail (g_atomic_int_get (&loop->ref_count) > 0, FALSE);
4159 return loop->is_running;
4163 * g_main_loop_get_context:
4164 * @loop: a #GMainLoop.
4166 * Returns the #GMainContext of @loop.
4168 * Returns: (transfer none): the #GMainContext of @loop
4170 GMainContext *
4171 g_main_loop_get_context (GMainLoop *loop)
4173 g_return_val_if_fail (loop != NULL, NULL);
4174 g_return_val_if_fail (g_atomic_int_get (&loop->ref_count) > 0, NULL);
4176 return loop->context;
4179 /* HOLDS: context's lock */
4180 static void
4181 g_main_context_poll (GMainContext *context,
4182 gint timeout,
4183 gint priority,
4184 GPollFD *fds,
4185 gint n_fds)
4187 #ifdef G_MAIN_POLL_DEBUG
4188 GTimer *poll_timer;
4189 GPollRec *pollrec;
4190 gint i;
4191 #endif
4193 GPollFunc poll_func;
4195 if (n_fds || timeout != 0)
4197 int ret, errsv;
4199 #ifdef G_MAIN_POLL_DEBUG
4200 poll_timer = NULL;
4201 if (_g_main_poll_debug)
4203 g_print ("polling context=%p n=%d timeout=%d\n",
4204 context, n_fds, timeout);
4205 poll_timer = g_timer_new ();
4207 #endif
4209 LOCK_CONTEXT (context);
4211 poll_func = context->poll_func;
4213 UNLOCK_CONTEXT (context);
4214 ret = (*poll_func) (fds, n_fds, timeout);
4215 errsv = errno;
4216 if (ret < 0 && errsv != EINTR)
4218 #ifndef G_OS_WIN32
4219 g_warning ("poll(2) failed due to: %s.",
4220 g_strerror (errsv));
4221 #else
4222 /* If g_poll () returns -1, it has already called g_warning() */
4223 #endif
4226 #ifdef G_MAIN_POLL_DEBUG
4227 if (_g_main_poll_debug)
4229 LOCK_CONTEXT (context);
4231 g_print ("g_main_poll(%d) timeout: %d - elapsed %12.10f seconds",
4232 n_fds,
4233 timeout,
4234 g_timer_elapsed (poll_timer, NULL));
4235 g_timer_destroy (poll_timer);
4236 pollrec = context->poll_records;
4238 while (pollrec != NULL)
4240 i = 0;
4241 while (i < n_fds)
4243 if (fds[i].fd == pollrec->fd->fd &&
4244 pollrec->fd->events &&
4245 fds[i].revents)
4247 g_print (" [" G_POLLFD_FORMAT " :", fds[i].fd);
4248 if (fds[i].revents & G_IO_IN)
4249 g_print ("i");
4250 if (fds[i].revents & G_IO_OUT)
4251 g_print ("o");
4252 if (fds[i].revents & G_IO_PRI)
4253 g_print ("p");
4254 if (fds[i].revents & G_IO_ERR)
4255 g_print ("e");
4256 if (fds[i].revents & G_IO_HUP)
4257 g_print ("h");
4258 if (fds[i].revents & G_IO_NVAL)
4259 g_print ("n");
4260 g_print ("]");
4262 i++;
4264 pollrec = pollrec->next;
4266 g_print ("\n");
4268 UNLOCK_CONTEXT (context);
4270 #endif
4271 } /* if (n_fds || timeout != 0) */
4275 * g_main_context_add_poll:
4276 * @context: (nullable): a #GMainContext (or %NULL for the default context)
4277 * @fd: a #GPollFD structure holding information about a file
4278 * descriptor to watch.
4279 * @priority: the priority for this file descriptor which should be
4280 * the same as the priority used for g_source_attach() to ensure that the
4281 * file descriptor is polled whenever the results may be needed.
4283 * Adds a file descriptor to the set of file descriptors polled for
4284 * this context. This will very seldom be used directly. Instead
4285 * a typical event source will use g_source_add_unix_fd() instead.
4287 void
4288 g_main_context_add_poll (GMainContext *context,
4289 GPollFD *fd,
4290 gint priority)
4292 if (!context)
4293 context = g_main_context_default ();
4295 g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
4296 g_return_if_fail (fd);
4298 LOCK_CONTEXT (context);
4299 g_main_context_add_poll_unlocked (context, priority, fd);
4300 UNLOCK_CONTEXT (context);
4303 /* HOLDS: main_loop_lock */
4304 static void
4305 g_main_context_add_poll_unlocked (GMainContext *context,
4306 gint priority,
4307 GPollFD *fd)
4309 GPollRec *prevrec, *nextrec;
4310 GPollRec *newrec = g_slice_new (GPollRec);
4312 /* This file descriptor may be checked before we ever poll */
4313 fd->revents = 0;
4314 newrec->fd = fd;
4315 newrec->priority = priority;
4317 prevrec = NULL;
4318 nextrec = context->poll_records;
4319 while (nextrec)
4321 if (nextrec->fd->fd > fd->fd)
4322 break;
4323 prevrec = nextrec;
4324 nextrec = nextrec->next;
4327 if (prevrec)
4328 prevrec->next = newrec;
4329 else
4330 context->poll_records = newrec;
4332 newrec->prev = prevrec;
4333 newrec->next = nextrec;
4335 if (nextrec)
4336 nextrec->prev = newrec;
4338 context->n_poll_records++;
4340 context->poll_changed = TRUE;
4342 /* Now wake up the main loop if it is waiting in the poll() */
4343 conditional_wakeup (context);
4347 * g_main_context_remove_poll:
4348 * @context:a #GMainContext
4349 * @fd: a #GPollFD descriptor previously added with g_main_context_add_poll()
4351 * Removes file descriptor from the set of file descriptors to be
4352 * polled for a particular context.
4354 void
4355 g_main_context_remove_poll (GMainContext *context,
4356 GPollFD *fd)
4358 if (!context)
4359 context = g_main_context_default ();
4361 g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
4362 g_return_if_fail (fd);
4364 LOCK_CONTEXT (context);
4365 g_main_context_remove_poll_unlocked (context, fd);
4366 UNLOCK_CONTEXT (context);
4369 static void
4370 g_main_context_remove_poll_unlocked (GMainContext *context,
4371 GPollFD *fd)
4373 GPollRec *pollrec, *prevrec, *nextrec;
4375 prevrec = NULL;
4376 pollrec = context->poll_records;
4378 while (pollrec)
4380 nextrec = pollrec->next;
4381 if (pollrec->fd == fd)
4383 if (prevrec != NULL)
4384 prevrec->next = nextrec;
4385 else
4386 context->poll_records = nextrec;
4388 if (nextrec != NULL)
4389 nextrec->prev = prevrec;
4391 g_slice_free (GPollRec, pollrec);
4393 context->n_poll_records--;
4394 break;
4396 prevrec = pollrec;
4397 pollrec = nextrec;
4400 context->poll_changed = TRUE;
4402 /* Now wake up the main loop if it is waiting in the poll() */
4403 conditional_wakeup (context);
4407 * g_source_get_current_time:
4408 * @source: a #GSource
4409 * @timeval: #GTimeVal structure in which to store current time.
4411 * This function ignores @source and is otherwise the same as
4412 * g_get_current_time().
4414 * Deprecated: 2.28: use g_source_get_time() instead
4416 void
4417 g_source_get_current_time (GSource *source,
4418 GTimeVal *timeval)
4420 g_get_current_time (timeval);
4424 * g_source_get_time:
4425 * @source: a #GSource
4427 * Gets the time to be used when checking this source. The advantage of
4428 * calling this function over calling g_get_monotonic_time() directly is
4429 * that when checking multiple sources, GLib can cache a single value
4430 * instead of having to repeatedly get the system monotonic time.
4432 * The time here is the system monotonic time, if available, or some
4433 * other reasonable alternative otherwise. See g_get_monotonic_time().
4435 * Returns: the monotonic time in microseconds
4437 * Since: 2.28
4439 gint64
4440 g_source_get_time (GSource *source)
4442 GMainContext *context;
4443 gint64 result;
4445 g_return_val_if_fail (source->context != NULL, 0);
4447 context = source->context;
4449 LOCK_CONTEXT (context);
4451 if (!context->time_is_fresh)
4453 context->time = g_get_monotonic_time ();
4454 context->time_is_fresh = TRUE;
4457 result = context->time;
4459 UNLOCK_CONTEXT (context);
4461 return result;
4465 * g_main_context_set_poll_func:
4466 * @context: a #GMainContext
4467 * @func: the function to call to poll all file descriptors
4469 * Sets the function to use to handle polling of file descriptors. It
4470 * will be used instead of the poll() system call
4471 * (or GLib's replacement function, which is used where
4472 * poll() isn't available).
4474 * This function could possibly be used to integrate the GLib event
4475 * loop with an external event loop.
4477 void
4478 g_main_context_set_poll_func (GMainContext *context,
4479 GPollFunc func)
4481 if (!context)
4482 context = g_main_context_default ();
4484 g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
4486 LOCK_CONTEXT (context);
4488 if (func)
4489 context->poll_func = func;
4490 else
4491 context->poll_func = g_poll;
4493 UNLOCK_CONTEXT (context);
4497 * g_main_context_get_poll_func:
4498 * @context: a #GMainContext
4500 * Gets the poll function set by g_main_context_set_poll_func().
4502 * Returns: the poll function
4504 GPollFunc
4505 g_main_context_get_poll_func (GMainContext *context)
4507 GPollFunc result;
4509 if (!context)
4510 context = g_main_context_default ();
4512 g_return_val_if_fail (g_atomic_int_get (&context->ref_count) > 0, NULL);
4514 LOCK_CONTEXT (context);
4515 result = context->poll_func;
4516 UNLOCK_CONTEXT (context);
4518 return result;
4522 * g_main_context_wakeup:
4523 * @context: a #GMainContext
4525 * If @context is currently blocking in g_main_context_iteration()
4526 * waiting for a source to become ready, cause it to stop blocking
4527 * and return. Otherwise, cause the next invocation of
4528 * g_main_context_iteration() to return without blocking.
4530 * This API is useful for low-level control over #GMainContext; for
4531 * example, integrating it with main loop implementations such as
4532 * #GMainLoop.
4534 * Another related use for this function is when implementing a main
4535 * loop with a termination condition, computed from multiple threads:
4537 * |[<!-- language="C" -->
4538 * #define NUM_TASKS 10
4539 * static volatile gint tasks_remaining = NUM_TASKS;
4540 * ...
4542 * while (g_atomic_int_get (&tasks_remaining) != 0)
4543 * g_main_context_iteration (NULL, TRUE);
4544 * ]|
4546 * Then in a thread:
4547 * |[<!-- language="C" -->
4548 * perform_work();
4550 * if (g_atomic_int_dec_and_test (&tasks_remaining))
4551 * g_main_context_wakeup (NULL);
4552 * ]|
4554 void
4555 g_main_context_wakeup (GMainContext *context)
4557 if (!context)
4558 context = g_main_context_default ();
4560 g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
4562 TRACE (GLIB_MAIN_CONTEXT_WAKEUP (context));
4564 g_wakeup_signal (context->wakeup);
4568 * g_main_context_is_owner:
4569 * @context: a #GMainContext
4571 * Determines whether this thread holds the (recursive)
4572 * ownership of this #GMainContext. This is useful to
4573 * know before waiting on another thread that may be
4574 * blocking to get ownership of @context.
4576 * Returns: %TRUE if current thread is owner of @context.
4578 * Since: 2.10
4580 gboolean
4581 g_main_context_is_owner (GMainContext *context)
4583 gboolean is_owner;
4585 if (!context)
4586 context = g_main_context_default ();
4588 LOCK_CONTEXT (context);
4589 is_owner = context->owner == G_THREAD_SELF;
4590 UNLOCK_CONTEXT (context);
4592 return is_owner;
4595 /* Timeouts */
4597 static void
4598 g_timeout_set_expiration (GTimeoutSource *timeout_source,
4599 gint64 current_time)
4601 gint64 expiration;
4603 expiration = current_time + (guint64) timeout_source->interval * 1000;
4605 if (timeout_source->seconds)
4607 gint64 remainder;
4608 static gint timer_perturb = -1;
4610 if (timer_perturb == -1)
4613 * we want a per machine/session unique 'random' value; try the dbus
4614 * address first, that has a UUID in it. If there is no dbus, use the
4615 * hostname for hashing.
4617 const char *session_bus_address = g_getenv ("DBUS_SESSION_BUS_ADDRESS");
4618 if (!session_bus_address)
4619 session_bus_address = g_getenv ("HOSTNAME");
4620 if (session_bus_address)
4621 timer_perturb = ABS ((gint) g_str_hash (session_bus_address)) % 1000000;
4622 else
4623 timer_perturb = 0;
4626 /* We want the microseconds part of the timeout to land on the
4627 * 'timer_perturb' mark, but we need to make sure we don't try to
4628 * set the timeout in the past. We do this by ensuring that we
4629 * always only *increase* the expiration time by adding a full
4630 * second in the case that the microsecond portion decreases.
4632 expiration -= timer_perturb;
4634 remainder = expiration % 1000000;
4635 if (remainder >= 1000000/4)
4636 expiration += 1000000;
4638 expiration -= remainder;
4639 expiration += timer_perturb;
4642 g_source_set_ready_time ((GSource *) timeout_source, expiration);
4645 static gboolean
4646 g_timeout_dispatch (GSource *source,
4647 GSourceFunc callback,
4648 gpointer user_data)
4650 GTimeoutSource *timeout_source = (GTimeoutSource *)source;
4651 gboolean again;
4653 if (!callback)
4655 g_warning ("Timeout source dispatched without callback\n"
4656 "You must call g_source_set_callback().");
4657 return FALSE;
4660 again = callback (user_data);
4662 TRACE (GLIB_TIMEOUT_DISPATCH (source, source->context, callback, user_data, again));
4664 if (again)
4665 g_timeout_set_expiration (timeout_source, g_source_get_time (source));
4667 return again;
4671 * g_timeout_source_new:
4672 * @interval: the timeout interval in milliseconds.
4674 * Creates a new timeout source.
4676 * The source will not initially be associated with any #GMainContext
4677 * and must be added to one with g_source_attach() before it will be
4678 * executed.
4680 * The interval given is in terms of monotonic time, not wall clock
4681 * time. See g_get_monotonic_time().
4683 * Returns: the newly-created timeout source
4685 GSource *
4686 g_timeout_source_new (guint interval)
4688 GSource *source = g_source_new (&g_timeout_funcs, sizeof (GTimeoutSource));
4689 GTimeoutSource *timeout_source = (GTimeoutSource *)source;
4691 timeout_source->interval = interval;
4692 g_timeout_set_expiration (timeout_source, g_get_monotonic_time ());
4694 return source;
4698 * g_timeout_source_new_seconds:
4699 * @interval: the timeout interval in seconds
4701 * Creates a new timeout source.
4703 * The source will not initially be associated with any #GMainContext
4704 * and must be added to one with g_source_attach() before it will be
4705 * executed.
4707 * The scheduling granularity/accuracy of this timeout source will be
4708 * in seconds.
4710 * The interval given in terms of monotonic time, not wall clock time.
4711 * See g_get_monotonic_time().
4713 * Returns: the newly-created timeout source
4715 * Since: 2.14
4717 GSource *
4718 g_timeout_source_new_seconds (guint interval)
4720 GSource *source = g_source_new (&g_timeout_funcs, sizeof (GTimeoutSource));
4721 GTimeoutSource *timeout_source = (GTimeoutSource *)source;
4723 timeout_source->interval = 1000 * interval;
4724 timeout_source->seconds = TRUE;
4726 g_timeout_set_expiration (timeout_source, g_get_monotonic_time ());
4728 return source;
4733 * g_timeout_add_full: (rename-to g_timeout_add)
4734 * @priority: the priority of the timeout source. Typically this will be in
4735 * the range between #G_PRIORITY_DEFAULT and #G_PRIORITY_HIGH.
4736 * @interval: the time between calls to the function, in milliseconds
4737 * (1/1000ths of a second)
4738 * @function: function to call
4739 * @data: data to pass to @function
4740 * @notify: (nullable): function to call when the timeout is removed, or %NULL
4742 * Sets a function to be called at regular intervals, with the given
4743 * priority. The function is called repeatedly until it returns
4744 * %FALSE, at which point the timeout is automatically destroyed and
4745 * the function will not be called again. The @notify function is
4746 * called when the timeout is destroyed. The first call to the
4747 * function will be at the end of the first @interval.
4749 * Note that timeout functions may be delayed, due to the processing of other
4750 * event sources. Thus they should not be relied on for precise timing.
4751 * After each call to the timeout function, the time of the next
4752 * timeout is recalculated based on the current time and the given interval
4753 * (it does not try to 'catch up' time lost in delays).
4755 * See [memory management of sources][mainloop-memory-management] for details
4756 * on how to handle the return value and memory management of @data.
4758 * This internally creates a main loop source using g_timeout_source_new()
4759 * and attaches it to the global #GMainContext using g_source_attach(), so
4760 * the callback will be invoked in whichever thread is running that main
4761 * context. You can do these steps manually if you need greater control or to
4762 * use a custom main context.
4764 * The interval given in terms of monotonic time, not wall clock time.
4765 * See g_get_monotonic_time().
4767 * Returns: the ID (greater than 0) of the event source.
4769 guint
4770 g_timeout_add_full (gint priority,
4771 guint interval,
4772 GSourceFunc function,
4773 gpointer data,
4774 GDestroyNotify notify)
4776 GSource *source;
4777 guint id;
4779 g_return_val_if_fail (function != NULL, 0);
4781 source = g_timeout_source_new (interval);
4783 if (priority != G_PRIORITY_DEFAULT)
4784 g_source_set_priority (source, priority);
4786 g_source_set_callback (source, function, data, notify);
4787 id = g_source_attach (source, NULL);
4789 TRACE (GLIB_TIMEOUT_ADD (source, g_main_context_default (), id, priority, interval, function, data));
4791 g_source_unref (source);
4793 return id;
4797 * g_timeout_add:
4798 * @interval: the time between calls to the function, in milliseconds
4799 * (1/1000ths of a second)
4800 * @function: function to call
4801 * @data: data to pass to @function
4803 * Sets a function to be called at regular intervals, with the default
4804 * priority, #G_PRIORITY_DEFAULT. The function is called repeatedly
4805 * until it returns %FALSE, at which point the timeout is automatically
4806 * destroyed and the function will not be called again. The first call
4807 * to the function will be at the end of the first @interval.
4809 * Note that timeout functions may be delayed, due to the processing of other
4810 * event sources. Thus they should not be relied on for precise timing.
4811 * After each call to the timeout function, the time of the next
4812 * timeout is recalculated based on the current time and the given interval
4813 * (it does not try to 'catch up' time lost in delays).
4815 * See [memory management of sources][mainloop-memory-management] for details
4816 * on how to handle the return value and memory management of @data.
4818 * If you want to have a timer in the "seconds" range and do not care
4819 * about the exact time of the first call of the timer, use the
4820 * g_timeout_add_seconds() function; this function allows for more
4821 * optimizations and more efficient system power usage.
4823 * This internally creates a main loop source using g_timeout_source_new()
4824 * and attaches it to the global #GMainContext using g_source_attach(), so
4825 * the callback will be invoked in whichever thread is running that main
4826 * context. You can do these steps manually if you need greater control or to
4827 * use a custom main context.
4829 * The interval given is in terms of monotonic time, not wall clock
4830 * time. See g_get_monotonic_time().
4832 * Returns: the ID (greater than 0) of the event source.
4834 guint
4835 g_timeout_add (guint32 interval,
4836 GSourceFunc function,
4837 gpointer data)
4839 return g_timeout_add_full (G_PRIORITY_DEFAULT,
4840 interval, function, data, NULL);
4844 * g_timeout_add_seconds_full: (rename-to g_timeout_add_seconds)
4845 * @priority: the priority of the timeout source. Typically this will be in
4846 * the range between #G_PRIORITY_DEFAULT and #G_PRIORITY_HIGH.
4847 * @interval: the time between calls to the function, in seconds
4848 * @function: function to call
4849 * @data: data to pass to @function
4850 * @notify: (nullable): function to call when the timeout is removed, or %NULL
4852 * Sets a function to be called at regular intervals, with @priority.
4853 * The function is called repeatedly until it returns %FALSE, at which
4854 * point the timeout is automatically destroyed and the function will
4855 * not be called again.
4857 * Unlike g_timeout_add(), this function operates at whole second granularity.
4858 * The initial starting point of the timer is determined by the implementation
4859 * and the implementation is expected to group multiple timers together so that
4860 * they fire all at the same time.
4861 * To allow this grouping, the @interval to the first timer is rounded
4862 * and can deviate up to one second from the specified interval.
4863 * Subsequent timer iterations will generally run at the specified interval.
4865 * Note that timeout functions may be delayed, due to the processing of other
4866 * event sources. Thus they should not be relied on for precise timing.
4867 * After each call to the timeout function, the time of the next
4868 * timeout is recalculated based on the current time and the given @interval
4870 * See [memory management of sources][mainloop-memory-management] for details
4871 * on how to handle the return value and memory management of @data.
4873 * If you want timing more precise than whole seconds, use g_timeout_add()
4874 * instead.
4876 * The grouping of timers to fire at the same time results in a more power
4877 * and CPU efficient behavior so if your timer is in multiples of seconds
4878 * and you don't require the first timer exactly one second from now, the
4879 * use of g_timeout_add_seconds() is preferred over g_timeout_add().
4881 * This internally creates a main loop source using
4882 * g_timeout_source_new_seconds() and attaches it to the main loop context
4883 * using g_source_attach(). You can do these steps manually if you need
4884 * greater control.
4886 * The interval given is in terms of monotonic time, not wall clock
4887 * time. See g_get_monotonic_time().
4889 * Returns: the ID (greater than 0) of the event source.
4891 * Since: 2.14
4893 guint
4894 g_timeout_add_seconds_full (gint priority,
4895 guint32 interval,
4896 GSourceFunc function,
4897 gpointer data,
4898 GDestroyNotify notify)
4900 GSource *source;
4901 guint id;
4903 g_return_val_if_fail (function != NULL, 0);
4905 source = g_timeout_source_new_seconds (interval);
4907 if (priority != G_PRIORITY_DEFAULT)
4908 g_source_set_priority (source, priority);
4910 g_source_set_callback (source, function, data, notify);
4911 id = g_source_attach (source, NULL);
4912 g_source_unref (source);
4914 return id;
4918 * g_timeout_add_seconds:
4919 * @interval: the time between calls to the function, in seconds
4920 * @function: function to call
4921 * @data: data to pass to @function
4923 * Sets a function to be called at regular intervals with the default
4924 * priority, #G_PRIORITY_DEFAULT. The function is called repeatedly until
4925 * it returns %FALSE, at which point the timeout is automatically destroyed
4926 * and the function will not be called again.
4928 * This internally creates a main loop source using
4929 * g_timeout_source_new_seconds() and attaches it to the main loop context
4930 * using g_source_attach(). You can do these steps manually if you need
4931 * greater control. Also see g_timeout_add_seconds_full().
4933 * Note that the first call of the timer may not be precise for timeouts
4934 * of one second. If you need finer precision and have such a timeout,
4935 * you may want to use g_timeout_add() instead.
4937 * See [memory management of sources][mainloop-memory-management] for details
4938 * on how to handle the return value and memory management of @data.
4940 * The interval given is in terms of monotonic time, not wall clock
4941 * time. See g_get_monotonic_time().
4943 * Returns: the ID (greater than 0) of the event source.
4945 * Since: 2.14
4947 guint
4948 g_timeout_add_seconds (guint interval,
4949 GSourceFunc function,
4950 gpointer data)
4952 g_return_val_if_fail (function != NULL, 0);
4954 return g_timeout_add_seconds_full (G_PRIORITY_DEFAULT, interval, function, data, NULL);
4957 /* Child watch functions */
4959 #ifdef G_OS_WIN32
4961 static gboolean
4962 g_child_watch_prepare (GSource *source,
4963 gint *timeout)
4965 *timeout = -1;
4966 return FALSE;
4969 static gboolean
4970 g_child_watch_check (GSource *source)
4972 GChildWatchSource *child_watch_source;
4973 gboolean child_exited;
4975 child_watch_source = (GChildWatchSource *) source;
4977 child_exited = child_watch_source->poll.revents & G_IO_IN;
4979 if (child_exited)
4981 DWORD child_status;
4984 * Note: We do _not_ check for the special value of STILL_ACTIVE
4985 * since we know that the process has exited and doing so runs into
4986 * problems if the child process "happens to return STILL_ACTIVE(259)"
4987 * as Microsoft's Platform SDK puts it.
4989 if (!GetExitCodeProcess (child_watch_source->pid, &child_status))
4991 gchar *emsg = g_win32_error_message (GetLastError ());
4992 g_warning (G_STRLOC ": GetExitCodeProcess() failed: %s", emsg);
4993 g_free (emsg);
4995 child_watch_source->child_status = -1;
4997 else
4998 child_watch_source->child_status = child_status;
5001 return child_exited;
5004 static void
5005 g_child_watch_finalize (GSource *source)
5009 #else /* G_OS_WIN32 */
5011 static void
5012 wake_source (GSource *source)
5014 GMainContext *context;
5016 /* This should be thread-safe:
5018 * - if the source is currently being added to a context, that
5019 * context will be woken up anyway
5021 * - if the source is currently being destroyed, we simply need not
5022 * to crash:
5024 * - the memory for the source will remain valid until after the
5025 * source finalize function was called (which would remove the
5026 * source from the global list which we are currently holding the
5027 * lock for)
5029 * - the GMainContext will either be NULL or point to a live
5030 * GMainContext
5032 * - the GMainContext will remain valid since we hold the
5033 * main_context_list lock
5035 * Since we are holding a lot of locks here, don't try to enter any
5036 * more GMainContext functions for fear of dealock -- just hit the
5037 * GWakeup and run. Even if that's safe now, it could easily become
5038 * unsafe with some very minor changes in the future, and signal
5039 * handling is not the most well-tested codepath.
5041 G_LOCK(main_context_list);
5042 context = source->context;
5043 if (context)
5044 g_wakeup_signal (context->wakeup);
5045 G_UNLOCK(main_context_list);
5048 static void
5049 dispatch_unix_signals_unlocked (void)
5051 gboolean pending[NSIG];
5052 GSList *node;
5053 gint i;
5055 /* clear this first in case another one arrives while we're processing */
5056 any_unix_signal_pending = FALSE;
5058 /* We atomically test/clear the bit from the global array in case
5059 * other signals arrive while we are dispatching.
5061 * We then can safely use our own array below without worrying about
5062 * races.
5064 for (i = 0; i < NSIG; i++)
5066 /* Be very careful with (the volatile) unix_signal_pending.
5068 * We must ensure that it's not possible that we clear it without
5069 * handling the signal. We therefore must ensure that our pending
5070 * array has a field set (ie: we will do something about the
5071 * signal) before we clear the item in unix_signal_pending.
5073 * Note specifically: we must check _our_ array.
5075 pending[i] = unix_signal_pending[i];
5076 if (pending[i])
5077 unix_signal_pending[i] = FALSE;
5080 /* handle GChildWatchSource instances */
5081 if (pending[SIGCHLD])
5083 /* The only way we can do this is to scan all of the children.
5085 * The docs promise that we will not reap children that we are not
5086 * explicitly watching, so that ties our hands from calling
5087 * waitpid(-1). We also can't use siginfo's si_pid field since if
5088 * multiple SIGCHLD arrive at the same time, one of them can be
5089 * dropped (since a given UNIX signal can only be pending once).
5091 for (node = unix_child_watches; node; node = node->next)
5093 GChildWatchSource *source = node->data;
5095 if (!source->child_exited)
5097 pid_t pid;
5100 g_assert (source->pid > 0);
5102 pid = waitpid (source->pid, &source->child_status, WNOHANG);
5103 if (pid > 0)
5105 source->child_exited = TRUE;
5106 wake_source ((GSource *) source);
5108 else if (pid == -1 && errno == ECHILD)
5110 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.");
5111 source->child_exited = TRUE;
5112 source->child_status = 0;
5113 wake_source ((GSource *) source);
5116 while (pid == -1 && errno == EINTR);
5121 /* handle GUnixSignalWatchSource instances */
5122 for (node = unix_signal_watches; node; node = node->next)
5124 GUnixSignalWatchSource *source = node->data;
5126 if (!source->pending)
5128 if (pending[source->signum])
5130 source->pending = TRUE;
5132 wake_source ((GSource *) source);
5139 static void
5140 dispatch_unix_signals (void)
5142 G_LOCK(unix_signal_lock);
5143 dispatch_unix_signals_unlocked ();
5144 G_UNLOCK(unix_signal_lock);
5147 static gboolean
5148 g_child_watch_prepare (GSource *source,
5149 gint *timeout)
5151 GChildWatchSource *child_watch_source;
5153 child_watch_source = (GChildWatchSource *) source;
5155 return child_watch_source->child_exited;
5158 static gboolean
5159 g_child_watch_check (GSource *source)
5161 GChildWatchSource *child_watch_source;
5163 child_watch_source = (GChildWatchSource *) source;
5165 return child_watch_source->child_exited;
5168 static gboolean
5169 g_unix_signal_watch_prepare (GSource *source,
5170 gint *timeout)
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_check (GSource *source)
5182 GUnixSignalWatchSource *unix_signal_source;
5184 unix_signal_source = (GUnixSignalWatchSource *) source;
5186 return unix_signal_source->pending;
5189 static gboolean
5190 g_unix_signal_watch_dispatch (GSource *source,
5191 GSourceFunc callback,
5192 gpointer user_data)
5194 GUnixSignalWatchSource *unix_signal_source;
5195 gboolean again;
5197 unix_signal_source = (GUnixSignalWatchSource *) source;
5199 if (!callback)
5201 g_warning ("Unix signal source dispatched without callback\n"
5202 "You must call g_source_set_callback().");
5203 return FALSE;
5206 again = (callback) (user_data);
5208 unix_signal_source->pending = FALSE;
5210 return again;
5213 static void
5214 ref_unix_signal_handler_unlocked (int signum)
5216 /* Ensure we have the worker context */
5217 g_get_worker_context ();
5218 unix_signal_refcount[signum]++;
5219 if (unix_signal_refcount[signum] == 1)
5221 struct sigaction action;
5222 action.sa_handler = g_unix_signal_handler;
5223 sigemptyset (&action.sa_mask);
5224 #ifdef SA_RESTART
5225 action.sa_flags = SA_RESTART | SA_NOCLDSTOP;
5226 #else
5227 action.sa_flags = SA_NOCLDSTOP;
5228 #endif
5229 sigaction (signum, &action, NULL);
5233 static void
5234 unref_unix_signal_handler_unlocked (int signum)
5236 unix_signal_refcount[signum]--;
5237 if (unix_signal_refcount[signum] == 0)
5239 struct sigaction action;
5240 memset (&action, 0, sizeof (action));
5241 action.sa_handler = SIG_DFL;
5242 sigemptyset (&action.sa_mask);
5243 sigaction (signum, &action, NULL);
5247 GSource *
5248 _g_main_create_unix_signal_watch (int signum)
5250 GSource *source;
5251 GUnixSignalWatchSource *unix_signal_source;
5253 source = g_source_new (&g_unix_signal_funcs, sizeof (GUnixSignalWatchSource));
5254 unix_signal_source = (GUnixSignalWatchSource *) source;
5256 unix_signal_source->signum = signum;
5257 unix_signal_source->pending = FALSE;
5259 G_LOCK (unix_signal_lock);
5260 ref_unix_signal_handler_unlocked (signum);
5261 unix_signal_watches = g_slist_prepend (unix_signal_watches, unix_signal_source);
5262 dispatch_unix_signals_unlocked ();
5263 G_UNLOCK (unix_signal_lock);
5265 return source;
5268 static void
5269 g_unix_signal_watch_finalize (GSource *source)
5271 GUnixSignalWatchSource *unix_signal_source;
5273 unix_signal_source = (GUnixSignalWatchSource *) source;
5275 G_LOCK (unix_signal_lock);
5276 unref_unix_signal_handler_unlocked (unix_signal_source->signum);
5277 unix_signal_watches = g_slist_remove (unix_signal_watches, source);
5278 G_UNLOCK (unix_signal_lock);
5281 static void
5282 g_child_watch_finalize (GSource *source)
5284 G_LOCK (unix_signal_lock);
5285 unix_child_watches = g_slist_remove (unix_child_watches, source);
5286 unref_unix_signal_handler_unlocked (SIGCHLD);
5287 G_UNLOCK (unix_signal_lock);
5290 #endif /* G_OS_WIN32 */
5292 static gboolean
5293 g_child_watch_dispatch (GSource *source,
5294 GSourceFunc callback,
5295 gpointer user_data)
5297 GChildWatchSource *child_watch_source;
5298 GChildWatchFunc child_watch_callback = (GChildWatchFunc) callback;
5300 child_watch_source = (GChildWatchSource *) source;
5302 if (!callback)
5304 g_warning ("Child watch source dispatched without callback\n"
5305 "You must call g_source_set_callback().");
5306 return FALSE;
5309 (child_watch_callback) (child_watch_source->pid, child_watch_source->child_status, user_data);
5311 /* We never keep a child watch source around as the child is gone */
5312 return FALSE;
5315 #ifndef G_OS_WIN32
5317 static void
5318 g_unix_signal_handler (int signum)
5320 gint saved_errno = errno;
5322 unix_signal_pending[signum] = TRUE;
5323 any_unix_signal_pending = TRUE;
5325 g_wakeup_signal (glib_worker_context->wakeup);
5327 errno = saved_errno;
5330 #endif /* !G_OS_WIN32 */
5333 * g_child_watch_source_new:
5334 * @pid: process to watch. On POSIX the positive pid of a child process. On
5335 * Windows a handle for a process (which doesn't have to be a child).
5337 * Creates a new child_watch source.
5339 * The source will not initially be associated with any #GMainContext
5340 * and must be added to one with g_source_attach() before it will be
5341 * executed.
5343 * Note that child watch sources can only be used in conjunction with
5344 * `g_spawn...` when the %G_SPAWN_DO_NOT_REAP_CHILD flag is used.
5346 * Note that on platforms where #GPid must be explicitly closed
5347 * (see g_spawn_close_pid()) @pid must not be closed while the
5348 * source is still active. Typically, you will want to call
5349 * g_spawn_close_pid() in the callback function for the source.
5351 * On POSIX platforms, the following restrictions apply to this API
5352 * due to limitations in POSIX process interfaces:
5354 * * @pid must be a child of this process
5355 * * @pid must be positive
5356 * * the application must not call `waitpid` with a non-positive
5357 * first argument, for instance in another thread
5358 * * the application must not wait for @pid to exit by any other
5359 * mechanism, including `waitpid(pid, ...)` or a second child-watch
5360 * source for the same @pid
5361 * * the application must not ignore SIGCHILD
5363 * If any of those conditions are not met, this and related APIs will
5364 * not work correctly. This can often be diagnosed via a GLib warning
5365 * stating that `ECHILD` was received by `waitpid`.
5367 * Calling `waitpid` for specific processes other than @pid remains a
5368 * valid thing to do.
5370 * Returns: the newly-created child watch source
5372 * Since: 2.4
5374 GSource *
5375 g_child_watch_source_new (GPid pid)
5377 GSource *source;
5378 GChildWatchSource *child_watch_source;
5380 #ifndef G_OS_WIN32
5381 g_return_val_if_fail (pid > 0, NULL);
5382 #endif
5384 source = g_source_new (&g_child_watch_funcs, sizeof (GChildWatchSource));
5385 child_watch_source = (GChildWatchSource *)source;
5387 child_watch_source->pid = pid;
5389 #ifdef G_OS_WIN32
5390 child_watch_source->poll.fd = (gintptr) pid;
5391 child_watch_source->poll.events = G_IO_IN;
5393 g_source_add_poll (source, &child_watch_source->poll);
5394 #else /* G_OS_WIN32 */
5395 G_LOCK (unix_signal_lock);
5396 ref_unix_signal_handler_unlocked (SIGCHLD);
5397 unix_child_watches = g_slist_prepend (unix_child_watches, child_watch_source);
5398 if (waitpid (pid, &child_watch_source->child_status, WNOHANG) > 0)
5399 child_watch_source->child_exited = TRUE;
5400 G_UNLOCK (unix_signal_lock);
5401 #endif /* G_OS_WIN32 */
5403 return source;
5407 * g_child_watch_add_full: (rename-to g_child_watch_add)
5408 * @priority: the priority of the idle source. Typically this will be in the
5409 * range between #G_PRIORITY_DEFAULT_IDLE and #G_PRIORITY_HIGH_IDLE.
5410 * @pid: process to watch. On POSIX the positive pid of a child process. On
5411 * Windows a handle for a process (which doesn't have to be a child).
5412 * @function: function to call
5413 * @data: data to pass to @function
5414 * @notify: (nullable): function to call when the idle is removed, or %NULL
5416 * Sets a function to be called when the child indicated by @pid
5417 * exits, at the priority @priority.
5419 * If you obtain @pid from g_spawn_async() or g_spawn_async_with_pipes()
5420 * you will need to pass #G_SPAWN_DO_NOT_REAP_CHILD as flag to
5421 * the spawn function for the child watching to work.
5423 * In many programs, you will want to call g_spawn_check_exit_status()
5424 * in the callback to determine whether or not the child exited
5425 * successfully.
5427 * Also, note that on platforms where #GPid must be explicitly closed
5428 * (see g_spawn_close_pid()) @pid must not be closed while the source
5429 * is still active. Typically, you should invoke g_spawn_close_pid()
5430 * in the callback function for the source.
5432 * GLib supports only a single callback per process id.
5433 * On POSIX platforms, the same restrictions mentioned for
5434 * g_child_watch_source_new() apply to this function.
5436 * This internally creates a main loop source using
5437 * g_child_watch_source_new() and attaches it to the main loop context
5438 * using g_source_attach(). You can do these steps manually if you
5439 * need greater control.
5441 * Returns: the ID (greater than 0) of the event source.
5443 * Since: 2.4
5445 guint
5446 g_child_watch_add_full (gint priority,
5447 GPid pid,
5448 GChildWatchFunc function,
5449 gpointer data,
5450 GDestroyNotify notify)
5452 GSource *source;
5453 guint id;
5455 g_return_val_if_fail (function != NULL, 0);
5456 #ifndef G_OS_WIN32
5457 g_return_val_if_fail (pid > 0, 0);
5458 #endif
5460 source = g_child_watch_source_new (pid);
5462 if (priority != G_PRIORITY_DEFAULT)
5463 g_source_set_priority (source, priority);
5465 g_source_set_callback (source, (GSourceFunc) function, data, notify);
5466 id = g_source_attach (source, NULL);
5467 g_source_unref (source);
5469 return id;
5473 * g_child_watch_add:
5474 * @pid: process id to watch. On POSIX the positive pid of a child
5475 * process. On Windows a handle for a process (which doesn't have to be
5476 * a child).
5477 * @function: function to call
5478 * @data: data to pass to @function
5480 * Sets a function to be called when the child indicated by @pid
5481 * exits, at a default priority, #G_PRIORITY_DEFAULT.
5483 * If you obtain @pid from g_spawn_async() or g_spawn_async_with_pipes()
5484 * you will need to pass #G_SPAWN_DO_NOT_REAP_CHILD as flag to
5485 * the spawn function for the child watching to work.
5487 * Note that on platforms where #GPid must be explicitly closed
5488 * (see g_spawn_close_pid()) @pid must not be closed while the
5489 * source is still active. Typically, you will want to call
5490 * g_spawn_close_pid() in the callback function for the source.
5492 * GLib supports only a single callback per process id.
5493 * On POSIX platforms, the same restrictions mentioned for
5494 * g_child_watch_source_new() apply to this function.
5496 * This internally creates a main loop source using
5497 * g_child_watch_source_new() and attaches it to the main loop context
5498 * using g_source_attach(). You can do these steps manually if you
5499 * need greater control.
5501 * Returns: the ID (greater than 0) of the event source.
5503 * Since: 2.4
5505 guint
5506 g_child_watch_add (GPid pid,
5507 GChildWatchFunc function,
5508 gpointer data)
5510 return g_child_watch_add_full (G_PRIORITY_DEFAULT, pid, function, data, NULL);
5514 /* Idle functions */
5516 static gboolean
5517 g_idle_prepare (GSource *source,
5518 gint *timeout)
5520 *timeout = 0;
5522 return TRUE;
5525 static gboolean
5526 g_idle_check (GSource *source)
5528 return TRUE;
5531 static gboolean
5532 g_idle_dispatch (GSource *source,
5533 GSourceFunc callback,
5534 gpointer user_data)
5536 gboolean again;
5538 if (!callback)
5540 g_warning ("Idle source dispatched without callback\n"
5541 "You must call g_source_set_callback().");
5542 return FALSE;
5545 again = callback (user_data);
5547 TRACE (GLIB_IDLE_DISPATCH (source, source->context, callback, user_data, again));
5549 return again;
5553 * g_idle_source_new:
5555 * Creates a new idle source.
5557 * The source will not initially be associated with any #GMainContext
5558 * and must be added to one with g_source_attach() before it will be
5559 * executed. Note that the default priority for idle sources is
5560 * %G_PRIORITY_DEFAULT_IDLE, as compared to other sources which
5561 * have a default priority of %G_PRIORITY_DEFAULT.
5563 * Returns: the newly-created idle source
5565 GSource *
5566 g_idle_source_new (void)
5568 GSource *source;
5570 source = g_source_new (&g_idle_funcs, sizeof (GSource));
5571 g_source_set_priority (source, G_PRIORITY_DEFAULT_IDLE);
5573 return source;
5577 * g_idle_add_full: (rename-to g_idle_add)
5578 * @priority: the priority of the idle source. Typically this will be in the
5579 * range between #G_PRIORITY_DEFAULT_IDLE and #G_PRIORITY_HIGH_IDLE.
5580 * @function: function to call
5581 * @data: data to pass to @function
5582 * @notify: (nullable): function to call when the idle is removed, or %NULL
5584 * Adds a function to be called whenever there are no higher priority
5585 * events pending. If the function returns %FALSE it is automatically
5586 * removed from the list of event sources and will not be called again.
5588 * See [memory management of sources][mainloop-memory-management] for details
5589 * on how to handle the return value and memory management of @data.
5591 * This internally creates a main loop source using g_idle_source_new()
5592 * and attaches it to the global #GMainContext using g_source_attach(), so
5593 * the callback will be invoked in whichever thread is running that main
5594 * context. You can do these steps manually if you need greater control or to
5595 * use a custom main context.
5597 * Returns: the ID (greater than 0) of the event source.
5599 guint
5600 g_idle_add_full (gint priority,
5601 GSourceFunc function,
5602 gpointer data,
5603 GDestroyNotify notify)
5605 GSource *source;
5606 guint id;
5608 g_return_val_if_fail (function != NULL, 0);
5610 source = g_idle_source_new ();
5612 if (priority != G_PRIORITY_DEFAULT_IDLE)
5613 g_source_set_priority (source, priority);
5615 g_source_set_callback (source, function, data, notify);
5616 id = g_source_attach (source, NULL);
5618 TRACE (GLIB_IDLE_ADD (source, g_main_context_default (), id, priority, function, data));
5620 g_source_unref (source);
5622 return id;
5626 * g_idle_add:
5627 * @function: function to call
5628 * @data: data to pass to @function.
5630 * Adds a function to be called whenever there are no higher priority
5631 * events pending to the default main loop. The function is given the
5632 * default idle priority, #G_PRIORITY_DEFAULT_IDLE. If the function
5633 * returns %FALSE it is automatically removed from the list of event
5634 * sources and will not be called again.
5636 * See [memory management of sources][mainloop-memory-management] for details
5637 * on how to handle the return value and memory management of @data.
5639 * This internally creates a main loop source using g_idle_source_new()
5640 * and attaches it to the global #GMainContext using g_source_attach(), so
5641 * the callback will be invoked in whichever thread is running that main
5642 * context. You can do these steps manually if you need greater control or to
5643 * use a custom main context.
5645 * Returns: the ID (greater than 0) of the event source.
5647 guint
5648 g_idle_add (GSourceFunc function,
5649 gpointer data)
5651 return g_idle_add_full (G_PRIORITY_DEFAULT_IDLE, function, data, NULL);
5655 * g_idle_remove_by_data:
5656 * @data: the data for the idle source's callback.
5658 * Removes the idle function with the given data.
5660 * Returns: %TRUE if an idle source was found and removed.
5662 gboolean
5663 g_idle_remove_by_data (gpointer data)
5665 return g_source_remove_by_funcs_user_data (&g_idle_funcs, data);
5669 * g_main_context_invoke:
5670 * @context: (nullable): a #GMainContext, or %NULL
5671 * @function: function to call
5672 * @data: data to pass to @function
5674 * Invokes a function in such a way that @context is owned during the
5675 * invocation of @function.
5677 * If @context is %NULL then the global default main context — as
5678 * returned by g_main_context_default() — is used.
5680 * If @context is owned by the current thread, @function is called
5681 * directly. Otherwise, if @context is the thread-default main context
5682 * of the current thread and g_main_context_acquire() succeeds, then
5683 * @function is called and g_main_context_release() is called
5684 * afterwards.
5686 * In any other case, an idle source is created to call @function and
5687 * that source is attached to @context (presumably to be run in another
5688 * thread). The idle source is attached with #G_PRIORITY_DEFAULT
5689 * priority. If you want a different priority, use
5690 * g_main_context_invoke_full().
5692 * Note that, as with normal idle functions, @function should probably
5693 * return %FALSE. If it returns %TRUE, it will be continuously run in a
5694 * loop (and may prevent this call from returning).
5696 * Since: 2.28
5698 void
5699 g_main_context_invoke (GMainContext *context,
5700 GSourceFunc function,
5701 gpointer data)
5703 g_main_context_invoke_full (context,
5704 G_PRIORITY_DEFAULT,
5705 function, data, NULL);
5709 * g_main_context_invoke_full:
5710 * @context: (nullable): a #GMainContext, or %NULL
5711 * @priority: the priority at which to run @function
5712 * @function: function to call
5713 * @data: data to pass to @function
5714 * @notify: (nullable): a function to call when @data is no longer in use, or %NULL.
5716 * Invokes a function in such a way that @context is owned during the
5717 * invocation of @function.
5719 * This function is the same as g_main_context_invoke() except that it
5720 * lets you specify the priority in case @function ends up being
5721 * scheduled as an idle and also lets you give a #GDestroyNotify for @data.
5723 * @notify should not assume that it is called from any particular
5724 * thread or with any particular context acquired.
5726 * Since: 2.28
5728 void
5729 g_main_context_invoke_full (GMainContext *context,
5730 gint priority,
5731 GSourceFunc function,
5732 gpointer data,
5733 GDestroyNotify notify)
5735 g_return_if_fail (function != NULL);
5737 if (!context)
5738 context = g_main_context_default ();
5740 if (g_main_context_is_owner (context))
5742 while (function (data));
5743 if (notify != NULL)
5744 notify (data);
5747 else
5749 GMainContext *thread_default;
5751 thread_default = g_main_context_get_thread_default ();
5753 if (!thread_default)
5754 thread_default = g_main_context_default ();
5756 if (thread_default == context && g_main_context_acquire (context))
5758 while (function (data));
5760 g_main_context_release (context);
5762 if (notify != NULL)
5763 notify (data);
5765 else
5767 GSource *source;
5769 source = g_idle_source_new ();
5770 g_source_set_priority (source, priority);
5771 g_source_set_callback (source, function, data, notify);
5772 g_source_attach (source, context);
5773 g_source_unref (source);
5778 static gpointer
5779 glib_worker_main (gpointer data)
5781 while (TRUE)
5783 g_main_context_iteration (glib_worker_context, TRUE);
5785 #ifdef G_OS_UNIX
5786 if (any_unix_signal_pending)
5787 dispatch_unix_signals ();
5788 #endif
5791 return NULL; /* worst GCC warning message ever... */
5794 GMainContext *
5795 g_get_worker_context (void)
5797 static gsize initialised;
5799 if (g_once_init_enter (&initialised))
5801 /* mask all signals in the worker thread */
5802 #ifdef G_OS_UNIX
5803 sigset_t prev_mask;
5804 sigset_t all;
5806 sigfillset (&all);
5807 pthread_sigmask (SIG_SETMASK, &all, &prev_mask);
5808 #endif
5809 glib_worker_context = g_main_context_new ();
5810 g_thread_new ("gmain", glib_worker_main, NULL);
5811 #ifdef G_OS_UNIX
5812 pthread_sigmask (SIG_SETMASK, &prev_mask, NULL);
5813 #endif
5814 g_once_init_leave (&initialised, TRUE);
5817 return glib_worker_context;