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, write to the
19 * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
20 * Boston, MA 02111-1307, USA.
24 * Modified by the GLib Team and others 1997-2000. See the AUTHORS
25 * file for a list of people on the GLib Team. See the ChangeLog
26 * files for a list of changes. These files are distributed with
27 * GLib at ftp://ftp.gtk.org/pub/gtk/.
35 #include "glibconfig.h"
37 /* Uncomment the next line (and the corresponding line in gpoll.c) to
38 * enable debugging printouts if the environment variable
39 * G_MAIN_POLL_DEBUG is set to some value.
41 /* #define G_MAIN_POLL_DEBUG */
44 /* Always enable debugging printout on Windows, as it is more often
47 #define G_MAIN_POLL_DEBUG
51 #include "glib-unix.h"
54 #include <sys/eventfd.h>
59 #include <sys/types.h>
62 #ifdef HAVE_SYS_TIME_H
64 #endif /* HAVE_SYS_TIME_H */
67 #endif /* HAVE_UNISTD_H */
74 #endif /* G_OS_WIN32 */
77 #include <sys/socket.h>
79 #endif /* G_OS_BEOS */
84 #include "giochannel.h"
88 #include "gstrfuncs.h"
89 #include "gtestutils.h"
95 #ifdef G_MAIN_POLL_DEBUG
100 #include "gmain-internal.h"
101 #include "glib-init.h"
102 #include "glib-private.h"
106 * @title: The Main Event Loop
107 * @short_description: manages all available sources of events
109 * The main event loop manages all the available sources of events for
110 * GLib and GTK+ applications. These events can come from any number of
111 * different types of sources such as file descriptors (plain files,
112 * pipes or sockets) and timeouts. New types of event sources can also
113 * be added using g_source_attach().
115 * To allow multiple independent sets of sources to be handled in
116 * different threads, each source is associated with a #GMainContext.
117 * A GMainContext can only be running in a single thread, but
118 * sources can be added to it and removed from it from other threads.
120 * Each event source is assigned a priority. The default priority,
121 * #G_PRIORITY_DEFAULT, is 0. Values less than 0 denote higher priorities.
122 * Values greater than 0 denote lower priorities. Events from high priority
123 * sources are always processed before events from lower priority sources.
125 * Idle functions can also be added, and assigned a priority. These will
126 * be run whenever no events with a higher priority are ready to be processed.
128 * The #GMainLoop data type represents a main event loop. A GMainLoop is
129 * created with g_main_loop_new(). After adding the initial event sources,
130 * g_main_loop_run() is called. This continuously checks for new events from
131 * each of the event sources and dispatches them. Finally, the processing of
132 * an event from one of the sources leads to a call to g_main_loop_quit() to
133 * exit the main loop, and g_main_loop_run() returns.
135 * It is possible to create new instances of #GMainLoop recursively.
136 * This is often used in GTK+ applications when showing modal dialog
137 * boxes. Note that event sources are associated with a particular
138 * #GMainContext, and will be checked and dispatched for all main
139 * loops associated with that GMainContext.
141 * GTK+ contains wrappers of some of these functions, e.g. gtk_main(),
142 * gtk_main_quit() and gtk_events_pending().
144 * <refsect2><title>Creating new source types</title>
145 * <para>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 <firstterm>deriving</firstterm> from the #GSource structure.
150 * The derived type of source is represented by a structure that has
151 * the #GSource structure as a first element, and other elements specific
152 * to the new source type. To create an instance of the new source type,
153 * call 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.</para>
156 * <para>New source types basically interact with the main context
157 * in two ways. Their prepare function in #GSourceFuncs can set a timeout
158 * to determine the maximum amount of time that the main loop will sleep
159 * before checking the source again. In addition, or as well, the source
160 * can add file descriptors to the set that the main context checks using
161 * g_source_add_poll().</para>
163 * <refsect2><title>Customizing the main loop iteration</title>
164 * <para>Single iterations of a #GMainContext can be run with
165 * g_main_context_iteration(). In some cases, more detailed control
166 * of exactly how the details of the main loop work is desired, for
167 * instance, when integrating the #GMainLoop with an external main loop.
168 * In such cases, you can call the component functions of
169 * g_main_context_iteration() directly. These functions are
170 * g_main_context_prepare(), g_main_context_query(),
171 * g_main_context_check() and g_main_context_dispatch().</para>
172 * <para>The operation of these functions can best be seen in terms
173 * of a state diagram, as shown in <xref linkend="mainloop-states"/>.</para>
174 * <figure id="mainloop-states"><title>States of a Main Context</title>
175 * <graphic fileref="mainloop-states.gif" format="GIF"></graphic>
179 * On Unix, the GLib mainloop is incompatible with fork(). Any program
180 * using the mainloop must either exec() or exit() from the child
181 * without returning to the mainloop.
186 typedef struct _GTimeoutSource GTimeoutSource;
187 typedef struct _GChildWatchSource GChildWatchSource;
188 typedef struct _GUnixSignalWatchSource GUnixSignalWatchSource;
189 typedef struct _GPollRec GPollRec;
190 typedef struct _GSourceCallback GSourceCallback;
194 G_SOURCE_READY = 1 << G_HOOK_FLAG_USER_SHIFT,
195 G_SOURCE_CAN_RECURSE = 1 << (G_HOOK_FLAG_USER_SHIFT + 1),
196 G_SOURCE_BLOCKED = 1 << (G_HOOK_FLAG_USER_SHIFT + 2)
199 typedef struct _GSourceList GSourceList;
203 GSource *head, *tail;
207 typedef struct _GMainWaiter GMainWaiter;
215 typedef struct _GMainDispatch GMainDispatch;
217 struct _GMainDispatch
223 #ifdef G_MAIN_POLL_DEBUG
224 gboolean _g_main_poll_debug = FALSE;
229 /* The following lock is used for both the list of sources
230 * and the list of poll records
240 GPtrArray *pending_dispatches;
241 gint timeout; /* Timeout for current iteration */
244 GHashTable *overflow_used_source_ids; /* set<guint> */
246 gint in_check_or_prepare;
248 GPollRec *poll_records, *poll_records_tail;
249 guint n_poll_records;
250 GPollFD *cached_poll_array;
251 guint cached_poll_array_size;
257 /* Flag indicating whether the set of fd's changed during a poll */
258 gboolean poll_changed;
263 gboolean time_is_fresh;
266 struct _GSourceCallback
271 GDestroyNotify notify;
276 GMainContext *context;
281 struct _GTimeoutSource
288 struct _GChildWatchSource
295 #else /* G_OS_WIN32 */
296 gboolean child_exited;
297 #endif /* G_OS_WIN32 */
300 struct _GUnixSignalWatchSource
315 struct _GSourcePrivate
317 GSList *child_sources;
318 GSource *parent_source;
322 /* This is currently only used on UNIX, but we always declare it (and
323 * let it remain empty on Windows) to avoid #ifdef all over the place.
328 typedef struct _GSourceIter
330 GMainContext *context;
336 #define LOCK_CONTEXT(context) g_mutex_lock (&context->mutex)
337 #define UNLOCK_CONTEXT(context) g_mutex_unlock (&context->mutex)
338 #define G_THREAD_SELF g_thread_self ()
340 #define SOURCE_DESTROYED(source) (((source)->flags & G_HOOK_FLAG_ACTIVE) == 0)
341 #define SOURCE_BLOCKED(source) (((source)->flags & G_SOURCE_BLOCKED) != 0)
343 #define SOURCE_UNREF(source, context) \
345 if ((source)->ref_count > 1) \
346 (source)->ref_count--; \
348 g_source_unref_internal ((source), (context), TRUE); \
352 /* Forward declarations */
354 static void g_source_unref_internal (GSource *source,
355 GMainContext *context,
357 static void g_source_destroy_internal (GSource *source,
358 GMainContext *context,
360 static void g_source_set_priority_unlocked (GSource *source,
361 GMainContext *context,
363 static void g_child_source_remove_internal (GSource *child_source,
364 GMainContext *context);
366 static void g_main_context_poll (GMainContext *context,
371 static void g_main_context_add_poll_unlocked (GMainContext *context,
374 static void g_main_context_remove_poll_unlocked (GMainContext *context,
377 static void g_source_iter_init (GSourceIter *iter,
378 GMainContext *context,
379 gboolean may_modify);
380 static gboolean g_source_iter_next (GSourceIter *iter,
382 static void g_source_iter_clear (GSourceIter *iter);
384 static gboolean g_timeout_dispatch (GSource *source,
385 GSourceFunc callback,
387 static gboolean g_child_watch_prepare (GSource *source,
389 static gboolean g_child_watch_check (GSource *source);
390 static gboolean g_child_watch_dispatch (GSource *source,
391 GSourceFunc callback,
393 static void g_child_watch_finalize (GSource *source);
395 static void g_unix_signal_handler (int signum);
396 static gboolean g_unix_signal_watch_prepare (GSource *source,
398 static gboolean g_unix_signal_watch_check (GSource *source);
399 static gboolean g_unix_signal_watch_dispatch (GSource *source,
400 GSourceFunc callback,
402 static void g_unix_signal_watch_finalize (GSource *source);
404 static gboolean g_idle_prepare (GSource *source,
406 static gboolean g_idle_check (GSource *source);
407 static gboolean g_idle_dispatch (GSource *source,
408 GSourceFunc callback,
411 static void block_source (GSource *source);
413 static GMainContext *glib_worker_context;
415 G_LOCK_DEFINE_STATIC (main_loop);
416 static GMainContext *default_main_context;
421 /* UNIX signals work by marking one of these variables then waking the
422 * worker context to check on them and dispatch accordingly.
424 #ifdef HAVE_SIG_ATOMIC_T
425 static volatile sig_atomic_t unix_signal_pending[NSIG];
426 static volatile sig_atomic_t any_unix_signal_pending;
428 static volatile int unix_signal_pending[NSIG];
429 static volatile int any_unix_signal_pending;
431 static volatile guint unix_signal_refcount[NSIG];
433 /* Guards all the data below */
434 G_LOCK_DEFINE_STATIC (unix_signal_lock);
435 static GSList *unix_signal_watches;
436 static GSList *unix_child_watches;
438 GSourceFuncs g_unix_signal_funcs =
440 g_unix_signal_watch_prepare,
441 g_unix_signal_watch_check,
442 g_unix_signal_watch_dispatch,
443 g_unix_signal_watch_finalize
445 #endif /* !G_OS_WIN32 */
446 G_LOCK_DEFINE_STATIC (main_context_list);
447 static GSList *main_context_list = NULL;
449 GSourceFuncs g_timeout_funcs =
457 GSourceFuncs g_child_watch_funcs =
459 g_child_watch_prepare,
461 g_child_watch_dispatch,
462 g_child_watch_finalize
465 GSourceFuncs g_idle_funcs =
474 * g_main_context_ref:
475 * @context: a #GMainContext
477 * Increases the reference count on a #GMainContext object by one.
479 * Returns: the @context that was passed in (since 2.6)
482 g_main_context_ref (GMainContext *context)
484 g_return_val_if_fail (context != NULL, NULL);
485 g_return_val_if_fail (g_atomic_int_get (&context->ref_count) > 0, NULL);
487 g_atomic_int_inc (&context->ref_count);
493 poll_rec_list_free (GMainContext *context,
496 g_slice_free_chain (GPollRec, list, next);
500 * g_main_context_unref:
501 * @context: a #GMainContext
503 * Decreases the reference count on a #GMainContext object by one. If
504 * the result is zero, free the context and free all associated memory.
507 g_main_context_unref (GMainContext *context)
514 g_return_if_fail (context != NULL);
515 g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
517 if (!g_atomic_int_dec_and_test (&context->ref_count))
520 G_LOCK (main_context_list);
521 main_context_list = g_slist_remove (main_context_list, context);
522 G_UNLOCK (main_context_list);
524 /* g_source_iter_next() assumes the context is locked. */
525 LOCK_CONTEXT (context);
526 g_source_iter_init (&iter, context, TRUE);
527 while (g_source_iter_next (&iter, &source))
529 source->context = NULL;
530 g_source_destroy_internal (source, context, TRUE);
532 UNLOCK_CONTEXT (context);
534 for (sl_iter = context->source_lists; sl_iter; sl_iter = sl_iter->next)
536 list = sl_iter->data;
537 g_slice_free (GSourceList, list);
539 g_list_free (context->source_lists);
541 if (context->overflow_used_source_ids)
542 g_hash_table_destroy (context->overflow_used_source_ids);
544 g_mutex_clear (&context->mutex);
546 g_ptr_array_free (context->pending_dispatches, TRUE);
547 g_free (context->cached_poll_array);
549 poll_rec_list_free (context, context->poll_records);
551 g_wakeup_free (context->wakeup);
552 g_cond_clear (&context->cond);
557 /* Helper function used by mainloop/overflow test.
560 g_main_context_new_with_next_id (guint next_id)
562 GMainContext *ret = g_main_context_new ();
564 ret->next_id = next_id;
570 * g_main_context_new:
572 * Creates a new #GMainContext structure.
574 * Return value: the new #GMainContext
577 g_main_context_new (void)
579 static gsize initialised;
580 GMainContext *context;
582 if (g_once_init_enter (&initialised))
584 #ifdef G_MAIN_POLL_DEBUG
585 if (getenv ("G_MAIN_POLL_DEBUG") != NULL)
586 _g_main_poll_debug = TRUE;
589 g_once_init_leave (&initialised, TRUE);
592 context = g_new0 (GMainContext, 1);
594 g_mutex_init (&context->mutex);
595 g_cond_init (&context->cond);
597 context->owner = NULL;
598 context->waiters = NULL;
600 context->ref_count = 1;
602 context->next_id = 1;
604 context->source_lists = NULL;
606 context->poll_func = g_poll;
608 context->cached_poll_array = NULL;
609 context->cached_poll_array_size = 0;
611 context->pending_dispatches = g_ptr_array_new ();
613 context->time_is_fresh = FALSE;
615 context->wakeup = g_wakeup_new ();
616 g_wakeup_get_pollfd (context->wakeup, &context->wake_up_rec);
617 g_main_context_add_poll_unlocked (context, 0, &context->wake_up_rec);
619 G_LOCK (main_context_list);
620 main_context_list = g_slist_append (main_context_list, context);
622 #ifdef G_MAIN_POLL_DEBUG
623 if (_g_main_poll_debug)
624 g_print ("created context=%p\n", context);
627 G_UNLOCK (main_context_list);
633 * g_main_context_default:
635 * Returns the global default main context. This is the main context
636 * used for main loop functions when a main loop is not explicitly
637 * specified, and corresponds to the "main" main loop. See also
638 * g_main_context_get_thread_default().
640 * Return value: (transfer none): the global default main context.
643 g_main_context_default (void)
649 if (!default_main_context)
651 default_main_context = g_main_context_new ();
652 #ifdef G_MAIN_POLL_DEBUG
653 if (_g_main_poll_debug)
654 g_print ("default context=%p\n", default_main_context);
658 G_UNLOCK (main_loop);
660 return default_main_context;
664 free_context (gpointer data)
666 GMainContext *context = data;
668 g_main_context_release (context);
670 g_main_context_unref (context);
674 free_context_stack (gpointer data)
676 g_queue_free_full((GQueue *) data, (GDestroyNotify) free_context);
679 static GPrivate thread_context_stack = G_PRIVATE_INIT (free_context_stack);
682 * g_main_context_push_thread_default:
683 * @context: (allow-none): a #GMainContext, or %NULL for the global default context
685 * Acquires @context and sets it as the thread-default context for the
686 * current thread. This will cause certain asynchronous operations
687 * (such as most <link linkend="gio">gio</link>-based I/O) which are
688 * started in this thread to run under @context and deliver their
689 * results to its main loop, rather than running under the global
690 * default context in the main thread. Note that calling this function
691 * changes the context returned by
692 * g_main_context_get_thread_default(), <emphasis>not</emphasis> the
693 * one returned by g_main_context_default(), so it does not affect the
694 * context used by functions like g_idle_add().
696 * Normally you would call this function shortly after creating a new
697 * thread, passing it a #GMainContext which will be run by a
698 * #GMainLoop in that thread, to set a new default context for all
699 * async operations in that thread. (In this case, you don't need to
700 * ever call g_main_context_pop_thread_default().) In some cases
701 * however, you may want to schedule a single operation in a
702 * non-default context, or temporarily use a non-default context in
703 * the main thread. In that case, you can wrap the call to the
704 * asynchronous operation inside a
705 * g_main_context_push_thread_default() /
706 * g_main_context_pop_thread_default() pair, but it is up to you to
707 * ensure that no other asynchronous operations accidentally get
708 * started while the non-default context is active.
710 * Beware that libraries that predate this function may not correctly
711 * handle being used from a thread with a thread-default context. Eg,
712 * see g_file_supports_thread_contexts().
717 g_main_context_push_thread_default (GMainContext *context)
720 gboolean acquired_context;
722 acquired_context = g_main_context_acquire (context);
723 g_return_if_fail (acquired_context);
725 if (context == g_main_context_default ())
728 g_main_context_ref (context);
730 stack = g_private_get (&thread_context_stack);
733 stack = g_queue_new ();
734 g_private_set (&thread_context_stack, stack);
737 g_queue_push_head (stack, context);
741 * g_main_context_pop_thread_default:
742 * @context: (allow-none): a #GMainContext object, or %NULL
744 * Pops @context off the thread-default context stack (verifying that
745 * it was on the top of the stack).
750 g_main_context_pop_thread_default (GMainContext *context)
754 if (context == g_main_context_default ())
757 stack = g_private_get (&thread_context_stack);
759 g_return_if_fail (stack != NULL);
760 g_return_if_fail (g_queue_peek_head (stack) == context);
762 g_queue_pop_head (stack);
764 g_main_context_release (context);
766 g_main_context_unref (context);
770 * g_main_context_get_thread_default:
772 * Gets the thread-default #GMainContext for this thread. Asynchronous
773 * operations that want to be able to be run in contexts other than
774 * the default one should call this method or
775 * g_main_context_ref_thread_default() to get a #GMainContext to add
776 * their #GSource<!-- -->s to. (Note that even in single-threaded
777 * programs applications may sometimes want to temporarily push a
778 * non-default context, so it is not safe to assume that this will
779 * always return %NULL if you are running in the default thread.)
781 * If you need to hold a reference on the context, use
782 * g_main_context_ref_thread_default() instead.
784 * Returns: (transfer none): the thread-default #GMainContext, or
785 * %NULL if the thread-default context is the global default context.
790 g_main_context_get_thread_default (void)
794 stack = g_private_get (&thread_context_stack);
796 return g_queue_peek_head (stack);
802 * g_main_context_ref_thread_default:
804 * Gets the thread-default #GMainContext for this thread, as with
805 * g_main_context_get_thread_default(), but also adds a reference to
806 * it with g_main_context_ref(). In addition, unlike
807 * g_main_context_get_thread_default(), if the thread-default context
808 * is the global default context, this will return that #GMainContext
809 * (with a ref added to it) rather than returning %NULL.
811 * Returns: (transfer full): the thread-default #GMainContext. Unref
812 * with g_main_context_unref() when you are done with it.
817 g_main_context_ref_thread_default (void)
819 GMainContext *context;
821 context = g_main_context_get_thread_default ();
823 context = g_main_context_default ();
824 return g_main_context_ref (context);
827 /* Hooks for adding to the main loop */
831 * @source_funcs: structure containing functions that implement
832 * the sources behavior.
833 * @struct_size: size of the #GSource structure to create.
835 * Creates a new #GSource structure. The size is specified to
836 * allow creating structures derived from #GSource that contain
837 * additional data. The size passed in must be at least
838 * <literal>sizeof (GSource)</literal>.
840 * The source will not initially be associated with any #GMainContext
841 * and must be added to one with g_source_attach() before it will be
844 * Return value: the newly-created #GSource.
847 g_source_new (GSourceFuncs *source_funcs,
852 g_return_val_if_fail (source_funcs != NULL, NULL);
853 g_return_val_if_fail (struct_size >= sizeof (GSource), NULL);
855 source = (GSource*) g_malloc0 (struct_size);
856 source->priv = g_slice_new0 (GSourcePrivate);
857 source->source_funcs = source_funcs;
858 source->ref_count = 1;
860 source->priority = G_PRIORITY_DEFAULT;
862 source->flags = G_HOOK_FLAG_ACTIVE;
864 source->priv->ready_time = -1;
866 /* NULL/0 initialization for all other fields */
871 /* Holds context's lock */
873 g_source_iter_init (GSourceIter *iter,
874 GMainContext *context,
877 iter->context = context;
878 iter->current_list = NULL;
880 iter->may_modify = may_modify;
883 /* Holds context's lock */
885 g_source_iter_next (GSourceIter *iter, GSource **source)
887 GSource *next_source;
890 next_source = iter->source->next;
896 if (iter->current_list)
897 iter->current_list = iter->current_list->next;
899 iter->current_list = iter->context->source_lists;
901 if (iter->current_list)
903 GSourceList *source_list = iter->current_list->data;
905 next_source = source_list->head;
909 /* Note: unreffing iter->source could potentially cause its
910 * GSourceList to be removed from source_lists (if iter->source is
911 * the only source in its list, and it is destroyed), so we have to
912 * keep it reffed until after we advance iter->current_list, above.
915 if (iter->source && iter->may_modify)
916 SOURCE_UNREF (iter->source, iter->context);
917 iter->source = next_source;
918 if (iter->source && iter->may_modify)
919 iter->source->ref_count++;
921 *source = iter->source;
922 return *source != NULL;
925 /* Holds context's lock. Only necessary to call if you broke out of
926 * the g_source_iter_next() loop early.
929 g_source_iter_clear (GSourceIter *iter)
931 if (iter->source && iter->may_modify)
933 SOURCE_UNREF (iter->source, iter->context);
938 /* Holds context's lock
941 find_source_list_for_priority (GMainContext *context,
946 GSourceList *source_list;
949 for (iter = context->source_lists; iter != NULL; last = iter, iter = iter->next)
951 source_list = iter->data;
953 if (source_list->priority == priority)
956 if (source_list->priority > priority)
961 source_list = g_slice_new0 (GSourceList);
962 source_list->priority = priority;
963 context->source_lists = g_list_insert_before (context->source_lists,
973 source_list = g_slice_new0 (GSourceList);
974 source_list->priority = priority;
977 context->source_lists = g_list_append (NULL, source_list);
980 /* This just appends source_list to the end of
981 * context->source_lists without having to walk the list again.
983 last = g_list_append (last, source_list);
988 /* Holds context's lock
991 source_add_to_context (GSource *source,
992 GMainContext *context)
994 GSourceList *source_list;
995 GSource *prev, *next;
997 source_list = find_source_list_for_priority (context, source->priority, TRUE);
999 if (source->priv->parent_source)
1001 g_assert (source_list->head != NULL);
1003 /* Put the source immediately before its parent */
1004 prev = source->priv->parent_source->prev;
1005 next = source->priv->parent_source;
1009 prev = source_list->tail;
1013 source->next = next;
1015 next->prev = source;
1017 source_list->tail = source;
1019 source->prev = prev;
1021 prev->next = source;
1023 source_list->head = source;
1026 /* Holds context's lock
1029 source_remove_from_context (GSource *source,
1030 GMainContext *context)
1032 GSourceList *source_list;
1034 source_list = find_source_list_for_priority (context, source->priority, FALSE);
1035 g_return_if_fail (source_list != NULL);
1038 source->prev->next = source->next;
1040 source_list->head = source->next;
1043 source->next->prev = source->prev;
1045 source_list->tail = source->prev;
1047 source->prev = NULL;
1048 source->next = NULL;
1050 if (source_list->head == NULL)
1052 context->source_lists = g_list_remove (context->source_lists, source_list);
1053 g_slice_free (GSourceList, source_list);
1056 if (context->overflow_used_source_ids)
1057 g_hash_table_remove (context->overflow_used_source_ids,
1058 GUINT_TO_POINTER (source->source_id));
1063 assign_source_id_unlocked (GMainContext *context,
1068 /* Are we about to overflow back to 0?
1069 * See https://bugzilla.gnome.org/show_bug.cgi?id=687098
1071 if (G_UNLIKELY (context->next_id == G_MAXUINT &&
1072 context->overflow_used_source_ids == NULL))
1077 context->overflow_used_source_ids = g_hash_table_new (NULL, NULL);
1079 g_source_iter_init (&iter, context, FALSE);
1080 while (g_source_iter_next (&iter, &source))
1082 g_hash_table_add (context->overflow_used_source_ids,
1083 GUINT_TO_POINTER (source->source_id));
1086 g_hash_table_add (context->overflow_used_source_ids, GUINT_TO_POINTER (id));
1088 else if (context->overflow_used_source_ids == NULL)
1090 id = context->next_id++;
1095 * If we overran G_MAXUINT, we fall back to randomly probing the
1096 * source ids for the current context. This will be slower the more
1097 * sources there are, but we're mainly concerned right now about
1098 * correctness and code size. There's time for a more clever solution
1102 id = g_random_int ();
1104 g_hash_table_contains (context->overflow_used_source_ids,
1105 GUINT_TO_POINTER (id)));
1106 g_hash_table_add (context->overflow_used_source_ids, GUINT_TO_POINTER (id));
1109 source->source_id = id;
1113 g_source_attach_unlocked (GSource *source,
1114 GMainContext *context)
1118 source->context = context;
1119 assign_source_id_unlocked (context, source);
1120 source->ref_count++;
1121 source_add_to_context (source, context);
1123 if (!SOURCE_BLOCKED (source))
1125 tmp_list = source->poll_fds;
1128 g_main_context_add_poll_unlocked (context, source->priority, tmp_list->data);
1129 tmp_list = tmp_list->next;
1132 for (tmp_list = source->priv->fds; tmp_list; tmp_list = tmp_list->next)
1133 g_main_context_add_poll_unlocked (context, source->priority, tmp_list->data);
1136 tmp_list = source->priv->child_sources;
1139 g_source_attach_unlocked (tmp_list->data, context);
1140 tmp_list = tmp_list->next;
1143 return source->source_id;
1148 * @source: a #GSource
1149 * @context: (allow-none): a #GMainContext (if %NULL, the default context will be used)
1151 * Adds a #GSource to a @context so that it will be executed within
1152 * that context. Remove it by calling g_source_destroy().
1154 * Return value: the ID (greater than 0) for the source within the
1158 g_source_attach (GSource *source,
1159 GMainContext *context)
1163 g_return_val_if_fail (source->context == NULL, 0);
1164 g_return_val_if_fail (!SOURCE_DESTROYED (source), 0);
1167 context = g_main_context_default ();
1169 LOCK_CONTEXT (context);
1171 result = g_source_attach_unlocked (source, context);
1173 /* If another thread has acquired the context, wake it up since it
1174 * might be in poll() right now.
1176 if (context->owner && context->owner != G_THREAD_SELF)
1177 g_wakeup_signal (context->wakeup);
1179 UNLOCK_CONTEXT (context);
1185 g_source_destroy_internal (GSource *source,
1186 GMainContext *context,
1190 LOCK_CONTEXT (context);
1192 if (!SOURCE_DESTROYED (source))
1195 gpointer old_cb_data;
1196 GSourceCallbackFuncs *old_cb_funcs;
1198 source->flags &= ~G_HOOK_FLAG_ACTIVE;
1200 old_cb_data = source->callback_data;
1201 old_cb_funcs = source->callback_funcs;
1203 source->callback_data = NULL;
1204 source->callback_funcs = NULL;
1208 UNLOCK_CONTEXT (context);
1209 old_cb_funcs->unref (old_cb_data);
1210 LOCK_CONTEXT (context);
1213 if (!SOURCE_BLOCKED (source))
1215 tmp_list = source->poll_fds;
1218 g_main_context_remove_poll_unlocked (context, tmp_list->data);
1219 tmp_list = tmp_list->next;
1222 for (tmp_list = source->priv->fds; tmp_list; tmp_list = tmp_list->next)
1223 g_main_context_remove_poll_unlocked (context, tmp_list->data);
1226 while (source->priv->child_sources)
1227 g_child_source_remove_internal (source->priv->child_sources->data, context);
1229 if (source->priv->parent_source)
1230 g_child_source_remove_internal (source, context);
1232 g_source_unref_internal (source, context, TRUE);
1236 UNLOCK_CONTEXT (context);
1241 * @source: a #GSource
1243 * Removes a source from its #GMainContext, if any, and mark it as
1244 * destroyed. The source cannot be subsequently added to another
1248 g_source_destroy (GSource *source)
1250 GMainContext *context;
1252 g_return_if_fail (source != NULL);
1254 context = source->context;
1257 g_source_destroy_internal (source, context, FALSE);
1259 source->flags &= ~G_HOOK_FLAG_ACTIVE;
1264 * @source: a #GSource
1266 * Returns the numeric ID for a particular source. The ID of a source
1267 * is a positive integer which is unique within a particular main loop
1268 * context. The reverse
1269 * mapping from ID to source is done by g_main_context_find_source_by_id().
1271 * Return value: the ID (greater than 0) for the source
1274 g_source_get_id (GSource *source)
1278 g_return_val_if_fail (source != NULL, 0);
1279 g_return_val_if_fail (source->context != NULL, 0);
1281 LOCK_CONTEXT (source->context);
1282 result = source->source_id;
1283 UNLOCK_CONTEXT (source->context);
1289 * g_source_get_context:
1290 * @source: a #GSource
1292 * Gets the #GMainContext with which the source is associated.
1294 * You can call this on a source that has been destroyed, provided
1295 * that the #GMainContext it was attached to still exists (in which
1296 * case it will return that #GMainContext). In particular, you can
1297 * always call this function on the source returned from
1298 * g_main_current_source(). But calling this function on a source
1299 * whose #GMainContext has been destroyed is an error.
1301 * Return value: (transfer none) (allow-none): the #GMainContext with which the
1302 * source is associated, or %NULL if the context has not
1303 * yet been added to a source.
1306 g_source_get_context (GSource *source)
1308 g_return_val_if_fail (source->context != NULL || !SOURCE_DESTROYED (source), NULL);
1310 return source->context;
1314 * g_source_add_poll:
1315 * @source:a #GSource
1316 * @fd: a #GPollFD structure holding information about a file
1317 * descriptor to watch.
1319 * Adds a file descriptor to the set of file descriptors polled for
1320 * this source. This is usually combined with g_source_new() to add an
1321 * event source. The event source's check function will typically test
1322 * the @revents field in the #GPollFD struct and return %TRUE if events need
1325 * Using this API forces the linear scanning of event sources on each
1326 * main loop iteration. Newly-written event sources should try to use
1327 * g_source_add_unix_fd() instead of this API.
1330 g_source_add_poll (GSource *source,
1333 GMainContext *context;
1335 g_return_if_fail (source != NULL);
1336 g_return_if_fail (fd != NULL);
1337 g_return_if_fail (!SOURCE_DESTROYED (source));
1339 context = source->context;
1342 LOCK_CONTEXT (context);
1344 source->poll_fds = g_slist_prepend (source->poll_fds, fd);
1348 if (!SOURCE_BLOCKED (source))
1349 g_main_context_add_poll_unlocked (context, source->priority, fd);
1350 UNLOCK_CONTEXT (context);
1355 * g_source_remove_poll:
1356 * @source:a #GSource
1357 * @fd: a #GPollFD structure previously passed to g_source_add_poll().
1359 * Removes a file descriptor from the set of file descriptors polled for
1363 g_source_remove_poll (GSource *source,
1366 GMainContext *context;
1368 g_return_if_fail (source != NULL);
1369 g_return_if_fail (fd != NULL);
1370 g_return_if_fail (!SOURCE_DESTROYED (source));
1372 context = source->context;
1375 LOCK_CONTEXT (context);
1377 source->poll_fds = g_slist_remove (source->poll_fds, fd);
1381 if (!SOURCE_BLOCKED (source))
1382 g_main_context_remove_poll_unlocked (context, fd);
1383 UNLOCK_CONTEXT (context);
1388 * g_source_add_child_source:
1389 * @source:a #GSource
1390 * @child_source: a second #GSource that @source should "poll"
1392 * Adds @child_source to @source as a "polled" source; when @source is
1393 * added to a #GMainContext, @child_source will be automatically added
1394 * with the same priority, when @child_source is triggered, it will
1395 * cause @source to dispatch (in addition to calling its own
1396 * callback), and when @source is destroyed, it will destroy
1397 * @child_source as well. (@source will also still be dispatched if
1398 * its own prepare/check functions indicate that it is ready.)
1400 * If you don't need @child_source to do anything on its own when it
1401 * triggers, you can call g_source_set_dummy_callback() on it to set a
1402 * callback that does nothing (except return %TRUE if appropriate).
1404 * @source will hold a reference on @child_source while @child_source
1405 * is attached to it.
1410 g_source_add_child_source (GSource *source,
1411 GSource *child_source)
1413 GMainContext *context;
1415 g_return_if_fail (source != NULL);
1416 g_return_if_fail (child_source != NULL);
1417 g_return_if_fail (!SOURCE_DESTROYED (source));
1418 g_return_if_fail (!SOURCE_DESTROYED (child_source));
1419 g_return_if_fail (child_source->context == NULL);
1420 g_return_if_fail (child_source->priv->parent_source == NULL);
1422 context = source->context;
1425 LOCK_CONTEXT (context);
1427 source->priv->child_sources = g_slist_prepend (source->priv->child_sources,
1428 g_source_ref (child_source));
1429 child_source->priv->parent_source = source;
1430 g_source_set_priority_unlocked (child_source, NULL, source->priority);
1431 if (SOURCE_BLOCKED (source))
1432 block_source (child_source);
1436 UNLOCK_CONTEXT (context);
1437 g_source_attach (child_source, context);
1442 g_child_source_remove_internal (GSource *child_source,
1443 GMainContext *context)
1445 GSource *parent_source = child_source->priv->parent_source;
1447 parent_source->priv->child_sources =
1448 g_slist_remove (parent_source->priv->child_sources, child_source);
1449 child_source->priv->parent_source = NULL;
1451 g_source_destroy_internal (child_source, context, TRUE);
1452 g_source_unref_internal (child_source, context, TRUE);
1456 * g_source_remove_child_source:
1457 * @source:a #GSource
1458 * @child_source: a #GSource previously passed to
1459 * g_source_add_child_source().
1461 * Detaches @child_source from @source and destroys it.
1466 g_source_remove_child_source (GSource *source,
1467 GSource *child_source)
1469 GMainContext *context;
1471 g_return_if_fail (source != NULL);
1472 g_return_if_fail (child_source != NULL);
1473 g_return_if_fail (child_source->priv->parent_source == source);
1474 g_return_if_fail (!SOURCE_DESTROYED (source));
1475 g_return_if_fail (!SOURCE_DESTROYED (child_source));
1477 context = source->context;
1480 LOCK_CONTEXT (context);
1482 g_child_source_remove_internal (child_source, context);
1485 UNLOCK_CONTEXT (context);
1489 * g_source_set_callback_indirect:
1490 * @source: the source
1491 * @callback_data: pointer to callback data "object"
1492 * @callback_funcs: functions for reference counting @callback_data
1493 * and getting the callback and data
1495 * Sets the callback function storing the data as a refcounted callback
1496 * "object". This is used internally. Note that calling
1497 * g_source_set_callback_indirect() assumes
1498 * an initial reference count on @callback_data, and thus
1499 * @callback_funcs->unref will eventually be called once more
1500 * than @callback_funcs->ref.
1503 g_source_set_callback_indirect (GSource *source,
1504 gpointer callback_data,
1505 GSourceCallbackFuncs *callback_funcs)
1507 GMainContext *context;
1508 gpointer old_cb_data;
1509 GSourceCallbackFuncs *old_cb_funcs;
1511 g_return_if_fail (source != NULL);
1512 g_return_if_fail (callback_funcs != NULL || callback_data == NULL);
1514 context = source->context;
1517 LOCK_CONTEXT (context);
1519 old_cb_data = source->callback_data;
1520 old_cb_funcs = source->callback_funcs;
1522 source->callback_data = callback_data;
1523 source->callback_funcs = callback_funcs;
1526 UNLOCK_CONTEXT (context);
1529 old_cb_funcs->unref (old_cb_data);
1533 g_source_callback_ref (gpointer cb_data)
1535 GSourceCallback *callback = cb_data;
1537 callback->ref_count++;
1542 g_source_callback_unref (gpointer cb_data)
1544 GSourceCallback *callback = cb_data;
1546 callback->ref_count--;
1547 if (callback->ref_count == 0)
1549 if (callback->notify)
1550 callback->notify (callback->data);
1556 g_source_callback_get (gpointer cb_data,
1561 GSourceCallback *callback = cb_data;
1563 *func = callback->func;
1564 *data = callback->data;
1567 static GSourceCallbackFuncs g_source_callback_funcs = {
1568 g_source_callback_ref,
1569 g_source_callback_unref,
1570 g_source_callback_get,
1574 * g_source_set_callback:
1575 * @source: the source
1576 * @func: a callback function
1577 * @data: the data to pass to callback function
1578 * @notify: (allow-none): a function to call when @data is no longer in use, or %NULL.
1580 * Sets the callback function for a source. The callback for a source is
1581 * called from the source's dispatch function.
1583 * The exact type of @func depends on the type of source; ie. you
1584 * should not count on @func being called with @data as its first
1587 * Typically, you won't use this function. Instead use functions specific
1588 * to the type of source you are using.
1591 g_source_set_callback (GSource *source,
1594 GDestroyNotify notify)
1596 GSourceCallback *new_callback;
1598 g_return_if_fail (source != NULL);
1600 new_callback = g_new (GSourceCallback, 1);
1602 new_callback->ref_count = 1;
1603 new_callback->func = func;
1604 new_callback->data = data;
1605 new_callback->notify = notify;
1607 g_source_set_callback_indirect (source, new_callback, &g_source_callback_funcs);
1612 * g_source_set_funcs:
1613 * @source: a #GSource
1614 * @funcs: the new #GSourceFuncs
1616 * Sets the source functions (can be used to override
1617 * default implementations) of an unattached source.
1622 g_source_set_funcs (GSource *source,
1623 GSourceFuncs *funcs)
1625 g_return_if_fail (source != NULL);
1626 g_return_if_fail (source->context == NULL);
1627 g_return_if_fail (source->ref_count > 0);
1628 g_return_if_fail (funcs != NULL);
1630 source->source_funcs = funcs;
1634 g_source_set_priority_unlocked (GSource *source,
1635 GMainContext *context,
1640 g_return_if_fail (source->priv->parent_source == NULL ||
1641 source->priv->parent_source->priority == priority);
1645 /* Remove the source from the context's source and then
1646 * add it back after so it is sorted in the correct place
1648 source_remove_from_context (source, source->context);
1651 source->priority = priority;
1655 source_add_to_context (source, source->context);
1657 if (!SOURCE_BLOCKED (source))
1659 tmp_list = source->poll_fds;
1662 g_main_context_remove_poll_unlocked (context, tmp_list->data);
1663 g_main_context_add_poll_unlocked (context, priority, tmp_list->data);
1665 tmp_list = tmp_list->next;
1668 for (tmp_list = source->priv->fds; tmp_list; tmp_list = tmp_list->next)
1670 g_main_context_remove_poll_unlocked (context, tmp_list->data);
1671 g_main_context_add_poll_unlocked (context, priority, tmp_list->data);
1676 if (source->priv->child_sources)
1678 tmp_list = source->priv->child_sources;
1681 g_source_set_priority_unlocked (tmp_list->data, context, priority);
1682 tmp_list = tmp_list->next;
1688 * g_source_set_priority:
1689 * @source: a #GSource
1690 * @priority: the new priority.
1692 * Sets the priority of a source. While the main loop is being run, a
1693 * source will be dispatched if it is ready to be dispatched and no
1694 * sources at a higher (numerically smaller) priority are ready to be
1698 g_source_set_priority (GSource *source,
1701 GMainContext *context;
1703 g_return_if_fail (source != NULL);
1705 context = source->context;
1708 LOCK_CONTEXT (context);
1709 g_source_set_priority_unlocked (source, context, priority);
1711 UNLOCK_CONTEXT (source->context);
1715 * g_source_get_priority:
1716 * @source: a #GSource
1718 * Gets the priority of a source.
1720 * Return value: the priority of the source
1723 g_source_get_priority (GSource *source)
1725 g_return_val_if_fail (source != NULL, 0);
1727 return source->priority;
1731 * g_source_set_ready_time:
1732 * @source: a #GSource
1733 * @ready_time: the monotonic time at which the source will be ready,
1734 * 0 for "immediately", -1 for "never"
1736 * Sets a #GSource to be dispatched when the given monotonic time is
1737 * reached (or passed). If the monotonic time is in the past (as it
1738 * always will be if @ready_time is 0) then the source will be
1739 * dispatched immediately.
1741 * If @ready_time is -1 then the source is never woken up on the basis
1742 * of the passage of time.
1744 * Dispatching the source does not reset the ready time. You should do
1745 * so yourself, from the source dispatch function.
1747 * Note that if you have a pair of sources where the ready time of one
1748 * suggests that it will be delivered first but the priority for the
1749 * other suggests that it would be delivered first, and the ready time
1750 * for both sources is reached during the same main context iteration
1751 * then the order of dispatch is undefined.
1756 g_source_set_ready_time (GSource *source,
1759 GMainContext *context;
1761 g_return_if_fail (source != NULL);
1762 g_return_if_fail (source->ref_count > 0);
1764 if (source->priv->ready_time == ready_time)
1767 context = source->context;
1770 LOCK_CONTEXT (context);
1772 source->priv->ready_time = ready_time;
1776 /* Quite likely that we need to change the timeout on the poll */
1777 if (!SOURCE_BLOCKED (source))
1778 g_wakeup_signal (context->wakeup);
1779 UNLOCK_CONTEXT (context);
1784 * g_source_get_ready_time:
1785 * @source: a #GSource
1787 * Gets the "ready time" of @source, as set by
1788 * g_source_set_ready_time().
1790 * Any time before the current monotonic time (including 0) is an
1791 * indication that the source will fire immediately.
1793 * Returns: the monotonic ready time, -1 for "never"
1796 g_source_get_ready_time (GSource *source)
1798 g_return_val_if_fail (source != NULL, -1);
1800 return source->priv->ready_time;
1804 * g_source_set_can_recurse:
1805 * @source: a #GSource
1806 * @can_recurse: whether recursion is allowed for this source
1808 * Sets whether a source can be called recursively. If @can_recurse is
1809 * %TRUE, then while the source is being dispatched then this source
1810 * will be processed normally. Otherwise, all processing of this
1811 * source is blocked until the dispatch function returns.
1814 g_source_set_can_recurse (GSource *source,
1815 gboolean can_recurse)
1817 GMainContext *context;
1819 g_return_if_fail (source != NULL);
1821 context = source->context;
1824 LOCK_CONTEXT (context);
1827 source->flags |= G_SOURCE_CAN_RECURSE;
1829 source->flags &= ~G_SOURCE_CAN_RECURSE;
1832 UNLOCK_CONTEXT (context);
1836 * g_source_get_can_recurse:
1837 * @source: a #GSource
1839 * Checks whether a source is allowed to be called recursively.
1840 * see g_source_set_can_recurse().
1842 * Return value: whether recursion is allowed.
1845 g_source_get_can_recurse (GSource *source)
1847 g_return_val_if_fail (source != NULL, FALSE);
1849 return (source->flags & G_SOURCE_CAN_RECURSE) != 0;
1854 * g_source_set_name:
1855 * @source: a #GSource
1856 * @name: debug name for the source
1858 * Sets a name for the source, used in debugging and profiling.
1859 * The name defaults to #NULL.
1861 * The source name should describe in a human-readable way
1862 * what the source does. For example, "X11 event queue"
1863 * or "GTK+ repaint idle handler" or whatever it is.
1865 * It is permitted to call this function multiple times, but is not
1866 * recommended due to the potential performance impact. For example,
1867 * one could change the name in the "check" function of a #GSourceFuncs
1868 * to include details like the event type in the source name.
1873 g_source_set_name (GSource *source,
1876 g_return_if_fail (source != NULL);
1878 /* setting back to NULL is allowed, just because it's
1879 * weird if get_name can return NULL but you can't
1883 g_free (source->name);
1884 source->name = g_strdup (name);
1888 * g_source_get_name:
1889 * @source: a #GSource
1891 * Gets a name for the source, used in debugging and profiling.
1892 * The name may be #NULL if it has never been set with
1893 * g_source_set_name().
1895 * Return value: the name of the source
1899 g_source_get_name (GSource *source)
1901 g_return_val_if_fail (source != NULL, NULL);
1903 return source->name;
1907 * g_source_set_name_by_id:
1908 * @tag: a #GSource ID
1909 * @name: debug name for the source
1911 * Sets the name of a source using its ID.
1913 * This is a convenience utility to set source names from the return
1914 * value of g_idle_add(), g_timeout_add(), etc.
1919 g_source_set_name_by_id (guint tag,
1924 g_return_if_fail (tag > 0);
1926 source = g_main_context_find_source_by_id (NULL, tag);
1930 g_source_set_name (source, name);
1936 * @source: a #GSource
1938 * Increases the reference count on a source by one.
1940 * Return value: @source
1943 g_source_ref (GSource *source)
1945 GMainContext *context;
1947 g_return_val_if_fail (source != NULL, NULL);
1949 context = source->context;
1952 LOCK_CONTEXT (context);
1954 source->ref_count++;
1957 UNLOCK_CONTEXT (context);
1962 /* g_source_unref() but possible to call within context lock
1965 g_source_unref_internal (GSource *source,
1966 GMainContext *context,
1969 gpointer old_cb_data = NULL;
1970 GSourceCallbackFuncs *old_cb_funcs = NULL;
1972 g_return_if_fail (source != NULL);
1974 if (!have_lock && context)
1975 LOCK_CONTEXT (context);
1977 source->ref_count--;
1978 if (source->ref_count == 0)
1980 old_cb_data = source->callback_data;
1981 old_cb_funcs = source->callback_funcs;
1983 source->callback_data = NULL;
1984 source->callback_funcs = NULL;
1988 if (!SOURCE_DESTROYED (source))
1989 g_warning (G_STRLOC ": ref_count == 0, but source was still attached to a context!");
1990 source_remove_from_context (source, context);
1993 if (source->source_funcs->finalize)
1996 UNLOCK_CONTEXT (context);
1997 source->source_funcs->finalize (source);
1999 LOCK_CONTEXT (context);
2002 g_free (source->name);
2003 source->name = NULL;
2005 g_slist_free (source->poll_fds);
2006 source->poll_fds = NULL;
2008 g_slist_free_full (source->priv->fds, g_free);
2010 g_slice_free (GSourcePrivate, source->priv);
2011 source->priv = NULL;
2016 if (!have_lock && context)
2017 UNLOCK_CONTEXT (context);
2022 UNLOCK_CONTEXT (context);
2024 old_cb_funcs->unref (old_cb_data);
2027 LOCK_CONTEXT (context);
2033 * @source: a #GSource
2035 * Decreases the reference count of a source by one. If the
2036 * resulting reference count is zero the source and associated
2037 * memory will be destroyed.
2040 g_source_unref (GSource *source)
2042 g_return_if_fail (source != NULL);
2044 g_source_unref_internal (source, source->context, FALSE);
2048 * g_main_context_find_source_by_id:
2049 * @context: (allow-none): a #GMainContext (if %NULL, the default context will be used)
2050 * @source_id: the source ID, as returned by g_source_get_id().
2052 * Finds a #GSource given a pair of context and ID.
2054 * Return value: (transfer none): the #GSource if found, otherwise, %NULL
2057 g_main_context_find_source_by_id (GMainContext *context,
2063 g_return_val_if_fail (source_id > 0, NULL);
2065 if (context == NULL)
2066 context = g_main_context_default ();
2068 LOCK_CONTEXT (context);
2070 g_source_iter_init (&iter, context, FALSE);
2071 while (g_source_iter_next (&iter, &source))
2073 if (!SOURCE_DESTROYED (source) &&
2074 source->source_id == source_id)
2077 g_source_iter_clear (&iter);
2079 UNLOCK_CONTEXT (context);
2085 * g_main_context_find_source_by_funcs_user_data:
2086 * @context: (allow-none): a #GMainContext (if %NULL, the default context will be used).
2087 * @funcs: the @source_funcs passed to g_source_new().
2088 * @user_data: the user data from the callback.
2090 * Finds a source with the given source functions and user data. If
2091 * multiple sources exist with the same source function and user data,
2092 * the first one found will be returned.
2094 * Return value: (transfer none): the source, if one was found, otherwise %NULL
2097 g_main_context_find_source_by_funcs_user_data (GMainContext *context,
2098 GSourceFuncs *funcs,
2104 g_return_val_if_fail (funcs != NULL, NULL);
2106 if (context == NULL)
2107 context = g_main_context_default ();
2109 LOCK_CONTEXT (context);
2111 g_source_iter_init (&iter, context, FALSE);
2112 while (g_source_iter_next (&iter, &source))
2114 if (!SOURCE_DESTROYED (source) &&
2115 source->source_funcs == funcs &&
2116 source->callback_funcs)
2118 GSourceFunc callback;
2119 gpointer callback_data;
2121 source->callback_funcs->get (source->callback_data, source, &callback, &callback_data);
2123 if (callback_data == user_data)
2127 g_source_iter_clear (&iter);
2129 UNLOCK_CONTEXT (context);
2135 * g_main_context_find_source_by_user_data:
2136 * @context: a #GMainContext
2137 * @user_data: the user_data for the callback.
2139 * Finds a source with the given user data for the callback. If
2140 * multiple sources exist with the same user data, the first
2141 * one found will be returned.
2143 * Return value: (transfer none): the source, if one was found, otherwise %NULL
2146 g_main_context_find_source_by_user_data (GMainContext *context,
2152 if (context == NULL)
2153 context = g_main_context_default ();
2155 LOCK_CONTEXT (context);
2157 g_source_iter_init (&iter, context, FALSE);
2158 while (g_source_iter_next (&iter, &source))
2160 if (!SOURCE_DESTROYED (source) &&
2161 source->callback_funcs)
2163 GSourceFunc callback;
2164 gpointer callback_data = NULL;
2166 source->callback_funcs->get (source->callback_data, source, &callback, &callback_data);
2168 if (callback_data == user_data)
2172 g_source_iter_clear (&iter);
2174 UNLOCK_CONTEXT (context);
2181 * @tag: the ID of the source to remove.
2183 * Removes the source with the given id from the default main context.
2185 * The id of a #GSource is given by g_source_get_id(), or will be
2186 * returned by the functions g_source_attach(), g_idle_add(),
2187 * g_idle_add_full(), g_timeout_add(), g_timeout_add_full(),
2188 * g_child_watch_add(), g_child_watch_add_full(), g_io_add_watch(), and
2189 * g_io_add_watch_full().
2191 * See also g_source_destroy(). You must use g_source_destroy() for sources
2192 * added to a non-default main context.
2194 * It is a programmer error to attempt to remove a non-existent source.
2196 * Return value: For historical reasons, this function always returns %TRUE
2199 g_source_remove (guint tag)
2203 g_return_val_if_fail (tag > 0, FALSE);
2205 source = g_main_context_find_source_by_id (NULL, tag);
2207 g_source_destroy (source);
2209 g_critical ("Source ID %u was not found when attempting to remove it", tag);
2211 return source != NULL;
2215 * g_source_remove_by_user_data:
2216 * @user_data: the user_data for the callback.
2218 * Removes a source from the default main loop context given the user
2219 * data for the callback. If multiple sources exist with the same user
2220 * data, only one will be destroyed.
2222 * Return value: %TRUE if a source was found and removed.
2225 g_source_remove_by_user_data (gpointer user_data)
2229 source = g_main_context_find_source_by_user_data (NULL, user_data);
2232 g_source_destroy (source);
2240 * g_source_remove_by_funcs_user_data:
2241 * @funcs: The @source_funcs passed to g_source_new()
2242 * @user_data: the user data for the callback
2244 * Removes a source from the default main loop context given the
2245 * source functions and user data. If multiple sources exist with the
2246 * same source functions and user data, only one will be destroyed.
2248 * Return value: %TRUE if a source was found and removed.
2251 g_source_remove_by_funcs_user_data (GSourceFuncs *funcs,
2256 g_return_val_if_fail (funcs != NULL, FALSE);
2258 source = g_main_context_find_source_by_funcs_user_data (NULL, funcs, user_data);
2261 g_source_destroy (source);
2270 * g_source_add_unix_fd:
2271 * @source: a #GSource
2272 * @fd: the fd to monitor
2273 * @events: an event mask
2275 * Monitors @fd for the IO events in @events.
2277 * The tag returned by this function can be used to remove or modify the
2278 * monitoring of the fd using g_source_remove_unix_fd() or
2279 * g_source_modify_unix_fd().
2281 * It is not necessary to remove the fd before destroying the source; it
2282 * will be cleaned up automatically.
2284 * As the name suggests, this function is not available on Windows.
2286 * Returns: an opaque tag
2291 g_source_add_unix_fd (GSource *source,
2293 GIOCondition events)
2295 GMainContext *context;
2298 g_return_val_if_fail (source != NULL, NULL);
2299 g_return_val_if_fail (!SOURCE_DESTROYED (source), NULL);
2301 poll_fd = g_new (GPollFD, 1);
2303 poll_fd->events = events;
2304 poll_fd->revents = 0;
2306 context = source->context;
2309 LOCK_CONTEXT (context);
2311 source->priv->fds = g_slist_prepend (source->priv->fds, poll_fd);
2315 if (!SOURCE_BLOCKED (source))
2316 g_main_context_add_poll_unlocked (context, source->priority, poll_fd);
2317 UNLOCK_CONTEXT (context);
2324 * g_source_modify_unix_fd:
2325 * @source: a #GSource
2326 * @tag: the tag from g_source_add_unix_fd()
2327 * @new_events: the new event mask to watch
2329 * Updates the event mask to watch for the fd identified by @tag.
2331 * @tag is the tag returned from g_source_add_unix_fd().
2333 * If you want to remove a fd, don't set its event mask to zero.
2334 * Instead, call g_source_remove_unix_fd().
2336 * As the name suggests, this function is not available on Windows.
2341 g_source_modify_unix_fd (GSource *source,
2343 GIOCondition new_events)
2345 GMainContext *context;
2348 g_return_if_fail (source != NULL);
2349 g_return_if_fail (g_slist_find (source->priv->fds, tag));
2351 context = source->context;
2354 poll_fd->events = new_events;
2357 g_main_context_wakeup (context);
2361 * g_source_remove_unix_fd:
2362 * @source: a #GSource
2363 * @tag: the tag from g_source_add_unix_fd()
2365 * Reverses the effect of a previous call to g_source_add_unix_fd().
2367 * You only need to call this if you want to remove an fd from being
2368 * watched while keeping the same source around. In the normal case you
2369 * will just want to destroy the source.
2371 * As the name suggests, this function is not available on Windows.
2376 g_source_remove_unix_fd (GSource *source,
2379 GMainContext *context;
2382 g_return_if_fail (source != NULL);
2383 g_return_if_fail (g_slist_find (source->priv->fds, tag));
2385 context = source->context;
2389 LOCK_CONTEXT (context);
2391 source->priv->fds = g_slist_remove (source->priv->fds, poll_fd);
2395 if (!SOURCE_BLOCKED (source))
2396 g_main_context_remove_poll_unlocked (context, poll_fd);
2398 UNLOCK_CONTEXT (context);
2405 * g_source_query_unix_fd:
2406 * @source: a #GSource
2407 * @tag: the tag from g_source_add_unix_fd()
2409 * Queries the events reported for the fd corresponding to @tag on
2410 * @source during the last poll.
2412 * The return value of this function is only defined when the function
2413 * is called from the check or dispatch functions for @source.
2415 * As the name suggests, this function is not available on Windows.
2417 * Returns: the conditions reported on the fd
2422 g_source_query_unix_fd (GSource *source,
2427 g_return_val_if_fail (source != NULL, 0);
2428 g_return_val_if_fail (g_slist_find (source->priv->fds, tag), 0);
2432 return poll_fd->revents;
2434 #endif /* G_OS_UNIX */
2437 * g_get_current_time:
2438 * @result: #GTimeVal structure in which to store current time.
2440 * Equivalent to the UNIX gettimeofday() function, but portable.
2442 * You may find g_get_real_time() to be more convenient.
2445 g_get_current_time (GTimeVal *result)
2450 g_return_if_fail (result != NULL);
2452 /*this is required on alpha, there the timeval structs are int's
2453 not longs and a cast only would fail horribly*/
2454 gettimeofday (&r, NULL);
2455 result->tv_sec = r.tv_sec;
2456 result->tv_usec = r.tv_usec;
2461 g_return_if_fail (result != NULL);
2463 GetSystemTimeAsFileTime (&ft);
2464 memmove (&time64, &ft, sizeof (FILETIME));
2466 /* Convert from 100s of nanoseconds since 1601-01-01
2467 * to Unix epoch. Yes, this is Y2038 unsafe.
2469 time64 -= G_GINT64_CONSTANT (116444736000000000);
2472 result->tv_sec = time64 / 1000000;
2473 result->tv_usec = time64 % 1000000;
2480 * Queries the system wall-clock time.
2482 * This call is functionally equivalent to g_get_current_time() except
2483 * that the return value is often more convenient than dealing with a
2486 * You should only use this call if you are actually interested in the real
2487 * wall-clock time. g_get_monotonic_time() is probably more useful for
2488 * measuring intervals.
2490 * Returns: the number of microseconds since January 1, 1970 UTC.
2495 g_get_real_time (void)
2499 g_get_current_time (&tv);
2501 return (((gint64) tv.tv_sec) * 1000000) + tv.tv_usec;
2505 static ULONGLONG (*g_GetTickCount64) (void) = NULL;
2506 static guint32 g_win32_tick_epoch = 0;
2509 g_clock_win32_init (void)
2513 g_GetTickCount64 = NULL;
2514 kernel32 = GetModuleHandle ("KERNEL32.DLL");
2515 if (kernel32 != NULL)
2516 g_GetTickCount64 = (void *) GetProcAddress (kernel32, "GetTickCount64");
2517 g_win32_tick_epoch = ((guint32)GetTickCount()) >> 31;
2522 * g_get_monotonic_time:
2524 * Queries the system monotonic time, if available.
2526 * On POSIX systems with clock_gettime() and <literal>CLOCK_MONOTONIC</literal> this call
2527 * is a very shallow wrapper for that. Otherwise, we make a best effort
2528 * that probably involves returning the wall clock time (with at least
2529 * microsecond accuracy, subject to the limitations of the OS kernel).
2531 * It's important to note that POSIX <literal>CLOCK_MONOTONIC</literal> does
2532 * not count time spent while the machine is suspended.
2534 * On Windows, "limitations of the OS kernel" is a rather substantial
2535 * statement. Depending on the configuration of the system, the wall
2536 * clock time is updated as infrequently as 64 times a second (which
2537 * is approximately every 16ms). Also, on XP (but not on Vista or later)
2538 * the monotonic clock is locally monotonic, but may differ in exact
2539 * value between processes due to timer wrap handling.
2541 * Returns: the monotonic time, in microseconds
2546 g_get_monotonic_time (void)
2548 #ifdef HAVE_CLOCK_GETTIME
2549 /* librt clock_gettime() is our first choice */
2552 #ifdef CLOCK_MONOTONIC
2553 clock_gettime (CLOCK_MONOTONIC, &ts);
2555 clock_gettime (CLOCK_REALTIME, &ts);
2558 /* In theory monotonic time can have any epoch.
2560 * glib presently assumes the following:
2562 * 1) The epoch comes some time after the birth of Jesus of Nazareth, but
2563 * not more than 10000 years later.
2565 * 2) The current time also falls sometime within this range.
2567 * These two reasonable assumptions leave us with a maximum deviation from
2568 * the epoch of 10000 years, or 315569520000000000 seconds.
2570 * If we restrict ourselves to this range then the number of microseconds
2571 * will always fit well inside the constraints of a int64 (by a factor of
2574 * If you actually hit the following assertion, probably you should file a
2575 * bug against your operating system for being excessively silly.
2577 g_assert (G_GINT64_CONSTANT (-315569520000000000) < ts.tv_sec &&
2578 ts.tv_sec < G_GINT64_CONSTANT (315569520000000000));
2580 return (((gint64) ts.tv_sec) * 1000000) + (ts.tv_nsec / 1000);
2582 #elif defined (G_OS_WIN32)
2586 /* There are four sources for the monotonic time on Windows:
2588 * Three are based on a (1 msec accuracy, but only read periodically) clock chip:
2589 * - GetTickCount (GTC)
2590 * 32bit msec counter, updated each ~15msec, wraps in ~50 days
2591 * - GetTickCount64 (GTC64)
2592 * Same as GetTickCount, but extended to 64bit, so no wrap
2593 * Only available in Vista or later
2594 * - timeGetTime (TGT)
2595 * similar to GetTickCount by default: 15msec, 50 day wrap.
2596 * available in winmm.dll (thus known as the multimedia timers)
2597 * However apps can raise the system timer clock frequency using timeBeginPeriod()
2598 * increasing the accuracy up to 1 msec, at a cost in general system performance
2601 * One is based on high precision clocks:
2602 * - QueryPrecisionCounter (QPC)
2603 * This has much higher accuracy, but is not guaranteed monotonic, and
2604 * has lots of complications like clock jumps and different times on different
2605 * CPUs. It also has lower long term accuracy (i.e. it will drift compared to
2606 * the low precision clocks.
2608 * Additionally, the precision available in the timer-based wakeup such as
2609 * MsgWaitForMultipleObjectsEx (which is what the mainloop is based on) is based
2610 * on the TGT resolution, so by default it is ~15msec, but can be increased by apps.
2612 * The QPC timer has too many issues to be used as is. The only way it could be used
2613 * is to use it to interpolate the lower precision clocks. Firefox does something like
2615 * https://bugzilla.mozilla.org/show_bug.cgi?id=363258
2617 * However this seems quite complicated, so we're not doing this right now.
2619 * The approach we take instead is to use the TGT timer, extending it to 64bit
2620 * either by using the GTC64 value, or if that is not available, a process local
2621 * time epoch that we increment when we detect a timer wrap (assumes that we read
2622 * the time at least once every 50 days).
2625 * - We have a globally consistent monotonic clock on Vista and later
2626 * - We have a locally monotonic clock on XP
2627 * - Apps that need higher precision in timeouts and clock reads can call
2628 * timeBeginPeriod() to increase it as much as they want
2631 if (g_GetTickCount64 != NULL)
2633 guint32 ticks_as_32bit;
2635 ticks = g_GetTickCount64 ();
2636 ticks32 = timeGetTime();
2638 /* GTC64 and TGT are sampled at different times, however they
2639 * have the same base and source (msecs since system boot).
2640 * They can differ by as much as -16 to +16 msecs.
2641 * We can't just inject the low bits into the 64bit counter
2642 * as one of the counters can have wrapped in 32bit space and
2643 * the other not. Instead we calculate the signed difference
2644 * in 32bit space and apply that difference to the 64bit counter.
2646 ticks_as_32bit = (guint32)ticks;
2648 /* We could do some 2's complement hack, but we play it safe */
2649 if (ticks32 - ticks_as_32bit <= G_MAXINT32)
2650 ticks += ticks32 - ticks_as_32bit;
2652 ticks -= ticks_as_32bit - ticks32;
2658 epoch = g_atomic_int_get (&g_win32_tick_epoch);
2660 /* Must read ticks after the epoch. Then we're guaranteed
2661 * that the ticks value we read is higher or equal to any
2662 * previous ones that lead to the writing of the epoch.
2664 ticks32 = timeGetTime();
2666 /* We store the MSB of the current time as the LSB
2667 * of the epoch. Comparing these bits lets us detect when
2668 * the 32bit counter has wrapped so we can increase the
2671 * This will work as long as this function is called at
2672 * least once every ~24 days, which is half the wrap time
2673 * of a 32bit msec counter. I think this is pretty likely.
2675 * Note that g_win32_tick_epoch is a process local state,
2676 * so the monotonic clock will not be the same between
2679 if ((ticks32 >> 31) != (epoch & 1))
2682 g_atomic_int_set (&g_win32_tick_epoch, epoch);
2686 ticks = (guint64)ticks32 | ((guint64)epoch) << 31;
2689 return ticks * 1000;
2691 #else /* !HAVE_CLOCK_GETTIME && ! G_OS_WIN32*/
2695 g_get_current_time (&tv);
2697 return (((gint64) tv.tv_sec) * 1000000) + tv.tv_usec;
2702 g_main_dispatch_free (gpointer dispatch)
2704 g_slice_free (GMainDispatch, dispatch);
2707 /* Running the main loop */
2709 static GMainDispatch *
2712 static GPrivate depth_private = G_PRIVATE_INIT (g_main_dispatch_free);
2713 GMainDispatch *dispatch;
2715 dispatch = g_private_get (&depth_private);
2719 dispatch = g_slice_new0 (GMainDispatch);
2720 g_private_set (&depth_private, dispatch);
2729 * Returns the depth of the stack of calls to
2730 * g_main_context_dispatch() on any #GMainContext in the current thread.
2731 * That is, when called from the toplevel, it gives 0. When
2732 * called from within a callback from g_main_context_iteration()
2733 * (or g_main_loop_run(), etc.) it returns 1. When called from within
2734 * a callback to a recursive call to g_main_context_iteration(),
2735 * it returns 2. And so forth.
2737 * This function is useful in a situation like the following:
2738 * Imagine an extremely simple "garbage collected" system.
2741 * static GList *free_list;
2744 * allocate_memory (gsize size)
2746 * gpointer result = g_malloc (size);
2747 * free_list = g_list_prepend (free_list, result);
2752 * free_allocated_memory (void)
2755 * for (l = free_list; l; l = l->next);
2757 * g_list_free (free_list);
2765 * g_main_context_iteration (NULL, TRUE);
2766 * free_allocated_memory();
2770 * This works from an application, however, if you want to do the same
2771 * thing from a library, it gets more difficult, since you no longer
2772 * control the main loop. You might think you can simply use an idle
2773 * function to make the call to free_allocated_memory(), but that
2774 * doesn't work, since the idle function could be called from a
2775 * recursive callback. This can be fixed by using g_main_depth()
2779 * allocate_memory (gsize size)
2781 * FreeListBlock *block = g_new (FreeListBlock, 1);
2782 * block->mem = g_malloc (size);
2783 * block->depth = g_main_depth ();
2784 * free_list = g_list_prepend (free_list, block);
2785 * return block->mem;
2789 * free_allocated_memory (void)
2793 * int depth = g_main_depth ();
2794 * for (l = free_list; l; );
2796 * GList *next = l->next;
2797 * FreeListBlock *block = l->data;
2798 * if (block->depth > depth)
2800 * g_free (block->mem);
2802 * free_list = g_list_delete_link (free_list, l);
2810 * There is a temptation to use g_main_depth() to solve
2811 * problems with reentrancy. For instance, while waiting for data
2812 * to be received from the network in response to a menu item,
2813 * the menu item might be selected again. It might seem that
2814 * one could make the menu item's callback return immediately
2815 * and do nothing if g_main_depth() returns a value greater than 1.
2816 * However, this should be avoided since the user then sees selecting
2817 * the menu item do nothing. Furthermore, you'll find yourself adding
2818 * these checks all over your code, since there are doubtless many,
2819 * many things that the user could do. Instead, you can use the
2820 * following techniques:
2825 * Use gtk_widget_set_sensitive() or modal dialogs to prevent
2826 * the user from interacting with elements while the main
2827 * loop is recursing.
2832 * Avoid main loop recursion in situations where you can't handle
2833 * arbitrary callbacks. Instead, structure your code so that you
2834 * simply return to the main loop and then get called again when
2835 * there is more work to do.
2840 * Return value: The main loop recursion level in the current thread
2845 GMainDispatch *dispatch = get_dispatch ();
2846 return dispatch->depth;
2850 * g_main_current_source:
2852 * Returns the currently firing source for this thread.
2854 * Return value: (transfer none): The currently firing source or %NULL.
2859 g_main_current_source (void)
2861 GMainDispatch *dispatch = get_dispatch ();
2862 return dispatch->source;
2866 * g_source_is_destroyed:
2867 * @source: a #GSource
2869 * Returns whether @source has been destroyed.
2871 * This is important when you operate upon your objects
2872 * from within idle handlers, but may have freed the object
2873 * before the dispatch of your idle handler.
2877 * idle_callback (gpointer data)
2879 * SomeWidget *self = data;
2881 * GDK_THREADS_ENTER (<!-- -->);
2882 * /<!-- -->* do stuff with self *<!-- -->/
2883 * self->idle_id = 0;
2884 * GDK_THREADS_LEAVE (<!-- -->);
2886 * return G_SOURCE_REMOVE;
2890 * some_widget_do_stuff_later (SomeWidget *self)
2892 * self->idle_id = g_idle_add (idle_callback, self);
2896 * some_widget_finalize (GObject *object)
2898 * SomeWidget *self = SOME_WIDGET (object);
2900 * if (self->idle_id)
2901 * g_source_remove (self->idle_id);
2903 * G_OBJECT_CLASS (parent_class)->finalize (object);
2907 * This will fail in a multi-threaded application if the
2908 * widget is destroyed before the idle handler fires due
2909 * to the use after free in the callback. A solution, to
2910 * this particular problem, is to check to if the source
2911 * has already been destroy within the callback.
2915 * idle_callback (gpointer data)
2917 * SomeWidget *self = data;
2919 * GDK_THREADS_ENTER ();
2920 * if (!g_source_is_destroyed (g_main_current_source ()))
2922 * /<!-- -->* do stuff with self *<!-- -->/
2924 * GDK_THREADS_LEAVE ();
2930 * Return value: %TRUE if the source has been destroyed
2935 g_source_is_destroyed (GSource *source)
2937 return SOURCE_DESTROYED (source);
2940 /* Temporarily remove all this source's file descriptors from the
2941 * poll(), so that if data comes available for one of the file descriptors
2942 * we don't continually spin in the poll()
2944 /* HOLDS: source->context's lock */
2946 block_source (GSource *source)
2950 g_return_if_fail (!SOURCE_BLOCKED (source));
2952 source->flags |= G_SOURCE_BLOCKED;
2954 if (source->context)
2956 tmp_list = source->poll_fds;
2959 g_main_context_remove_poll_unlocked (source->context, tmp_list->data);
2960 tmp_list = tmp_list->next;
2963 for (tmp_list = source->priv->fds; tmp_list; tmp_list = tmp_list->next)
2964 g_main_context_remove_poll_unlocked (source->context, tmp_list->data);
2967 if (source->priv && source->priv->child_sources)
2969 tmp_list = source->priv->child_sources;
2972 block_source (tmp_list->data);
2973 tmp_list = tmp_list->next;
2978 /* HOLDS: source->context's lock */
2980 unblock_source (GSource *source)
2984 g_return_if_fail (SOURCE_BLOCKED (source)); /* Source already unblocked */
2985 g_return_if_fail (!SOURCE_DESTROYED (source));
2987 source->flags &= ~G_SOURCE_BLOCKED;
2989 tmp_list = source->poll_fds;
2992 g_main_context_add_poll_unlocked (source->context, source->priority, tmp_list->data);
2993 tmp_list = tmp_list->next;
2996 for (tmp_list = source->priv->fds; tmp_list; tmp_list = tmp_list->next)
2997 g_main_context_add_poll_unlocked (source->context, source->priority, tmp_list->data);
2999 if (source->priv && source->priv->child_sources)
3001 tmp_list = source->priv->child_sources;
3004 unblock_source (tmp_list->data);
3005 tmp_list = tmp_list->next;
3010 /* HOLDS: context's lock */
3012 g_main_dispatch (GMainContext *context)
3014 GMainDispatch *current = get_dispatch ();
3017 for (i = 0; i < context->pending_dispatches->len; i++)
3019 GSource *source = context->pending_dispatches->pdata[i];
3021 context->pending_dispatches->pdata[i] = NULL;
3024 source->flags &= ~G_SOURCE_READY;
3026 if (!SOURCE_DESTROYED (source))
3028 gboolean was_in_call;
3029 gpointer user_data = NULL;
3030 GSourceFunc callback = NULL;
3031 GSourceCallbackFuncs *cb_funcs;
3033 gboolean need_destroy;
3035 gboolean (*dispatch) (GSource *,
3038 GSource *prev_source;
3040 dispatch = source->source_funcs->dispatch;
3041 cb_funcs = source->callback_funcs;
3042 cb_data = source->callback_data;
3045 cb_funcs->ref (cb_data);
3047 if ((source->flags & G_SOURCE_CAN_RECURSE) == 0)
3048 block_source (source);
3050 was_in_call = source->flags & G_HOOK_FLAG_IN_CALL;
3051 source->flags |= G_HOOK_FLAG_IN_CALL;
3054 cb_funcs->get (cb_data, source, &callback, &user_data);
3056 UNLOCK_CONTEXT (context);
3058 /* These operations are safe because 'current' is thread-local
3059 * and not modified from anywhere but this function.
3061 prev_source = current->source;
3062 current->source = source;
3065 need_destroy = !(* dispatch) (source, callback, user_data);
3067 current->source = prev_source;
3071 cb_funcs->unref (cb_data);
3073 LOCK_CONTEXT (context);
3076 source->flags &= ~G_HOOK_FLAG_IN_CALL;
3078 if (SOURCE_BLOCKED (source) && !SOURCE_DESTROYED (source))
3079 unblock_source (source);
3081 /* Note: this depends on the fact that we can't switch
3082 * sources from one main context to another
3084 if (need_destroy && !SOURCE_DESTROYED (source))
3086 g_assert (source->context == context);
3087 g_source_destroy_internal (source, context, TRUE);
3091 SOURCE_UNREF (source, context);
3094 g_ptr_array_set_size (context->pending_dispatches, 0);
3098 * g_main_context_acquire:
3099 * @context: a #GMainContext
3101 * Tries to become the owner of the specified context.
3102 * If some other thread is the owner of the context,
3103 * returns %FALSE immediately. Ownership is properly
3104 * recursive: the owner can require ownership again
3105 * and will release ownership when g_main_context_release()
3106 * is called as many times as g_main_context_acquire().
3108 * You must be the owner of a context before you
3109 * can call g_main_context_prepare(), g_main_context_query(),
3110 * g_main_context_check(), g_main_context_dispatch().
3112 * Return value: %TRUE if the operation succeeded, and
3113 * this thread is now the owner of @context.
3116 g_main_context_acquire (GMainContext *context)
3118 gboolean result = FALSE;
3119 GThread *self = G_THREAD_SELF;
3121 if (context == NULL)
3122 context = g_main_context_default ();
3124 LOCK_CONTEXT (context);
3126 if (!context->owner)
3128 context->owner = self;
3129 g_assert (context->owner_count == 0);
3132 if (context->owner == self)
3134 context->owner_count++;
3138 UNLOCK_CONTEXT (context);
3144 * g_main_context_release:
3145 * @context: a #GMainContext
3147 * Releases ownership of a context previously acquired by this thread
3148 * with g_main_context_acquire(). If the context was acquired multiple
3149 * times, the ownership will be released only when g_main_context_release()
3150 * is called as many times as it was acquired.
3153 g_main_context_release (GMainContext *context)
3155 if (context == NULL)
3156 context = g_main_context_default ();
3158 LOCK_CONTEXT (context);
3160 context->owner_count--;
3161 if (context->owner_count == 0)
3163 context->owner = NULL;
3165 if (context->waiters)
3167 GMainWaiter *waiter = context->waiters->data;
3168 gboolean loop_internal_waiter = (waiter->mutex == &context->mutex);
3169 context->waiters = g_slist_delete_link (context->waiters,
3171 if (!loop_internal_waiter)
3172 g_mutex_lock (waiter->mutex);
3174 g_cond_signal (waiter->cond);
3176 if (!loop_internal_waiter)
3177 g_mutex_unlock (waiter->mutex);
3181 UNLOCK_CONTEXT (context);
3185 * g_main_context_wait:
3186 * @context: a #GMainContext
3187 * @cond: a condition variable
3188 * @mutex: a mutex, currently held
3190 * Tries to become the owner of the specified context,
3191 * as with g_main_context_acquire(). But if another thread
3192 * is the owner, atomically drop @mutex and wait on @cond until
3193 * that owner releases ownership or until @cond is signaled, then
3194 * try again (once) to become the owner.
3196 * Return value: %TRUE if the operation succeeded, and
3197 * this thread is now the owner of @context.
3200 g_main_context_wait (GMainContext *context,
3204 gboolean result = FALSE;
3205 GThread *self = G_THREAD_SELF;
3206 gboolean loop_internal_waiter;
3208 if (context == NULL)
3209 context = g_main_context_default ();
3211 loop_internal_waiter = (mutex == &context->mutex);
3213 if (!loop_internal_waiter)
3214 LOCK_CONTEXT (context);
3216 if (context->owner && context->owner != self)
3221 waiter.mutex = mutex;
3223 context->waiters = g_slist_append (context->waiters, &waiter);
3225 if (!loop_internal_waiter)
3226 UNLOCK_CONTEXT (context);
3227 g_cond_wait (cond, mutex);
3228 if (!loop_internal_waiter)
3229 LOCK_CONTEXT (context);
3231 context->waiters = g_slist_remove (context->waiters, &waiter);
3234 if (!context->owner)
3236 context->owner = self;
3237 g_assert (context->owner_count == 0);
3240 if (context->owner == self)
3242 context->owner_count++;
3246 if (!loop_internal_waiter)
3247 UNLOCK_CONTEXT (context);
3253 * g_main_context_prepare:
3254 * @context: a #GMainContext
3255 * @priority: location to store priority of highest priority
3256 * source already ready.
3258 * Prepares to poll sources within a main loop. The resulting information
3259 * for polling is determined by calling g_main_context_query ().
3261 * Return value: %TRUE if some source is ready to be dispatched
3265 g_main_context_prepare (GMainContext *context,
3270 gint current_priority = G_MAXINT;
3274 if (context == NULL)
3275 context = g_main_context_default ();
3277 LOCK_CONTEXT (context);
3279 context->time_is_fresh = FALSE;
3281 if (context->in_check_or_prepare)
3283 g_warning ("g_main_context_prepare() called recursively from within a source's check() or "
3284 "prepare() member.");
3285 UNLOCK_CONTEXT (context);
3290 /* If recursing, finish up current dispatch, before starting over */
3291 if (context->pending_dispatches)
3294 g_main_dispatch (context, ¤t_time);
3296 UNLOCK_CONTEXT (context);
3301 /* If recursing, clear list of pending dispatches */
3303 for (i = 0; i < context->pending_dispatches->len; i++)
3305 if (context->pending_dispatches->pdata[i])
3306 SOURCE_UNREF ((GSource *)context->pending_dispatches->pdata[i], context);
3308 g_ptr_array_set_size (context->pending_dispatches, 0);
3310 /* Prepare all sources */
3312 context->timeout = -1;
3314 g_source_iter_init (&iter, context, TRUE);
3315 while (g_source_iter_next (&iter, &source))
3317 gint source_timeout = -1;
3319 if (SOURCE_DESTROYED (source) || SOURCE_BLOCKED (source))
3321 if ((n_ready > 0) && (source->priority > current_priority))
3324 if (!(source->flags & G_SOURCE_READY))
3327 gboolean (* prepare) (GSource *source,
3330 prepare = source->source_funcs->prepare;
3334 context->in_check_or_prepare++;
3335 UNLOCK_CONTEXT (context);
3337 result = (* prepare) (source, &source_timeout);
3339 LOCK_CONTEXT (context);
3340 context->in_check_or_prepare--;
3344 source_timeout = -1;
3348 if (result == FALSE && source->priv->ready_time != -1)
3350 if (!context->time_is_fresh)
3352 context->time = g_get_monotonic_time ();
3353 context->time_is_fresh = TRUE;
3356 if (source->priv->ready_time <= context->time)
3365 /* rounding down will lead to spinning, so always round up */
3366 timeout = (source->priv->ready_time - context->time + 999) / 1000;
3368 if (source_timeout < 0 || timeout < source_timeout)
3369 source_timeout = timeout;
3375 GSource *ready_source = source;
3377 while (ready_source)
3379 ready_source->flags |= G_SOURCE_READY;
3380 ready_source = ready_source->priv->parent_source;
3385 if (source->flags & G_SOURCE_READY)
3388 current_priority = source->priority;
3389 context->timeout = 0;
3392 if (source_timeout >= 0)
3394 if (context->timeout < 0)
3395 context->timeout = source_timeout;
3397 context->timeout = MIN (context->timeout, source_timeout);
3400 g_source_iter_clear (&iter);
3402 UNLOCK_CONTEXT (context);
3405 *priority = current_priority;
3407 return (n_ready > 0);
3411 * g_main_context_query:
3412 * @context: a #GMainContext
3413 * @max_priority: maximum priority source to check
3414 * @timeout_: (out): location to store timeout to be used in polling
3415 * @fds: (out caller-allocates) (array length=n_fds): location to
3416 * store #GPollFD records that need to be polled.
3417 * @n_fds: length of @fds.
3419 * Determines information necessary to poll this main loop.
3421 * Return value: the number of records actually stored in @fds,
3422 * or, if more than @n_fds records need to be stored, the number
3423 * of records that need to be stored.
3426 g_main_context_query (GMainContext *context,
3435 LOCK_CONTEXT (context);
3437 pollrec = context->poll_records;
3439 while (pollrec && max_priority >= pollrec->priority)
3441 /* We need to include entries with fd->events == 0 in the array because
3442 * otherwise if the application changes fd->events behind our back and
3443 * makes it non-zero, we'll be out of sync when we check the fds[] array.
3444 * (Changing fd->events after adding an FD wasn't an anticipated use of
3445 * this API, but it occurs in practice.) */
3448 fds[n_poll].fd = pollrec->fd->fd;
3449 /* In direct contradiction to the Unix98 spec, IRIX runs into
3450 * difficulty if you pass in POLLERR, POLLHUP or POLLNVAL
3451 * flags in the events field of the pollfd while it should
3452 * just ignoring them. So we mask them out here.
3454 fds[n_poll].events = pollrec->fd->events & ~(G_IO_ERR|G_IO_HUP|G_IO_NVAL);
3455 fds[n_poll].revents = 0;
3458 pollrec = pollrec->next;
3462 context->poll_changed = FALSE;
3466 *timeout = context->timeout;
3468 context->time_is_fresh = FALSE;
3471 UNLOCK_CONTEXT (context);
3477 * g_main_context_check:
3478 * @context: a #GMainContext
3479 * @max_priority: the maximum numerical priority of sources to check
3480 * @fds: (array length=n_fds): array of #GPollFD's that was passed to
3481 * the last call to g_main_context_query()
3482 * @n_fds: return value of g_main_context_query()
3484 * Passes the results of polling back to the main loop.
3486 * Return value: %TRUE if some sources are ready to be dispatched.
3489 g_main_context_check (GMainContext *context,
3500 LOCK_CONTEXT (context);
3502 if (context->in_check_or_prepare)
3504 g_warning ("g_main_context_check() called recursively from within a source's check() or "
3505 "prepare() member.");
3506 UNLOCK_CONTEXT (context);
3510 if (context->wake_up_rec.revents)
3511 g_wakeup_acknowledge (context->wakeup);
3513 /* If the set of poll file descriptors changed, bail out
3514 * and let the main loop rerun
3516 if (context->poll_changed)
3518 UNLOCK_CONTEXT (context);
3522 pollrec = context->poll_records;
3526 if (pollrec->fd->events)
3527 pollrec->fd->revents = fds[i].revents;
3529 pollrec = pollrec->next;
3533 g_source_iter_init (&iter, context, TRUE);
3534 while (g_source_iter_next (&iter, &source))
3536 if (SOURCE_DESTROYED (source) || SOURCE_BLOCKED (source))
3538 if ((n_ready > 0) && (source->priority > max_priority))
3541 if (!(source->flags & G_SOURCE_READY))
3544 gboolean (* check) (GSource *source);
3546 check = source->source_funcs->check;
3550 /* If the check function is set, call it. */
3551 context->in_check_or_prepare++;
3552 UNLOCK_CONTEXT (context);
3554 result = (* check) (source);
3556 LOCK_CONTEXT (context);
3557 context->in_check_or_prepare--;
3562 if (result == FALSE)
3566 /* If not already explicitly flagged ready by ->check()
3567 * (or if we have no check) then we can still be ready if
3568 * any of our fds poll as ready.
3570 for (tmp_list = source->priv->fds; tmp_list; tmp_list = tmp_list->next)
3572 GPollFD *pollfd = tmp_list->data;
3574 if (pollfd->revents)
3582 if (result == FALSE && source->priv->ready_time != -1)
3584 if (!context->time_is_fresh)
3586 context->time = g_get_monotonic_time ();
3587 context->time_is_fresh = TRUE;
3590 if (source->priv->ready_time <= context->time)
3596 GSource *ready_source = source;
3598 while (ready_source)
3600 ready_source->flags |= G_SOURCE_READY;
3601 ready_source = ready_source->priv->parent_source;
3606 if (source->flags & G_SOURCE_READY)
3608 source->ref_count++;
3609 g_ptr_array_add (context->pending_dispatches, source);
3613 /* never dispatch sources with less priority than the first
3614 * one we choose to dispatch
3616 max_priority = source->priority;
3619 g_source_iter_clear (&iter);
3621 UNLOCK_CONTEXT (context);
3627 * g_main_context_dispatch:
3628 * @context: a #GMainContext
3630 * Dispatches all pending sources.
3633 g_main_context_dispatch (GMainContext *context)
3635 LOCK_CONTEXT (context);
3637 if (context->pending_dispatches->len > 0)
3639 g_main_dispatch (context);
3642 UNLOCK_CONTEXT (context);
3645 /* HOLDS context lock */
3647 g_main_context_iterate (GMainContext *context,
3654 gboolean some_ready;
3655 gint nfds, allocated_nfds;
3656 GPollFD *fds = NULL;
3658 UNLOCK_CONTEXT (context);
3660 if (!g_main_context_acquire (context))
3662 gboolean got_ownership;
3664 LOCK_CONTEXT (context);
3669 got_ownership = g_main_context_wait (context,
3677 LOCK_CONTEXT (context);
3679 if (!context->cached_poll_array)
3681 context->cached_poll_array_size = context->n_poll_records;
3682 context->cached_poll_array = g_new (GPollFD, context->n_poll_records);
3685 allocated_nfds = context->cached_poll_array_size;
3686 fds = context->cached_poll_array;
3688 UNLOCK_CONTEXT (context);
3690 g_main_context_prepare (context, &max_priority);
3692 while ((nfds = g_main_context_query (context, max_priority, &timeout, fds,
3693 allocated_nfds)) > allocated_nfds)
3695 LOCK_CONTEXT (context);
3697 context->cached_poll_array_size = allocated_nfds = nfds;
3698 context->cached_poll_array = fds = g_new (GPollFD, nfds);
3699 UNLOCK_CONTEXT (context);
3705 g_main_context_poll (context, timeout, max_priority, fds, nfds);
3707 some_ready = g_main_context_check (context, max_priority, fds, nfds);
3710 g_main_context_dispatch (context);
3712 g_main_context_release (context);
3714 LOCK_CONTEXT (context);
3720 * g_main_context_pending:
3721 * @context: (allow-none): a #GMainContext (if %NULL, the default context will be used)
3723 * Checks if any sources have pending events for the given context.
3725 * Return value: %TRUE if events are pending.
3728 g_main_context_pending (GMainContext *context)
3733 context = g_main_context_default();
3735 LOCK_CONTEXT (context);
3736 retval = g_main_context_iterate (context, FALSE, FALSE, G_THREAD_SELF);
3737 UNLOCK_CONTEXT (context);
3743 * g_main_context_iteration:
3744 * @context: (allow-none): a #GMainContext (if %NULL, the default context will be used)
3745 * @may_block: whether the call may block.
3747 * Runs a single iteration for the given main loop. This involves
3748 * checking to see if any event sources are ready to be processed,
3749 * then if no events sources are ready and @may_block is %TRUE, waiting
3750 * for a source to become ready, then dispatching the highest priority
3751 * events sources that are ready. Otherwise, if @may_block is %FALSE
3752 * sources are not waited to become ready, only those highest priority
3753 * events sources will be dispatched (if any), that are ready at this
3754 * given moment without further waiting.
3756 * Note that even when @may_block is %TRUE, it is still possible for
3757 * g_main_context_iteration() to return %FALSE, since the wait may
3758 * be interrupted for other reasons than an event source becoming ready.
3760 * Return value: %TRUE if events were dispatched.
3763 g_main_context_iteration (GMainContext *context, gboolean may_block)
3768 context = g_main_context_default();
3770 LOCK_CONTEXT (context);
3771 retval = g_main_context_iterate (context, may_block, TRUE, G_THREAD_SELF);
3772 UNLOCK_CONTEXT (context);
3779 * @context: (allow-none): a #GMainContext (if %NULL, the default context will be used).
3780 * @is_running: set to %TRUE to indicate that the loop is running. This
3781 * is not very important since calling g_main_loop_run() will set this to
3784 * Creates a new #GMainLoop structure.
3786 * Return value: a new #GMainLoop.
3789 g_main_loop_new (GMainContext *context,
3790 gboolean is_running)
3795 context = g_main_context_default();
3797 g_main_context_ref (context);
3799 loop = g_new0 (GMainLoop, 1);
3800 loop->context = context;
3801 loop->is_running = is_running != FALSE;
3802 loop->ref_count = 1;
3809 * @loop: a #GMainLoop
3811 * Increases the reference count on a #GMainLoop object by one.
3813 * Return value: @loop
3816 g_main_loop_ref (GMainLoop *loop)
3818 g_return_val_if_fail (loop != NULL, NULL);
3819 g_return_val_if_fail (g_atomic_int_get (&loop->ref_count) > 0, NULL);
3821 g_atomic_int_inc (&loop->ref_count);
3827 * g_main_loop_unref:
3828 * @loop: a #GMainLoop
3830 * Decreases the reference count on a #GMainLoop object by one. If
3831 * the result is zero, free the loop and free all associated memory.
3834 g_main_loop_unref (GMainLoop *loop)
3836 g_return_if_fail (loop != NULL);
3837 g_return_if_fail (g_atomic_int_get (&loop->ref_count) > 0);
3839 if (!g_atomic_int_dec_and_test (&loop->ref_count))
3842 g_main_context_unref (loop->context);
3848 * @loop: a #GMainLoop
3850 * Runs a main loop until g_main_loop_quit() is called on the loop.
3851 * If this is called for the thread of the loop's #GMainContext,
3852 * it will process events from the loop, otherwise it will
3856 g_main_loop_run (GMainLoop *loop)
3858 GThread *self = G_THREAD_SELF;
3860 g_return_if_fail (loop != NULL);
3861 g_return_if_fail (g_atomic_int_get (&loop->ref_count) > 0);
3863 if (!g_main_context_acquire (loop->context))
3865 gboolean got_ownership = FALSE;
3867 /* Another thread owns this context */
3868 LOCK_CONTEXT (loop->context);
3870 g_atomic_int_inc (&loop->ref_count);
3872 if (!loop->is_running)
3873 loop->is_running = TRUE;
3875 while (loop->is_running && !got_ownership)
3876 got_ownership = g_main_context_wait (loop->context,
3877 &loop->context->cond,
3878 &loop->context->mutex);
3880 if (!loop->is_running)
3882 UNLOCK_CONTEXT (loop->context);
3884 g_main_context_release (loop->context);
3885 g_main_loop_unref (loop);
3889 g_assert (got_ownership);
3892 LOCK_CONTEXT (loop->context);
3894 if (loop->context->in_check_or_prepare)
3896 g_warning ("g_main_loop_run(): called recursively from within a source's "
3897 "check() or prepare() member, iteration not possible.");
3901 g_atomic_int_inc (&loop->ref_count);
3902 loop->is_running = TRUE;
3903 while (loop->is_running)
3904 g_main_context_iterate (loop->context, TRUE, TRUE, self);
3906 UNLOCK_CONTEXT (loop->context);
3908 g_main_context_release (loop->context);
3910 g_main_loop_unref (loop);
3915 * @loop: a #GMainLoop
3917 * Stops a #GMainLoop from running. Any calls to g_main_loop_run()
3918 * for the loop will return.
3920 * Note that sources that have already been dispatched when
3921 * g_main_loop_quit() is called will still be executed.
3924 g_main_loop_quit (GMainLoop *loop)
3926 g_return_if_fail (loop != NULL);
3927 g_return_if_fail (g_atomic_int_get (&loop->ref_count) > 0);
3929 LOCK_CONTEXT (loop->context);
3930 loop->is_running = FALSE;
3931 g_wakeup_signal (loop->context->wakeup);
3933 g_cond_broadcast (&loop->context->cond);
3935 UNLOCK_CONTEXT (loop->context);
3939 * g_main_loop_is_running:
3940 * @loop: a #GMainLoop.
3942 * Checks to see if the main loop is currently being run via g_main_loop_run().
3944 * Return value: %TRUE if the mainloop is currently being run.
3947 g_main_loop_is_running (GMainLoop *loop)
3949 g_return_val_if_fail (loop != NULL, FALSE);
3950 g_return_val_if_fail (g_atomic_int_get (&loop->ref_count) > 0, FALSE);
3952 return loop->is_running;
3956 * g_main_loop_get_context:
3957 * @loop: a #GMainLoop.
3959 * Returns the #GMainContext of @loop.
3961 * Return value: (transfer none): the #GMainContext of @loop
3964 g_main_loop_get_context (GMainLoop *loop)
3966 g_return_val_if_fail (loop != NULL, NULL);
3967 g_return_val_if_fail (g_atomic_int_get (&loop->ref_count) > 0, NULL);
3969 return loop->context;
3972 /* HOLDS: context's lock */
3974 g_main_context_poll (GMainContext *context,
3980 #ifdef G_MAIN_POLL_DEBUG
3986 GPollFunc poll_func;
3988 if (n_fds || timeout != 0)
3990 #ifdef G_MAIN_POLL_DEBUG
3991 if (_g_main_poll_debug)
3993 g_print ("polling context=%p n=%d timeout=%d\n",
3994 context, n_fds, timeout);
3995 poll_timer = g_timer_new ();
3999 LOCK_CONTEXT (context);
4001 poll_func = context->poll_func;
4003 UNLOCK_CONTEXT (context);
4004 if ((*poll_func) (fds, n_fds, timeout) < 0 && errno != EINTR)
4007 g_warning ("poll(2) failed due to: %s.",
4008 g_strerror (errno));
4010 /* If g_poll () returns -1, it has already called g_warning() */
4014 #ifdef G_MAIN_POLL_DEBUG
4015 if (_g_main_poll_debug)
4017 LOCK_CONTEXT (context);
4019 g_print ("g_main_poll(%d) timeout: %d - elapsed %12.10f seconds",
4022 g_timer_elapsed (poll_timer, NULL));
4023 g_timer_destroy (poll_timer);
4024 pollrec = context->poll_records;
4026 while (pollrec != NULL)
4031 if (fds[i].fd == pollrec->fd->fd &&
4032 pollrec->fd->events &&
4035 g_print (" [" G_POLLFD_FORMAT " :", fds[i].fd);
4036 if (fds[i].revents & G_IO_IN)
4038 if (fds[i].revents & G_IO_OUT)
4040 if (fds[i].revents & G_IO_PRI)
4042 if (fds[i].revents & G_IO_ERR)
4044 if (fds[i].revents & G_IO_HUP)
4046 if (fds[i].revents & G_IO_NVAL)
4052 pollrec = pollrec->next;
4056 UNLOCK_CONTEXT (context);
4059 } /* if (n_fds || timeout != 0) */
4063 * g_main_context_add_poll:
4064 * @context: (allow-none): a #GMainContext (or %NULL for the default context)
4065 * @fd: a #GPollFD structure holding information about a file
4066 * descriptor to watch.
4067 * @priority: the priority for this file descriptor which should be
4068 * the same as the priority used for g_source_attach() to ensure that the
4069 * file descriptor is polled whenever the results may be needed.
4071 * Adds a file descriptor to the set of file descriptors polled for
4072 * this context. This will very seldom be used directly. Instead
4073 * a typical event source will use g_source_add_unix_fd() instead.
4076 g_main_context_add_poll (GMainContext *context,
4081 context = g_main_context_default ();
4083 g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
4084 g_return_if_fail (fd);
4086 LOCK_CONTEXT (context);
4087 g_main_context_add_poll_unlocked (context, priority, fd);
4088 UNLOCK_CONTEXT (context);
4091 /* HOLDS: main_loop_lock */
4093 g_main_context_add_poll_unlocked (GMainContext *context,
4097 GPollRec *prevrec, *nextrec;
4098 GPollRec *newrec = g_slice_new (GPollRec);
4100 /* This file descriptor may be checked before we ever poll */
4103 newrec->priority = priority;
4105 prevrec = context->poll_records_tail;
4107 while (prevrec && priority < prevrec->priority)
4110 prevrec = prevrec->prev;
4114 prevrec->next = newrec;
4116 context->poll_records = newrec;
4118 newrec->prev = prevrec;
4119 newrec->next = nextrec;
4122 nextrec->prev = newrec;
4124 context->poll_records_tail = newrec;
4126 context->n_poll_records++;
4128 context->poll_changed = TRUE;
4130 /* Now wake up the main loop if it is waiting in the poll() */
4131 g_wakeup_signal (context->wakeup);
4135 * g_main_context_remove_poll:
4136 * @context:a #GMainContext
4137 * @fd: a #GPollFD descriptor previously added with g_main_context_add_poll()
4139 * Removes file descriptor from the set of file descriptors to be
4140 * polled for a particular context.
4143 g_main_context_remove_poll (GMainContext *context,
4147 context = g_main_context_default ();
4149 g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
4150 g_return_if_fail (fd);
4152 LOCK_CONTEXT (context);
4153 g_main_context_remove_poll_unlocked (context, fd);
4154 UNLOCK_CONTEXT (context);
4158 g_main_context_remove_poll_unlocked (GMainContext *context,
4161 GPollRec *pollrec, *prevrec, *nextrec;
4164 pollrec = context->poll_records;
4168 nextrec = pollrec->next;
4169 if (pollrec->fd == fd)
4171 if (prevrec != NULL)
4172 prevrec->next = nextrec;
4174 context->poll_records = nextrec;
4176 if (nextrec != NULL)
4177 nextrec->prev = prevrec;
4179 context->poll_records_tail = prevrec;
4181 g_slice_free (GPollRec, pollrec);
4183 context->n_poll_records--;
4190 context->poll_changed = TRUE;
4192 /* Now wake up the main loop if it is waiting in the poll() */
4193 g_wakeup_signal (context->wakeup);
4197 * g_source_get_current_time:
4198 * @source: a #GSource
4199 * @timeval: #GTimeVal structure in which to store current time.
4201 * This function ignores @source and is otherwise the same as
4202 * g_get_current_time().
4204 * Deprecated: 2.28: use g_source_get_time() instead
4207 g_source_get_current_time (GSource *source,
4210 g_get_current_time (timeval);
4214 * g_source_get_time:
4215 * @source: a #GSource
4217 * Gets the time to be used when checking this source. The advantage of
4218 * calling this function over calling g_get_monotonic_time() directly is
4219 * that when checking multiple sources, GLib can cache a single value
4220 * instead of having to repeatedly get the system monotonic time.
4222 * The time here is the system monotonic time, if available, or some
4223 * other reasonable alternative otherwise. See g_get_monotonic_time().
4225 * Returns: the monotonic time in microseconds
4230 g_source_get_time (GSource *source)
4232 GMainContext *context;
4235 g_return_val_if_fail (source->context != NULL, 0);
4237 context = source->context;
4239 LOCK_CONTEXT (context);
4241 if (!context->time_is_fresh)
4243 context->time = g_get_monotonic_time ();
4244 context->time_is_fresh = TRUE;
4247 result = context->time;
4249 UNLOCK_CONTEXT (context);
4255 * g_main_context_set_poll_func:
4256 * @context: a #GMainContext
4257 * @func: the function to call to poll all file descriptors
4259 * Sets the function to use to handle polling of file descriptors. It
4260 * will be used instead of the poll() system call
4261 * (or GLib's replacement function, which is used where
4262 * poll() isn't available).
4264 * This function could possibly be used to integrate the GLib event
4265 * loop with an external event loop.
4268 g_main_context_set_poll_func (GMainContext *context,
4272 context = g_main_context_default ();
4274 g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
4276 LOCK_CONTEXT (context);
4279 context->poll_func = func;
4281 context->poll_func = g_poll;
4283 UNLOCK_CONTEXT (context);
4287 * g_main_context_get_poll_func:
4288 * @context: a #GMainContext
4290 * Gets the poll function set by g_main_context_set_poll_func().
4292 * Return value: the poll function
4295 g_main_context_get_poll_func (GMainContext *context)
4300 context = g_main_context_default ();
4302 g_return_val_if_fail (g_atomic_int_get (&context->ref_count) > 0, NULL);
4304 LOCK_CONTEXT (context);
4305 result = context->poll_func;
4306 UNLOCK_CONTEXT (context);
4312 * g_main_context_wakeup:
4313 * @context: a #GMainContext
4315 * If @context is currently blocking in g_main_context_iteration()
4316 * waiting for a source to become ready, cause it to stop blocking
4317 * and return. Otherwise, cause the next invocation of
4318 * g_main_context_iteration() to return without blocking.
4320 * This API is useful for low-level control over #GMainContext; for
4321 * example, integrating it with main loop implementations such as
4324 * Another related use for this function is when implementing a main
4325 * loop with a termination condition, computed from multiple threads:
4328 * #define NUM_TASKS 10
4329 * static volatile gint tasks_remaining = NUM_TASKS;
4332 * while (g_atomic_int_get (&tasks_remaining) != 0)
4333 * g_main_context_iteration (NULL, TRUE);
4340 * if (g_atomic_int_dec_and_test (&tasks_remaining))
4341 * g_main_context_wakeup (NULL);
4345 g_main_context_wakeup (GMainContext *context)
4348 context = g_main_context_default ();
4350 g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
4352 g_wakeup_signal (context->wakeup);
4356 * g_main_context_is_owner:
4357 * @context: a #GMainContext
4359 * Determines whether this thread holds the (recursive)
4360 * ownership of this #GMainContext. This is useful to
4361 * know before waiting on another thread that may be
4362 * blocking to get ownership of @context.
4364 * Returns: %TRUE if current thread is owner of @context.
4369 g_main_context_is_owner (GMainContext *context)
4374 context = g_main_context_default ();
4376 LOCK_CONTEXT (context);
4377 is_owner = context->owner == G_THREAD_SELF;
4378 UNLOCK_CONTEXT (context);
4386 g_timeout_set_expiration (GTimeoutSource *timeout_source,
4387 gint64 current_time)
4391 expiration = current_time + (guint64) timeout_source->interval * 1000;
4393 if (timeout_source->seconds)
4396 static gint timer_perturb = -1;
4398 if (timer_perturb == -1)
4401 * we want a per machine/session unique 'random' value; try the dbus
4402 * address first, that has a UUID in it. If there is no dbus, use the
4403 * hostname for hashing.
4405 const char *session_bus_address = g_getenv ("DBUS_SESSION_BUS_ADDRESS");
4406 if (!session_bus_address)
4407 session_bus_address = g_getenv ("HOSTNAME");
4408 if (session_bus_address)
4409 timer_perturb = ABS ((gint) g_str_hash (session_bus_address)) % 1000000;
4414 /* We want the microseconds part of the timeout to land on the
4415 * 'timer_perturb' mark, but we need to make sure we don't try to
4416 * set the timeout in the past. We do this by ensuring that we
4417 * always only *increase* the expiration time by adding a full
4418 * second in the case that the microsecond portion decreases.
4420 expiration -= timer_perturb;
4422 remainder = expiration % 1000000;
4423 if (remainder >= 1000000/4)
4424 expiration += 1000000;
4426 expiration -= remainder;
4427 expiration += timer_perturb;
4430 g_source_set_ready_time ((GSource *) timeout_source, expiration);
4434 g_timeout_dispatch (GSource *source,
4435 GSourceFunc callback,
4438 GTimeoutSource *timeout_source = (GTimeoutSource *)source;
4443 g_warning ("Timeout source dispatched without callback\n"
4444 "You must call g_source_set_callback().");
4448 again = callback (user_data);
4451 g_timeout_set_expiration (timeout_source, g_source_get_time (source));
4457 * g_timeout_source_new:
4458 * @interval: the timeout interval in milliseconds.
4460 * Creates a new timeout source.
4462 * The source will not initially be associated with any #GMainContext
4463 * and must be added to one with g_source_attach() before it will be
4466 * The interval given is in terms of monotonic time, not wall clock
4467 * time. See g_get_monotonic_time().
4469 * Return value: the newly-created timeout source
4472 g_timeout_source_new (guint interval)
4474 GSource *source = g_source_new (&g_timeout_funcs, sizeof (GTimeoutSource));
4475 GTimeoutSource *timeout_source = (GTimeoutSource *)source;
4477 timeout_source->interval = interval;
4478 g_timeout_set_expiration (timeout_source, g_get_monotonic_time ());
4484 * g_timeout_source_new_seconds:
4485 * @interval: the timeout interval in seconds
4487 * Creates a new timeout source.
4489 * The source will not initially be associated with any #GMainContext
4490 * and must be added to one with g_source_attach() before it will be
4493 * The scheduling granularity/accuracy of this timeout source will be
4496 * The interval given in terms of monotonic time, not wall clock time.
4497 * See g_get_monotonic_time().
4499 * Return value: the newly-created timeout source
4504 g_timeout_source_new_seconds (guint interval)
4506 GSource *source = g_source_new (&g_timeout_funcs, sizeof (GTimeoutSource));
4507 GTimeoutSource *timeout_source = (GTimeoutSource *)source;
4509 timeout_source->interval = 1000 * interval;
4510 timeout_source->seconds = TRUE;
4512 g_timeout_set_expiration (timeout_source, g_get_monotonic_time ());
4519 * g_timeout_add_full:
4520 * @priority: the priority of the timeout source. Typically this will be in
4521 * the range between #G_PRIORITY_DEFAULT and #G_PRIORITY_HIGH.
4522 * @interval: the time between calls to the function, in milliseconds
4523 * (1/1000ths of a second)
4524 * @function: function to call
4525 * @data: data to pass to @function
4526 * @notify: (allow-none): function to call when the timeout is removed, or %NULL
4528 * Sets a function to be called at regular intervals, with the given
4529 * priority. The function is called repeatedly until it returns
4530 * %FALSE, at which point the timeout is automatically destroyed and
4531 * the function will not be called again. The @notify function is
4532 * called when the timeout is destroyed. The first call to the
4533 * function will be at the end of the first @interval.
4535 * Note that timeout functions may be delayed, due to the processing of other
4536 * event sources. Thus they should not be relied on for precise timing.
4537 * After each call to the timeout function, the time of the next
4538 * timeout is recalculated based on the current time and the given interval
4539 * (it does not try to 'catch up' time lost in delays).
4541 * This internally creates a main loop source using g_timeout_source_new()
4542 * and attaches it to the main loop context using g_source_attach(). You can
4543 * do these steps manually if you need greater control.
4545 * The interval given in terms of monotonic time, not wall clock time.
4546 * See g_get_monotonic_time().
4548 * Return value: the ID (greater than 0) of the event source.
4549 * Rename to: g_timeout_add
4552 g_timeout_add_full (gint priority,
4554 GSourceFunc function,
4556 GDestroyNotify notify)
4561 g_return_val_if_fail (function != NULL, 0);
4563 source = g_timeout_source_new (interval);
4565 if (priority != G_PRIORITY_DEFAULT)
4566 g_source_set_priority (source, priority);
4568 g_source_set_callback (source, function, data, notify);
4569 id = g_source_attach (source, NULL);
4570 g_source_unref (source);
4577 * @interval: the time between calls to the function, in milliseconds
4578 * (1/1000ths of a second)
4579 * @function: function to call
4580 * @data: data to pass to @function
4582 * Sets a function to be called at regular intervals, with the default
4583 * priority, #G_PRIORITY_DEFAULT. The function is called repeatedly
4584 * until it returns %FALSE, at which point the timeout is automatically
4585 * destroyed and the function will not be called again. The first call
4586 * to the function will be at the end of the first @interval.
4588 * Note that timeout functions may be delayed, due to the processing of other
4589 * event sources. Thus they should not be relied on for precise timing.
4590 * After each call to the timeout function, the time of the next
4591 * timeout is recalculated based on the current time and the given interval
4592 * (it does not try to 'catch up' time lost in delays).
4594 * If you want to have a timer in the "seconds" range and do not care
4595 * about the exact time of the first call of the timer, use the
4596 * g_timeout_add_seconds() function; this function allows for more
4597 * optimizations and more efficient system power usage.
4599 * This internally creates a main loop source using g_timeout_source_new()
4600 * and attaches it to the main loop context using g_source_attach(). You can
4601 * do these steps manually if you need greater control.
4603 * The interval given is in terms of monotonic time, not wall clock
4604 * time. See g_get_monotonic_time().
4606 * Return value: the ID (greater than 0) of the event source.
4609 g_timeout_add (guint32 interval,
4610 GSourceFunc function,
4613 return g_timeout_add_full (G_PRIORITY_DEFAULT,
4614 interval, function, data, NULL);
4618 * g_timeout_add_seconds_full:
4619 * @priority: the priority of the timeout source. Typically this will be in
4620 * the range between #G_PRIORITY_DEFAULT and #G_PRIORITY_HIGH.
4621 * @interval: the time between calls to the function, in seconds
4622 * @function: function to call
4623 * @data: data to pass to @function
4624 * @notify: (allow-none): function to call when the timeout is removed, or %NULL
4626 * Sets a function to be called at regular intervals, with @priority.
4627 * The function is called repeatedly until it returns %FALSE, at which
4628 * point the timeout is automatically destroyed and the function will
4629 * not be called again.
4631 * Unlike g_timeout_add(), this function operates at whole second granularity.
4632 * The initial starting point of the timer is determined by the implementation
4633 * and the implementation is expected to group multiple timers together so that
4634 * they fire all at the same time.
4635 * To allow this grouping, the @interval to the first timer is rounded
4636 * and can deviate up to one second from the specified interval.
4637 * Subsequent timer iterations will generally run at the specified interval.
4639 * Note that timeout functions may be delayed, due to the processing of other
4640 * event sources. Thus they should not be relied on for precise timing.
4641 * After each call to the timeout function, the time of the next
4642 * timeout is recalculated based on the current time and the given @interval
4644 * If you want timing more precise than whole seconds, use g_timeout_add()
4647 * The grouping of timers to fire at the same time results in a more power
4648 * and CPU efficient behavior so if your timer is in multiples of seconds
4649 * and you don't require the first timer exactly one second from now, the
4650 * use of g_timeout_add_seconds() is preferred over g_timeout_add().
4652 * This internally creates a main loop source using
4653 * g_timeout_source_new_seconds() and attaches it to the main loop context
4654 * using g_source_attach(). You can do these steps manually if you need
4657 * The interval given is in terms of monotonic time, not wall clock
4658 * time. See g_get_monotonic_time().
4660 * Return value: the ID (greater than 0) of the event source.
4662 * Rename to: g_timeout_add_seconds
4666 g_timeout_add_seconds_full (gint priority,
4668 GSourceFunc function,
4670 GDestroyNotify notify)
4675 g_return_val_if_fail (function != NULL, 0);
4677 source = g_timeout_source_new_seconds (interval);
4679 if (priority != G_PRIORITY_DEFAULT)
4680 g_source_set_priority (source, priority);
4682 g_source_set_callback (source, function, data, notify);
4683 id = g_source_attach (source, NULL);
4684 g_source_unref (source);
4690 * g_timeout_add_seconds:
4691 * @interval: the time between calls to the function, in seconds
4692 * @function: function to call
4693 * @data: data to pass to @function
4695 * Sets a function to be called at regular intervals with the default
4696 * priority, #G_PRIORITY_DEFAULT. The function is called repeatedly until
4697 * it returns %FALSE, at which point the timeout is automatically destroyed
4698 * and the function will not be called again.
4700 * This internally creates a main loop source using
4701 * g_timeout_source_new_seconds() and attaches it to the main loop context
4702 * using g_source_attach(). You can do these steps manually if you need
4703 * greater control. Also see g_timeout_add_seconds_full().
4705 * Note that the first call of the timer may not be precise for timeouts
4706 * of one second. If you need finer precision and have such a timeout,
4707 * you may want to use g_timeout_add() instead.
4709 * The interval given is in terms of monotonic time, not wall clock
4710 * time. See g_get_monotonic_time().
4712 * Return value: the ID (greater than 0) of the event source.
4717 g_timeout_add_seconds (guint interval,
4718 GSourceFunc function,
4721 g_return_val_if_fail (function != NULL, 0);
4723 return g_timeout_add_seconds_full (G_PRIORITY_DEFAULT, interval, function, data, NULL);
4726 /* Child watch functions */
4731 g_child_watch_prepare (GSource *source,
4739 g_child_watch_check (GSource *source)
4741 GChildWatchSource *child_watch_source;
4742 gboolean child_exited;
4744 child_watch_source = (GChildWatchSource *) source;
4746 child_exited = child_watch_source->poll.revents & G_IO_IN;
4753 * Note: We do _not_ check for the special value of STILL_ACTIVE
4754 * since we know that the process has exited and doing so runs into
4755 * problems if the child process "happens to return STILL_ACTIVE(259)"
4756 * as Microsoft's Platform SDK puts it.
4758 if (!GetExitCodeProcess (child_watch_source->pid, &child_status))
4760 gchar *emsg = g_win32_error_message (GetLastError ());
4761 g_warning (G_STRLOC ": GetExitCodeProcess() failed: %s", emsg);
4764 child_watch_source->child_status = -1;
4767 child_watch_source->child_status = child_status;
4770 return child_exited;
4774 g_child_watch_finalize (GSource *source)
4778 #else /* G_OS_WIN32 */
4781 wake_source (GSource *source)
4783 GMainContext *context;
4785 /* This should be thread-safe:
4787 * - if the source is currently being added to a context, that
4788 * context will be woken up anyway
4790 * - if the source is currently being destroyed, we simply need not
4793 * - the memory for the source will remain valid until after the
4794 * source finalize function was called (which would remove the
4795 * source from the global list which we are currently holding the
4798 * - the GMainContext will either be NULL or point to a live
4801 * - the GMainContext will remain valid since we hold the
4802 * main_context_list lock
4804 * Since we are holding a lot of locks here, don't try to enter any
4805 * more GMainContext functions for fear of dealock -- just hit the
4806 * GWakeup and run. Even if that's safe now, it could easily become
4807 * unsafe with some very minor changes in the future, and signal
4808 * handling is not the most well-tested codepath.
4810 G_LOCK(main_context_list);
4811 context = source->context;
4813 g_wakeup_signal (context->wakeup);
4814 G_UNLOCK(main_context_list);
4818 dispatch_unix_signals (void)
4822 /* clear this first incase another one arrives while we're processing */
4823 any_unix_signal_pending = FALSE;
4825 G_LOCK(unix_signal_lock);
4827 /* handle GChildWatchSource instances */
4828 if (unix_signal_pending[SIGCHLD])
4830 /* The only way we can do this is to scan all of the children.
4832 * The docs promise that we will not reap children that we are not
4833 * explicitly watching, so that ties our hands from calling
4834 * waitpid(-1). We also can't use siginfo's si_pid field since if
4835 * multiple SIGCHLD arrive at the same time, one of them can be
4836 * dropped (since a given UNIX signal can only be pending once).
4838 for (node = unix_child_watches; node; node = node->next)
4840 GChildWatchSource *source = node->data;
4842 if (!source->child_exited)
4847 pid = waitpid (source->pid, &source->child_status, WNOHANG);
4850 source->child_exited = TRUE;
4851 wake_source ((GSource *) source);
4853 else if (pid == -1 && errno == ECHILD)
4855 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.");
4856 source->child_exited = TRUE;
4857 source->child_status = 0;
4858 wake_source ((GSource *) source);
4861 while (pid == -1 && errno == EINTR);
4866 /* handle GUnixSignalWatchSource instances */
4867 for (node = unix_signal_watches; node; node = node->next)
4869 GUnixSignalWatchSource *source = node->data;
4871 if (!source->pending)
4873 if (unix_signal_pending[source->signum])
4875 source->pending = TRUE;
4877 wake_source ((GSource *) source);
4882 memset ((void*)unix_signal_pending, 0, sizeof (unix_signal_pending));
4884 G_UNLOCK(unix_signal_lock);
4888 g_child_watch_prepare (GSource *source,
4891 GChildWatchSource *child_watch_source;
4893 child_watch_source = (GChildWatchSource *) source;
4895 return child_watch_source->child_exited;
4899 g_child_watch_check (GSource *source)
4901 GChildWatchSource *child_watch_source;
4903 child_watch_source = (GChildWatchSource *) source;
4905 return child_watch_source->child_exited;
4909 g_unix_signal_watch_prepare (GSource *source,
4912 GUnixSignalWatchSource *unix_signal_source;
4914 unix_signal_source = (GUnixSignalWatchSource *) source;
4916 return unix_signal_source->pending;
4920 g_unix_signal_watch_check (GSource *source)
4922 GUnixSignalWatchSource *unix_signal_source;
4924 unix_signal_source = (GUnixSignalWatchSource *) source;
4926 return unix_signal_source->pending;
4930 g_unix_signal_watch_dispatch (GSource *source,
4931 GSourceFunc callback,
4934 GUnixSignalWatchSource *unix_signal_source;
4937 unix_signal_source = (GUnixSignalWatchSource *) source;
4941 g_warning ("Unix signal source dispatched without callback\n"
4942 "You must call g_source_set_callback().");
4946 again = (callback) (user_data);
4948 unix_signal_source->pending = FALSE;
4954 ref_unix_signal_handler_unlocked (int signum)
4956 /* Ensure we have the worker context */
4957 g_get_worker_context ();
4958 unix_signal_refcount[signum]++;
4959 if (unix_signal_refcount[signum] == 1)
4961 struct sigaction action;
4962 action.sa_handler = g_unix_signal_handler;
4963 sigemptyset (&action.sa_mask);
4965 action.sa_flags = SA_RESTART | SA_NOCLDSTOP;
4967 action.sa_flags = SA_NOCLDSTOP;
4969 sigaction (signum, &action, NULL);
4974 unref_unix_signal_handler_unlocked (int signum)
4976 unix_signal_refcount[signum]--;
4977 if (unix_signal_refcount[signum] == 0)
4979 struct sigaction action;
4980 action.sa_handler = SIG_DFL;
4981 sigemptyset (&action.sa_mask);
4982 sigaction (signum, &action, NULL);
4987 _g_main_create_unix_signal_watch (int signum)
4990 GUnixSignalWatchSource *unix_signal_source;
4992 source = g_source_new (&g_unix_signal_funcs, sizeof (GUnixSignalWatchSource));
4993 unix_signal_source = (GUnixSignalWatchSource *) source;
4995 unix_signal_source->signum = signum;
4996 unix_signal_source->pending = FALSE;
4998 G_LOCK (unix_signal_lock);
4999 ref_unix_signal_handler_unlocked (signum);
5000 unix_signal_watches = g_slist_prepend (unix_signal_watches, unix_signal_source);
5001 if (unix_signal_pending[signum])
5002 unix_signal_source->pending = TRUE;
5003 G_UNLOCK (unix_signal_lock);
5009 g_unix_signal_watch_finalize (GSource *source)
5011 GUnixSignalWatchSource *unix_signal_source;
5013 unix_signal_source = (GUnixSignalWatchSource *) source;
5015 G_LOCK (unix_signal_lock);
5016 unref_unix_signal_handler_unlocked (unix_signal_source->signum);
5017 unix_signal_watches = g_slist_remove (unix_signal_watches, source);
5018 G_UNLOCK (unix_signal_lock);
5022 g_child_watch_finalize (GSource *source)
5024 G_LOCK (unix_signal_lock);
5025 unix_child_watches = g_slist_remove (unix_child_watches, source);
5026 unref_unix_signal_handler_unlocked (SIGCHLD);
5027 G_UNLOCK (unix_signal_lock);
5030 #endif /* G_OS_WIN32 */
5033 g_child_watch_dispatch (GSource *source,
5034 GSourceFunc callback,
5037 GChildWatchSource *child_watch_source;
5038 GChildWatchFunc child_watch_callback = (GChildWatchFunc) callback;
5040 child_watch_source = (GChildWatchSource *) source;
5044 g_warning ("Child watch source dispatched without callback\n"
5045 "You must call g_source_set_callback().");
5049 (child_watch_callback) (child_watch_source->pid, child_watch_source->child_status, user_data);
5051 /* We never keep a child watch source around as the child is gone */
5058 g_unix_signal_handler (int signum)
5060 unix_signal_pending[signum] = TRUE;
5061 any_unix_signal_pending = TRUE;
5063 g_wakeup_signal (glib_worker_context->wakeup);
5066 #endif /* !G_OS_WIN32 */
5069 * g_child_watch_source_new:
5070 * @pid: process to watch. On POSIX the pid of a child process. On
5071 * Windows a handle for a process (which doesn't have to be a child).
5073 * Creates a new child_watch source.
5075 * The source will not initially be associated with any #GMainContext
5076 * and must be added to one with g_source_attach() before it will be
5079 * Note that child watch sources can only be used in conjunction with
5080 * <literal>g_spawn...</literal> when the %G_SPAWN_DO_NOT_REAP_CHILD
5083 * Note that on platforms where #GPid must be explicitly closed
5084 * (see g_spawn_close_pid()) @pid must not be closed while the
5085 * source is still active. Typically, you will want to call
5086 * g_spawn_close_pid() in the callback function for the source.
5088 * Note further that using g_child_watch_source_new() is not
5089 * compatible with calling <literal>waitpid</literal> with a
5090 * nonpositive first argument in the application. Calling waitpid()
5091 * for individual pids will still work fine.
5093 * Return value: the newly-created child watch source
5098 g_child_watch_source_new (GPid pid)
5100 GSource *source = g_source_new (&g_child_watch_funcs, sizeof (GChildWatchSource));
5101 GChildWatchSource *child_watch_source = (GChildWatchSource *)source;
5103 child_watch_source->pid = pid;
5106 child_watch_source->poll.fd = (gintptr) pid;
5107 child_watch_source->poll.events = G_IO_IN;
5109 g_source_add_poll (source, &child_watch_source->poll);
5110 #else /* G_OS_WIN32 */
5111 G_LOCK (unix_signal_lock);
5112 ref_unix_signal_handler_unlocked (SIGCHLD);
5113 unix_child_watches = g_slist_prepend (unix_child_watches, child_watch_source);
5114 if (waitpid (pid, &child_watch_source->child_status, WNOHANG) > 0)
5115 child_watch_source->child_exited = TRUE;
5116 G_UNLOCK (unix_signal_lock);
5117 #endif /* G_OS_WIN32 */
5123 * g_child_watch_add_full:
5124 * @priority: the priority of the idle source. Typically this will be in the
5125 * range between #G_PRIORITY_DEFAULT_IDLE and #G_PRIORITY_HIGH_IDLE.
5126 * @pid: process to watch. On POSIX the pid of a child process. On
5127 * Windows a handle for a process (which doesn't have to be a child).
5128 * @function: function to call
5129 * @data: data to pass to @function
5130 * @notify: (allow-none): function to call when the idle is removed, or %NULL
5132 * Sets a function to be called when the child indicated by @pid
5133 * exits, at the priority @priority.
5135 * If you obtain @pid from g_spawn_async() or g_spawn_async_with_pipes()
5136 * you will need to pass #G_SPAWN_DO_NOT_REAP_CHILD as flag to
5137 * the spawn function for the child watching to work.
5139 * In many programs, you will want to call g_spawn_check_exit_status()
5140 * in the callback to determine whether or not the child exited
5143 * Also, note that on platforms where #GPid must be explicitly closed
5144 * (see g_spawn_close_pid()) @pid must not be closed while the source
5145 * is still active. Typically, you should invoke g_spawn_close_pid()
5146 * in the callback function for the source.
5148 * GLib supports only a single callback per process id.
5150 * This internally creates a main loop source using
5151 * g_child_watch_source_new() and attaches it to the main loop context
5152 * using g_source_attach(). You can do these steps manually if you
5153 * need greater control.
5155 * Return value: the ID (greater than 0) of the event source.
5157 * Rename to: g_child_watch_add
5161 g_child_watch_add_full (gint priority,
5163 GChildWatchFunc function,
5165 GDestroyNotify notify)
5170 g_return_val_if_fail (function != NULL, 0);
5172 source = g_child_watch_source_new (pid);
5174 if (priority != G_PRIORITY_DEFAULT)
5175 g_source_set_priority (source, priority);
5177 g_source_set_callback (source, (GSourceFunc) function, data, notify);
5178 id = g_source_attach (source, NULL);
5179 g_source_unref (source);
5185 * g_child_watch_add:
5186 * @pid: process id to watch. On POSIX the pid of a child process. On
5187 * Windows a handle for a process (which doesn't have to be a child).
5188 * @function: function to call
5189 * @data: data to pass to @function
5191 * Sets a function to be called when the child indicated by @pid
5192 * exits, at a default priority, #G_PRIORITY_DEFAULT.
5194 * If you obtain @pid from g_spawn_async() or g_spawn_async_with_pipes()
5195 * you will need to pass #G_SPAWN_DO_NOT_REAP_CHILD as flag to
5196 * the spawn function for the child watching to work.
5198 * Note that on platforms where #GPid must be explicitly closed
5199 * (see g_spawn_close_pid()) @pid must not be closed while the
5200 * source is still active. Typically, you will want to call
5201 * g_spawn_close_pid() in the callback function for the source.
5203 * GLib supports only a single callback per process id.
5205 * This internally creates a main loop source using
5206 * g_child_watch_source_new() and attaches it to the main loop context
5207 * using g_source_attach(). You can do these steps manually if you
5208 * need greater control.
5210 * Return value: the ID (greater than 0) of the event source.
5215 g_child_watch_add (GPid pid,
5216 GChildWatchFunc function,
5219 return g_child_watch_add_full (G_PRIORITY_DEFAULT, pid, function, data, NULL);
5223 /* Idle functions */
5226 g_idle_prepare (GSource *source,
5235 g_idle_check (GSource *source)
5241 g_idle_dispatch (GSource *source,
5242 GSourceFunc callback,
5247 g_warning ("Idle source dispatched without callback\n"
5248 "You must call g_source_set_callback().");
5252 return callback (user_data);
5256 * g_idle_source_new:
5258 * Creates a new idle source.
5260 * The source will not initially be associated with any #GMainContext
5261 * and must be added to one with g_source_attach() before it will be
5262 * executed. Note that the default priority for idle sources is
5263 * %G_PRIORITY_DEFAULT_IDLE, as compared to other sources which
5264 * have a default priority of %G_PRIORITY_DEFAULT.
5266 * Return value: the newly-created idle source
5269 g_idle_source_new (void)
5273 source = g_source_new (&g_idle_funcs, sizeof (GSource));
5274 g_source_set_priority (source, G_PRIORITY_DEFAULT_IDLE);
5281 * @priority: the priority of the idle source. Typically this will be in the
5282 * range between #G_PRIORITY_DEFAULT_IDLE and #G_PRIORITY_HIGH_IDLE.
5283 * @function: function to call
5284 * @data: data to pass to @function
5285 * @notify: (allow-none): function to call when the idle is removed, or %NULL
5287 * Adds a function to be called whenever there are no higher priority
5288 * events pending. If the function returns %FALSE it is automatically
5289 * removed from the list of event sources and will not be called again.
5291 * This internally creates a main loop source using g_idle_source_new()
5292 * and attaches it to the main loop context using g_source_attach().
5293 * You can do these steps manually if you need greater control.
5295 * Return value: the ID (greater than 0) of the event source.
5296 * Rename to: g_idle_add
5299 g_idle_add_full (gint priority,
5300 GSourceFunc function,
5302 GDestroyNotify notify)
5307 g_return_val_if_fail (function != NULL, 0);
5309 source = g_idle_source_new ();
5311 if (priority != G_PRIORITY_DEFAULT_IDLE)
5312 g_source_set_priority (source, priority);
5314 g_source_set_callback (source, function, data, notify);
5315 id = g_source_attach (source, NULL);
5316 g_source_unref (source);
5323 * @function: function to call
5324 * @data: data to pass to @function.
5326 * Adds a function to be called whenever there are no higher priority
5327 * events pending to the default main loop. The function is given the
5328 * default idle priority, #G_PRIORITY_DEFAULT_IDLE. If the function
5329 * returns %FALSE it is automatically removed from the list of event
5330 * sources and will not be called again.
5332 * This internally creates a main loop source using g_idle_source_new()
5333 * and attaches it to the main loop context using g_source_attach().
5334 * You can do these steps manually if you need greater control.
5336 * Return value: the ID (greater than 0) of the event source.
5339 g_idle_add (GSourceFunc function,
5342 return g_idle_add_full (G_PRIORITY_DEFAULT_IDLE, function, data, NULL);
5346 * g_idle_remove_by_data:
5347 * @data: the data for the idle source's callback.
5349 * Removes the idle function with the given data.
5351 * Return value: %TRUE if an idle source was found and removed.
5354 g_idle_remove_by_data (gpointer data)
5356 return g_source_remove_by_funcs_user_data (&g_idle_funcs, data);
5360 * g_main_context_invoke:
5361 * @context: (allow-none): a #GMainContext, or %NULL
5362 * @function: function to call
5363 * @data: data to pass to @function
5365 * Invokes a function in such a way that @context is owned during the
5366 * invocation of @function.
5368 * If @context is %NULL then the global default main context — as
5369 * returned by g_main_context_default() — is used.
5371 * If @context is owned by the current thread, @function is called
5372 * directly. Otherwise, if @context is the thread-default main context
5373 * of the current thread and g_main_context_acquire() succeeds, then
5374 * @function is called and g_main_context_release() is called
5377 * In any other case, an idle source is created to call @function and
5378 * that source is attached to @context (presumably to be run in another
5379 * thread). The idle source is attached with #G_PRIORITY_DEFAULT
5380 * priority. If you want a different priority, use
5381 * g_main_context_invoke_full().
5383 * Note that, as with normal idle functions, @function should probably
5384 * return %FALSE. If it returns %TRUE, it will be continuously run in a
5385 * loop (and may prevent this call from returning).
5390 g_main_context_invoke (GMainContext *context,
5391 GSourceFunc function,
5394 g_main_context_invoke_full (context,
5396 function, data, NULL);
5400 * g_main_context_invoke_full:
5401 * @context: (allow-none): a #GMainContext, or %NULL
5402 * @priority: the priority at which to run @function
5403 * @function: function to call
5404 * @data: data to pass to @function
5405 * @notify: (allow-none): a function to call when @data is no longer in use, or %NULL.
5407 * Invokes a function in such a way that @context is owned during the
5408 * invocation of @function.
5410 * This function is the same as g_main_context_invoke() except that it
5411 * lets you specify the priority incase @function ends up being
5412 * scheduled as an idle and also lets you give a #GDestroyNotify for @data.
5414 * @notify should not assume that it is called from any particular
5415 * thread or with any particular context acquired.
5420 g_main_context_invoke_full (GMainContext *context,
5422 GSourceFunc function,
5424 GDestroyNotify notify)
5426 g_return_if_fail (function != NULL);
5429 context = g_main_context_default ();
5431 if (g_main_context_is_owner (context))
5433 while (function (data));
5440 GMainContext *thread_default;
5442 thread_default = g_main_context_get_thread_default ();
5444 if (!thread_default)
5445 thread_default = g_main_context_default ();
5447 if (thread_default == context && g_main_context_acquire (context))
5449 while (function (data));
5451 g_main_context_release (context);
5460 source = g_idle_source_new ();
5461 g_source_set_priority (source, priority);
5462 g_source_set_callback (source, function, data, notify);
5463 g_source_attach (source, context);
5464 g_source_unref (source);
5470 glib_worker_main (gpointer data)
5474 g_main_context_iteration (glib_worker_context, TRUE);
5477 if (any_unix_signal_pending)
5478 dispatch_unix_signals ();
5482 return NULL; /* worst GCC warning message ever... */
5486 g_get_worker_context (void)
5488 static gsize initialised;
5490 if (g_once_init_enter (&initialised))
5492 /* mask all signals in the worker thread */
5498 pthread_sigmask (SIG_SETMASK, &all, &prev_mask);
5500 glib_worker_context = g_main_context_new ();
5501 g_thread_new ("gmain", glib_worker_main, NULL);
5503 pthread_sigmask (SIG_SETMASK, &prev_mask, NULL);
5505 g_once_init_leave (&initialised, TRUE);
5508 return glib_worker_context;