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 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/.
33 #include "glibconfig.h"
35 /* Uncomment the next line (and the corresponding line in gpoll.c) to
36 * enable debugging printouts if the environment variable
37 * G_MAIN_POLL_DEBUG is set to some value.
39 /* #define G_MAIN_POLL_DEBUG */
42 /* Always enable debugging printout on Windows, as it is more often
45 #define G_MAIN_POLL_DEBUG
49 #include "glib-unix.h"
52 #include <sys/eventfd.h>
57 #include <sys/types.h>
60 #ifdef HAVE_SYS_TIME_H
62 #endif /* HAVE_SYS_TIME_H */
65 #endif /* G_OS_UNIX */
72 #endif /* G_OS_WIN32 */
74 #ifdef HAVE_MACH_MACH_TIME_H
75 #include <mach/mach_time.h>
78 #include "glib_trace.h"
83 #include "giochannel.h"
87 #include "gstrfuncs.h"
88 #include "gtestutils.h"
94 #ifdef G_MAIN_POLL_DEBUG
99 #include "gmain-internal.h"
100 #include "glib-init.h"
101 #include "glib-private.h"
105 * @title: The Main Event Loop
106 * @short_description: manages all available sources of events
108 * The main event loop manages all the available sources of events for
109 * GLib and GTK+ applications. These events can come from any number of
110 * different types of sources such as file descriptors (plain files,
111 * pipes or sockets) and timeouts. New types of event sources can also
112 * be added using g_source_attach().
114 * To allow multiple independent sets of sources to be handled in
115 * different threads, each source is associated with a #GMainContext.
116 * A GMainContext can only be running in a single thread, but
117 * sources can be added to it and removed from it from other threads.
119 * Each event source is assigned a priority. The default priority,
120 * #G_PRIORITY_DEFAULT, is 0. Values less than 0 denote higher priorities.
121 * Values greater than 0 denote lower priorities. Events from high priority
122 * sources are always processed before events from lower priority sources.
124 * Idle functions can also be added, and assigned a priority. These will
125 * be run whenever no events with a higher priority are ready to be processed.
127 * The #GMainLoop data type represents a main event loop. A GMainLoop is
128 * created with g_main_loop_new(). After adding the initial event sources,
129 * g_main_loop_run() is called. This continuously checks for new events from
130 * each of the event sources and dispatches them. Finally, the processing of
131 * an event from one of the sources leads to a call to g_main_loop_quit() to
132 * exit the main loop, and g_main_loop_run() returns.
134 * It is possible to create new instances of #GMainLoop recursively.
135 * This is often used in GTK+ applications when showing modal dialog
136 * boxes. Note that event sources are associated with a particular
137 * #GMainContext, and will be checked and dispatched for all main
138 * loops associated with that GMainContext.
140 * GTK+ contains wrappers of some of these functions, e.g. gtk_main(),
141 * gtk_main_quit() and gtk_events_pending().
143 * ## Creating new source types
145 * One of the unusual features of the #GMainLoop functionality
146 * is that new types of event source can be created and used in
147 * addition to the builtin type of event source. A new event source
148 * type is used for handling GDK events. A new source type is created
149 * by "deriving" from the #GSource structure. The derived type of
150 * source is represented by a structure that has the #GSource structure
151 * as a first element, and other elements specific to the new source
152 * type. To create an instance of the new source type, call
153 * g_source_new() passing in the size of the derived structure and
154 * a table of functions. These #GSourceFuncs determine the behavior of
155 * the new source type.
157 * New source types basically interact with the main context
158 * in two ways. Their prepare function in #GSourceFuncs can set a timeout
159 * to determine the maximum amount of time that the main loop will sleep
160 * before checking the source again. In addition, or as well, the source
161 * can add file descriptors to the set that the main context checks using
162 * g_source_add_poll().
164 * ## Customizing the main loop iteration
166 * Single iterations of a #GMainContext can be run with
167 * g_main_context_iteration(). In some cases, more detailed control
168 * of exactly how the details of the main loop work is desired, for
169 * instance, when integrating the #GMainLoop with an external main loop.
170 * In such cases, you can call the component functions of
171 * g_main_context_iteration() directly. These functions are
172 * g_main_context_prepare(), g_main_context_query(),
173 * g_main_context_check() and g_main_context_dispatch().
175 * ## State of a Main Context # {#mainloop-states}
177 * The operation of these functions can best be seen in terms
178 * of a state diagram, as shown in this image.
180 * ![](mainloop-states.gif)
182 * On UNIX, the GLib mainloop is incompatible with fork(). Any program
183 * using the mainloop must either exec() or exit() from the child
184 * without returning to the mainloop.
189 typedef struct _GTimeoutSource GTimeoutSource;
190 typedef struct _GChildWatchSource GChildWatchSource;
191 typedef struct _GUnixSignalWatchSource GUnixSignalWatchSource;
192 typedef struct _GPollRec GPollRec;
193 typedef struct _GSourceCallback GSourceCallback;
197 G_SOURCE_READY = 1 << G_HOOK_FLAG_USER_SHIFT,
198 G_SOURCE_CAN_RECURSE = 1 << (G_HOOK_FLAG_USER_SHIFT + 1),
199 G_SOURCE_BLOCKED = 1 << (G_HOOK_FLAG_USER_SHIFT + 2)
202 typedef struct _GSourceList GSourceList;
206 GSource *head, *tail;
210 typedef struct _GMainWaiter GMainWaiter;
218 typedef struct _GMainDispatch GMainDispatch;
220 struct _GMainDispatch
226 #ifdef G_MAIN_POLL_DEBUG
227 gboolean _g_main_poll_debug = FALSE;
232 /* The following lock is used for both the list of sources
233 * and the list of poll records
243 GHashTable *sources; /* guint -> GSource */
245 GPtrArray *pending_dispatches;
246 gint timeout; /* Timeout for current iteration */
250 gint in_check_or_prepare;
252 GPollRec *poll_records, *poll_records_tail;
253 guint n_poll_records;
254 GPollFD *cached_poll_array;
255 guint cached_poll_array_size;
261 /* Flag indicating whether the set of fd's changed during a poll */
262 gboolean poll_changed;
267 gboolean time_is_fresh;
270 struct _GSourceCallback
275 GDestroyNotify notify;
280 GMainContext *context;
285 struct _GTimeoutSource
292 struct _GChildWatchSource
299 #else /* G_OS_WIN32 */
300 gboolean child_exited;
301 #endif /* G_OS_WIN32 */
304 struct _GUnixSignalWatchSource
319 struct _GSourcePrivate
321 GSList *child_sources;
322 GSource *parent_source;
326 /* This is currently only used on UNIX, but we always declare it (and
327 * let it remain empty on Windows) to avoid #ifdef all over the place.
332 typedef struct _GSourceIter
334 GMainContext *context;
340 #define LOCK_CONTEXT(context) g_mutex_lock (&context->mutex)
341 #define UNLOCK_CONTEXT(context) g_mutex_unlock (&context->mutex)
342 #define G_THREAD_SELF g_thread_self ()
344 #define SOURCE_DESTROYED(source) (((source)->flags & G_HOOK_FLAG_ACTIVE) == 0)
345 #define SOURCE_BLOCKED(source) (((source)->flags & G_SOURCE_BLOCKED) != 0)
347 #define SOURCE_UNREF(source, context) \
349 if ((source)->ref_count > 1) \
350 (source)->ref_count--; \
352 g_source_unref_internal ((source), (context), TRUE); \
356 /* Forward declarations */
358 static void g_source_unref_internal (GSource *source,
359 GMainContext *context,
361 static void g_source_destroy_internal (GSource *source,
362 GMainContext *context,
364 static void g_source_set_priority_unlocked (GSource *source,
365 GMainContext *context,
367 static void g_child_source_remove_internal (GSource *child_source,
368 GMainContext *context);
370 static void g_main_context_poll (GMainContext *context,
375 static void g_main_context_add_poll_unlocked (GMainContext *context,
378 static void g_main_context_remove_poll_unlocked (GMainContext *context,
381 static void g_source_iter_init (GSourceIter *iter,
382 GMainContext *context,
383 gboolean may_modify);
384 static gboolean g_source_iter_next (GSourceIter *iter,
386 static void g_source_iter_clear (GSourceIter *iter);
388 static gboolean g_timeout_dispatch (GSource *source,
389 GSourceFunc callback,
391 static gboolean g_child_watch_prepare (GSource *source,
393 static gboolean g_child_watch_check (GSource *source);
394 static gboolean g_child_watch_dispatch (GSource *source,
395 GSourceFunc callback,
397 static void g_child_watch_finalize (GSource *source);
399 static void g_unix_signal_handler (int signum);
400 static gboolean g_unix_signal_watch_prepare (GSource *source,
402 static gboolean g_unix_signal_watch_check (GSource *source);
403 static gboolean g_unix_signal_watch_dispatch (GSource *source,
404 GSourceFunc callback,
406 static void g_unix_signal_watch_finalize (GSource *source);
408 static gboolean g_idle_prepare (GSource *source,
410 static gboolean g_idle_check (GSource *source);
411 static gboolean g_idle_dispatch (GSource *source,
412 GSourceFunc callback,
415 static void block_source (GSource *source);
417 static GMainContext *glib_worker_context;
419 G_LOCK_DEFINE_STATIC (main_loop);
420 static GMainContext *default_main_context;
425 /* UNIX signals work by marking one of these variables then waking the
426 * worker context to check on them and dispatch accordingly.
428 #ifdef HAVE_SIG_ATOMIC_T
429 static volatile sig_atomic_t unix_signal_pending[NSIG];
430 static volatile sig_atomic_t any_unix_signal_pending;
432 static volatile int unix_signal_pending[NSIG];
433 static volatile int any_unix_signal_pending;
435 static volatile guint unix_signal_refcount[NSIG];
437 /* Guards all the data below */
438 G_LOCK_DEFINE_STATIC (unix_signal_lock);
439 static GSList *unix_signal_watches;
440 static GSList *unix_child_watches;
442 GSourceFuncs g_unix_signal_funcs =
444 g_unix_signal_watch_prepare,
445 g_unix_signal_watch_check,
446 g_unix_signal_watch_dispatch,
447 g_unix_signal_watch_finalize
449 #endif /* !G_OS_WIN32 */
450 G_LOCK_DEFINE_STATIC (main_context_list);
451 static GSList *main_context_list = NULL;
453 GSourceFuncs g_timeout_funcs =
461 GSourceFuncs g_child_watch_funcs =
463 g_child_watch_prepare,
465 g_child_watch_dispatch,
466 g_child_watch_finalize
469 GSourceFuncs g_idle_funcs =
478 * g_main_context_ref:
479 * @context: a #GMainContext
481 * Increases the reference count on a #GMainContext object by one.
483 * Returns: the @context that was passed in (since 2.6)
486 g_main_context_ref (GMainContext *context)
488 g_return_val_if_fail (context != NULL, NULL);
489 g_return_val_if_fail (g_atomic_int_get (&context->ref_count) > 0, NULL);
491 g_atomic_int_inc (&context->ref_count);
497 poll_rec_list_free (GMainContext *context,
500 g_slice_free_chain (GPollRec, list, next);
504 * g_main_context_unref:
505 * @context: a #GMainContext
507 * Decreases the reference count on a #GMainContext object by one. If
508 * the result is zero, free the context and free all associated memory.
511 g_main_context_unref (GMainContext *context)
519 g_return_if_fail (context != NULL);
520 g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
522 if (!g_atomic_int_dec_and_test (&context->ref_count))
525 G_LOCK (main_context_list);
526 main_context_list = g_slist_remove (main_context_list, context);
527 G_UNLOCK (main_context_list);
529 /* Free pending dispatches */
530 for (i = 0; i < context->pending_dispatches->len; i++)
531 g_source_unref_internal (context->pending_dispatches->pdata[i], context, FALSE);
533 /* g_source_iter_next() assumes the context is locked. */
534 LOCK_CONTEXT (context);
535 g_source_iter_init (&iter, context, TRUE);
536 while (g_source_iter_next (&iter, &source))
538 source->context = NULL;
539 g_source_destroy_internal (source, context, TRUE);
541 UNLOCK_CONTEXT (context);
543 for (sl_iter = context->source_lists; sl_iter; sl_iter = sl_iter->next)
545 list = sl_iter->data;
546 g_slice_free (GSourceList, list);
548 g_list_free (context->source_lists);
550 g_hash_table_destroy (context->sources);
552 g_mutex_clear (&context->mutex);
554 g_ptr_array_free (context->pending_dispatches, TRUE);
555 g_free (context->cached_poll_array);
557 poll_rec_list_free (context, context->poll_records);
559 g_wakeup_free (context->wakeup);
560 g_cond_clear (&context->cond);
565 /* Helper function used by mainloop/overflow test.
568 g_main_context_new_with_next_id (guint next_id)
570 GMainContext *ret = g_main_context_new ();
572 ret->next_id = next_id;
578 * g_main_context_new:
580 * Creates a new #GMainContext structure.
582 * Returns: the new #GMainContext
585 g_main_context_new (void)
587 static gsize initialised;
588 GMainContext *context;
590 if (g_once_init_enter (&initialised))
592 #ifdef G_MAIN_POLL_DEBUG
593 if (getenv ("G_MAIN_POLL_DEBUG") != NULL)
594 _g_main_poll_debug = TRUE;
597 g_once_init_leave (&initialised, TRUE);
600 context = g_new0 (GMainContext, 1);
602 g_mutex_init (&context->mutex);
603 g_cond_init (&context->cond);
605 context->sources = g_hash_table_new (NULL, NULL);
606 context->owner = NULL;
607 context->waiters = NULL;
609 context->ref_count = 1;
611 context->next_id = 1;
613 context->source_lists = NULL;
615 context->poll_func = g_poll;
617 context->cached_poll_array = NULL;
618 context->cached_poll_array_size = 0;
620 context->pending_dispatches = g_ptr_array_new ();
622 context->time_is_fresh = FALSE;
624 context->wakeup = g_wakeup_new ();
625 g_wakeup_get_pollfd (context->wakeup, &context->wake_up_rec);
626 g_main_context_add_poll_unlocked (context, 0, &context->wake_up_rec);
628 G_LOCK (main_context_list);
629 main_context_list = g_slist_append (main_context_list, context);
631 #ifdef G_MAIN_POLL_DEBUG
632 if (_g_main_poll_debug)
633 g_print ("created context=%p\n", context);
636 G_UNLOCK (main_context_list);
642 * g_main_context_default:
644 * Returns the global default main context. This is the main context
645 * used for main loop functions when a main loop is not explicitly
646 * specified, and corresponds to the "main" main loop. See also
647 * g_main_context_get_thread_default().
649 * Returns: (transfer none): the global default main context.
652 g_main_context_default (void)
658 if (!default_main_context)
660 default_main_context = g_main_context_new ();
661 #ifdef G_MAIN_POLL_DEBUG
662 if (_g_main_poll_debug)
663 g_print ("default context=%p\n", default_main_context);
667 G_UNLOCK (main_loop);
669 return default_main_context;
673 free_context (gpointer data)
675 GMainContext *context = data;
677 g_main_context_release (context);
679 g_main_context_unref (context);
683 free_context_stack (gpointer data)
685 g_queue_free_full((GQueue *) data, (GDestroyNotify) free_context);
688 static GPrivate thread_context_stack = G_PRIVATE_INIT (free_context_stack);
691 * g_main_context_push_thread_default:
692 * @context: (allow-none): a #GMainContext, or %NULL for the global default context
694 * Acquires @context and sets it as the thread-default context for the
695 * current thread. This will cause certain asynchronous operations
696 * (such as most [gio][gio]-based I/O) which are
697 * started in this thread to run under @context and deliver their
698 * results to its main loop, rather than running under the global
699 * default context in the main thread. Note that calling this function
700 * changes the context returned by g_main_context_get_thread_default(),
701 * not the one returned by g_main_context_default(), so it does not affect
702 * the context used by functions like g_idle_add().
704 * Normally you would call this function shortly after creating a new
705 * thread, passing it a #GMainContext which will be run by a
706 * #GMainLoop in that thread, to set a new default context for all
707 * async operations in that thread. (In this case, you don't need to
708 * ever call g_main_context_pop_thread_default().) In some cases
709 * however, you may want to schedule a single operation in a
710 * non-default context, or temporarily use a non-default context in
711 * the main thread. In that case, you can wrap the call to the
712 * asynchronous operation inside a
713 * g_main_context_push_thread_default() /
714 * g_main_context_pop_thread_default() pair, but it is up to you to
715 * ensure that no other asynchronous operations accidentally get
716 * started while the non-default context is active.
718 * Beware that libraries that predate this function may not correctly
719 * handle being used from a thread with a thread-default context. Eg,
720 * see g_file_supports_thread_contexts().
725 g_main_context_push_thread_default (GMainContext *context)
728 gboolean acquired_context;
730 acquired_context = g_main_context_acquire (context);
731 g_return_if_fail (acquired_context);
733 if (context == g_main_context_default ())
736 g_main_context_ref (context);
738 stack = g_private_get (&thread_context_stack);
741 stack = g_queue_new ();
742 g_private_set (&thread_context_stack, stack);
745 g_queue_push_head (stack, context);
749 * g_main_context_pop_thread_default:
750 * @context: (allow-none): a #GMainContext object, or %NULL
752 * Pops @context off the thread-default context stack (verifying that
753 * it was on the top of the stack).
758 g_main_context_pop_thread_default (GMainContext *context)
762 if (context == g_main_context_default ())
765 stack = g_private_get (&thread_context_stack);
767 g_return_if_fail (stack != NULL);
768 g_return_if_fail (g_queue_peek_head (stack) == context);
770 g_queue_pop_head (stack);
772 g_main_context_release (context);
774 g_main_context_unref (context);
778 * g_main_context_get_thread_default:
780 * Gets the thread-default #GMainContext for this thread. Asynchronous
781 * operations that want to be able to be run in contexts other than
782 * the default one should call this method or
783 * g_main_context_ref_thread_default() to get a #GMainContext to add
784 * their #GSources to. (Note that even in single-threaded
785 * programs applications may sometimes want to temporarily push a
786 * non-default context, so it is not safe to assume that this will
787 * always return %NULL if you are running in the default thread.)
789 * If you need to hold a reference on the context, use
790 * g_main_context_ref_thread_default() instead.
792 * Returns: (transfer none): the thread-default #GMainContext, or
793 * %NULL if the thread-default context is the global default context.
798 g_main_context_get_thread_default (void)
802 stack = g_private_get (&thread_context_stack);
804 return g_queue_peek_head (stack);
810 * g_main_context_ref_thread_default:
812 * Gets the thread-default #GMainContext for this thread, as with
813 * g_main_context_get_thread_default(), but also adds a reference to
814 * it with g_main_context_ref(). In addition, unlike
815 * g_main_context_get_thread_default(), if the thread-default context
816 * is the global default context, this will return that #GMainContext
817 * (with a ref added to it) rather than returning %NULL.
819 * Returns: (transfer full): the thread-default #GMainContext. Unref
820 * with g_main_context_unref() when you are done with it.
825 g_main_context_ref_thread_default (void)
827 GMainContext *context;
829 context = g_main_context_get_thread_default ();
831 context = g_main_context_default ();
832 return g_main_context_ref (context);
835 /* Hooks for adding to the main loop */
839 * @source_funcs: structure containing functions that implement
840 * the sources behavior.
841 * @struct_size: size of the #GSource structure to create.
843 * Creates a new #GSource structure. The size is specified to
844 * allow creating structures derived from #GSource that contain
845 * additional data. The size passed in must be at least
846 * `sizeof (GSource)`.
848 * The source will not initially be associated with any #GMainContext
849 * and must be added to one with g_source_attach() before it will be
852 * Returns: the newly-created #GSource.
855 g_source_new (GSourceFuncs *source_funcs,
860 g_return_val_if_fail (source_funcs != NULL, NULL);
861 g_return_val_if_fail (struct_size >= sizeof (GSource), NULL);
863 source = (GSource*) g_malloc0 (struct_size);
864 source->priv = g_slice_new0 (GSourcePrivate);
865 source->source_funcs = source_funcs;
866 source->ref_count = 1;
868 source->priority = G_PRIORITY_DEFAULT;
870 source->flags = G_HOOK_FLAG_ACTIVE;
872 source->priv->ready_time = -1;
874 /* NULL/0 initialization for all other fields */
879 /* Holds context's lock */
881 g_source_iter_init (GSourceIter *iter,
882 GMainContext *context,
885 iter->context = context;
886 iter->current_list = NULL;
888 iter->may_modify = may_modify;
891 /* Holds context's lock */
893 g_source_iter_next (GSourceIter *iter, GSource **source)
895 GSource *next_source;
898 next_source = iter->source->next;
904 if (iter->current_list)
905 iter->current_list = iter->current_list->next;
907 iter->current_list = iter->context->source_lists;
909 if (iter->current_list)
911 GSourceList *source_list = iter->current_list->data;
913 next_source = source_list->head;
917 /* Note: unreffing iter->source could potentially cause its
918 * GSourceList to be removed from source_lists (if iter->source is
919 * the only source in its list, and it is destroyed), so we have to
920 * keep it reffed until after we advance iter->current_list, above.
923 if (iter->source && iter->may_modify)
924 SOURCE_UNREF (iter->source, iter->context);
925 iter->source = next_source;
926 if (iter->source && iter->may_modify)
927 iter->source->ref_count++;
929 *source = iter->source;
930 return *source != NULL;
933 /* Holds context's lock. Only necessary to call if you broke out of
934 * the g_source_iter_next() loop early.
937 g_source_iter_clear (GSourceIter *iter)
939 if (iter->source && iter->may_modify)
941 SOURCE_UNREF (iter->source, iter->context);
946 /* Holds context's lock
949 find_source_list_for_priority (GMainContext *context,
954 GSourceList *source_list;
957 for (iter = context->source_lists; iter != NULL; last = iter, iter = iter->next)
959 source_list = iter->data;
961 if (source_list->priority == priority)
964 if (source_list->priority > priority)
969 source_list = g_slice_new0 (GSourceList);
970 source_list->priority = priority;
971 context->source_lists = g_list_insert_before (context->source_lists,
981 source_list = g_slice_new0 (GSourceList);
982 source_list->priority = priority;
985 context->source_lists = g_list_append (NULL, source_list);
988 /* This just appends source_list to the end of
989 * context->source_lists without having to walk the list again.
991 last = g_list_append (last, source_list);
996 /* Holds context's lock
999 source_add_to_context (GSource *source,
1000 GMainContext *context)
1002 GSourceList *source_list;
1003 GSource *prev, *next;
1005 source_list = find_source_list_for_priority (context, source->priority, TRUE);
1007 if (source->priv->parent_source)
1009 g_assert (source_list->head != NULL);
1011 /* Put the source immediately before its parent */
1012 prev = source->priv->parent_source->prev;
1013 next = source->priv->parent_source;
1017 prev = source_list->tail;
1021 source->next = next;
1023 next->prev = source;
1025 source_list->tail = source;
1027 source->prev = prev;
1029 prev->next = source;
1031 source_list->head = source;
1034 /* Holds context's lock
1037 source_remove_from_context (GSource *source,
1038 GMainContext *context)
1040 GSourceList *source_list;
1042 source_list = find_source_list_for_priority (context, source->priority, FALSE);
1043 g_return_if_fail (source_list != NULL);
1046 source->prev->next = source->next;
1048 source_list->head = source->next;
1051 source->next->prev = source->prev;
1053 source_list->tail = source->prev;
1055 source->prev = NULL;
1056 source->next = NULL;
1058 if (source_list->head == NULL)
1060 context->source_lists = g_list_remove (context->source_lists, source_list);
1061 g_slice_free (GSourceList, source_list);
1066 g_source_attach_unlocked (GSource *source,
1067 GMainContext *context,
1073 /* The counter may have wrapped, so we must ensure that we do not
1074 * reuse the source id of an existing source.
1077 id = context->next_id++;
1078 while (id == 0 || g_hash_table_contains (context->sources, GUINT_TO_POINTER (id)));
1080 source->context = context;
1081 source->source_id = id;
1082 source->ref_count++;
1084 g_hash_table_insert (context->sources, GUINT_TO_POINTER (id), source);
1086 source_add_to_context (source, context);
1088 if (!SOURCE_BLOCKED (source))
1090 tmp_list = source->poll_fds;
1093 g_main_context_add_poll_unlocked (context, source->priority, tmp_list->data);
1094 tmp_list = tmp_list->next;
1097 for (tmp_list = source->priv->fds; tmp_list; tmp_list = tmp_list->next)
1098 g_main_context_add_poll_unlocked (context, source->priority, tmp_list->data);
1101 tmp_list = source->priv->child_sources;
1104 g_source_attach_unlocked (tmp_list->data, context, FALSE);
1105 tmp_list = tmp_list->next;
1108 /* If another thread has acquired the context, wake it up since it
1109 * might be in poll() right now.
1111 if (do_wakeup && context->owner && context->owner != G_THREAD_SELF)
1112 g_wakeup_signal (context->wakeup);
1114 return source->source_id;
1119 * @source: a #GSource
1120 * @context: (allow-none): a #GMainContext (if %NULL, the default context will be used)
1122 * Adds a #GSource to a @context so that it will be executed within
1123 * that context. Remove it by calling g_source_destroy().
1125 * Returns: the ID (greater than 0) for the source within the
1129 g_source_attach (GSource *source,
1130 GMainContext *context)
1134 g_return_val_if_fail (source->context == NULL, 0);
1135 g_return_val_if_fail (!SOURCE_DESTROYED (source), 0);
1137 TRACE (GLIB_MAIN_SOURCE_ATTACH (g_source_get_name (source)));
1140 context = g_main_context_default ();
1142 LOCK_CONTEXT (context);
1144 result = g_source_attach_unlocked (source, context, TRUE);
1146 UNLOCK_CONTEXT (context);
1152 g_source_destroy_internal (GSource *source,
1153 GMainContext *context,
1156 TRACE (GLIB_MAIN_SOURCE_DESTROY (g_source_get_name (source)));
1159 LOCK_CONTEXT (context);
1161 if (!SOURCE_DESTROYED (source))
1164 gpointer old_cb_data;
1165 GSourceCallbackFuncs *old_cb_funcs;
1167 source->flags &= ~G_HOOK_FLAG_ACTIVE;
1169 old_cb_data = source->callback_data;
1170 old_cb_funcs = source->callback_funcs;
1172 source->callback_data = NULL;
1173 source->callback_funcs = NULL;
1177 UNLOCK_CONTEXT (context);
1178 old_cb_funcs->unref (old_cb_data);
1179 LOCK_CONTEXT (context);
1182 if (!SOURCE_BLOCKED (source))
1184 tmp_list = source->poll_fds;
1187 g_main_context_remove_poll_unlocked (context, tmp_list->data);
1188 tmp_list = tmp_list->next;
1191 for (tmp_list = source->priv->fds; tmp_list; tmp_list = tmp_list->next)
1192 g_main_context_remove_poll_unlocked (context, tmp_list->data);
1195 while (source->priv->child_sources)
1196 g_child_source_remove_internal (source->priv->child_sources->data, context);
1198 if (source->priv->parent_source)
1199 g_child_source_remove_internal (source, context);
1201 g_source_unref_internal (source, context, TRUE);
1205 UNLOCK_CONTEXT (context);
1210 * @source: a #GSource
1212 * Removes a source from its #GMainContext, if any, and mark it as
1213 * destroyed. The source cannot be subsequently added to another
1214 * context. It is safe to call this on sources which have already been
1215 * removed from their context.
1218 g_source_destroy (GSource *source)
1220 GMainContext *context;
1222 g_return_if_fail (source != NULL);
1224 context = source->context;
1227 g_source_destroy_internal (source, context, FALSE);
1229 source->flags &= ~G_HOOK_FLAG_ACTIVE;
1234 * @source: a #GSource
1236 * Returns the numeric ID for a particular source. The ID of a source
1237 * is a positive integer which is unique within a particular main loop
1238 * context. The reverse
1239 * mapping from ID to source is done by g_main_context_find_source_by_id().
1241 * Returns: the ID (greater than 0) for the source
1244 g_source_get_id (GSource *source)
1248 g_return_val_if_fail (source != NULL, 0);
1249 g_return_val_if_fail (source->context != NULL, 0);
1251 LOCK_CONTEXT (source->context);
1252 result = source->source_id;
1253 UNLOCK_CONTEXT (source->context);
1259 * g_source_get_context:
1260 * @source: a #GSource
1262 * Gets the #GMainContext with which the source is associated.
1264 * You can call this on a source that has been destroyed, provided
1265 * that the #GMainContext it was attached to still exists (in which
1266 * case it will return that #GMainContext). In particular, you can
1267 * always call this function on the source returned from
1268 * g_main_current_source(). But calling this function on a source
1269 * whose #GMainContext has been destroyed is an error.
1271 * Returns: (transfer none) (allow-none): the #GMainContext with which the
1272 * source is associated, or %NULL if the context has not
1273 * yet been added to a source.
1276 g_source_get_context (GSource *source)
1278 g_return_val_if_fail (source->context != NULL || !SOURCE_DESTROYED (source), NULL);
1280 return source->context;
1284 * g_source_add_poll:
1285 * @source:a #GSource
1286 * @fd: a #GPollFD structure holding information about a file
1287 * descriptor to watch.
1289 * Adds a file descriptor to the set of file descriptors polled for
1290 * this source. This is usually combined with g_source_new() to add an
1291 * event source. The event source's check function will typically test
1292 * the @revents field in the #GPollFD struct and return %TRUE if events need
1295 * This API is only intended to be used by implementations of #GSource.
1296 * Do not call this API on a #GSource that you did not create.
1298 * Using this API forces the linear scanning of event sources on each
1299 * main loop iteration. Newly-written event sources should try to use
1300 * g_source_add_unix_fd() instead of this API.
1303 g_source_add_poll (GSource *source,
1306 GMainContext *context;
1308 g_return_if_fail (source != NULL);
1309 g_return_if_fail (fd != NULL);
1310 g_return_if_fail (!SOURCE_DESTROYED (source));
1312 context = source->context;
1315 LOCK_CONTEXT (context);
1317 source->poll_fds = g_slist_prepend (source->poll_fds, fd);
1321 if (!SOURCE_BLOCKED (source))
1322 g_main_context_add_poll_unlocked (context, source->priority, fd);
1323 UNLOCK_CONTEXT (context);
1328 * g_source_remove_poll:
1329 * @source:a #GSource
1330 * @fd: a #GPollFD structure previously passed to g_source_add_poll().
1332 * Removes a file descriptor from the set of file descriptors polled for
1335 * This API is only intended to be used by implementations of #GSource.
1336 * Do not call this API on a #GSource that you did not create.
1339 g_source_remove_poll (GSource *source,
1342 GMainContext *context;
1344 g_return_if_fail (source != NULL);
1345 g_return_if_fail (fd != NULL);
1346 g_return_if_fail (!SOURCE_DESTROYED (source));
1348 context = source->context;
1351 LOCK_CONTEXT (context);
1353 source->poll_fds = g_slist_remove (source->poll_fds, fd);
1357 if (!SOURCE_BLOCKED (source))
1358 g_main_context_remove_poll_unlocked (context, fd);
1359 UNLOCK_CONTEXT (context);
1364 * g_source_add_child_source:
1365 * @source:a #GSource
1366 * @child_source: a second #GSource that @source should "poll"
1368 * Adds @child_source to @source as a "polled" source; when @source is
1369 * added to a #GMainContext, @child_source will be automatically added
1370 * with the same priority, when @child_source is triggered, it will
1371 * cause @source to dispatch (in addition to calling its own
1372 * callback), and when @source is destroyed, it will destroy
1373 * @child_source as well. (@source will also still be dispatched if
1374 * its own prepare/check functions indicate that it is ready.)
1376 * If you don't need @child_source to do anything on its own when it
1377 * triggers, you can call g_source_set_dummy_callback() on it to set a
1378 * callback that does nothing (except return %TRUE if appropriate).
1380 * @source will hold a reference on @child_source while @child_source
1381 * is attached to it.
1383 * This API is only intended to be used by implementations of #GSource.
1384 * Do not call this API on a #GSource that you did not create.
1389 g_source_add_child_source (GSource *source,
1390 GSource *child_source)
1392 GMainContext *context;
1394 g_return_if_fail (source != NULL);
1395 g_return_if_fail (child_source != NULL);
1396 g_return_if_fail (!SOURCE_DESTROYED (source));
1397 g_return_if_fail (!SOURCE_DESTROYED (child_source));
1398 g_return_if_fail (child_source->context == NULL);
1399 g_return_if_fail (child_source->priv->parent_source == NULL);
1401 context = source->context;
1404 LOCK_CONTEXT (context);
1406 source->priv->child_sources = g_slist_prepend (source->priv->child_sources,
1407 g_source_ref (child_source));
1408 child_source->priv->parent_source = source;
1409 g_source_set_priority_unlocked (child_source, NULL, source->priority);
1410 if (SOURCE_BLOCKED (source))
1411 block_source (child_source);
1415 g_source_attach_unlocked (child_source, context, TRUE);
1416 UNLOCK_CONTEXT (context);
1421 g_child_source_remove_internal (GSource *child_source,
1422 GMainContext *context)
1424 GSource *parent_source = child_source->priv->parent_source;
1426 parent_source->priv->child_sources =
1427 g_slist_remove (parent_source->priv->child_sources, child_source);
1428 child_source->priv->parent_source = NULL;
1430 g_source_destroy_internal (child_source, context, TRUE);
1431 g_source_unref_internal (child_source, context, TRUE);
1435 * g_source_remove_child_source:
1436 * @source:a #GSource
1437 * @child_source: a #GSource previously passed to
1438 * g_source_add_child_source().
1440 * Detaches @child_source from @source and destroys it.
1442 * This API is only intended to be used by implementations of #GSource.
1443 * Do not call this API on a #GSource that you did not create.
1448 g_source_remove_child_source (GSource *source,
1449 GSource *child_source)
1451 GMainContext *context;
1453 g_return_if_fail (source != NULL);
1454 g_return_if_fail (child_source != NULL);
1455 g_return_if_fail (child_source->priv->parent_source == source);
1456 g_return_if_fail (!SOURCE_DESTROYED (source));
1457 g_return_if_fail (!SOURCE_DESTROYED (child_source));
1459 context = source->context;
1462 LOCK_CONTEXT (context);
1464 g_child_source_remove_internal (child_source, context);
1467 UNLOCK_CONTEXT (context);
1471 * g_source_set_callback_indirect:
1472 * @source: the source
1473 * @callback_data: pointer to callback data "object"
1474 * @callback_funcs: functions for reference counting @callback_data
1475 * and getting the callback and data
1477 * Sets the callback function storing the data as a refcounted callback
1478 * "object". This is used internally. Note that calling
1479 * g_source_set_callback_indirect() assumes
1480 * an initial reference count on @callback_data, and thus
1481 * @callback_funcs->unref will eventually be called once more
1482 * than @callback_funcs->ref.
1485 g_source_set_callback_indirect (GSource *source,
1486 gpointer callback_data,
1487 GSourceCallbackFuncs *callback_funcs)
1489 GMainContext *context;
1490 gpointer old_cb_data;
1491 GSourceCallbackFuncs *old_cb_funcs;
1493 g_return_if_fail (source != NULL);
1494 g_return_if_fail (callback_funcs != NULL || callback_data == NULL);
1496 context = source->context;
1499 LOCK_CONTEXT (context);
1501 old_cb_data = source->callback_data;
1502 old_cb_funcs = source->callback_funcs;
1504 source->callback_data = callback_data;
1505 source->callback_funcs = callback_funcs;
1508 UNLOCK_CONTEXT (context);
1511 old_cb_funcs->unref (old_cb_data);
1515 g_source_callback_ref (gpointer cb_data)
1517 GSourceCallback *callback = cb_data;
1519 callback->ref_count++;
1524 g_source_callback_unref (gpointer cb_data)
1526 GSourceCallback *callback = cb_data;
1528 callback->ref_count--;
1529 if (callback->ref_count == 0)
1531 if (callback->notify)
1532 callback->notify (callback->data);
1538 g_source_callback_get (gpointer cb_data,
1543 GSourceCallback *callback = cb_data;
1545 *func = callback->func;
1546 *data = callback->data;
1549 static GSourceCallbackFuncs g_source_callback_funcs = {
1550 g_source_callback_ref,
1551 g_source_callback_unref,
1552 g_source_callback_get,
1556 * g_source_set_callback:
1557 * @source: the source
1558 * @func: a callback function
1559 * @data: the data to pass to callback function
1560 * @notify: (allow-none): a function to call when @data is no longer in use, or %NULL.
1562 * Sets the callback function for a source. The callback for a source is
1563 * called from the source's dispatch function.
1565 * The exact type of @func depends on the type of source; ie. you
1566 * should not count on @func being called with @data as its first
1569 * Typically, you won't use this function. Instead use functions specific
1570 * to the type of source you are using.
1573 g_source_set_callback (GSource *source,
1576 GDestroyNotify notify)
1578 GSourceCallback *new_callback;
1580 g_return_if_fail (source != NULL);
1582 new_callback = g_new (GSourceCallback, 1);
1584 new_callback->ref_count = 1;
1585 new_callback->func = func;
1586 new_callback->data = data;
1587 new_callback->notify = notify;
1589 g_source_set_callback_indirect (source, new_callback, &g_source_callback_funcs);
1594 * g_source_set_funcs:
1595 * @source: a #GSource
1596 * @funcs: the new #GSourceFuncs
1598 * Sets the source functions (can be used to override
1599 * default implementations) of an unattached source.
1604 g_source_set_funcs (GSource *source,
1605 GSourceFuncs *funcs)
1607 g_return_if_fail (source != NULL);
1608 g_return_if_fail (source->context == NULL);
1609 g_return_if_fail (source->ref_count > 0);
1610 g_return_if_fail (funcs != NULL);
1612 source->source_funcs = funcs;
1616 g_source_set_priority_unlocked (GSource *source,
1617 GMainContext *context,
1622 g_return_if_fail (source->priv->parent_source == NULL ||
1623 source->priv->parent_source->priority == priority);
1627 /* Remove the source from the context's source and then
1628 * add it back after so it is sorted in the correct place
1630 source_remove_from_context (source, source->context);
1633 source->priority = priority;
1637 source_add_to_context (source, source->context);
1639 if (!SOURCE_BLOCKED (source))
1641 tmp_list = source->poll_fds;
1644 g_main_context_remove_poll_unlocked (context, tmp_list->data);
1645 g_main_context_add_poll_unlocked (context, priority, tmp_list->data);
1647 tmp_list = tmp_list->next;
1650 for (tmp_list = source->priv->fds; tmp_list; tmp_list = tmp_list->next)
1652 g_main_context_remove_poll_unlocked (context, tmp_list->data);
1653 g_main_context_add_poll_unlocked (context, priority, tmp_list->data);
1658 if (source->priv->child_sources)
1660 tmp_list = source->priv->child_sources;
1663 g_source_set_priority_unlocked (tmp_list->data, context, priority);
1664 tmp_list = tmp_list->next;
1670 * g_source_set_priority:
1671 * @source: a #GSource
1672 * @priority: the new priority.
1674 * Sets the priority of a source. While the main loop is being run, a
1675 * source will be dispatched if it is ready to be dispatched and no
1676 * sources at a higher (numerically smaller) priority are ready to be
1679 * A child source always has the same priority as its parent. It is not
1680 * permitted to change the priority of a source once it has been added
1681 * as a child of another source.
1684 g_source_set_priority (GSource *source,
1687 GMainContext *context;
1689 g_return_if_fail (source != NULL);
1690 g_return_if_fail (source->priv->parent_source == NULL);
1692 context = source->context;
1695 LOCK_CONTEXT (context);
1696 g_source_set_priority_unlocked (source, context, priority);
1698 UNLOCK_CONTEXT (source->context);
1702 * g_source_get_priority:
1703 * @source: a #GSource
1705 * Gets the priority of a source.
1707 * Returns: the priority of the source
1710 g_source_get_priority (GSource *source)
1712 g_return_val_if_fail (source != NULL, 0);
1714 return source->priority;
1718 * g_source_set_ready_time:
1719 * @source: a #GSource
1720 * @ready_time: the monotonic time at which the source will be ready,
1721 * 0 for "immediately", -1 for "never"
1723 * Sets a #GSource to be dispatched when the given monotonic time is
1724 * reached (or passed). If the monotonic time is in the past (as it
1725 * always will be if @ready_time is 0) then the source will be
1726 * dispatched immediately.
1728 * If @ready_time is -1 then the source is never woken up on the basis
1729 * of the passage of time.
1731 * Dispatching the source does not reset the ready time. You should do
1732 * so yourself, from the source dispatch function.
1734 * Note that if you have a pair of sources where the ready time of one
1735 * suggests that it will be delivered first but the priority for the
1736 * other suggests that it would be delivered first, and the ready time
1737 * for both sources is reached during the same main context iteration
1738 * then the order of dispatch is undefined.
1740 * This API is only intended to be used by implementations of #GSource.
1741 * Do not call this API on a #GSource that you did not create.
1746 g_source_set_ready_time (GSource *source,
1749 GMainContext *context;
1751 g_return_if_fail (source != NULL);
1752 g_return_if_fail (source->ref_count > 0);
1754 if (source->priv->ready_time == ready_time)
1757 context = source->context;
1760 LOCK_CONTEXT (context);
1762 source->priv->ready_time = ready_time;
1766 /* Quite likely that we need to change the timeout on the poll */
1767 if (!SOURCE_BLOCKED (source))
1768 g_wakeup_signal (context->wakeup);
1769 UNLOCK_CONTEXT (context);
1774 * g_source_get_ready_time:
1775 * @source: a #GSource
1777 * Gets the "ready time" of @source, as set by
1778 * g_source_set_ready_time().
1780 * Any time before the current monotonic time (including 0) is an
1781 * indication that the source will fire immediately.
1783 * Returns: the monotonic ready time, -1 for "never"
1786 g_source_get_ready_time (GSource *source)
1788 g_return_val_if_fail (source != NULL, -1);
1790 return source->priv->ready_time;
1794 * g_source_set_can_recurse:
1795 * @source: a #GSource
1796 * @can_recurse: whether recursion is allowed for this source
1798 * Sets whether a source can be called recursively. If @can_recurse is
1799 * %TRUE, then while the source is being dispatched then this source
1800 * will be processed normally. Otherwise, all processing of this
1801 * source is blocked until the dispatch function returns.
1804 g_source_set_can_recurse (GSource *source,
1805 gboolean can_recurse)
1807 GMainContext *context;
1809 g_return_if_fail (source != NULL);
1811 context = source->context;
1814 LOCK_CONTEXT (context);
1817 source->flags |= G_SOURCE_CAN_RECURSE;
1819 source->flags &= ~G_SOURCE_CAN_RECURSE;
1822 UNLOCK_CONTEXT (context);
1826 * g_source_get_can_recurse:
1827 * @source: a #GSource
1829 * Checks whether a source is allowed to be called recursively.
1830 * see g_source_set_can_recurse().
1832 * Returns: whether recursion is allowed.
1835 g_source_get_can_recurse (GSource *source)
1837 g_return_val_if_fail (source != NULL, FALSE);
1839 return (source->flags & G_SOURCE_CAN_RECURSE) != 0;
1844 * g_source_set_name:
1845 * @source: a #GSource
1846 * @name: debug name for the source
1848 * Sets a name for the source, used in debugging and profiling.
1849 * The name defaults to #NULL.
1851 * The source name should describe in a human-readable way
1852 * what the source does. For example, "X11 event queue"
1853 * or "GTK+ repaint idle handler" or whatever it is.
1855 * It is permitted to call this function multiple times, but is not
1856 * recommended due to the potential performance impact. For example,
1857 * one could change the name in the "check" function of a #GSourceFuncs
1858 * to include details like the event type in the source name.
1860 * Use caution if changing the name while another thread may be
1861 * accessing it with g_source_get_name(); that function does not copy
1862 * the value, and changing the value will free it while the other thread
1863 * may be attempting to use it.
1868 g_source_set_name (GSource *source,
1871 GMainContext *context;
1873 g_return_if_fail (source != NULL);
1875 context = source->context;
1878 LOCK_CONTEXT (context);
1880 /* setting back to NULL is allowed, just because it's
1881 * weird if get_name can return NULL but you can't
1885 g_free (source->name);
1886 source->name = g_strdup (name);
1889 UNLOCK_CONTEXT (context);
1893 * g_source_get_name:
1894 * @source: a #GSource
1896 * Gets a name for the source, used in debugging and profiling. The
1897 * name may be #NULL if it has never been set with g_source_set_name().
1899 * Returns: the name of the source
1904 g_source_get_name (GSource *source)
1906 g_return_val_if_fail (source != NULL, NULL);
1908 return source->name;
1912 * g_source_set_name_by_id:
1913 * @tag: a #GSource ID
1914 * @name: debug name for the source
1916 * Sets the name of a source using its ID.
1918 * This is a convenience utility to set source names from the return
1919 * value of g_idle_add(), g_timeout_add(), etc.
1921 * It is a programmer error to attempt to set the name of a non-existent
1924 * More specifically: source IDs can be reissued after a source has been
1925 * destroyed and therefore it is never valid to use this function with a
1926 * source ID which may have already been removed. An example is when
1927 * scheduling an idle to run in another thread with g_idle_add(): the
1928 * idle may already have run and been removed by the time this function
1929 * is called on its (now invalid) source ID. This source ID may have
1930 * been reissued, leading to the operation being performed against the
1936 g_source_set_name_by_id (guint tag,
1941 g_return_if_fail (tag > 0);
1943 source = g_main_context_find_source_by_id (NULL, tag);
1947 g_source_set_name (source, name);
1953 * @source: a #GSource
1955 * Increases the reference count on a source by one.
1960 g_source_ref (GSource *source)
1962 GMainContext *context;
1964 g_return_val_if_fail (source != NULL, NULL);
1966 context = source->context;
1969 LOCK_CONTEXT (context);
1971 source->ref_count++;
1974 UNLOCK_CONTEXT (context);
1979 /* g_source_unref() but possible to call within context lock
1982 g_source_unref_internal (GSource *source,
1983 GMainContext *context,
1986 gpointer old_cb_data = NULL;
1987 GSourceCallbackFuncs *old_cb_funcs = NULL;
1989 g_return_if_fail (source != NULL);
1991 if (!have_lock && context)
1992 LOCK_CONTEXT (context);
1994 source->ref_count--;
1995 if (source->ref_count == 0)
1997 old_cb_data = source->callback_data;
1998 old_cb_funcs = source->callback_funcs;
2000 source->callback_data = NULL;
2001 source->callback_funcs = NULL;
2005 if (!SOURCE_DESTROYED (source))
2006 g_warning (G_STRLOC ": ref_count == 0, but source was still attached to a context!");
2007 source_remove_from_context (source, context);
2009 g_hash_table_remove (context->sources, GUINT_TO_POINTER (source->source_id));
2012 if (source->source_funcs->finalize)
2015 UNLOCK_CONTEXT (context);
2016 source->source_funcs->finalize (source);
2018 LOCK_CONTEXT (context);
2021 g_free (source->name);
2022 source->name = NULL;
2024 g_slist_free (source->poll_fds);
2025 source->poll_fds = NULL;
2027 g_slist_free_full (source->priv->fds, g_free);
2029 g_slice_free (GSourcePrivate, source->priv);
2030 source->priv = NULL;
2035 if (!have_lock && context)
2036 UNLOCK_CONTEXT (context);
2041 UNLOCK_CONTEXT (context);
2043 old_cb_funcs->unref (old_cb_data);
2046 LOCK_CONTEXT (context);
2052 * @source: a #GSource
2054 * Decreases the reference count of a source by one. If the
2055 * resulting reference count is zero the source and associated
2056 * memory will be destroyed.
2059 g_source_unref (GSource *source)
2061 g_return_if_fail (source != NULL);
2063 g_source_unref_internal (source, source->context, FALSE);
2067 * g_main_context_find_source_by_id:
2068 * @context: (allow-none): a #GMainContext (if %NULL, the default context will be used)
2069 * @source_id: the source ID, as returned by g_source_get_id().
2071 * Finds a #GSource given a pair of context and ID.
2073 * It is a programmer error to attempt to lookup a non-existent source.
2075 * More specifically: source IDs can be reissued after a source has been
2076 * destroyed and therefore it is never valid to use this function with a
2077 * source ID which may have already been removed. An example is when
2078 * scheduling an idle to run in another thread with g_idle_add(): the
2079 * idle may already have run and been removed by the time this function
2080 * is called on its (now invalid) source ID. This source ID may have
2081 * been reissued, leading to the operation being performed against the
2084 * Returns: (transfer none): the #GSource
2087 g_main_context_find_source_by_id (GMainContext *context,
2092 g_return_val_if_fail (source_id > 0, NULL);
2094 if (context == NULL)
2095 context = g_main_context_default ();
2097 LOCK_CONTEXT (context);
2098 source = g_hash_table_lookup (context->sources, GUINT_TO_POINTER (source_id));
2099 UNLOCK_CONTEXT (context);
2101 if (source && SOURCE_DESTROYED (source))
2108 * g_main_context_find_source_by_funcs_user_data:
2109 * @context: (allow-none): a #GMainContext (if %NULL, the default context will be used).
2110 * @funcs: the @source_funcs passed to g_source_new().
2111 * @user_data: the user data from the callback.
2113 * Finds a source with the given source functions and user data. If
2114 * multiple sources exist with the same source function and user data,
2115 * the first one found will be returned.
2117 * Returns: (transfer none): the source, if one was found, otherwise %NULL
2120 g_main_context_find_source_by_funcs_user_data (GMainContext *context,
2121 GSourceFuncs *funcs,
2127 g_return_val_if_fail (funcs != NULL, NULL);
2129 if (context == NULL)
2130 context = g_main_context_default ();
2132 LOCK_CONTEXT (context);
2134 g_source_iter_init (&iter, context, FALSE);
2135 while (g_source_iter_next (&iter, &source))
2137 if (!SOURCE_DESTROYED (source) &&
2138 source->source_funcs == funcs &&
2139 source->callback_funcs)
2141 GSourceFunc callback;
2142 gpointer callback_data;
2144 source->callback_funcs->get (source->callback_data, source, &callback, &callback_data);
2146 if (callback_data == user_data)
2150 g_source_iter_clear (&iter);
2152 UNLOCK_CONTEXT (context);
2158 * g_main_context_find_source_by_user_data:
2159 * @context: a #GMainContext
2160 * @user_data: the user_data for the callback.
2162 * Finds a source with the given user data for the callback. If
2163 * multiple sources exist with the same user data, the first
2164 * one found will be returned.
2166 * Returns: (transfer none): the source, if one was found, otherwise %NULL
2169 g_main_context_find_source_by_user_data (GMainContext *context,
2175 if (context == NULL)
2176 context = g_main_context_default ();
2178 LOCK_CONTEXT (context);
2180 g_source_iter_init (&iter, context, FALSE);
2181 while (g_source_iter_next (&iter, &source))
2183 if (!SOURCE_DESTROYED (source) &&
2184 source->callback_funcs)
2186 GSourceFunc callback;
2187 gpointer callback_data = NULL;
2189 source->callback_funcs->get (source->callback_data, source, &callback, &callback_data);
2191 if (callback_data == user_data)
2195 g_source_iter_clear (&iter);
2197 UNLOCK_CONTEXT (context);
2204 * @tag: the ID of the source to remove.
2206 * Removes the source with the given id from the default main context.
2208 * The id of a #GSource is given by g_source_get_id(), or will be
2209 * returned by the functions g_source_attach(), g_idle_add(),
2210 * g_idle_add_full(), g_timeout_add(), g_timeout_add_full(),
2211 * g_child_watch_add(), g_child_watch_add_full(), g_io_add_watch(), and
2212 * g_io_add_watch_full().
2214 * See also g_source_destroy(). You must use g_source_destroy() for sources
2215 * added to a non-default main context.
2217 * It is a programmer error to attempt to remove a non-existent source.
2219 * More specifically: source IDs can be reissued after a source has been
2220 * destroyed and therefore it is never valid to use this function with a
2221 * source ID which may have already been removed. An example is when
2222 * scheduling an idle to run in another thread with g_idle_add(): the
2223 * idle may already have run and been removed by the time this function
2224 * is called on its (now invalid) source ID. This source ID may have
2225 * been reissued, leading to the operation being performed against the
2228 * Returns: For historical reasons, this function always returns %TRUE
2231 g_source_remove (guint tag)
2235 g_return_val_if_fail (tag > 0, FALSE);
2237 source = g_main_context_find_source_by_id (NULL, tag);
2239 g_source_destroy (source);
2241 g_critical ("Source ID %u was not found when attempting to remove it", tag);
2243 return source != NULL;
2247 * g_source_remove_by_user_data:
2248 * @user_data: the user_data for the callback.
2250 * Removes a source from the default main loop context given the user
2251 * data for the callback. If multiple sources exist with the same user
2252 * data, only one will be destroyed.
2254 * Returns: %TRUE if a source was found and removed.
2257 g_source_remove_by_user_data (gpointer user_data)
2261 source = g_main_context_find_source_by_user_data (NULL, user_data);
2264 g_source_destroy (source);
2272 * g_source_remove_by_funcs_user_data:
2273 * @funcs: The @source_funcs passed to g_source_new()
2274 * @user_data: the user data for the callback
2276 * Removes a source from the default main loop context given the
2277 * source functions and user data. If multiple sources exist with the
2278 * same source functions and user data, only one will be destroyed.
2280 * Returns: %TRUE if a source was found and removed.
2283 g_source_remove_by_funcs_user_data (GSourceFuncs *funcs,
2288 g_return_val_if_fail (funcs != NULL, FALSE);
2290 source = g_main_context_find_source_by_funcs_user_data (NULL, funcs, user_data);
2293 g_source_destroy (source);
2302 * g_source_add_unix_fd:
2303 * @source: a #GSource
2304 * @fd: the fd to monitor
2305 * @events: an event mask
2307 * Monitors @fd for the IO events in @events.
2309 * The tag returned by this function can be used to remove or modify the
2310 * monitoring of the fd using g_source_remove_unix_fd() or
2311 * g_source_modify_unix_fd().
2313 * It is not necessary to remove the fd before destroying the source; it
2314 * will be cleaned up automatically.
2316 * This API is only intended to be used by implementations of #GSource.
2317 * Do not call this API on a #GSource that you did not create.
2319 * As the name suggests, this function is not available on Windows.
2321 * Returns: an opaque tag
2326 g_source_add_unix_fd (GSource *source,
2328 GIOCondition events)
2330 GMainContext *context;
2333 g_return_val_if_fail (source != NULL, NULL);
2334 g_return_val_if_fail (!SOURCE_DESTROYED (source), NULL);
2336 poll_fd = g_new (GPollFD, 1);
2338 poll_fd->events = events;
2339 poll_fd->revents = 0;
2341 context = source->context;
2344 LOCK_CONTEXT (context);
2346 source->priv->fds = g_slist_prepend (source->priv->fds, poll_fd);
2350 if (!SOURCE_BLOCKED (source))
2351 g_main_context_add_poll_unlocked (context, source->priority, poll_fd);
2352 UNLOCK_CONTEXT (context);
2359 * g_source_modify_unix_fd:
2360 * @source: a #GSource
2361 * @tag: the tag from g_source_add_unix_fd()
2362 * @new_events: the new event mask to watch
2364 * Updates the event mask to watch for the fd identified by @tag.
2366 * @tag is the tag returned from g_source_add_unix_fd().
2368 * If you want to remove a fd, don't set its event mask to zero.
2369 * Instead, call g_source_remove_unix_fd().
2371 * This API is only intended to be used by implementations of #GSource.
2372 * Do not call this API on a #GSource that you did not create.
2374 * As the name suggests, this function is not available on Windows.
2379 g_source_modify_unix_fd (GSource *source,
2381 GIOCondition new_events)
2383 GMainContext *context;
2386 g_return_if_fail (source != NULL);
2387 g_return_if_fail (g_slist_find (source->priv->fds, tag));
2389 context = source->context;
2392 poll_fd->events = new_events;
2395 g_main_context_wakeup (context);
2399 * g_source_remove_unix_fd:
2400 * @source: a #GSource
2401 * @tag: the tag from g_source_add_unix_fd()
2403 * Reverses the effect of a previous call to g_source_add_unix_fd().
2405 * You only need to call this if you want to remove an fd from being
2406 * watched while keeping the same source around. In the normal case you
2407 * will just want to destroy the source.
2409 * This API is only intended to be used by implementations of #GSource.
2410 * Do not call this API on a #GSource that you did not create.
2412 * As the name suggests, this function is not available on Windows.
2417 g_source_remove_unix_fd (GSource *source,
2420 GMainContext *context;
2423 g_return_if_fail (source != NULL);
2424 g_return_if_fail (g_slist_find (source->priv->fds, tag));
2426 context = source->context;
2430 LOCK_CONTEXT (context);
2432 source->priv->fds = g_slist_remove (source->priv->fds, poll_fd);
2436 if (!SOURCE_BLOCKED (source))
2437 g_main_context_remove_poll_unlocked (context, poll_fd);
2439 UNLOCK_CONTEXT (context);
2446 * g_source_query_unix_fd:
2447 * @source: a #GSource
2448 * @tag: the tag from g_source_add_unix_fd()
2450 * Queries the events reported for the fd corresponding to @tag on
2451 * @source during the last poll.
2453 * The return value of this function is only defined when the function
2454 * is called from the check or dispatch functions for @source.
2456 * This API is only intended to be used by implementations of #GSource.
2457 * Do not call this API on a #GSource that you did not create.
2459 * As the name suggests, this function is not available on Windows.
2461 * Returns: the conditions reported on the fd
2466 g_source_query_unix_fd (GSource *source,
2471 g_return_val_if_fail (source != NULL, 0);
2472 g_return_val_if_fail (g_slist_find (source->priv->fds, tag), 0);
2476 return poll_fd->revents;
2478 #endif /* G_OS_UNIX */
2481 * g_get_current_time:
2482 * @result: #GTimeVal structure in which to store current time.
2484 * Equivalent to the UNIX gettimeofday() function, but portable.
2486 * You may find g_get_real_time() to be more convenient.
2489 g_get_current_time (GTimeVal *result)
2494 g_return_if_fail (result != NULL);
2496 /*this is required on alpha, there the timeval structs are int's
2497 not longs and a cast only would fail horribly*/
2498 gettimeofday (&r, NULL);
2499 result->tv_sec = r.tv_sec;
2500 result->tv_usec = r.tv_usec;
2505 g_return_if_fail (result != NULL);
2507 GetSystemTimeAsFileTime (&ft);
2508 memmove (&time64, &ft, sizeof (FILETIME));
2510 /* Convert from 100s of nanoseconds since 1601-01-01
2511 * to Unix epoch. Yes, this is Y2038 unsafe.
2513 time64 -= G_GINT64_CONSTANT (116444736000000000);
2516 result->tv_sec = time64 / 1000000;
2517 result->tv_usec = time64 % 1000000;
2524 * Queries the system wall-clock time.
2526 * This call is functionally equivalent to g_get_current_time() except
2527 * that the return value is often more convenient than dealing with a
2530 * You should only use this call if you are actually interested in the real
2531 * wall-clock time. g_get_monotonic_time() is probably more useful for
2532 * measuring intervals.
2534 * Returns: the number of microseconds since January 1, 1970 UTC.
2539 g_get_real_time (void)
2543 g_get_current_time (&tv);
2545 return (((gint64) tv.tv_sec) * 1000000) + tv.tv_usec;
2549 * g_get_monotonic_time:
2551 * Queries the system monotonic time.
2553 * The monotonic clock will always increase and doesn't suffer
2554 * discontinuities when the user (or NTP) changes the system time. It
2555 * may or may not continue to tick during times where the machine is
2558 * We try to use the clock that corresponds as closely as possible to
2559 * the passage of time as measured by system calls such as poll() but it
2560 * may not always be possible to do this.
2562 * Returns: the monotonic time, in microseconds
2566 #if defined (G_OS_WIN32)
2567 static ULONGLONG (*g_GetTickCount64) (void) = NULL;
2568 static guint32 g_win32_tick_epoch = 0;
2571 g_clock_win32_init (void)
2575 g_GetTickCount64 = NULL;
2576 kernel32 = GetModuleHandle ("KERNEL32.DLL");
2577 if (kernel32 != NULL)
2578 g_GetTickCount64 = (void *) GetProcAddress (kernel32, "GetTickCount64");
2579 g_win32_tick_epoch = ((guint32)GetTickCount()) >> 31;
2583 g_get_monotonic_time (void)
2588 /* There are four sources for the monotonic time on Windows:
2590 * Three are based on a (1 msec accuracy, but only read periodically) clock chip:
2591 * - GetTickCount (GTC)
2592 * 32bit msec counter, updated each ~15msec, wraps in ~50 days
2593 * - GetTickCount64 (GTC64)
2594 * Same as GetTickCount, but extended to 64bit, so no wrap
2595 * Only available in Vista or later
2596 * - timeGetTime (TGT)
2597 * similar to GetTickCount by default: 15msec, 50 day wrap.
2598 * available in winmm.dll (thus known as the multimedia timers)
2599 * However apps can raise the system timer clock frequency using timeBeginPeriod()
2600 * increasing the accuracy up to 1 msec, at a cost in general system performance
2603 * One is based on high precision clocks:
2604 * - QueryPrecisionCounter (QPC)
2605 * This has much higher accuracy, but is not guaranteed monotonic, and
2606 * has lots of complications like clock jumps and different times on different
2607 * CPUs. It also has lower long term accuracy (i.e. it will drift compared to
2608 * the low precision clocks.
2610 * Additionally, the precision available in the timer-based wakeup such as
2611 * MsgWaitForMultipleObjectsEx (which is what the mainloop is based on) is based
2612 * on the TGT resolution, so by default it is ~15msec, but can be increased by apps.
2614 * The QPC timer has too many issues to be used as is. The only way it could be used
2615 * is to use it to interpolate the lower precision clocks. Firefox does something like
2617 * https://bugzilla.mozilla.org/show_bug.cgi?id=363258
2619 * However this seems quite complicated, so we're not doing this right now.
2621 * The approach we take instead is to use the TGT timer, extending it to 64bit
2622 * either by using the GTC64 value, or if that is not available, a process local
2623 * time epoch that we increment when we detect a timer wrap (assumes that we read
2624 * the time at least once every 50 days).
2627 * - We have a globally consistent monotonic clock on Vista and later
2628 * - We have a locally monotonic clock on XP
2629 * - Apps that need higher precision in timeouts and clock reads can call
2630 * timeBeginPeriod() to increase it as much as they want
2633 if (g_GetTickCount64 != NULL)
2635 guint32 ticks_as_32bit;
2637 ticks = g_GetTickCount64 ();
2638 ticks32 = timeGetTime();
2640 /* GTC64 and TGT are sampled at different times, however they
2641 * have the same base and source (msecs since system boot).
2642 * They can differ by as much as -16 to +16 msecs.
2643 * We can't just inject the low bits into the 64bit counter
2644 * as one of the counters can have wrapped in 32bit space and
2645 * the other not. Instead we calculate the signed difference
2646 * in 32bit space and apply that difference to the 64bit counter.
2648 ticks_as_32bit = (guint32)ticks;
2650 /* We could do some 2's complement hack, but we play it safe */
2651 if (ticks32 - ticks_as_32bit <= G_MAXINT32)
2652 ticks += ticks32 - ticks_as_32bit;
2654 ticks -= ticks_as_32bit - ticks32;
2660 epoch = g_atomic_int_get (&g_win32_tick_epoch);
2662 /* Must read ticks after the epoch. Then we're guaranteed
2663 * that the ticks value we read is higher or equal to any
2664 * previous ones that lead to the writing of the epoch.
2666 ticks32 = timeGetTime();
2668 /* We store the MSB of the current time as the LSB
2669 * of the epoch. Comparing these bits lets us detect when
2670 * the 32bit counter has wrapped so we can increase the
2673 * This will work as long as this function is called at
2674 * least once every ~24 days, which is half the wrap time
2675 * of a 32bit msec counter. I think this is pretty likely.
2677 * Note that g_win32_tick_epoch is a process local state,
2678 * so the monotonic clock will not be the same between
2681 if ((ticks32 >> 31) != (epoch & 1))
2684 g_atomic_int_set (&g_win32_tick_epoch, epoch);
2688 ticks = (guint64)ticks32 | ((guint64)epoch) << 31;
2691 return ticks * 1000;
2693 #elif defined(HAVE_MACH_MACH_TIME_H) /* Mac OS */
2695 g_get_monotonic_time (void)
2697 static mach_timebase_info_data_t timebase_info;
2699 if (timebase_info.denom == 0)
2701 /* This is a fraction that we must use to scale
2702 * mach_absolute_time() by in order to reach nanoseconds.
2704 * We've only ever observed this to be 1/1, but maybe it could be
2705 * 1000/1 if mach time is microseconds already, or 1/1000 if
2706 * picoseconds. Try to deal nicely with that.
2708 mach_timebase_info (&timebase_info);
2710 /* We actually want microseconds... */
2711 if (timebase_info.numer % 1000 == 0)
2712 timebase_info.numer /= 1000;
2714 timebase_info.denom *= 1000;
2716 /* We want to make the numer 1 to avoid having to multiply... */
2717 if (timebase_info.denom % timebase_info.numer == 0)
2719 timebase_info.denom /= timebase_info.numer;
2720 timebase_info.numer = 1;
2724 /* We could just multiply by timebase_info.numer below, but why
2725 * bother for a case that may never actually exist...
2727 * Plus -- performing the multiplication would risk integer
2728 * overflow. If we ever actually end up in this situation, we
2729 * should more carefully evaluate the correct course of action.
2731 mach_timebase_info (&timebase_info); /* Get a fresh copy for a better message */
2732 g_error ("Got weird mach timebase info of %d/%d. Please file a bug against GLib.",
2733 timebase_info.numer, timebase_info.denom);
2737 return mach_absolute_time () / timebase_info.denom;
2741 g_get_monotonic_time (void)
2746 result = clock_gettime (CLOCK_MONOTONIC, &ts);
2748 if G_UNLIKELY (result != 0)
2749 g_error ("GLib requires working CLOCK_MONOTONIC");
2751 return (((gint64) ts.tv_sec) * 1000000) + (ts.tv_nsec / 1000);
2756 g_main_dispatch_free (gpointer dispatch)
2758 g_slice_free (GMainDispatch, dispatch);
2761 /* Running the main loop */
2763 static GMainDispatch *
2766 static GPrivate depth_private = G_PRIVATE_INIT (g_main_dispatch_free);
2767 GMainDispatch *dispatch;
2769 dispatch = g_private_get (&depth_private);
2773 dispatch = g_slice_new0 (GMainDispatch);
2774 g_private_set (&depth_private, dispatch);
2783 * Returns the depth of the stack of calls to
2784 * g_main_context_dispatch() on any #GMainContext in the current thread.
2785 * That is, when called from the toplevel, it gives 0. When
2786 * called from within a callback from g_main_context_iteration()
2787 * (or g_main_loop_run(), etc.) it returns 1. When called from within
2788 * a callback to a recursive call to g_main_context_iteration(),
2789 * it returns 2. And so forth.
2791 * This function is useful in a situation like the following:
2792 * Imagine an extremely simple "garbage collected" system.
2794 * |[<!-- language="C" -->
2795 * static GList *free_list;
2798 * allocate_memory (gsize size)
2800 * gpointer result = g_malloc (size);
2801 * free_list = g_list_prepend (free_list, result);
2806 * free_allocated_memory (void)
2809 * for (l = free_list; l; l = l->next);
2811 * g_list_free (free_list);
2819 * g_main_context_iteration (NULL, TRUE);
2820 * free_allocated_memory();
2824 * This works from an application, however, if you want to do the same
2825 * thing from a library, it gets more difficult, since you no longer
2826 * control the main loop. You might think you can simply use an idle
2827 * function to make the call to free_allocated_memory(), but that
2828 * doesn't work, since the idle function could be called from a
2829 * recursive callback. This can be fixed by using g_main_depth()
2831 * |[<!-- language="C" -->
2833 * allocate_memory (gsize size)
2835 * FreeListBlock *block = g_new (FreeListBlock, 1);
2836 * block->mem = g_malloc (size);
2837 * block->depth = g_main_depth ();
2838 * free_list = g_list_prepend (free_list, block);
2839 * return block->mem;
2843 * free_allocated_memory (void)
2847 * int depth = g_main_depth ();
2848 * for (l = free_list; l; );
2850 * GList *next = l->next;
2851 * FreeListBlock *block = l->data;
2852 * if (block->depth > depth)
2854 * g_free (block->mem);
2856 * free_list = g_list_delete_link (free_list, l);
2864 * There is a temptation to use g_main_depth() to solve
2865 * problems with reentrancy. For instance, while waiting for data
2866 * to be received from the network in response to a menu item,
2867 * the menu item might be selected again. It might seem that
2868 * one could make the menu item's callback return immediately
2869 * and do nothing if g_main_depth() returns a value greater than 1.
2870 * However, this should be avoided since the user then sees selecting
2871 * the menu item do nothing. Furthermore, you'll find yourself adding
2872 * these checks all over your code, since there are doubtless many,
2873 * many things that the user could do. Instead, you can use the
2874 * following techniques:
2876 * 1. Use gtk_widget_set_sensitive() or modal dialogs to prevent
2877 * the user from interacting with elements while the main
2878 * loop is recursing.
2880 * 2. Avoid main loop recursion in situations where you can't handle
2881 * arbitrary callbacks. Instead, structure your code so that you
2882 * simply return to the main loop and then get called again when
2883 * there is more work to do.
2885 * Returns: The main loop recursion level in the current thread
2890 GMainDispatch *dispatch = get_dispatch ();
2891 return dispatch->depth;
2895 * g_main_current_source:
2897 * Returns the currently firing source for this thread.
2899 * Returns: (transfer none): The currently firing source or %NULL.
2904 g_main_current_source (void)
2906 GMainDispatch *dispatch = get_dispatch ();
2907 return dispatch->source;
2911 * g_source_is_destroyed:
2912 * @source: a #GSource
2914 * Returns whether @source has been destroyed.
2916 * This is important when you operate upon your objects
2917 * from within idle handlers, but may have freed the object
2918 * before the dispatch of your idle handler.
2920 * |[<!-- language="C" -->
2922 * idle_callback (gpointer data)
2924 * SomeWidget *self = data;
2926 * GDK_THREADS_ENTER ();
2927 * // do stuff with self
2928 * self->idle_id = 0;
2929 * GDK_THREADS_LEAVE ();
2931 * return G_SOURCE_REMOVE;
2935 * some_widget_do_stuff_later (SomeWidget *self)
2937 * self->idle_id = g_idle_add (idle_callback, self);
2941 * some_widget_finalize (GObject *object)
2943 * SomeWidget *self = SOME_WIDGET (object);
2945 * if (self->idle_id)
2946 * g_source_remove (self->idle_id);
2948 * G_OBJECT_CLASS (parent_class)->finalize (object);
2952 * This will fail in a multi-threaded application if the
2953 * widget is destroyed before the idle handler fires due
2954 * to the use after free in the callback. A solution, to
2955 * this particular problem, is to check to if the source
2956 * has already been destroy within the callback.
2958 * |[<!-- language="C" -->
2960 * idle_callback (gpointer data)
2962 * SomeWidget *self = data;
2964 * GDK_THREADS_ENTER ();
2965 * if (!g_source_is_destroyed (g_main_current_source ()))
2967 * // do stuff with self
2969 * GDK_THREADS_LEAVE ();
2975 * Returns: %TRUE if the source has been destroyed
2980 g_source_is_destroyed (GSource *source)
2982 return SOURCE_DESTROYED (source);
2985 /* Temporarily remove all this source's file descriptors from the
2986 * poll(), so that if data comes available for one of the file descriptors
2987 * we don't continually spin in the poll()
2989 /* HOLDS: source->context's lock */
2991 block_source (GSource *source)
2995 g_return_if_fail (!SOURCE_BLOCKED (source));
2997 source->flags |= G_SOURCE_BLOCKED;
2999 if (source->context)
3001 tmp_list = source->poll_fds;
3004 g_main_context_remove_poll_unlocked (source->context, tmp_list->data);
3005 tmp_list = tmp_list->next;
3008 for (tmp_list = source->priv->fds; tmp_list; tmp_list = tmp_list->next)
3009 g_main_context_remove_poll_unlocked (source->context, tmp_list->data);
3012 if (source->priv && source->priv->child_sources)
3014 tmp_list = source->priv->child_sources;
3017 block_source (tmp_list->data);
3018 tmp_list = tmp_list->next;
3023 /* HOLDS: source->context's lock */
3025 unblock_source (GSource *source)
3029 g_return_if_fail (SOURCE_BLOCKED (source)); /* Source already unblocked */
3030 g_return_if_fail (!SOURCE_DESTROYED (source));
3032 source->flags &= ~G_SOURCE_BLOCKED;
3034 tmp_list = source->poll_fds;
3037 g_main_context_add_poll_unlocked (source->context, source->priority, tmp_list->data);
3038 tmp_list = tmp_list->next;
3041 for (tmp_list = source->priv->fds; tmp_list; tmp_list = tmp_list->next)
3042 g_main_context_add_poll_unlocked (source->context, source->priority, tmp_list->data);
3044 if (source->priv && source->priv->child_sources)
3046 tmp_list = source->priv->child_sources;
3049 unblock_source (tmp_list->data);
3050 tmp_list = tmp_list->next;
3055 /* HOLDS: context's lock */
3057 g_main_dispatch (GMainContext *context)
3059 GMainDispatch *current = get_dispatch ();
3062 for (i = 0; i < context->pending_dispatches->len; i++)
3064 GSource *source = context->pending_dispatches->pdata[i];
3066 context->pending_dispatches->pdata[i] = NULL;
3069 source->flags &= ~G_SOURCE_READY;
3071 if (!SOURCE_DESTROYED (source))
3073 gboolean was_in_call;
3074 gpointer user_data = NULL;
3075 GSourceFunc callback = NULL;
3076 GSourceCallbackFuncs *cb_funcs;
3078 gboolean need_destroy;
3080 gboolean (*dispatch) (GSource *,
3083 GSource *prev_source;
3085 dispatch = source->source_funcs->dispatch;
3086 cb_funcs = source->callback_funcs;
3087 cb_data = source->callback_data;
3090 cb_funcs->ref (cb_data);
3092 if ((source->flags & G_SOURCE_CAN_RECURSE) == 0)
3093 block_source (source);
3095 was_in_call = source->flags & G_HOOK_FLAG_IN_CALL;
3096 source->flags |= G_HOOK_FLAG_IN_CALL;
3099 cb_funcs->get (cb_data, source, &callback, &user_data);
3101 UNLOCK_CONTEXT (context);
3103 /* These operations are safe because 'current' is thread-local
3104 * and not modified from anywhere but this function.
3106 prev_source = current->source;
3107 current->source = source;
3110 TRACE( GLIB_MAIN_BEFORE_DISPATCH (g_source_get_name (source)));
3111 need_destroy = !(* dispatch) (source, callback, user_data);
3112 TRACE( GLIB_MAIN_AFTER_DISPATCH (g_source_get_name (source)));
3114 current->source = prev_source;
3118 cb_funcs->unref (cb_data);
3120 LOCK_CONTEXT (context);
3123 source->flags &= ~G_HOOK_FLAG_IN_CALL;
3125 if (SOURCE_BLOCKED (source) && !SOURCE_DESTROYED (source))
3126 unblock_source (source);
3128 /* Note: this depends on the fact that we can't switch
3129 * sources from one main context to another
3131 if (need_destroy && !SOURCE_DESTROYED (source))
3133 g_assert (source->context == context);
3134 g_source_destroy_internal (source, context, TRUE);
3138 SOURCE_UNREF (source, context);
3141 g_ptr_array_set_size (context->pending_dispatches, 0);
3145 * g_main_context_acquire:
3146 * @context: a #GMainContext
3148 * Tries to become the owner of the specified context.
3149 * If some other thread is the owner of the context,
3150 * returns %FALSE immediately. Ownership is properly
3151 * recursive: the owner can require ownership again
3152 * and will release ownership when g_main_context_release()
3153 * is called as many times as g_main_context_acquire().
3155 * You must be the owner of a context before you
3156 * can call g_main_context_prepare(), g_main_context_query(),
3157 * g_main_context_check(), g_main_context_dispatch().
3159 * Returns: %TRUE if the operation succeeded, and
3160 * this thread is now the owner of @context.
3163 g_main_context_acquire (GMainContext *context)
3165 gboolean result = FALSE;
3166 GThread *self = G_THREAD_SELF;
3168 if (context == NULL)
3169 context = g_main_context_default ();
3171 LOCK_CONTEXT (context);
3173 if (!context->owner)
3175 context->owner = self;
3176 g_assert (context->owner_count == 0);
3179 if (context->owner == self)
3181 context->owner_count++;
3185 UNLOCK_CONTEXT (context);
3191 * g_main_context_release:
3192 * @context: a #GMainContext
3194 * Releases ownership of a context previously acquired by this thread
3195 * with g_main_context_acquire(). If the context was acquired multiple
3196 * times, the ownership will be released only when g_main_context_release()
3197 * is called as many times as it was acquired.
3200 g_main_context_release (GMainContext *context)
3202 if (context == NULL)
3203 context = g_main_context_default ();
3205 LOCK_CONTEXT (context);
3207 context->owner_count--;
3208 if (context->owner_count == 0)
3210 context->owner = NULL;
3212 if (context->waiters)
3214 GMainWaiter *waiter = context->waiters->data;
3215 gboolean loop_internal_waiter = (waiter->mutex == &context->mutex);
3216 context->waiters = g_slist_delete_link (context->waiters,
3218 if (!loop_internal_waiter)
3219 g_mutex_lock (waiter->mutex);
3221 g_cond_signal (waiter->cond);
3223 if (!loop_internal_waiter)
3224 g_mutex_unlock (waiter->mutex);
3228 UNLOCK_CONTEXT (context);
3232 * g_main_context_wait:
3233 * @context: a #GMainContext
3234 * @cond: a condition variable
3235 * @mutex: a mutex, currently held
3237 * Tries to become the owner of the specified context,
3238 * as with g_main_context_acquire(). But if another thread
3239 * is the owner, atomically drop @mutex and wait on @cond until
3240 * that owner releases ownership or until @cond is signaled, then
3241 * try again (once) to become the owner.
3243 * Returns: %TRUE if the operation succeeded, and
3244 * this thread is now the owner of @context.
3247 g_main_context_wait (GMainContext *context,
3251 gboolean result = FALSE;
3252 GThread *self = G_THREAD_SELF;
3253 gboolean loop_internal_waiter;
3255 if (context == NULL)
3256 context = g_main_context_default ();
3258 if G_UNLIKELY (cond != &context->cond || mutex != &context->mutex)
3260 static gboolean warned;
3264 g_critical ("WARNING!! g_main_context_wait() will be removed in a future release. "
3265 "If you see this message, please file a bug immediately.");
3270 loop_internal_waiter = (mutex == &context->mutex);
3272 if (!loop_internal_waiter)
3273 LOCK_CONTEXT (context);
3275 if (context->owner && context->owner != self)
3280 waiter.mutex = mutex;
3282 context->waiters = g_slist_append (context->waiters, &waiter);
3284 if (!loop_internal_waiter)
3285 UNLOCK_CONTEXT (context);
3286 g_cond_wait (cond, mutex);
3287 if (!loop_internal_waiter)
3288 LOCK_CONTEXT (context);
3290 context->waiters = g_slist_remove (context->waiters, &waiter);
3293 if (!context->owner)
3295 context->owner = self;
3296 g_assert (context->owner_count == 0);
3299 if (context->owner == self)
3301 context->owner_count++;
3305 if (!loop_internal_waiter)
3306 UNLOCK_CONTEXT (context);
3312 * g_main_context_prepare:
3313 * @context: a #GMainContext
3314 * @priority: location to store priority of highest priority
3315 * source already ready.
3317 * Prepares to poll sources within a main loop. The resulting information
3318 * for polling is determined by calling g_main_context_query ().
3320 * You must have successfully acquired the context with
3321 * g_main_context_acquire() before you may call this function.
3323 * Returns: %TRUE if some source is ready to be dispatched
3327 g_main_context_prepare (GMainContext *context,
3332 gint current_priority = G_MAXINT;
3336 if (context == NULL)
3337 context = g_main_context_default ();
3339 LOCK_CONTEXT (context);
3341 context->time_is_fresh = FALSE;
3343 if (context->in_check_or_prepare)
3345 g_warning ("g_main_context_prepare() called recursively from within a source's check() or "
3346 "prepare() member.");
3347 UNLOCK_CONTEXT (context);
3352 /* If recursing, finish up current dispatch, before starting over */
3353 if (context->pending_dispatches)
3356 g_main_dispatch (context, ¤t_time);
3358 UNLOCK_CONTEXT (context);
3363 /* If recursing, clear list of pending dispatches */
3365 for (i = 0; i < context->pending_dispatches->len; i++)
3367 if (context->pending_dispatches->pdata[i])
3368 SOURCE_UNREF ((GSource *)context->pending_dispatches->pdata[i], context);
3370 g_ptr_array_set_size (context->pending_dispatches, 0);
3372 /* Prepare all sources */
3374 context->timeout = -1;
3376 g_source_iter_init (&iter, context, TRUE);
3377 while (g_source_iter_next (&iter, &source))
3379 gint source_timeout = -1;
3381 if (SOURCE_DESTROYED (source) || SOURCE_BLOCKED (source))
3383 if ((n_ready > 0) && (source->priority > current_priority))
3386 if (!(source->flags & G_SOURCE_READY))
3389 gboolean (* prepare) (GSource *source,
3392 prepare = source->source_funcs->prepare;
3396 context->in_check_or_prepare++;
3397 UNLOCK_CONTEXT (context);
3399 result = (* prepare) (source, &source_timeout);
3401 LOCK_CONTEXT (context);
3402 context->in_check_or_prepare--;
3406 source_timeout = -1;
3410 if (result == FALSE && source->priv->ready_time != -1)
3412 if (!context->time_is_fresh)
3414 context->time = g_get_monotonic_time ();
3415 context->time_is_fresh = TRUE;
3418 if (source->priv->ready_time <= context->time)
3427 /* rounding down will lead to spinning, so always round up */
3428 timeout = (source->priv->ready_time - context->time + 999) / 1000;
3430 if (source_timeout < 0 || timeout < source_timeout)
3431 source_timeout = timeout;
3437 GSource *ready_source = source;
3439 while (ready_source)
3441 ready_source->flags |= G_SOURCE_READY;
3442 ready_source = ready_source->priv->parent_source;
3447 if (source->flags & G_SOURCE_READY)
3450 current_priority = source->priority;
3451 context->timeout = 0;
3454 if (source_timeout >= 0)
3456 if (context->timeout < 0)
3457 context->timeout = source_timeout;
3459 context->timeout = MIN (context->timeout, source_timeout);
3462 g_source_iter_clear (&iter);
3464 UNLOCK_CONTEXT (context);
3467 *priority = current_priority;
3469 return (n_ready > 0);
3473 * g_main_context_query:
3474 * @context: a #GMainContext
3475 * @max_priority: maximum priority source to check
3476 * @timeout_: (out): location to store timeout to be used in polling
3477 * @fds: (out caller-allocates) (array length=n_fds): location to
3478 * store #GPollFD records that need to be polled.
3479 * @n_fds: length of @fds.
3481 * Determines information necessary to poll this main loop.
3483 * You must have successfully acquired the context with
3484 * g_main_context_acquire() before you may call this function.
3486 * Returns: the number of records actually stored in @fds,
3487 * or, if more than @n_fds records need to be stored, the number
3488 * of records that need to be stored.
3491 g_main_context_query (GMainContext *context,
3500 LOCK_CONTEXT (context);
3502 pollrec = context->poll_records;
3504 while (pollrec && max_priority >= pollrec->priority)
3506 /* We need to include entries with fd->events == 0 in the array because
3507 * otherwise if the application changes fd->events behind our back and
3508 * makes it non-zero, we'll be out of sync when we check the fds[] array.
3509 * (Changing fd->events after adding an FD wasn't an anticipated use of
3510 * this API, but it occurs in practice.) */
3513 fds[n_poll].fd = pollrec->fd->fd;
3514 /* In direct contradiction to the Unix98 spec, IRIX runs into
3515 * difficulty if you pass in POLLERR, POLLHUP or POLLNVAL
3516 * flags in the events field of the pollfd while it should
3517 * just ignoring them. So we mask them out here.
3519 fds[n_poll].events = pollrec->fd->events & ~(G_IO_ERR|G_IO_HUP|G_IO_NVAL);
3520 fds[n_poll].revents = 0;
3523 pollrec = pollrec->next;
3527 context->poll_changed = FALSE;
3531 *timeout = context->timeout;
3533 context->time_is_fresh = FALSE;
3536 UNLOCK_CONTEXT (context);
3542 * g_main_context_check:
3543 * @context: a #GMainContext
3544 * @max_priority: the maximum numerical priority of sources to check
3545 * @fds: (array length=n_fds): array of #GPollFD's that was passed to
3546 * the last call to g_main_context_query()
3547 * @n_fds: return value of g_main_context_query()
3549 * Passes the results of polling back to the main loop.
3551 * You must have successfully acquired the context with
3552 * g_main_context_acquire() before you may call this function.
3554 * Returns: %TRUE if some sources are ready to be dispatched.
3557 g_main_context_check (GMainContext *context,
3568 LOCK_CONTEXT (context);
3570 if (context->in_check_or_prepare)
3572 g_warning ("g_main_context_check() called recursively from within a source's check() or "
3573 "prepare() member.");
3574 UNLOCK_CONTEXT (context);
3578 if (context->wake_up_rec.revents)
3579 g_wakeup_acknowledge (context->wakeup);
3581 /* If the set of poll file descriptors changed, bail out
3582 * and let the main loop rerun
3584 if (context->poll_changed)
3586 UNLOCK_CONTEXT (context);
3590 pollrec = context->poll_records;
3594 if (pollrec->fd->events)
3595 pollrec->fd->revents = fds[i].revents;
3597 pollrec = pollrec->next;
3601 g_source_iter_init (&iter, context, TRUE);
3602 while (g_source_iter_next (&iter, &source))
3604 if (SOURCE_DESTROYED (source) || SOURCE_BLOCKED (source))
3606 if ((n_ready > 0) && (source->priority > max_priority))
3609 if (!(source->flags & G_SOURCE_READY))
3612 gboolean (* check) (GSource *source);
3614 check = source->source_funcs->check;
3618 /* If the check function is set, call it. */
3619 context->in_check_or_prepare++;
3620 UNLOCK_CONTEXT (context);
3622 result = (* check) (source);
3624 LOCK_CONTEXT (context);
3625 context->in_check_or_prepare--;
3630 if (result == FALSE)
3634 /* If not already explicitly flagged ready by ->check()
3635 * (or if we have no check) then we can still be ready if
3636 * any of our fds poll as ready.
3638 for (tmp_list = source->priv->fds; tmp_list; tmp_list = tmp_list->next)
3640 GPollFD *pollfd = tmp_list->data;
3642 if (pollfd->revents)
3650 if (result == FALSE && source->priv->ready_time != -1)
3652 if (!context->time_is_fresh)
3654 context->time = g_get_monotonic_time ();
3655 context->time_is_fresh = TRUE;
3658 if (source->priv->ready_time <= context->time)
3664 GSource *ready_source = source;
3666 while (ready_source)
3668 ready_source->flags |= G_SOURCE_READY;
3669 ready_source = ready_source->priv->parent_source;
3674 if (source->flags & G_SOURCE_READY)
3676 source->ref_count++;
3677 g_ptr_array_add (context->pending_dispatches, source);
3681 /* never dispatch sources with less priority than the first
3682 * one we choose to dispatch
3684 max_priority = source->priority;
3687 g_source_iter_clear (&iter);
3689 UNLOCK_CONTEXT (context);
3695 * g_main_context_dispatch:
3696 * @context: a #GMainContext
3698 * Dispatches all pending sources.
3700 * You must have successfully acquired the context with
3701 * g_main_context_acquire() before you may call this function.
3704 g_main_context_dispatch (GMainContext *context)
3706 LOCK_CONTEXT (context);
3708 if (context->pending_dispatches->len > 0)
3710 g_main_dispatch (context);
3713 UNLOCK_CONTEXT (context);
3716 /* HOLDS context lock */
3718 g_main_context_iterate (GMainContext *context,
3725 gboolean some_ready;
3726 gint nfds, allocated_nfds;
3727 GPollFD *fds = NULL;
3729 UNLOCK_CONTEXT (context);
3731 if (!g_main_context_acquire (context))
3733 gboolean got_ownership;
3735 LOCK_CONTEXT (context);
3740 got_ownership = g_main_context_wait (context,
3748 LOCK_CONTEXT (context);
3750 if (!context->cached_poll_array)
3752 context->cached_poll_array_size = context->n_poll_records;
3753 context->cached_poll_array = g_new (GPollFD, context->n_poll_records);
3756 allocated_nfds = context->cached_poll_array_size;
3757 fds = context->cached_poll_array;
3759 UNLOCK_CONTEXT (context);
3761 g_main_context_prepare (context, &max_priority);
3763 while ((nfds = g_main_context_query (context, max_priority, &timeout, fds,
3764 allocated_nfds)) > allocated_nfds)
3766 LOCK_CONTEXT (context);
3768 context->cached_poll_array_size = allocated_nfds = nfds;
3769 context->cached_poll_array = fds = g_new (GPollFD, nfds);
3770 UNLOCK_CONTEXT (context);
3776 g_main_context_poll (context, timeout, max_priority, fds, nfds);
3778 some_ready = g_main_context_check (context, max_priority, fds, nfds);
3781 g_main_context_dispatch (context);
3783 g_main_context_release (context);
3785 LOCK_CONTEXT (context);
3791 * g_main_context_pending:
3792 * @context: (allow-none): a #GMainContext (if %NULL, the default context will be used)
3794 * Checks if any sources have pending events for the given context.
3796 * Returns: %TRUE if events are pending.
3799 g_main_context_pending (GMainContext *context)
3804 context = g_main_context_default();
3806 LOCK_CONTEXT (context);
3807 retval = g_main_context_iterate (context, FALSE, FALSE, G_THREAD_SELF);
3808 UNLOCK_CONTEXT (context);
3814 * g_main_context_iteration:
3815 * @context: (allow-none): a #GMainContext (if %NULL, the default context will be used)
3816 * @may_block: whether the call may block.
3818 * Runs a single iteration for the given main loop. This involves
3819 * checking to see if any event sources are ready to be processed,
3820 * then if no events sources are ready and @may_block is %TRUE, waiting
3821 * for a source to become ready, then dispatching the highest priority
3822 * events sources that are ready. Otherwise, if @may_block is %FALSE
3823 * sources are not waited to become ready, only those highest priority
3824 * events sources will be dispatched (if any), that are ready at this
3825 * given moment without further waiting.
3827 * Note that even when @may_block is %TRUE, it is still possible for
3828 * g_main_context_iteration() to return %FALSE, since the wait may
3829 * be interrupted for other reasons than an event source becoming ready.
3831 * Returns: %TRUE if events were dispatched.
3834 g_main_context_iteration (GMainContext *context, gboolean may_block)
3839 context = g_main_context_default();
3841 LOCK_CONTEXT (context);
3842 retval = g_main_context_iterate (context, may_block, TRUE, G_THREAD_SELF);
3843 UNLOCK_CONTEXT (context);
3850 * @context: (allow-none): a #GMainContext (if %NULL, the default context will be used).
3851 * @is_running: set to %TRUE to indicate that the loop is running. This
3852 * is not very important since calling g_main_loop_run() will set this to
3855 * Creates a new #GMainLoop structure.
3857 * Returns: a new #GMainLoop.
3860 g_main_loop_new (GMainContext *context,
3861 gboolean is_running)
3866 context = g_main_context_default();
3868 g_main_context_ref (context);
3870 loop = g_new0 (GMainLoop, 1);
3871 loop->context = context;
3872 loop->is_running = is_running != FALSE;
3873 loop->ref_count = 1;
3880 * @loop: a #GMainLoop
3882 * Increases the reference count on a #GMainLoop object by one.
3887 g_main_loop_ref (GMainLoop *loop)
3889 g_return_val_if_fail (loop != NULL, NULL);
3890 g_return_val_if_fail (g_atomic_int_get (&loop->ref_count) > 0, NULL);
3892 g_atomic_int_inc (&loop->ref_count);
3898 * g_main_loop_unref:
3899 * @loop: a #GMainLoop
3901 * Decreases the reference count on a #GMainLoop object by one. If
3902 * the result is zero, free the loop and free all associated memory.
3905 g_main_loop_unref (GMainLoop *loop)
3907 g_return_if_fail (loop != NULL);
3908 g_return_if_fail (g_atomic_int_get (&loop->ref_count) > 0);
3910 if (!g_atomic_int_dec_and_test (&loop->ref_count))
3913 g_main_context_unref (loop->context);
3919 * @loop: a #GMainLoop
3921 * Runs a main loop until g_main_loop_quit() is called on the loop.
3922 * If this is called for the thread of the loop's #GMainContext,
3923 * it will process events from the loop, otherwise it will
3927 g_main_loop_run (GMainLoop *loop)
3929 GThread *self = G_THREAD_SELF;
3931 g_return_if_fail (loop != NULL);
3932 g_return_if_fail (g_atomic_int_get (&loop->ref_count) > 0);
3934 if (!g_main_context_acquire (loop->context))
3936 gboolean got_ownership = FALSE;
3938 /* Another thread owns this context */
3939 LOCK_CONTEXT (loop->context);
3941 g_atomic_int_inc (&loop->ref_count);
3943 if (!loop->is_running)
3944 loop->is_running = TRUE;
3946 while (loop->is_running && !got_ownership)
3947 got_ownership = g_main_context_wait (loop->context,
3948 &loop->context->cond,
3949 &loop->context->mutex);
3951 if (!loop->is_running)
3953 UNLOCK_CONTEXT (loop->context);
3955 g_main_context_release (loop->context);
3956 g_main_loop_unref (loop);
3960 g_assert (got_ownership);
3963 LOCK_CONTEXT (loop->context);
3965 if (loop->context->in_check_or_prepare)
3967 g_warning ("g_main_loop_run(): called recursively from within a source's "
3968 "check() or prepare() member, iteration not possible.");
3972 g_atomic_int_inc (&loop->ref_count);
3973 loop->is_running = TRUE;
3974 while (loop->is_running)
3975 g_main_context_iterate (loop->context, TRUE, TRUE, self);
3977 UNLOCK_CONTEXT (loop->context);
3979 g_main_context_release (loop->context);
3981 g_main_loop_unref (loop);
3986 * @loop: a #GMainLoop
3988 * Stops a #GMainLoop from running. Any calls to g_main_loop_run()
3989 * for the loop will return.
3991 * Note that sources that have already been dispatched when
3992 * g_main_loop_quit() is called will still be executed.
3995 g_main_loop_quit (GMainLoop *loop)
3997 g_return_if_fail (loop != NULL);
3998 g_return_if_fail (g_atomic_int_get (&loop->ref_count) > 0);
4000 LOCK_CONTEXT (loop->context);
4001 loop->is_running = FALSE;
4002 g_wakeup_signal (loop->context->wakeup);
4004 g_cond_broadcast (&loop->context->cond);
4006 UNLOCK_CONTEXT (loop->context);
4010 * g_main_loop_is_running:
4011 * @loop: a #GMainLoop.
4013 * Checks to see if the main loop is currently being run via g_main_loop_run().
4015 * Returns: %TRUE if the mainloop is currently being run.
4018 g_main_loop_is_running (GMainLoop *loop)
4020 g_return_val_if_fail (loop != NULL, FALSE);
4021 g_return_val_if_fail (g_atomic_int_get (&loop->ref_count) > 0, FALSE);
4023 return loop->is_running;
4027 * g_main_loop_get_context:
4028 * @loop: a #GMainLoop.
4030 * Returns the #GMainContext of @loop.
4032 * Returns: (transfer none): the #GMainContext of @loop
4035 g_main_loop_get_context (GMainLoop *loop)
4037 g_return_val_if_fail (loop != NULL, NULL);
4038 g_return_val_if_fail (g_atomic_int_get (&loop->ref_count) > 0, NULL);
4040 return loop->context;
4043 /* HOLDS: context's lock */
4045 g_main_context_poll (GMainContext *context,
4051 #ifdef G_MAIN_POLL_DEBUG
4057 GPollFunc poll_func;
4059 if (n_fds || timeout != 0)
4061 #ifdef G_MAIN_POLL_DEBUG
4063 if (_g_main_poll_debug)
4065 g_print ("polling context=%p n=%d timeout=%d\n",
4066 context, n_fds, timeout);
4067 poll_timer = g_timer_new ();
4071 LOCK_CONTEXT (context);
4073 poll_func = context->poll_func;
4075 UNLOCK_CONTEXT (context);
4076 if ((*poll_func) (fds, n_fds, timeout) < 0 && errno != EINTR)
4079 g_warning ("poll(2) failed due to: %s.",
4080 g_strerror (errno));
4082 /* If g_poll () returns -1, it has already called g_warning() */
4086 #ifdef G_MAIN_POLL_DEBUG
4087 if (_g_main_poll_debug)
4089 LOCK_CONTEXT (context);
4091 g_print ("g_main_poll(%d) timeout: %d - elapsed %12.10f seconds",
4094 g_timer_elapsed (poll_timer, NULL));
4095 g_timer_destroy (poll_timer);
4096 pollrec = context->poll_records;
4098 while (pollrec != NULL)
4103 if (fds[i].fd == pollrec->fd->fd &&
4104 pollrec->fd->events &&
4107 g_print (" [" G_POLLFD_FORMAT " :", fds[i].fd);
4108 if (fds[i].revents & G_IO_IN)
4110 if (fds[i].revents & G_IO_OUT)
4112 if (fds[i].revents & G_IO_PRI)
4114 if (fds[i].revents & G_IO_ERR)
4116 if (fds[i].revents & G_IO_HUP)
4118 if (fds[i].revents & G_IO_NVAL)
4124 pollrec = pollrec->next;
4128 UNLOCK_CONTEXT (context);
4131 } /* if (n_fds || timeout != 0) */
4135 * g_main_context_add_poll:
4136 * @context: (allow-none): a #GMainContext (or %NULL for the default context)
4137 * @fd: a #GPollFD structure holding information about a file
4138 * descriptor to watch.
4139 * @priority: the priority for this file descriptor which should be
4140 * the same as the priority used for g_source_attach() to ensure that the
4141 * file descriptor is polled whenever the results may be needed.
4143 * Adds a file descriptor to the set of file descriptors polled for
4144 * this context. This will very seldom be used directly. Instead
4145 * a typical event source will use g_source_add_unix_fd() instead.
4148 g_main_context_add_poll (GMainContext *context,
4153 context = g_main_context_default ();
4155 g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
4156 g_return_if_fail (fd);
4158 LOCK_CONTEXT (context);
4159 g_main_context_add_poll_unlocked (context, priority, fd);
4160 UNLOCK_CONTEXT (context);
4163 /* HOLDS: main_loop_lock */
4165 g_main_context_add_poll_unlocked (GMainContext *context,
4169 GPollRec *prevrec, *nextrec;
4170 GPollRec *newrec = g_slice_new (GPollRec);
4172 /* This file descriptor may be checked before we ever poll */
4175 newrec->priority = priority;
4177 prevrec = context->poll_records_tail;
4179 while (prevrec && priority < prevrec->priority)
4182 prevrec = prevrec->prev;
4186 prevrec->next = newrec;
4188 context->poll_records = newrec;
4190 newrec->prev = prevrec;
4191 newrec->next = nextrec;
4194 nextrec->prev = newrec;
4196 context->poll_records_tail = newrec;
4198 context->n_poll_records++;
4200 context->poll_changed = TRUE;
4202 /* Now wake up the main loop if it is waiting in the poll() */
4203 g_wakeup_signal (context->wakeup);
4207 * g_main_context_remove_poll:
4208 * @context:a #GMainContext
4209 * @fd: a #GPollFD descriptor previously added with g_main_context_add_poll()
4211 * Removes file descriptor from the set of file descriptors to be
4212 * polled for a particular context.
4215 g_main_context_remove_poll (GMainContext *context,
4219 context = g_main_context_default ();
4221 g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
4222 g_return_if_fail (fd);
4224 LOCK_CONTEXT (context);
4225 g_main_context_remove_poll_unlocked (context, fd);
4226 UNLOCK_CONTEXT (context);
4230 g_main_context_remove_poll_unlocked (GMainContext *context,
4233 GPollRec *pollrec, *prevrec, *nextrec;
4236 pollrec = context->poll_records;
4240 nextrec = pollrec->next;
4241 if (pollrec->fd == fd)
4243 if (prevrec != NULL)
4244 prevrec->next = nextrec;
4246 context->poll_records = nextrec;
4248 if (nextrec != NULL)
4249 nextrec->prev = prevrec;
4251 context->poll_records_tail = prevrec;
4253 g_slice_free (GPollRec, pollrec);
4255 context->n_poll_records--;
4262 context->poll_changed = TRUE;
4264 /* Now wake up the main loop if it is waiting in the poll() */
4265 g_wakeup_signal (context->wakeup);
4269 * g_source_get_current_time:
4270 * @source: a #GSource
4271 * @timeval: #GTimeVal structure in which to store current time.
4273 * This function ignores @source and is otherwise the same as
4274 * g_get_current_time().
4276 * Deprecated: 2.28: use g_source_get_time() instead
4279 g_source_get_current_time (GSource *source,
4282 g_get_current_time (timeval);
4286 * g_source_get_time:
4287 * @source: a #GSource
4289 * Gets the time to be used when checking this source. The advantage of
4290 * calling this function over calling g_get_monotonic_time() directly is
4291 * that when checking multiple sources, GLib can cache a single value
4292 * instead of having to repeatedly get the system monotonic time.
4294 * The time here is the system monotonic time, if available, or some
4295 * other reasonable alternative otherwise. See g_get_monotonic_time().
4297 * Returns: the monotonic time in microseconds
4302 g_source_get_time (GSource *source)
4304 GMainContext *context;
4307 g_return_val_if_fail (source->context != NULL, 0);
4309 context = source->context;
4311 LOCK_CONTEXT (context);
4313 if (!context->time_is_fresh)
4315 context->time = g_get_monotonic_time ();
4316 context->time_is_fresh = TRUE;
4319 result = context->time;
4321 UNLOCK_CONTEXT (context);
4327 * g_main_context_set_poll_func:
4328 * @context: a #GMainContext
4329 * @func: the function to call to poll all file descriptors
4331 * Sets the function to use to handle polling of file descriptors. It
4332 * will be used instead of the poll() system call
4333 * (or GLib's replacement function, which is used where
4334 * poll() isn't available).
4336 * This function could possibly be used to integrate the GLib event
4337 * loop with an external event loop.
4340 g_main_context_set_poll_func (GMainContext *context,
4344 context = g_main_context_default ();
4346 g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
4348 LOCK_CONTEXT (context);
4351 context->poll_func = func;
4353 context->poll_func = g_poll;
4355 UNLOCK_CONTEXT (context);
4359 * g_main_context_get_poll_func:
4360 * @context: a #GMainContext
4362 * Gets the poll function set by g_main_context_set_poll_func().
4364 * Returns: the poll function
4367 g_main_context_get_poll_func (GMainContext *context)
4372 context = g_main_context_default ();
4374 g_return_val_if_fail (g_atomic_int_get (&context->ref_count) > 0, NULL);
4376 LOCK_CONTEXT (context);
4377 result = context->poll_func;
4378 UNLOCK_CONTEXT (context);
4384 * g_main_context_wakeup:
4385 * @context: a #GMainContext
4387 * If @context is currently blocking in g_main_context_iteration()
4388 * waiting for a source to become ready, cause it to stop blocking
4389 * and return. Otherwise, cause the next invocation of
4390 * g_main_context_iteration() to return without blocking.
4392 * This API is useful for low-level control over #GMainContext; for
4393 * example, integrating it with main loop implementations such as
4396 * Another related use for this function is when implementing a main
4397 * loop with a termination condition, computed from multiple threads:
4399 * |[<!-- language="C" -->
4400 * #define NUM_TASKS 10
4401 * static volatile gint tasks_remaining = NUM_TASKS;
4404 * while (g_atomic_int_get (&tasks_remaining) != 0)
4405 * g_main_context_iteration (NULL, TRUE);
4409 * |[<!-- language="C" -->
4412 * if (g_atomic_int_dec_and_test (&tasks_remaining))
4413 * g_main_context_wakeup (NULL);
4417 g_main_context_wakeup (GMainContext *context)
4420 context = g_main_context_default ();
4422 g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
4424 g_wakeup_signal (context->wakeup);
4428 * g_main_context_is_owner:
4429 * @context: a #GMainContext
4431 * Determines whether this thread holds the (recursive)
4432 * ownership of this #GMainContext. This is useful to
4433 * know before waiting on another thread that may be
4434 * blocking to get ownership of @context.
4436 * Returns: %TRUE if current thread is owner of @context.
4441 g_main_context_is_owner (GMainContext *context)
4446 context = g_main_context_default ();
4448 LOCK_CONTEXT (context);
4449 is_owner = context->owner == G_THREAD_SELF;
4450 UNLOCK_CONTEXT (context);
4458 g_timeout_set_expiration (GTimeoutSource *timeout_source,
4459 gint64 current_time)
4463 expiration = current_time + (guint64) timeout_source->interval * 1000;
4465 if (timeout_source->seconds)
4468 static gint timer_perturb = -1;
4470 if (timer_perturb == -1)
4473 * we want a per machine/session unique 'random' value; try the dbus
4474 * address first, that has a UUID in it. If there is no dbus, use the
4475 * hostname for hashing.
4477 const char *session_bus_address = g_getenv ("DBUS_SESSION_BUS_ADDRESS");
4478 if (!session_bus_address)
4479 session_bus_address = g_getenv ("HOSTNAME");
4480 if (session_bus_address)
4481 timer_perturb = ABS ((gint) g_str_hash (session_bus_address)) % 1000000;
4486 /* We want the microseconds part of the timeout to land on the
4487 * 'timer_perturb' mark, but we need to make sure we don't try to
4488 * set the timeout in the past. We do this by ensuring that we
4489 * always only *increase* the expiration time by adding a full
4490 * second in the case that the microsecond portion decreases.
4492 expiration -= timer_perturb;
4494 remainder = expiration % 1000000;
4495 if (remainder >= 1000000/4)
4496 expiration += 1000000;
4498 expiration -= remainder;
4499 expiration += timer_perturb;
4502 g_source_set_ready_time ((GSource *) timeout_source, expiration);
4506 g_timeout_dispatch (GSource *source,
4507 GSourceFunc callback,
4510 GTimeoutSource *timeout_source = (GTimeoutSource *)source;
4515 g_warning ("Timeout source dispatched without callback\n"
4516 "You must call g_source_set_callback().");
4520 again = callback (user_data);
4523 g_timeout_set_expiration (timeout_source, g_source_get_time (source));
4529 * g_timeout_source_new:
4530 * @interval: the timeout interval in milliseconds.
4532 * Creates a new timeout source.
4534 * The source will not initially be associated with any #GMainContext
4535 * and must be added to one with g_source_attach() before it will be
4538 * The interval given is in terms of monotonic time, not wall clock
4539 * time. See g_get_monotonic_time().
4541 * Returns: the newly-created timeout source
4544 g_timeout_source_new (guint interval)
4546 GSource *source = g_source_new (&g_timeout_funcs, sizeof (GTimeoutSource));
4547 GTimeoutSource *timeout_source = (GTimeoutSource *)source;
4549 timeout_source->interval = interval;
4550 g_timeout_set_expiration (timeout_source, g_get_monotonic_time ());
4556 * g_timeout_source_new_seconds:
4557 * @interval: the timeout interval in seconds
4559 * Creates a new timeout source.
4561 * The source will not initially be associated with any #GMainContext
4562 * and must be added to one with g_source_attach() before it will be
4565 * The scheduling granularity/accuracy of this timeout source will be
4568 * The interval given in terms of monotonic time, not wall clock time.
4569 * See g_get_monotonic_time().
4571 * Returns: the newly-created timeout source
4576 g_timeout_source_new_seconds (guint interval)
4578 GSource *source = g_source_new (&g_timeout_funcs, sizeof (GTimeoutSource));
4579 GTimeoutSource *timeout_source = (GTimeoutSource *)source;
4581 timeout_source->interval = 1000 * interval;
4582 timeout_source->seconds = TRUE;
4584 g_timeout_set_expiration (timeout_source, g_get_monotonic_time ());
4591 * g_timeout_add_full:
4592 * @priority: the priority of the timeout source. Typically this will be in
4593 * the range between #G_PRIORITY_DEFAULT and #G_PRIORITY_HIGH.
4594 * @interval: the time between calls to the function, in milliseconds
4595 * (1/1000ths of a second)
4596 * @function: function to call
4597 * @data: data to pass to @function
4598 * @notify: (allow-none): function to call when the timeout is removed, or %NULL
4600 * Sets a function to be called at regular intervals, with the given
4601 * priority. The function is called repeatedly until it returns
4602 * %FALSE, at which point the timeout is automatically destroyed and
4603 * the function will not be called again. The @notify function is
4604 * called when the timeout is destroyed. The first call to the
4605 * function will be at the end of the first @interval.
4607 * Note that timeout functions may be delayed, due to the processing of other
4608 * event sources. Thus they should not be relied on for precise timing.
4609 * After each call to the timeout function, the time of the next
4610 * timeout is recalculated based on the current time and the given interval
4611 * (it does not try to 'catch up' time lost in delays).
4613 * This internally creates a main loop source using g_timeout_source_new()
4614 * and attaches it to the main loop context using g_source_attach(). You can
4615 * do these steps manually if you need greater control.
4617 * The interval given in terms of monotonic time, not wall clock time.
4618 * See g_get_monotonic_time().
4620 * Returns: the ID (greater than 0) of the event source.
4621 * Rename to: g_timeout_add
4624 g_timeout_add_full (gint priority,
4626 GSourceFunc function,
4628 GDestroyNotify notify)
4633 g_return_val_if_fail (function != NULL, 0);
4635 source = g_timeout_source_new (interval);
4637 if (priority != G_PRIORITY_DEFAULT)
4638 g_source_set_priority (source, priority);
4640 g_source_set_callback (source, function, data, notify);
4641 id = g_source_attach (source, NULL);
4642 g_source_unref (source);
4649 * @interval: the time between calls to the function, in milliseconds
4650 * (1/1000ths of a second)
4651 * @function: function to call
4652 * @data: data to pass to @function
4654 * Sets a function to be called at regular intervals, with the default
4655 * priority, #G_PRIORITY_DEFAULT. The function is called repeatedly
4656 * until it returns %FALSE, at which point the timeout is automatically
4657 * destroyed and the function will not be called again. The first call
4658 * to the function will be at the end of the first @interval.
4660 * Note that timeout functions may be delayed, due to the processing of other
4661 * event sources. Thus they should not be relied on for precise timing.
4662 * After each call to the timeout function, the time of the next
4663 * timeout is recalculated based on the current time and the given interval
4664 * (it does not try to 'catch up' time lost in delays).
4666 * If you want to have a timer in the "seconds" range and do not care
4667 * about the exact time of the first call of the timer, use the
4668 * g_timeout_add_seconds() function; this function allows for more
4669 * optimizations and more efficient system power usage.
4671 * This internally creates a main loop source using g_timeout_source_new()
4672 * and attaches it to the main loop context using g_source_attach(). You can
4673 * do these steps manually if you need greater control.
4675 * The interval given is in terms of monotonic time, not wall clock
4676 * time. See g_get_monotonic_time().
4678 * Returns: the ID (greater than 0) of the event source.
4681 g_timeout_add (guint32 interval,
4682 GSourceFunc function,
4685 return g_timeout_add_full (G_PRIORITY_DEFAULT,
4686 interval, function, data, NULL);
4690 * g_timeout_add_seconds_full:
4691 * @priority: the priority of the timeout source. Typically this will be in
4692 * the range between #G_PRIORITY_DEFAULT and #G_PRIORITY_HIGH.
4693 * @interval: the time between calls to the function, in seconds
4694 * @function: function to call
4695 * @data: data to pass to @function
4696 * @notify: (allow-none): function to call when the timeout is removed, or %NULL
4698 * Sets a function to be called at regular intervals, with @priority.
4699 * The function is called repeatedly until it returns %FALSE, at which
4700 * point the timeout is automatically destroyed and the function will
4701 * not be called again.
4703 * Unlike g_timeout_add(), this function operates at whole second granularity.
4704 * The initial starting point of the timer is determined by the implementation
4705 * and the implementation is expected to group multiple timers together so that
4706 * they fire all at the same time.
4707 * To allow this grouping, the @interval to the first timer is rounded
4708 * and can deviate up to one second from the specified interval.
4709 * Subsequent timer iterations will generally run at the specified interval.
4711 * Note that timeout functions may be delayed, due to the processing of other
4712 * event sources. Thus they should not be relied on for precise timing.
4713 * After each call to the timeout function, the time of the next
4714 * timeout is recalculated based on the current time and the given @interval
4716 * If you want timing more precise than whole seconds, use g_timeout_add()
4719 * The grouping of timers to fire at the same time results in a more power
4720 * and CPU efficient behavior so if your timer is in multiples of seconds
4721 * and you don't require the first timer exactly one second from now, the
4722 * use of g_timeout_add_seconds() is preferred over g_timeout_add().
4724 * This internally creates a main loop source using
4725 * g_timeout_source_new_seconds() and attaches it to the main loop context
4726 * using g_source_attach(). You can do these steps manually if you need
4729 * The interval given is in terms of monotonic time, not wall clock
4730 * time. See g_get_monotonic_time().
4732 * Returns: the ID (greater than 0) of the event source.
4734 * Rename to: g_timeout_add_seconds
4738 g_timeout_add_seconds_full (gint priority,
4740 GSourceFunc function,
4742 GDestroyNotify notify)
4747 g_return_val_if_fail (function != NULL, 0);
4749 source = g_timeout_source_new_seconds (interval);
4751 if (priority != G_PRIORITY_DEFAULT)
4752 g_source_set_priority (source, priority);
4754 g_source_set_callback (source, function, data, notify);
4755 id = g_source_attach (source, NULL);
4756 g_source_unref (source);
4762 * g_timeout_add_seconds:
4763 * @interval: the time between calls to the function, in seconds
4764 * @function: function to call
4765 * @data: data to pass to @function
4767 * Sets a function to be called at regular intervals with the default
4768 * priority, #G_PRIORITY_DEFAULT. The function is called repeatedly until
4769 * it returns %FALSE, at which point the timeout is automatically destroyed
4770 * and the function will not be called again.
4772 * This internally creates a main loop source using
4773 * g_timeout_source_new_seconds() and attaches it to the main loop context
4774 * using g_source_attach(). You can do these steps manually if you need
4775 * greater control. Also see g_timeout_add_seconds_full().
4777 * Note that the first call of the timer may not be precise for timeouts
4778 * of one second. If you need finer precision and have such a timeout,
4779 * you may want to use g_timeout_add() instead.
4781 * The interval given is in terms of monotonic time, not wall clock
4782 * time. See g_get_monotonic_time().
4784 * Returns: the ID (greater than 0) of the event source.
4789 g_timeout_add_seconds (guint interval,
4790 GSourceFunc function,
4793 g_return_val_if_fail (function != NULL, 0);
4795 return g_timeout_add_seconds_full (G_PRIORITY_DEFAULT, interval, function, data, NULL);
4798 /* Child watch functions */
4803 g_child_watch_prepare (GSource *source,
4811 g_child_watch_check (GSource *source)
4813 GChildWatchSource *child_watch_source;
4814 gboolean child_exited;
4816 child_watch_source = (GChildWatchSource *) source;
4818 child_exited = child_watch_source->poll.revents & G_IO_IN;
4825 * Note: We do _not_ check for the special value of STILL_ACTIVE
4826 * since we know that the process has exited and doing so runs into
4827 * problems if the child process "happens to return STILL_ACTIVE(259)"
4828 * as Microsoft's Platform SDK puts it.
4830 if (!GetExitCodeProcess (child_watch_source->pid, &child_status))
4832 gchar *emsg = g_win32_error_message (GetLastError ());
4833 g_warning (G_STRLOC ": GetExitCodeProcess() failed: %s", emsg);
4836 child_watch_source->child_status = -1;
4839 child_watch_source->child_status = child_status;
4842 return child_exited;
4846 g_child_watch_finalize (GSource *source)
4850 #else /* G_OS_WIN32 */
4853 wake_source (GSource *source)
4855 GMainContext *context;
4857 /* This should be thread-safe:
4859 * - if the source is currently being added to a context, that
4860 * context will be woken up anyway
4862 * - if the source is currently being destroyed, we simply need not
4865 * - the memory for the source will remain valid until after the
4866 * source finalize function was called (which would remove the
4867 * source from the global list which we are currently holding the
4870 * - the GMainContext will either be NULL or point to a live
4873 * - the GMainContext will remain valid since we hold the
4874 * main_context_list lock
4876 * Since we are holding a lot of locks here, don't try to enter any
4877 * more GMainContext functions for fear of dealock -- just hit the
4878 * GWakeup and run. Even if that's safe now, it could easily become
4879 * unsafe with some very minor changes in the future, and signal
4880 * handling is not the most well-tested codepath.
4882 G_LOCK(main_context_list);
4883 context = source->context;
4885 g_wakeup_signal (context->wakeup);
4886 G_UNLOCK(main_context_list);
4890 dispatch_unix_signals_unlocked (void)
4892 gboolean pending[NSIG];
4896 /* clear this first incase another one arrives while we're processing */
4897 any_unix_signal_pending = FALSE;
4899 /* We atomically test/clear the bit from the global array in case
4900 * other signals arrive while we are dispatching.
4902 * We then can safely use our own array below without worrying about
4905 for (i = 0; i < NSIG; i++)
4907 /* Be very careful with (the volatile) unix_signal_pending.
4909 * We must ensure that it's not possible that we clear it without
4910 * handling the signal. We therefore must ensure that our pending
4911 * array has a field set (ie: we will do something about the
4912 * signal) before we clear the item in unix_signal_pending.
4914 * Note specifically: we must check _our_ array.
4916 pending[i] = unix_signal_pending[i];
4918 unix_signal_pending[i] = FALSE;
4921 /* handle GChildWatchSource instances */
4922 if (pending[SIGCHLD])
4924 /* The only way we can do this is to scan all of the children.
4926 * The docs promise that we will not reap children that we are not
4927 * explicitly watching, so that ties our hands from calling
4928 * waitpid(-1). We also can't use siginfo's si_pid field since if
4929 * multiple SIGCHLD arrive at the same time, one of them can be
4930 * dropped (since a given UNIX signal can only be pending once).
4932 for (node = unix_child_watches; node; node = node->next)
4934 GChildWatchSource *source = node->data;
4936 if (!source->child_exited)
4941 g_assert (source->pid > 0);
4943 pid = waitpid (source->pid, &source->child_status, WNOHANG);
4946 source->child_exited = TRUE;
4947 wake_source ((GSource *) source);
4949 else if (pid == -1 && errno == ECHILD)
4951 g_warning ("GChildWatchSource: Exit status of a child process was requested but ECHILD was received by waitpid(). Most likely the process is ignoring SIGCHLD, or some other thread is invoking waitpid() with a nonpositive first argument; either behavior can break applications that use g_child_watch_add()/g_spawn_sync() either directly or indirectly.");
4952 source->child_exited = TRUE;
4953 source->child_status = 0;
4954 wake_source ((GSource *) source);
4957 while (pid == -1 && errno == EINTR);
4962 /* handle GUnixSignalWatchSource instances */
4963 for (node = unix_signal_watches; node; node = node->next)
4965 GUnixSignalWatchSource *source = node->data;
4967 if (!source->pending)
4969 if (pending[source->signum])
4971 source->pending = TRUE;
4973 wake_source ((GSource *) source);
4981 dispatch_unix_signals (void)
4983 G_LOCK(unix_signal_lock);
4984 dispatch_unix_signals_unlocked ();
4985 G_UNLOCK(unix_signal_lock);
4989 g_child_watch_prepare (GSource *source,
4992 GChildWatchSource *child_watch_source;
4994 child_watch_source = (GChildWatchSource *) source;
4996 return child_watch_source->child_exited;
5000 g_child_watch_check (GSource *source)
5002 GChildWatchSource *child_watch_source;
5004 child_watch_source = (GChildWatchSource *) source;
5006 return child_watch_source->child_exited;
5010 g_unix_signal_watch_prepare (GSource *source,
5013 GUnixSignalWatchSource *unix_signal_source;
5015 unix_signal_source = (GUnixSignalWatchSource *) source;
5017 return unix_signal_source->pending;
5021 g_unix_signal_watch_check (GSource *source)
5023 GUnixSignalWatchSource *unix_signal_source;
5025 unix_signal_source = (GUnixSignalWatchSource *) source;
5027 return unix_signal_source->pending;
5031 g_unix_signal_watch_dispatch (GSource *source,
5032 GSourceFunc callback,
5035 GUnixSignalWatchSource *unix_signal_source;
5038 unix_signal_source = (GUnixSignalWatchSource *) source;
5042 g_warning ("Unix signal source dispatched without callback\n"
5043 "You must call g_source_set_callback().");
5047 again = (callback) (user_data);
5049 unix_signal_source->pending = FALSE;
5055 ref_unix_signal_handler_unlocked (int signum)
5057 /* Ensure we have the worker context */
5058 g_get_worker_context ();
5059 unix_signal_refcount[signum]++;
5060 if (unix_signal_refcount[signum] == 1)
5062 struct sigaction action;
5063 action.sa_handler = g_unix_signal_handler;
5064 sigemptyset (&action.sa_mask);
5066 action.sa_flags = SA_RESTART | SA_NOCLDSTOP;
5068 action.sa_flags = SA_NOCLDSTOP;
5070 sigaction (signum, &action, NULL);
5075 unref_unix_signal_handler_unlocked (int signum)
5077 unix_signal_refcount[signum]--;
5078 if (unix_signal_refcount[signum] == 0)
5080 struct sigaction action;
5081 memset (&action, 0, sizeof (action));
5082 action.sa_handler = SIG_DFL;
5083 sigemptyset (&action.sa_mask);
5084 sigaction (signum, &action, NULL);
5089 _g_main_create_unix_signal_watch (int signum)
5092 GUnixSignalWatchSource *unix_signal_source;
5094 source = g_source_new (&g_unix_signal_funcs, sizeof (GUnixSignalWatchSource));
5095 unix_signal_source = (GUnixSignalWatchSource *) source;
5097 unix_signal_source->signum = signum;
5098 unix_signal_source->pending = FALSE;
5100 G_LOCK (unix_signal_lock);
5101 ref_unix_signal_handler_unlocked (signum);
5102 unix_signal_watches = g_slist_prepend (unix_signal_watches, unix_signal_source);
5103 dispatch_unix_signals_unlocked ();
5104 G_UNLOCK (unix_signal_lock);
5110 g_unix_signal_watch_finalize (GSource *source)
5112 GUnixSignalWatchSource *unix_signal_source;
5114 unix_signal_source = (GUnixSignalWatchSource *) source;
5116 G_LOCK (unix_signal_lock);
5117 unref_unix_signal_handler_unlocked (unix_signal_source->signum);
5118 unix_signal_watches = g_slist_remove (unix_signal_watches, source);
5119 G_UNLOCK (unix_signal_lock);
5123 g_child_watch_finalize (GSource *source)
5125 G_LOCK (unix_signal_lock);
5126 unix_child_watches = g_slist_remove (unix_child_watches, source);
5127 unref_unix_signal_handler_unlocked (SIGCHLD);
5128 G_UNLOCK (unix_signal_lock);
5131 #endif /* G_OS_WIN32 */
5134 g_child_watch_dispatch (GSource *source,
5135 GSourceFunc callback,
5138 GChildWatchSource *child_watch_source;
5139 GChildWatchFunc child_watch_callback = (GChildWatchFunc) callback;
5141 child_watch_source = (GChildWatchSource *) source;
5145 g_warning ("Child watch source dispatched without callback\n"
5146 "You must call g_source_set_callback().");
5150 (child_watch_callback) (child_watch_source->pid, child_watch_source->child_status, user_data);
5152 /* We never keep a child watch source around as the child is gone */
5159 g_unix_signal_handler (int signum)
5161 unix_signal_pending[signum] = TRUE;
5162 any_unix_signal_pending = TRUE;
5164 g_wakeup_signal (glib_worker_context->wakeup);
5167 #endif /* !G_OS_WIN32 */
5170 * g_child_watch_source_new:
5171 * @pid: process to watch. On POSIX the positive pid of a child process. On
5172 * Windows a handle for a process (which doesn't have to be a child).
5174 * Creates a new child_watch source.
5176 * The source will not initially be associated with any #GMainContext
5177 * and must be added to one with g_source_attach() before it will be
5180 * Note that child watch sources can only be used in conjunction with
5181 * `g_spawn...` when the %G_SPAWN_DO_NOT_REAP_CHILD flag is used.
5183 * Note that on platforms where #GPid must be explicitly closed
5184 * (see g_spawn_close_pid()) @pid must not be closed while the
5185 * source is still active. Typically, you will want to call
5186 * g_spawn_close_pid() in the callback function for the source.
5188 * Note further that using g_child_watch_source_new() is not
5189 * compatible with calling `waitpid` with a nonpositive first
5190 * argument in the application. Calling waitpid() for individual
5191 * pids will still work fine.
5193 * Similarly, on POSIX platforms, the @pid passed to this function must
5194 * be greater than 0 (i.e. this function must wait for a specific child,
5195 * and cannot wait for one of many children by using a nonpositive argument).
5197 * Returns: the newly-created child watch source
5202 g_child_watch_source_new (GPid pid)
5205 GChildWatchSource *child_watch_source;
5208 g_return_val_if_fail (pid > 0, NULL);
5211 source = g_source_new (&g_child_watch_funcs, sizeof (GChildWatchSource));
5212 child_watch_source = (GChildWatchSource *)source;
5214 child_watch_source->pid = pid;
5217 child_watch_source->poll.fd = (gintptr) pid;
5218 child_watch_source->poll.events = G_IO_IN;
5220 g_source_add_poll (source, &child_watch_source->poll);
5221 #else /* G_OS_WIN32 */
5222 G_LOCK (unix_signal_lock);
5223 ref_unix_signal_handler_unlocked (SIGCHLD);
5224 unix_child_watches = g_slist_prepend (unix_child_watches, child_watch_source);
5225 if (waitpid (pid, &child_watch_source->child_status, WNOHANG) > 0)
5226 child_watch_source->child_exited = TRUE;
5227 G_UNLOCK (unix_signal_lock);
5228 #endif /* G_OS_WIN32 */
5234 * g_child_watch_add_full:
5235 * @priority: the priority of the idle source. Typically this will be in the
5236 * range between #G_PRIORITY_DEFAULT_IDLE and #G_PRIORITY_HIGH_IDLE.
5237 * @pid: process to watch. On POSIX the positive pid of a child process. On
5238 * Windows a handle for a process (which doesn't have to be a child).
5239 * @function: function to call
5240 * @data: data to pass to @function
5241 * @notify: (allow-none): function to call when the idle is removed, or %NULL
5243 * Sets a function to be called when the child indicated by @pid
5244 * exits, at the priority @priority.
5246 * If you obtain @pid from g_spawn_async() or g_spawn_async_with_pipes()
5247 * you will need to pass #G_SPAWN_DO_NOT_REAP_CHILD as flag to
5248 * the spawn function for the child watching to work.
5250 * In many programs, you will want to call g_spawn_check_exit_status()
5251 * in the callback to determine whether or not the child exited
5254 * Also, note that on platforms where #GPid must be explicitly closed
5255 * (see g_spawn_close_pid()) @pid must not be closed while the source
5256 * is still active. Typically, you should invoke g_spawn_close_pid()
5257 * in the callback function for the source.
5259 * GLib supports only a single callback per process id.
5261 * This internally creates a main loop source using
5262 * g_child_watch_source_new() and attaches it to the main loop context
5263 * using g_source_attach(). You can do these steps manually if you
5264 * need greater control.
5266 * Returns: the ID (greater than 0) of the event source.
5268 * Rename to: g_child_watch_add
5272 g_child_watch_add_full (gint priority,
5274 GChildWatchFunc function,
5276 GDestroyNotify notify)
5281 g_return_val_if_fail (function != NULL, 0);
5283 g_return_val_if_fail (pid > 0, 0);
5286 source = g_child_watch_source_new (pid);
5288 if (priority != G_PRIORITY_DEFAULT)
5289 g_source_set_priority (source, priority);
5291 g_source_set_callback (source, (GSourceFunc) function, data, notify);
5292 id = g_source_attach (source, NULL);
5293 g_source_unref (source);
5299 * g_child_watch_add:
5300 * @pid: process id to watch. On POSIX the positive pid of a child
5301 * process. On Windows a handle for a process (which doesn't have to be
5303 * @function: function to call
5304 * @data: data to pass to @function
5306 * Sets a function to be called when the child indicated by @pid
5307 * exits, at a default priority, #G_PRIORITY_DEFAULT.
5309 * If you obtain @pid from g_spawn_async() or g_spawn_async_with_pipes()
5310 * you will need to pass #G_SPAWN_DO_NOT_REAP_CHILD as flag to
5311 * the spawn function for the child watching to work.
5313 * Note that on platforms where #GPid must be explicitly closed
5314 * (see g_spawn_close_pid()) @pid must not be closed while the
5315 * source is still active. Typically, you will want to call
5316 * g_spawn_close_pid() in the callback function for the source.
5318 * GLib supports only a single callback per process id.
5320 * This internally creates a main loop source using
5321 * g_child_watch_source_new() and attaches it to the main loop context
5322 * using g_source_attach(). You can do these steps manually if you
5323 * need greater control.
5325 * Returns: the ID (greater than 0) of the event source.
5330 g_child_watch_add (GPid pid,
5331 GChildWatchFunc function,
5334 return g_child_watch_add_full (G_PRIORITY_DEFAULT, pid, function, data, NULL);
5338 /* Idle functions */
5341 g_idle_prepare (GSource *source,
5350 g_idle_check (GSource *source)
5356 g_idle_dispatch (GSource *source,
5357 GSourceFunc callback,
5362 g_warning ("Idle source dispatched without callback\n"
5363 "You must call g_source_set_callback().");
5367 return callback (user_data);
5371 * g_idle_source_new:
5373 * Creates a new idle source.
5375 * The source will not initially be associated with any #GMainContext
5376 * and must be added to one with g_source_attach() before it will be
5377 * executed. Note that the default priority for idle sources is
5378 * %G_PRIORITY_DEFAULT_IDLE, as compared to other sources which
5379 * have a default priority of %G_PRIORITY_DEFAULT.
5381 * Returns: the newly-created idle source
5384 g_idle_source_new (void)
5388 source = g_source_new (&g_idle_funcs, sizeof (GSource));
5389 g_source_set_priority (source, G_PRIORITY_DEFAULT_IDLE);
5396 * @priority: the priority of the idle source. Typically this will be in the
5397 * range between #G_PRIORITY_DEFAULT_IDLE and #G_PRIORITY_HIGH_IDLE.
5398 * @function: function to call
5399 * @data: data to pass to @function
5400 * @notify: (allow-none): function to call when the idle is removed, or %NULL
5402 * Adds a function to be called whenever there are no higher priority
5403 * events pending. If the function returns %FALSE it is automatically
5404 * removed from the list of event sources and will not be called again.
5406 * This internally creates a main loop source using g_idle_source_new()
5407 * and attaches it to the main loop context using g_source_attach().
5408 * You can do these steps manually if you need greater control.
5410 * Returns: the ID (greater than 0) of the event source.
5411 * Rename to: g_idle_add
5414 g_idle_add_full (gint priority,
5415 GSourceFunc function,
5417 GDestroyNotify notify)
5422 g_return_val_if_fail (function != NULL, 0);
5424 source = g_idle_source_new ();
5426 if (priority != G_PRIORITY_DEFAULT_IDLE)
5427 g_source_set_priority (source, priority);
5429 g_source_set_callback (source, function, data, notify);
5430 id = g_source_attach (source, NULL);
5431 g_source_unref (source);
5438 * @function: function to call
5439 * @data: data to pass to @function.
5441 * Adds a function to be called whenever there are no higher priority
5442 * events pending to the default main loop. The function is given the
5443 * default idle priority, #G_PRIORITY_DEFAULT_IDLE. If the function
5444 * returns %FALSE it is automatically removed from the list of event
5445 * sources and will not be called again.
5447 * This internally creates a main loop source using g_idle_source_new()
5448 * and attaches it to the main loop context using g_source_attach().
5449 * You can do these steps manually if you need greater control.
5451 * Returns: the ID (greater than 0) of the event source.
5454 g_idle_add (GSourceFunc function,
5457 return g_idle_add_full (G_PRIORITY_DEFAULT_IDLE, function, data, NULL);
5461 * g_idle_remove_by_data:
5462 * @data: the data for the idle source's callback.
5464 * Removes the idle function with the given data.
5466 * Returns: %TRUE if an idle source was found and removed.
5469 g_idle_remove_by_data (gpointer data)
5471 return g_source_remove_by_funcs_user_data (&g_idle_funcs, data);
5475 * g_main_context_invoke:
5476 * @context: (allow-none): a #GMainContext, or %NULL
5477 * @function: function to call
5478 * @data: data to pass to @function
5480 * Invokes a function in such a way that @context is owned during the
5481 * invocation of @function.
5483 * If @context is %NULL then the global default main context — as
5484 * returned by g_main_context_default() — is used.
5486 * If @context is owned by the current thread, @function is called
5487 * directly. Otherwise, if @context is the thread-default main context
5488 * of the current thread and g_main_context_acquire() succeeds, then
5489 * @function is called and g_main_context_release() is called
5492 * In any other case, an idle source is created to call @function and
5493 * that source is attached to @context (presumably to be run in another
5494 * thread). The idle source is attached with #G_PRIORITY_DEFAULT
5495 * priority. If you want a different priority, use
5496 * g_main_context_invoke_full().
5498 * Note that, as with normal idle functions, @function should probably
5499 * return %FALSE. If it returns %TRUE, it will be continuously run in a
5500 * loop (and may prevent this call from returning).
5505 g_main_context_invoke (GMainContext *context,
5506 GSourceFunc function,
5509 g_main_context_invoke_full (context,
5511 function, data, NULL);
5515 * g_main_context_invoke_full:
5516 * @context: (allow-none): a #GMainContext, or %NULL
5517 * @priority: the priority at which to run @function
5518 * @function: function to call
5519 * @data: data to pass to @function
5520 * @notify: (allow-none): a function to call when @data is no longer in use, or %NULL.
5522 * Invokes a function in such a way that @context is owned during the
5523 * invocation of @function.
5525 * This function is the same as g_main_context_invoke() except that it
5526 * lets you specify the priority incase @function ends up being
5527 * scheduled as an idle and also lets you give a #GDestroyNotify for @data.
5529 * @notify should not assume that it is called from any particular
5530 * thread or with any particular context acquired.
5535 g_main_context_invoke_full (GMainContext *context,
5537 GSourceFunc function,
5539 GDestroyNotify notify)
5541 g_return_if_fail (function != NULL);
5544 context = g_main_context_default ();
5546 if (g_main_context_is_owner (context))
5548 while (function (data));
5555 GMainContext *thread_default;
5557 thread_default = g_main_context_get_thread_default ();
5559 if (!thread_default)
5560 thread_default = g_main_context_default ();
5562 if (thread_default == context && g_main_context_acquire (context))
5564 while (function (data));
5566 g_main_context_release (context);
5575 source = g_idle_source_new ();
5576 g_source_set_priority (source, priority);
5577 g_source_set_callback (source, function, data, notify);
5578 g_source_attach (source, context);
5579 g_source_unref (source);
5585 glib_worker_main (gpointer data)
5589 g_main_context_iteration (glib_worker_context, TRUE);
5592 if (any_unix_signal_pending)
5593 dispatch_unix_signals ();
5597 return NULL; /* worst GCC warning message ever... */
5601 g_get_worker_context (void)
5603 static gsize initialised;
5605 if (g_once_init_enter (&initialised))
5607 /* mask all signals in the worker thread */
5613 pthread_sigmask (SIG_SETMASK, &all, &prev_mask);
5615 glib_worker_context = g_main_context_new ();
5616 g_thread_new ("gmain", glib_worker_main, NULL);
5618 pthread_sigmask (SIG_SETMASK, &prev_mask, NULL);
5620 g_once_init_leave (&initialised, TRUE);
5623 return glib_worker_context;