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));
1087 else if (context->overflow_used_source_ids == NULL)
1089 id = context->next_id++;
1094 * If we overran G_MAXUINT, we fall back to randomly probing the
1095 * source ids for the current context. This will be slower the more
1096 * sources there are, but we're mainly concerned right now about
1097 * correctness and code size. There's time for a more clever solution
1101 id = g_random_int ();
1103 g_hash_table_contains (context->overflow_used_source_ids,
1104 GUINT_TO_POINTER (id)));
1105 g_hash_table_add (context->overflow_used_source_ids, GUINT_TO_POINTER (id));
1108 source->source_id = id;
1112 g_source_attach_unlocked (GSource *source,
1113 GMainContext *context)
1117 source->context = context;
1118 assign_source_id_unlocked (context, source);
1119 source->ref_count++;
1120 source_add_to_context (source, context);
1122 if (!SOURCE_BLOCKED (source))
1124 tmp_list = source->poll_fds;
1127 g_main_context_add_poll_unlocked (context, source->priority, tmp_list->data);
1128 tmp_list = tmp_list->next;
1131 for (tmp_list = source->priv->fds; tmp_list; tmp_list = tmp_list->next)
1132 g_main_context_add_poll_unlocked (context, source->priority, tmp_list->data);
1135 tmp_list = source->priv->child_sources;
1138 g_source_attach_unlocked (tmp_list->data, context);
1139 tmp_list = tmp_list->next;
1142 return source->source_id;
1147 * @source: a #GSource
1148 * @context: (allow-none): a #GMainContext (if %NULL, the default context will be used)
1150 * Adds a #GSource to a @context so that it will be executed within
1151 * that context. Remove it by calling g_source_destroy().
1153 * Return value: the ID (greater than 0) for the source within the
1157 g_source_attach (GSource *source,
1158 GMainContext *context)
1162 g_return_val_if_fail (source->context == NULL, 0);
1163 g_return_val_if_fail (!SOURCE_DESTROYED (source), 0);
1166 context = g_main_context_default ();
1168 LOCK_CONTEXT (context);
1170 result = g_source_attach_unlocked (source, context);
1172 /* If another thread has acquired the context, wake it up since it
1173 * might be in poll() right now.
1175 if (context->owner && context->owner != G_THREAD_SELF)
1176 g_wakeup_signal (context->wakeup);
1178 UNLOCK_CONTEXT (context);
1184 g_source_destroy_internal (GSource *source,
1185 GMainContext *context,
1189 LOCK_CONTEXT (context);
1191 if (!SOURCE_DESTROYED (source))
1194 gpointer old_cb_data;
1195 GSourceCallbackFuncs *old_cb_funcs;
1197 source->flags &= ~G_HOOK_FLAG_ACTIVE;
1199 old_cb_data = source->callback_data;
1200 old_cb_funcs = source->callback_funcs;
1202 source->callback_data = NULL;
1203 source->callback_funcs = NULL;
1207 UNLOCK_CONTEXT (context);
1208 old_cb_funcs->unref (old_cb_data);
1209 LOCK_CONTEXT (context);
1212 if (!SOURCE_BLOCKED (source))
1214 tmp_list = source->poll_fds;
1217 g_main_context_remove_poll_unlocked (context, tmp_list->data);
1218 tmp_list = tmp_list->next;
1221 for (tmp_list = source->priv->fds; tmp_list; tmp_list = tmp_list->next)
1222 g_main_context_remove_poll_unlocked (context, tmp_list->data);
1225 while (source->priv->child_sources)
1226 g_child_source_remove_internal (source->priv->child_sources->data, context);
1228 if (source->priv->parent_source)
1229 g_child_source_remove_internal (source, context);
1231 g_source_unref_internal (source, context, TRUE);
1235 UNLOCK_CONTEXT (context);
1240 * @source: a #GSource
1242 * Removes a source from its #GMainContext, if any, and mark it as
1243 * destroyed. The source cannot be subsequently added to another
1247 g_source_destroy (GSource *source)
1249 GMainContext *context;
1251 g_return_if_fail (source != NULL);
1253 context = source->context;
1256 g_source_destroy_internal (source, context, FALSE);
1258 source->flags &= ~G_HOOK_FLAG_ACTIVE;
1263 * @source: a #GSource
1265 * Returns the numeric ID for a particular source. The ID of a source
1266 * is a positive integer which is unique within a particular main loop
1267 * context. The reverse
1268 * mapping from ID to source is done by g_main_context_find_source_by_id().
1270 * Return value: the ID (greater than 0) for the source
1273 g_source_get_id (GSource *source)
1277 g_return_val_if_fail (source != NULL, 0);
1278 g_return_val_if_fail (source->context != NULL, 0);
1280 LOCK_CONTEXT (source->context);
1281 result = source->source_id;
1282 UNLOCK_CONTEXT (source->context);
1288 * g_source_get_context:
1289 * @source: a #GSource
1291 * Gets the #GMainContext with which the source is associated.
1293 * You can call this on a source that has been destroyed, provided
1294 * that the #GMainContext it was attached to still exists (in which
1295 * case it will return that #GMainContext). In particular, you can
1296 * always call this function on the source returned from
1297 * g_main_current_source(). But calling this function on a source
1298 * whose #GMainContext has been destroyed is an error.
1300 * Return value: (transfer none) (allow-none): the #GMainContext with which the
1301 * source is associated, or %NULL if the context has not
1302 * yet been added to a source.
1305 g_source_get_context (GSource *source)
1307 g_return_val_if_fail (source->context != NULL || !SOURCE_DESTROYED (source), NULL);
1309 return source->context;
1313 * g_source_add_poll:
1314 * @source:a #GSource
1315 * @fd: a #GPollFD structure holding information about a file
1316 * descriptor to watch.
1318 * Adds a file descriptor to the set of file descriptors polled for
1319 * this source. This is usually combined with g_source_new() to add an
1320 * event source. The event source's check function will typically test
1321 * the @revents field in the #GPollFD struct and return %TRUE if events need
1324 * Using this API forces the linear scanning of event sources on each
1325 * main loop iteration. Newly-written event sources should try to use
1326 * g_source_add_unix_fd() instead of this API.
1329 g_source_add_poll (GSource *source,
1332 GMainContext *context;
1334 g_return_if_fail (source != NULL);
1335 g_return_if_fail (fd != NULL);
1336 g_return_if_fail (!SOURCE_DESTROYED (source));
1338 context = source->context;
1341 LOCK_CONTEXT (context);
1343 source->poll_fds = g_slist_prepend (source->poll_fds, fd);
1347 if (!SOURCE_BLOCKED (source))
1348 g_main_context_add_poll_unlocked (context, source->priority, fd);
1349 UNLOCK_CONTEXT (context);
1354 * g_source_remove_poll:
1355 * @source:a #GSource
1356 * @fd: a #GPollFD structure previously passed to g_source_add_poll().
1358 * Removes a file descriptor from the set of file descriptors polled for
1362 g_source_remove_poll (GSource *source,
1365 GMainContext *context;
1367 g_return_if_fail (source != NULL);
1368 g_return_if_fail (fd != NULL);
1369 g_return_if_fail (!SOURCE_DESTROYED (source));
1371 context = source->context;
1374 LOCK_CONTEXT (context);
1376 source->poll_fds = g_slist_remove (source->poll_fds, fd);
1380 if (!SOURCE_BLOCKED (source))
1381 g_main_context_remove_poll_unlocked (context, fd);
1382 UNLOCK_CONTEXT (context);
1387 * g_source_add_child_source:
1388 * @source:a #GSource
1389 * @child_source: a second #GSource that @source should "poll"
1391 * Adds @child_source to @source as a "polled" source; when @source is
1392 * added to a #GMainContext, @child_source will be automatically added
1393 * with the same priority, when @child_source is triggered, it will
1394 * cause @source to dispatch (in addition to calling its own
1395 * callback), and when @source is destroyed, it will destroy
1396 * @child_source as well. (@source will also still be dispatched if
1397 * its own prepare/check functions indicate that it is ready.)
1399 * If you don't need @child_source to do anything on its own when it
1400 * triggers, you can call g_source_set_dummy_callback() on it to set a
1401 * callback that does nothing (except return %TRUE if appropriate).
1403 * @source will hold a reference on @child_source while @child_source
1404 * is attached to it.
1409 g_source_add_child_source (GSource *source,
1410 GSource *child_source)
1412 GMainContext *context;
1414 g_return_if_fail (source != NULL);
1415 g_return_if_fail (child_source != NULL);
1416 g_return_if_fail (!SOURCE_DESTROYED (source));
1417 g_return_if_fail (!SOURCE_DESTROYED (child_source));
1418 g_return_if_fail (child_source->context == NULL);
1419 g_return_if_fail (child_source->priv->parent_source == NULL);
1421 context = source->context;
1424 LOCK_CONTEXT (context);
1426 source->priv->child_sources = g_slist_prepend (source->priv->child_sources,
1427 g_source_ref (child_source));
1428 child_source->priv->parent_source = source;
1429 g_source_set_priority_unlocked (child_source, NULL, source->priority);
1430 if (SOURCE_BLOCKED (source))
1431 block_source (child_source);
1435 UNLOCK_CONTEXT (context);
1436 g_source_attach (child_source, context);
1441 g_child_source_remove_internal (GSource *child_source,
1442 GMainContext *context)
1444 GSource *parent_source = child_source->priv->parent_source;
1446 parent_source->priv->child_sources =
1447 g_slist_remove (parent_source->priv->child_sources, child_source);
1448 child_source->priv->parent_source = NULL;
1450 g_source_destroy_internal (child_source, context, TRUE);
1451 g_source_unref_internal (child_source, context, TRUE);
1455 * g_source_remove_child_source:
1456 * @source:a #GSource
1457 * @child_source: a #GSource previously passed to
1458 * g_source_add_child_source().
1460 * Detaches @child_source from @source and destroys it.
1465 g_source_remove_child_source (GSource *source,
1466 GSource *child_source)
1468 GMainContext *context;
1470 g_return_if_fail (source != NULL);
1471 g_return_if_fail (child_source != NULL);
1472 g_return_if_fail (child_source->priv->parent_source == source);
1473 g_return_if_fail (!SOURCE_DESTROYED (source));
1474 g_return_if_fail (!SOURCE_DESTROYED (child_source));
1476 context = source->context;
1479 LOCK_CONTEXT (context);
1481 g_child_source_remove_internal (child_source, context);
1484 UNLOCK_CONTEXT (context);
1488 * g_source_set_callback_indirect:
1489 * @source: the source
1490 * @callback_data: pointer to callback data "object"
1491 * @callback_funcs: functions for reference counting @callback_data
1492 * and getting the callback and data
1494 * Sets the callback function storing the data as a refcounted callback
1495 * "object". This is used internally. Note that calling
1496 * g_source_set_callback_indirect() assumes
1497 * an initial reference count on @callback_data, and thus
1498 * @callback_funcs->unref will eventually be called once more
1499 * than @callback_funcs->ref.
1502 g_source_set_callback_indirect (GSource *source,
1503 gpointer callback_data,
1504 GSourceCallbackFuncs *callback_funcs)
1506 GMainContext *context;
1507 gpointer old_cb_data;
1508 GSourceCallbackFuncs *old_cb_funcs;
1510 g_return_if_fail (source != NULL);
1511 g_return_if_fail (callback_funcs != NULL || callback_data == NULL);
1513 context = source->context;
1516 LOCK_CONTEXT (context);
1518 old_cb_data = source->callback_data;
1519 old_cb_funcs = source->callback_funcs;
1521 source->callback_data = callback_data;
1522 source->callback_funcs = callback_funcs;
1525 UNLOCK_CONTEXT (context);
1528 old_cb_funcs->unref (old_cb_data);
1532 g_source_callback_ref (gpointer cb_data)
1534 GSourceCallback *callback = cb_data;
1536 callback->ref_count++;
1541 g_source_callback_unref (gpointer cb_data)
1543 GSourceCallback *callback = cb_data;
1545 callback->ref_count--;
1546 if (callback->ref_count == 0)
1548 if (callback->notify)
1549 callback->notify (callback->data);
1555 g_source_callback_get (gpointer cb_data,
1560 GSourceCallback *callback = cb_data;
1562 *func = callback->func;
1563 *data = callback->data;
1566 static GSourceCallbackFuncs g_source_callback_funcs = {
1567 g_source_callback_ref,
1568 g_source_callback_unref,
1569 g_source_callback_get,
1573 * g_source_set_callback:
1574 * @source: the source
1575 * @func: a callback function
1576 * @data: the data to pass to callback function
1577 * @notify: (allow-none): a function to call when @data is no longer in use, or %NULL.
1579 * Sets the callback function for a source. The callback for a source is
1580 * called from the source's dispatch function.
1582 * The exact type of @func depends on the type of source; ie. you
1583 * should not count on @func being called with @data as its first
1586 * Typically, you won't use this function. Instead use functions specific
1587 * to the type of source you are using.
1590 g_source_set_callback (GSource *source,
1593 GDestroyNotify notify)
1595 GSourceCallback *new_callback;
1597 g_return_if_fail (source != NULL);
1599 new_callback = g_new (GSourceCallback, 1);
1601 new_callback->ref_count = 1;
1602 new_callback->func = func;
1603 new_callback->data = data;
1604 new_callback->notify = notify;
1606 g_source_set_callback_indirect (source, new_callback, &g_source_callback_funcs);
1611 * g_source_set_funcs:
1612 * @source: a #GSource
1613 * @funcs: the new #GSourceFuncs
1615 * Sets the source functions (can be used to override
1616 * default implementations) of an unattached source.
1621 g_source_set_funcs (GSource *source,
1622 GSourceFuncs *funcs)
1624 g_return_if_fail (source != NULL);
1625 g_return_if_fail (source->context == NULL);
1626 g_return_if_fail (source->ref_count > 0);
1627 g_return_if_fail (funcs != NULL);
1629 source->source_funcs = funcs;
1633 g_source_set_priority_unlocked (GSource *source,
1634 GMainContext *context,
1639 g_return_if_fail (source->priv->parent_source == NULL ||
1640 source->priv->parent_source->priority == priority);
1644 /* Remove the source from the context's source and then
1645 * add it back after so it is sorted in the correct place
1647 source_remove_from_context (source, source->context);
1650 source->priority = priority;
1654 source_add_to_context (source, source->context);
1656 if (!SOURCE_BLOCKED (source))
1658 tmp_list = source->poll_fds;
1661 g_main_context_remove_poll_unlocked (context, tmp_list->data);
1662 g_main_context_add_poll_unlocked (context, priority, tmp_list->data);
1664 tmp_list = tmp_list->next;
1667 for (tmp_list = source->priv->fds; tmp_list; tmp_list = tmp_list->next)
1669 g_main_context_remove_poll_unlocked (context, tmp_list->data);
1670 g_main_context_add_poll_unlocked (context, priority, tmp_list->data);
1675 if (source->priv->child_sources)
1677 tmp_list = source->priv->child_sources;
1680 g_source_set_priority_unlocked (tmp_list->data, context, priority);
1681 tmp_list = tmp_list->next;
1687 * g_source_set_priority:
1688 * @source: a #GSource
1689 * @priority: the new priority.
1691 * Sets the priority of a source. While the main loop is being run, a
1692 * source will be dispatched if it is ready to be dispatched and no
1693 * sources at a higher (numerically smaller) priority are ready to be
1697 g_source_set_priority (GSource *source,
1700 GMainContext *context;
1702 g_return_if_fail (source != NULL);
1704 context = source->context;
1707 LOCK_CONTEXT (context);
1708 g_source_set_priority_unlocked (source, context, priority);
1710 UNLOCK_CONTEXT (source->context);
1714 * g_source_get_priority:
1715 * @source: a #GSource
1717 * Gets the priority of a source.
1719 * Return value: the priority of the source
1722 g_source_get_priority (GSource *source)
1724 g_return_val_if_fail (source != NULL, 0);
1726 return source->priority;
1730 * g_source_set_ready_time:
1731 * @source: a #GSource
1732 * @ready_time: the monotonic time at which the source will be ready,
1733 * 0 for "immediately", -1 for "never"
1735 * Sets a #GSource to be dispatched when the given monotonic time is
1736 * reached (or passed). If the monotonic time is in the past (as it
1737 * always will be if @ready_time is 0) then the source will be
1738 * dispatched immediately.
1740 * If @ready_time is -1 then the source is never woken up on the basis
1741 * of the passage of time.
1743 * Dispatching the source does not reset the ready time. You should do
1744 * so yourself, from the source dispatch function.
1746 * Note that if you have a pair of sources where the ready time of one
1747 * suggests that it will be delivered first but the priority for the
1748 * other suggests that it would be delivered first, and the ready time
1749 * for both sources is reached during the same main context iteration
1750 * then the order of dispatch is undefined.
1755 g_source_set_ready_time (GSource *source,
1758 GMainContext *context;
1760 g_return_if_fail (source != NULL);
1761 g_return_if_fail (source->ref_count > 0);
1763 if (source->priv->ready_time == ready_time)
1766 context = source->context;
1769 LOCK_CONTEXT (context);
1771 source->priv->ready_time = ready_time;
1775 /* Quite likely that we need to change the timeout on the poll */
1776 if (!SOURCE_BLOCKED (source))
1777 g_wakeup_signal (context->wakeup);
1778 UNLOCK_CONTEXT (context);
1783 * g_source_get_ready_time:
1784 * @source: a #GSource
1786 * Gets the "ready time" of @source, as set by
1787 * g_source_set_ready_time().
1789 * Any time before the current monotonic time (including 0) is an
1790 * indication that the source will fire immediately.
1792 * Returns: the monotonic ready time, -1 for "never"
1795 g_source_get_ready_time (GSource *source)
1797 g_return_val_if_fail (source != NULL, -1);
1799 return source->priv->ready_time;
1803 * g_source_set_can_recurse:
1804 * @source: a #GSource
1805 * @can_recurse: whether recursion is allowed for this source
1807 * Sets whether a source can be called recursively. If @can_recurse is
1808 * %TRUE, then while the source is being dispatched then this source
1809 * will be processed normally. Otherwise, all processing of this
1810 * source is blocked until the dispatch function returns.
1813 g_source_set_can_recurse (GSource *source,
1814 gboolean can_recurse)
1816 GMainContext *context;
1818 g_return_if_fail (source != NULL);
1820 context = source->context;
1823 LOCK_CONTEXT (context);
1826 source->flags |= G_SOURCE_CAN_RECURSE;
1828 source->flags &= ~G_SOURCE_CAN_RECURSE;
1831 UNLOCK_CONTEXT (context);
1835 * g_source_get_can_recurse:
1836 * @source: a #GSource
1838 * Checks whether a source is allowed to be called recursively.
1839 * see g_source_set_can_recurse().
1841 * Return value: whether recursion is allowed.
1844 g_source_get_can_recurse (GSource *source)
1846 g_return_val_if_fail (source != NULL, FALSE);
1848 return (source->flags & G_SOURCE_CAN_RECURSE) != 0;
1853 * g_source_set_name:
1854 * @source: a #GSource
1855 * @name: debug name for the source
1857 * Sets a name for the source, used in debugging and profiling.
1858 * The name defaults to #NULL.
1860 * The source name should describe in a human-readable way
1861 * what the source does. For example, "X11 event queue"
1862 * or "GTK+ repaint idle handler" or whatever it is.
1864 * It is permitted to call this function multiple times, but is not
1865 * recommended due to the potential performance impact. For example,
1866 * one could change the name in the "check" function of a #GSourceFuncs
1867 * to include details like the event type in the source name.
1872 g_source_set_name (GSource *source,
1875 g_return_if_fail (source != NULL);
1877 /* setting back to NULL is allowed, just because it's
1878 * weird if get_name can return NULL but you can't
1882 g_free (source->name);
1883 source->name = g_strdup (name);
1887 * g_source_get_name:
1888 * @source: a #GSource
1890 * Gets a name for the source, used in debugging and profiling.
1891 * The name may be #NULL if it has never been set with
1892 * g_source_set_name().
1894 * Return value: the name of the source
1898 g_source_get_name (GSource *source)
1900 g_return_val_if_fail (source != NULL, NULL);
1902 return source->name;
1906 * g_source_set_name_by_id:
1907 * @tag: a #GSource ID
1908 * @name: debug name for the source
1910 * Sets the name of a source using its ID.
1912 * This is a convenience utility to set source names from the return
1913 * value of g_idle_add(), g_timeout_add(), etc.
1918 g_source_set_name_by_id (guint tag,
1923 g_return_if_fail (tag > 0);
1925 source = g_main_context_find_source_by_id (NULL, tag);
1929 g_source_set_name (source, name);
1935 * @source: a #GSource
1937 * Increases the reference count on a source by one.
1939 * Return value: @source
1942 g_source_ref (GSource *source)
1944 GMainContext *context;
1946 g_return_val_if_fail (source != NULL, NULL);
1948 context = source->context;
1951 LOCK_CONTEXT (context);
1953 source->ref_count++;
1956 UNLOCK_CONTEXT (context);
1961 /* g_source_unref() but possible to call within context lock
1964 g_source_unref_internal (GSource *source,
1965 GMainContext *context,
1968 gpointer old_cb_data = NULL;
1969 GSourceCallbackFuncs *old_cb_funcs = NULL;
1971 g_return_if_fail (source != NULL);
1973 if (!have_lock && context)
1974 LOCK_CONTEXT (context);
1976 source->ref_count--;
1977 if (source->ref_count == 0)
1979 old_cb_data = source->callback_data;
1980 old_cb_funcs = source->callback_funcs;
1982 source->callback_data = NULL;
1983 source->callback_funcs = NULL;
1987 if (!SOURCE_DESTROYED (source))
1988 g_warning (G_STRLOC ": ref_count == 0, but source was still attached to a context!");
1989 source_remove_from_context (source, context);
1992 if (source->source_funcs->finalize)
1995 UNLOCK_CONTEXT (context);
1996 source->source_funcs->finalize (source);
1998 LOCK_CONTEXT (context);
2001 g_free (source->name);
2002 source->name = NULL;
2004 g_slist_free (source->poll_fds);
2005 source->poll_fds = NULL;
2007 g_slist_free_full (source->priv->fds, g_free);
2009 g_slice_free (GSourcePrivate, source->priv);
2010 source->priv = NULL;
2015 if (!have_lock && context)
2016 UNLOCK_CONTEXT (context);
2021 UNLOCK_CONTEXT (context);
2023 old_cb_funcs->unref (old_cb_data);
2026 LOCK_CONTEXT (context);
2032 * @source: a #GSource
2034 * Decreases the reference count of a source by one. If the
2035 * resulting reference count is zero the source and associated
2036 * memory will be destroyed.
2039 g_source_unref (GSource *source)
2041 g_return_if_fail (source != NULL);
2043 g_source_unref_internal (source, source->context, FALSE);
2047 * g_main_context_find_source_by_id:
2048 * @context: (allow-none): a #GMainContext (if %NULL, the default context will be used)
2049 * @source_id: the source ID, as returned by g_source_get_id().
2051 * Finds a #GSource given a pair of context and ID.
2053 * Return value: (transfer none): the #GSource if found, otherwise, %NULL
2056 g_main_context_find_source_by_id (GMainContext *context,
2062 g_return_val_if_fail (source_id > 0, NULL);
2064 if (context == NULL)
2065 context = g_main_context_default ();
2067 LOCK_CONTEXT (context);
2069 g_source_iter_init (&iter, context, FALSE);
2070 while (g_source_iter_next (&iter, &source))
2072 if (!SOURCE_DESTROYED (source) &&
2073 source->source_id == source_id)
2076 g_source_iter_clear (&iter);
2078 UNLOCK_CONTEXT (context);
2084 * g_main_context_find_source_by_funcs_user_data:
2085 * @context: (allow-none): a #GMainContext (if %NULL, the default context will be used).
2086 * @funcs: the @source_funcs passed to g_source_new().
2087 * @user_data: the user data from the callback.
2089 * Finds a source with the given source functions and user data. If
2090 * multiple sources exist with the same source function and user data,
2091 * the first one found will be returned.
2093 * Return value: (transfer none): the source, if one was found, otherwise %NULL
2096 g_main_context_find_source_by_funcs_user_data (GMainContext *context,
2097 GSourceFuncs *funcs,
2103 g_return_val_if_fail (funcs != NULL, NULL);
2105 if (context == NULL)
2106 context = g_main_context_default ();
2108 LOCK_CONTEXT (context);
2110 g_source_iter_init (&iter, context, FALSE);
2111 while (g_source_iter_next (&iter, &source))
2113 if (!SOURCE_DESTROYED (source) &&
2114 source->source_funcs == funcs &&
2115 source->callback_funcs)
2117 GSourceFunc callback;
2118 gpointer callback_data;
2120 source->callback_funcs->get (source->callback_data, source, &callback, &callback_data);
2122 if (callback_data == user_data)
2126 g_source_iter_clear (&iter);
2128 UNLOCK_CONTEXT (context);
2134 * g_main_context_find_source_by_user_data:
2135 * @context: a #GMainContext
2136 * @user_data: the user_data for the callback.
2138 * Finds a source with the given user data for the callback. If
2139 * multiple sources exist with the same user data, the first
2140 * one found will be returned.
2142 * Return value: (transfer none): the source, if one was found, otherwise %NULL
2145 g_main_context_find_source_by_user_data (GMainContext *context,
2151 if (context == NULL)
2152 context = g_main_context_default ();
2154 LOCK_CONTEXT (context);
2156 g_source_iter_init (&iter, context, FALSE);
2157 while (g_source_iter_next (&iter, &source))
2159 if (!SOURCE_DESTROYED (source) &&
2160 source->callback_funcs)
2162 GSourceFunc callback;
2163 gpointer callback_data = NULL;
2165 source->callback_funcs->get (source->callback_data, source, &callback, &callback_data);
2167 if (callback_data == user_data)
2171 g_source_iter_clear (&iter);
2173 UNLOCK_CONTEXT (context);
2180 * @tag: the ID of the source to remove.
2182 * Removes the source with the given id from the default main context.
2184 * a #GSource is given by g_source_get_id(), or will be returned by the
2185 * functions g_source_attach(), g_idle_add(), g_idle_add_full(),
2186 * g_timeout_add(), g_timeout_add_full(), g_child_watch_add(),
2187 * g_child_watch_add_full(), g_io_add_watch(), and g_io_add_watch_full().
2189 * See also g_source_destroy(). You must use g_source_destroy() for sources
2190 * added to a non-default main context.
2192 * Return value: %TRUE if the source was found and removed.
2195 g_source_remove (guint tag)
2199 g_return_val_if_fail (tag > 0, FALSE);
2201 source = g_main_context_find_source_by_id (NULL, tag);
2203 g_source_destroy (source);
2205 return source != NULL;
2209 * g_source_remove_by_user_data:
2210 * @user_data: the user_data for the callback.
2212 * Removes a source from the default main loop context given the user
2213 * data for the callback. If multiple sources exist with the same user
2214 * data, only one will be destroyed.
2216 * Return value: %TRUE if a source was found and removed.
2219 g_source_remove_by_user_data (gpointer user_data)
2223 source = g_main_context_find_source_by_user_data (NULL, user_data);
2226 g_source_destroy (source);
2234 * g_source_remove_by_funcs_user_data:
2235 * @funcs: The @source_funcs passed to g_source_new()
2236 * @user_data: the user data for the callback
2238 * Removes a source from the default main loop context given the
2239 * source functions and user data. If multiple sources exist with the
2240 * same source functions and user data, only one will be destroyed.
2242 * Return value: %TRUE if a source was found and removed.
2245 g_source_remove_by_funcs_user_data (GSourceFuncs *funcs,
2250 g_return_val_if_fail (funcs != NULL, FALSE);
2252 source = g_main_context_find_source_by_funcs_user_data (NULL, funcs, user_data);
2255 g_source_destroy (source);
2264 * g_source_add_unix_fd:
2265 * @source: a #GSource
2266 * @fd: the fd to monitor
2267 * @events: an event mask
2269 * Monitors @fd for the IO events in @events.
2271 * The tag returned by this function can be used to remove or modify the
2272 * monitoring of the fd using g_source_remove_unix_fd() or
2273 * g_source_modify_unix_fd().
2275 * It is not necessary to remove the fd before destroying the source; it
2276 * will be cleaned up automatically.
2278 * As the name suggests, this function is not available on Windows.
2280 * Returns: an opaque tag
2285 g_source_add_unix_fd (GSource *source,
2287 GIOCondition events)
2289 GMainContext *context;
2292 g_return_val_if_fail (source != NULL, NULL);
2293 g_return_val_if_fail (!SOURCE_DESTROYED (source), NULL);
2295 poll_fd = g_new (GPollFD, 1);
2297 poll_fd->events = events;
2298 poll_fd->revents = 0;
2300 context = source->context;
2303 LOCK_CONTEXT (context);
2305 source->priv->fds = g_slist_prepend (source->priv->fds, poll_fd);
2309 if (!SOURCE_BLOCKED (source))
2310 g_main_context_add_poll_unlocked (context, source->priority, poll_fd);
2311 UNLOCK_CONTEXT (context);
2318 * g_source_modify_unix_fd:
2319 * @source: a #GSource
2320 * @tag: the tag from g_source_add_unix_fd()
2321 * @new_events: the new event mask to watch
2323 * Updates the event mask to watch for the fd identified by @tag.
2325 * @tag is the tag returned from g_source_add_unix_fd().
2327 * If you want to remove a fd, don't set its event mask to zero.
2328 * Instead, call g_source_remove_unix_fd().
2330 * As the name suggests, this function is not available on Windows.
2335 g_source_modify_unix_fd (GSource *source,
2337 GIOCondition new_events)
2339 GMainContext *context;
2342 g_return_if_fail (source != NULL);
2343 g_return_if_fail (g_slist_find (source->priv->fds, tag));
2345 context = source->context;
2348 poll_fd->events = new_events;
2351 g_main_context_wakeup (context);
2355 * g_source_remove_unix_fd:
2356 * @source: a #GSource
2357 * @tag: the tag from g_source_add_unix_fd()
2359 * Reverses the effect of a previous call to g_source_add_unix_fd().
2361 * You only need to call this if you want to remove an fd from being
2362 * watched while keeping the same source around. In the normal case you
2363 * will just want to destroy the source.
2365 * As the name suggests, this function is not available on Windows.
2370 g_source_remove_unix_fd (GSource *source,
2373 GMainContext *context;
2376 g_return_if_fail (source != NULL);
2377 g_return_if_fail (g_slist_find (source->priv->fds, tag));
2379 context = source->context;
2383 LOCK_CONTEXT (context);
2385 source->priv->fds = g_slist_remove (source->priv->fds, poll_fd);
2389 if (!SOURCE_BLOCKED (source))
2390 g_main_context_remove_poll_unlocked (context, poll_fd);
2392 UNLOCK_CONTEXT (context);
2399 * g_source_query_unix_fd:
2400 * @source: a #GSource
2401 * @tag: the tag from g_source_add_unix_fd()
2403 * Queries the events reported for the fd corresponding to @tag on
2404 * @source during the last poll.
2406 * The return value of this function is only defined when the function
2407 * is called from the check or dispatch functions for @source.
2409 * As the name suggests, this function is not available on Windows.
2411 * Returns: the conditions reported on the fd
2416 g_source_query_unix_fd (GSource *source,
2421 g_return_val_if_fail (source != NULL, 0);
2422 g_return_val_if_fail (g_slist_find (source->priv->fds, tag), 0);
2426 return poll_fd->revents;
2428 #endif /* G_OS_UNIX */
2431 * g_get_current_time:
2432 * @result: #GTimeVal structure in which to store current time.
2434 * Equivalent to the UNIX gettimeofday() function, but portable.
2436 * You may find g_get_real_time() to be more convenient.
2439 g_get_current_time (GTimeVal *result)
2444 g_return_if_fail (result != NULL);
2446 /*this is required on alpha, there the timeval structs are int's
2447 not longs and a cast only would fail horribly*/
2448 gettimeofday (&r, NULL);
2449 result->tv_sec = r.tv_sec;
2450 result->tv_usec = r.tv_usec;
2455 g_return_if_fail (result != NULL);
2457 GetSystemTimeAsFileTime (&ft);
2458 memmove (&time64, &ft, sizeof (FILETIME));
2460 /* Convert from 100s of nanoseconds since 1601-01-01
2461 * to Unix epoch. Yes, this is Y2038 unsafe.
2463 time64 -= G_GINT64_CONSTANT (116444736000000000);
2466 result->tv_sec = time64 / 1000000;
2467 result->tv_usec = time64 % 1000000;
2474 * Queries the system wall-clock time.
2476 * This call is functionally equivalent to g_get_current_time() except
2477 * that the return value is often more convenient than dealing with a
2480 * You should only use this call if you are actually interested in the real
2481 * wall-clock time. g_get_monotonic_time() is probably more useful for
2482 * measuring intervals.
2484 * Returns: the number of microseconds since January 1, 1970 UTC.
2489 g_get_real_time (void)
2493 g_get_current_time (&tv);
2495 return (((gint64) tv.tv_sec) * 1000000) + tv.tv_usec;
2499 static ULONGLONG (*g_GetTickCount64) (void) = NULL;
2500 static guint32 g_win32_tick_epoch = 0;
2503 g_clock_win32_init (void)
2507 g_GetTickCount64 = NULL;
2508 kernel32 = GetModuleHandle ("KERNEL32.DLL");
2509 if (kernel32 != NULL)
2510 g_GetTickCount64 = (void *) GetProcAddress (kernel32, "GetTickCount64");
2511 g_win32_tick_epoch = ((guint32)GetTickCount()) >> 31;
2516 * g_get_monotonic_time:
2518 * Queries the system monotonic time, if available.
2520 * On POSIX systems with clock_gettime() and <literal>CLOCK_MONOTONIC</literal> this call
2521 * is a very shallow wrapper for that. Otherwise, we make a best effort
2522 * that probably involves returning the wall clock time (with at least
2523 * microsecond accuracy, subject to the limitations of the OS kernel).
2525 * It's important to note that POSIX <literal>CLOCK_MONOTONIC</literal> does
2526 * not count time spent while the machine is suspended.
2528 * On Windows, "limitations of the OS kernel" is a rather substantial
2529 * statement. Depending on the configuration of the system, the wall
2530 * clock time is updated as infrequently as 64 times a second (which
2531 * is approximately every 16ms). Also, on XP (but not on Vista or later)
2532 * the monotonic clock is locally monotonic, but may differ in exact
2533 * value between processes due to timer wrap handling.
2535 * Returns: the monotonic time, in microseconds
2540 g_get_monotonic_time (void)
2542 #ifdef HAVE_CLOCK_GETTIME
2543 /* librt clock_gettime() is our first choice */
2546 #ifdef CLOCK_MONOTONIC
2547 clock_gettime (CLOCK_MONOTONIC, &ts);
2549 clock_gettime (CLOCK_REALTIME, &ts);
2552 /* In theory monotonic time can have any epoch.
2554 * glib presently assumes the following:
2556 * 1) The epoch comes some time after the birth of Jesus of Nazareth, but
2557 * not more than 10000 years later.
2559 * 2) The current time also falls sometime within this range.
2561 * These two reasonable assumptions leave us with a maximum deviation from
2562 * the epoch of 10000 years, or 315569520000000000 seconds.
2564 * If we restrict ourselves to this range then the number of microseconds
2565 * will always fit well inside the constraints of a int64 (by a factor of
2568 * If you actually hit the following assertion, probably you should file a
2569 * bug against your operating system for being excessively silly.
2571 g_assert (G_GINT64_CONSTANT (-315569520000000000) < ts.tv_sec &&
2572 ts.tv_sec < G_GINT64_CONSTANT (315569520000000000));
2574 return (((gint64) ts.tv_sec) * 1000000) + (ts.tv_nsec / 1000);
2576 #elif defined (G_OS_WIN32)
2580 /* There are four sources for the monotonic time on Windows:
2582 * Three are based on a (1 msec accuracy, but only read periodically) clock chip:
2583 * - GetTickCount (GTC)
2584 * 32bit msec counter, updated each ~15msec, wraps in ~50 days
2585 * - GetTickCount64 (GTC64)
2586 * Same as GetTickCount, but extended to 64bit, so no wrap
2587 * Only available in Vista or later
2588 * - timeGetTime (TGT)
2589 * similar to GetTickCount by default: 15msec, 50 day wrap.
2590 * available in winmm.dll (thus known as the multimedia timers)
2591 * However apps can raise the system timer clock frequency using timeBeginPeriod()
2592 * increasing the accuracy up to 1 msec, at a cost in general system performance
2595 * One is based on high precision clocks:
2596 * - QueryPrecisionCounter (QPC)
2597 * This has much higher accuracy, but is not guaranteed monotonic, and
2598 * has lots of complications like clock jumps and different times on different
2599 * CPUs. It also has lower long term accuracy (i.e. it will drift compared to
2600 * the low precision clocks.
2602 * Additionally, the precision available in the timer-based wakeup such as
2603 * MsgWaitForMultipleObjectsEx (which is what the mainloop is based on) is based
2604 * on the TGT resolution, so by default it is ~15msec, but can be increased by apps.
2606 * The QPC timer has too many issues to be used as is. The only way it could be used
2607 * is to use it to interpolate the lower precision clocks. Firefox does something like
2609 * https://bugzilla.mozilla.org/show_bug.cgi?id=363258
2611 * However this seems quite complicated, so we're not doing this right now.
2613 * The approach we take instead is to use the TGT timer, extending it to 64bit
2614 * either by using the GTC64 value, or if that is not available, a process local
2615 * time epoch that we increment when we detect a timer wrap (assumes that we read
2616 * the time at least once every 50 days).
2619 * - We have a globally consistent monotonic clock on Vista and later
2620 * - We have a locally monotonic clock on XP
2621 * - Apps that need higher precision in timeouts and clock reads can call
2622 * timeBeginPeriod() to increase it as much as they want
2625 if (g_GetTickCount64 != NULL)
2627 guint32 ticks_as_32bit;
2629 ticks = g_GetTickCount64 ();
2630 ticks32 = timeGetTime();
2632 /* GTC64 and TGT are sampled at different times, however they
2633 * have the same base and source (msecs since system boot).
2634 * They can differ by as much as -16 to +16 msecs.
2635 * We can't just inject the low bits into the 64bit counter
2636 * as one of the counters can have wrapped in 32bit space and
2637 * the other not. Instead we calculate the signed difference
2638 * in 32bit space and apply that difference to the 64bit counter.
2640 ticks_as_32bit = (guint32)ticks;
2642 /* We could do some 2's complement hack, but we play it safe */
2643 if (ticks32 - ticks_as_32bit <= G_MAXINT32)
2644 ticks += ticks32 - ticks_as_32bit;
2646 ticks -= ticks_as_32bit - ticks32;
2652 epoch = g_atomic_int_get (&g_win32_tick_epoch);
2654 /* Must read ticks after the epoch. Then we're guaranteed
2655 * that the ticks value we read is higher or equal to any
2656 * previous ones that lead to the writing of the epoch.
2658 ticks32 = timeGetTime();
2660 /* We store the MSB of the current time as the LSB
2661 * of the epoch. Comparing these bits lets us detect when
2662 * the 32bit counter has wrapped so we can increase the
2665 * This will work as long as this function is called at
2666 * least once every ~24 days, which is half the wrap time
2667 * of a 32bit msec counter. I think this is pretty likely.
2669 * Note that g_win32_tick_epoch is a process local state,
2670 * so the monotonic clock will not be the same between
2673 if ((ticks32 >> 31) != (epoch & 1))
2676 g_atomic_int_set (&g_win32_tick_epoch, epoch);
2680 ticks = (guint64)ticks32 | ((guint64)epoch) << 31;
2683 return ticks * 1000;
2685 #else /* !HAVE_CLOCK_GETTIME && ! G_OS_WIN32*/
2689 g_get_current_time (&tv);
2691 return (((gint64) tv.tv_sec) * 1000000) + tv.tv_usec;
2696 g_main_dispatch_free (gpointer dispatch)
2698 g_slice_free (GMainDispatch, dispatch);
2701 /* Running the main loop */
2703 static GMainDispatch *
2706 static GPrivate depth_private = G_PRIVATE_INIT (g_main_dispatch_free);
2707 GMainDispatch *dispatch;
2709 dispatch = g_private_get (&depth_private);
2713 dispatch = g_slice_new0 (GMainDispatch);
2714 g_private_set (&depth_private, dispatch);
2723 * Returns the depth of the stack of calls to
2724 * g_main_context_dispatch() on any #GMainContext in the current thread.
2725 * That is, when called from the toplevel, it gives 0. When
2726 * called from within a callback from g_main_context_iteration()
2727 * (or g_main_loop_run(), etc.) it returns 1. When called from within
2728 * a callback to a recursive call to g_main_context_iteration(),
2729 * it returns 2. And so forth.
2731 * This function is useful in a situation like the following:
2732 * Imagine an extremely simple "garbage collected" system.
2735 * static GList *free_list;
2738 * allocate_memory (gsize size)
2740 * gpointer result = g_malloc (size);
2741 * free_list = g_list_prepend (free_list, result);
2746 * free_allocated_memory (void)
2749 * for (l = free_list; l; l = l->next);
2751 * g_list_free (free_list);
2759 * g_main_context_iteration (NULL, TRUE);
2760 * free_allocated_memory();
2764 * This works from an application, however, if you want to do the same
2765 * thing from a library, it gets more difficult, since you no longer
2766 * control the main loop. You might think you can simply use an idle
2767 * function to make the call to free_allocated_memory(), but that
2768 * doesn't work, since the idle function could be called from a
2769 * recursive callback. This can be fixed by using g_main_depth()
2773 * allocate_memory (gsize size)
2775 * FreeListBlock *block = g_new (FreeListBlock, 1);
2776 * block->mem = g_malloc (size);
2777 * block->depth = g_main_depth ();
2778 * free_list = g_list_prepend (free_list, block);
2779 * return block->mem;
2783 * free_allocated_memory (void)
2787 * int depth = g_main_depth ();
2788 * for (l = free_list; l; );
2790 * GList *next = l->next;
2791 * FreeListBlock *block = l->data;
2792 * if (block->depth > depth)
2794 * g_free (block->mem);
2796 * free_list = g_list_delete_link (free_list, l);
2804 * There is a temptation to use g_main_depth() to solve
2805 * problems with reentrancy. For instance, while waiting for data
2806 * to be received from the network in response to a menu item,
2807 * the menu item might be selected again. It might seem that
2808 * one could make the menu item's callback return immediately
2809 * and do nothing if g_main_depth() returns a value greater than 1.
2810 * However, this should be avoided since the user then sees selecting
2811 * the menu item do nothing. Furthermore, you'll find yourself adding
2812 * these checks all over your code, since there are doubtless many,
2813 * many things that the user could do. Instead, you can use the
2814 * following techniques:
2819 * Use gtk_widget_set_sensitive() or modal dialogs to prevent
2820 * the user from interacting with elements while the main
2821 * loop is recursing.
2826 * Avoid main loop recursion in situations where you can't handle
2827 * arbitrary callbacks. Instead, structure your code so that you
2828 * simply return to the main loop and then get called again when
2829 * there is more work to do.
2834 * Return value: The main loop recursion level in the current thread
2839 GMainDispatch *dispatch = get_dispatch ();
2840 return dispatch->depth;
2844 * g_main_current_source:
2846 * Returns the currently firing source for this thread.
2848 * Return value: (transfer none): The currently firing source or %NULL.
2853 g_main_current_source (void)
2855 GMainDispatch *dispatch = get_dispatch ();
2856 return dispatch->source;
2860 * g_source_is_destroyed:
2861 * @source: a #GSource
2863 * Returns whether @source has been destroyed.
2865 * This is important when you operate upon your objects
2866 * from within idle handlers, but may have freed the object
2867 * before the dispatch of your idle handler.
2871 * idle_callback (gpointer data)
2873 * SomeWidget *self = data;
2875 * GDK_THREADS_ENTER (<!-- -->);
2876 * /<!-- -->* do stuff with self *<!-- -->/
2877 * self->idle_id = 0;
2878 * GDK_THREADS_LEAVE (<!-- -->);
2880 * return G_SOURCE_REMOVE;
2884 * some_widget_do_stuff_later (SomeWidget *self)
2886 * self->idle_id = g_idle_add (idle_callback, self);
2890 * some_widget_finalize (GObject *object)
2892 * SomeWidget *self = SOME_WIDGET (object);
2894 * if (self->idle_id)
2895 * g_source_remove (self->idle_id);
2897 * G_OBJECT_CLASS (parent_class)->finalize (object);
2901 * This will fail in a multi-threaded application if the
2902 * widget is destroyed before the idle handler fires due
2903 * to the use after free in the callback. A solution, to
2904 * this particular problem, is to check to if the source
2905 * has already been destroy within the callback.
2909 * idle_callback (gpointer data)
2911 * SomeWidget *self = data;
2913 * GDK_THREADS_ENTER ();
2914 * if (!g_source_is_destroyed (g_main_current_source ()))
2916 * /<!-- -->* do stuff with self *<!-- -->/
2918 * GDK_THREADS_LEAVE ();
2924 * Return value: %TRUE if the source has been destroyed
2929 g_source_is_destroyed (GSource *source)
2931 return SOURCE_DESTROYED (source);
2934 /* Temporarily remove all this source's file descriptors from the
2935 * poll(), so that if data comes available for one of the file descriptors
2936 * we don't continually spin in the poll()
2938 /* HOLDS: source->context's lock */
2940 block_source (GSource *source)
2944 g_return_if_fail (!SOURCE_BLOCKED (source));
2946 source->flags |= G_SOURCE_BLOCKED;
2948 if (source->context)
2950 tmp_list = source->poll_fds;
2953 g_main_context_remove_poll_unlocked (source->context, tmp_list->data);
2954 tmp_list = tmp_list->next;
2957 for (tmp_list = source->priv->fds; tmp_list; tmp_list = tmp_list->next)
2958 g_main_context_remove_poll_unlocked (source->context, tmp_list->data);
2961 if (source->priv && source->priv->child_sources)
2963 tmp_list = source->priv->child_sources;
2966 block_source (tmp_list->data);
2967 tmp_list = tmp_list->next;
2972 /* HOLDS: source->context's lock */
2974 unblock_source (GSource *source)
2978 g_return_if_fail (SOURCE_BLOCKED (source)); /* Source already unblocked */
2979 g_return_if_fail (!SOURCE_DESTROYED (source));
2981 source->flags &= ~G_SOURCE_BLOCKED;
2983 tmp_list = source->poll_fds;
2986 g_main_context_add_poll_unlocked (source->context, source->priority, tmp_list->data);
2987 tmp_list = tmp_list->next;
2990 for (tmp_list = source->priv->fds; tmp_list; tmp_list = tmp_list->next)
2991 g_main_context_add_poll_unlocked (source->context, source->priority, tmp_list->data);
2993 if (source->priv && source->priv->child_sources)
2995 tmp_list = source->priv->child_sources;
2998 unblock_source (tmp_list->data);
2999 tmp_list = tmp_list->next;
3004 /* HOLDS: context's lock */
3006 g_main_dispatch (GMainContext *context)
3008 GMainDispatch *current = get_dispatch ();
3011 for (i = 0; i < context->pending_dispatches->len; i++)
3013 GSource *source = context->pending_dispatches->pdata[i];
3015 context->pending_dispatches->pdata[i] = NULL;
3018 source->flags &= ~G_SOURCE_READY;
3020 if (!SOURCE_DESTROYED (source))
3022 gboolean was_in_call;
3023 gpointer user_data = NULL;
3024 GSourceFunc callback = NULL;
3025 GSourceCallbackFuncs *cb_funcs;
3027 gboolean need_destroy;
3029 gboolean (*dispatch) (GSource *,
3032 GSource *prev_source;
3034 dispatch = source->source_funcs->dispatch;
3035 cb_funcs = source->callback_funcs;
3036 cb_data = source->callback_data;
3039 cb_funcs->ref (cb_data);
3041 if ((source->flags & G_SOURCE_CAN_RECURSE) == 0)
3042 block_source (source);
3044 was_in_call = source->flags & G_HOOK_FLAG_IN_CALL;
3045 source->flags |= G_HOOK_FLAG_IN_CALL;
3048 cb_funcs->get (cb_data, source, &callback, &user_data);
3050 UNLOCK_CONTEXT (context);
3052 /* These operations are safe because 'current' is thread-local
3053 * and not modified from anywhere but this function.
3055 prev_source = current->source;
3056 current->source = source;
3059 need_destroy = !(* dispatch) (source, callback, user_data);
3061 current->source = prev_source;
3065 cb_funcs->unref (cb_data);
3067 LOCK_CONTEXT (context);
3070 source->flags &= ~G_HOOK_FLAG_IN_CALL;
3072 if (SOURCE_BLOCKED (source) && !SOURCE_DESTROYED (source))
3073 unblock_source (source);
3075 /* Note: this depends on the fact that we can't switch
3076 * sources from one main context to another
3078 if (need_destroy && !SOURCE_DESTROYED (source))
3080 g_assert (source->context == context);
3081 g_source_destroy_internal (source, context, TRUE);
3085 SOURCE_UNREF (source, context);
3088 g_ptr_array_set_size (context->pending_dispatches, 0);
3092 * g_main_context_acquire:
3093 * @context: a #GMainContext
3095 * Tries to become the owner of the specified context.
3096 * If some other thread is the owner of the context,
3097 * returns %FALSE immediately. Ownership is properly
3098 * recursive: the owner can require ownership again
3099 * and will release ownership when g_main_context_release()
3100 * is called as many times as g_main_context_acquire().
3102 * You must be the owner of a context before you
3103 * can call g_main_context_prepare(), g_main_context_query(),
3104 * g_main_context_check(), g_main_context_dispatch().
3106 * Return value: %TRUE if the operation succeeded, and
3107 * this thread is now the owner of @context.
3110 g_main_context_acquire (GMainContext *context)
3112 gboolean result = FALSE;
3113 GThread *self = G_THREAD_SELF;
3115 if (context == NULL)
3116 context = g_main_context_default ();
3118 LOCK_CONTEXT (context);
3120 if (!context->owner)
3122 context->owner = self;
3123 g_assert (context->owner_count == 0);
3126 if (context->owner == self)
3128 context->owner_count++;
3132 UNLOCK_CONTEXT (context);
3138 * g_main_context_release:
3139 * @context: a #GMainContext
3141 * Releases ownership of a context previously acquired by this thread
3142 * with g_main_context_acquire(). If the context was acquired multiple
3143 * times, the ownership will be released only when g_main_context_release()
3144 * is called as many times as it was acquired.
3147 g_main_context_release (GMainContext *context)
3149 if (context == NULL)
3150 context = g_main_context_default ();
3152 LOCK_CONTEXT (context);
3154 context->owner_count--;
3155 if (context->owner_count == 0)
3157 context->owner = NULL;
3159 if (context->waiters)
3161 GMainWaiter *waiter = context->waiters->data;
3162 gboolean loop_internal_waiter = (waiter->mutex == &context->mutex);
3163 context->waiters = g_slist_delete_link (context->waiters,
3165 if (!loop_internal_waiter)
3166 g_mutex_lock (waiter->mutex);
3168 g_cond_signal (waiter->cond);
3170 if (!loop_internal_waiter)
3171 g_mutex_unlock (waiter->mutex);
3175 UNLOCK_CONTEXT (context);
3179 * g_main_context_wait:
3180 * @context: a #GMainContext
3181 * @cond: a condition variable
3182 * @mutex: a mutex, currently held
3184 * Tries to become the owner of the specified context,
3185 * as with g_main_context_acquire(). But if another thread
3186 * is the owner, atomically drop @mutex and wait on @cond until
3187 * that owner releases ownership or until @cond is signaled, then
3188 * try again (once) to become the owner.
3190 * Return value: %TRUE if the operation succeeded, and
3191 * this thread is now the owner of @context.
3194 g_main_context_wait (GMainContext *context,
3198 gboolean result = FALSE;
3199 GThread *self = G_THREAD_SELF;
3200 gboolean loop_internal_waiter;
3202 if (context == NULL)
3203 context = g_main_context_default ();
3205 loop_internal_waiter = (mutex == &context->mutex);
3207 if (!loop_internal_waiter)
3208 LOCK_CONTEXT (context);
3210 if (context->owner && context->owner != self)
3215 waiter.mutex = mutex;
3217 context->waiters = g_slist_append (context->waiters, &waiter);
3219 if (!loop_internal_waiter)
3220 UNLOCK_CONTEXT (context);
3221 g_cond_wait (cond, mutex);
3222 if (!loop_internal_waiter)
3223 LOCK_CONTEXT (context);
3225 context->waiters = g_slist_remove (context->waiters, &waiter);
3228 if (!context->owner)
3230 context->owner = self;
3231 g_assert (context->owner_count == 0);
3234 if (context->owner == self)
3236 context->owner_count++;
3240 if (!loop_internal_waiter)
3241 UNLOCK_CONTEXT (context);
3247 * g_main_context_prepare:
3248 * @context: a #GMainContext
3249 * @priority: location to store priority of highest priority
3250 * source already ready.
3252 * Prepares to poll sources within a main loop. The resulting information
3253 * for polling is determined by calling g_main_context_query ().
3255 * Return value: %TRUE if some source is ready to be dispatched
3259 g_main_context_prepare (GMainContext *context,
3264 gint current_priority = G_MAXINT;
3268 if (context == NULL)
3269 context = g_main_context_default ();
3271 LOCK_CONTEXT (context);
3273 context->time_is_fresh = FALSE;
3275 if (context->in_check_or_prepare)
3277 g_warning ("g_main_context_prepare() called recursively from within a source's check() or "
3278 "prepare() member.");
3279 UNLOCK_CONTEXT (context);
3284 /* If recursing, finish up current dispatch, before starting over */
3285 if (context->pending_dispatches)
3288 g_main_dispatch (context, ¤t_time);
3290 UNLOCK_CONTEXT (context);
3295 /* If recursing, clear list of pending dispatches */
3297 for (i = 0; i < context->pending_dispatches->len; i++)
3299 if (context->pending_dispatches->pdata[i])
3300 SOURCE_UNREF ((GSource *)context->pending_dispatches->pdata[i], context);
3302 g_ptr_array_set_size (context->pending_dispatches, 0);
3304 /* Prepare all sources */
3306 context->timeout = -1;
3308 g_source_iter_init (&iter, context, TRUE);
3309 while (g_source_iter_next (&iter, &source))
3311 gint source_timeout = -1;
3313 if (SOURCE_DESTROYED (source) || SOURCE_BLOCKED (source))
3315 if ((n_ready > 0) && (source->priority > current_priority))
3318 if (!(source->flags & G_SOURCE_READY))
3321 gboolean (* prepare) (GSource *source,
3324 prepare = source->source_funcs->prepare;
3328 context->in_check_or_prepare++;
3329 UNLOCK_CONTEXT (context);
3331 result = (* prepare) (source, &source_timeout);
3333 LOCK_CONTEXT (context);
3334 context->in_check_or_prepare--;
3338 source_timeout = -1;
3342 if (result == FALSE && source->priv->ready_time != -1)
3344 if (!context->time_is_fresh)
3346 context->time = g_get_monotonic_time ();
3347 context->time_is_fresh = TRUE;
3350 if (source->priv->ready_time <= context->time)
3359 /* rounding down will lead to spinning, so always round up */
3360 timeout = (source->priv->ready_time - context->time + 999) / 1000;
3362 if (source_timeout < 0 || timeout < source_timeout)
3363 source_timeout = timeout;
3369 GSource *ready_source = source;
3371 while (ready_source)
3373 ready_source->flags |= G_SOURCE_READY;
3374 ready_source = ready_source->priv->parent_source;
3379 if (source->flags & G_SOURCE_READY)
3382 current_priority = source->priority;
3383 context->timeout = 0;
3386 if (source_timeout >= 0)
3388 if (context->timeout < 0)
3389 context->timeout = source_timeout;
3391 context->timeout = MIN (context->timeout, source_timeout);
3394 g_source_iter_clear (&iter);
3396 UNLOCK_CONTEXT (context);
3399 *priority = current_priority;
3401 return (n_ready > 0);
3405 * g_main_context_query:
3406 * @context: a #GMainContext
3407 * @max_priority: maximum priority source to check
3408 * @timeout_: (out): location to store timeout to be used in polling
3409 * @fds: (out caller-allocates) (array length=n_fds): location to
3410 * store #GPollFD records that need to be polled.
3411 * @n_fds: length of @fds.
3413 * Determines information necessary to poll this main loop.
3415 * Return value: the number of records actually stored in @fds,
3416 * or, if more than @n_fds records need to be stored, the number
3417 * of records that need to be stored.
3420 g_main_context_query (GMainContext *context,
3429 LOCK_CONTEXT (context);
3431 pollrec = context->poll_records;
3433 while (pollrec && max_priority >= pollrec->priority)
3435 /* We need to include entries with fd->events == 0 in the array because
3436 * otherwise if the application changes fd->events behind our back and
3437 * makes it non-zero, we'll be out of sync when we check the fds[] array.
3438 * (Changing fd->events after adding an FD wasn't an anticipated use of
3439 * this API, but it occurs in practice.) */
3442 fds[n_poll].fd = pollrec->fd->fd;
3443 /* In direct contradiction to the Unix98 spec, IRIX runs into
3444 * difficulty if you pass in POLLERR, POLLHUP or POLLNVAL
3445 * flags in the events field of the pollfd while it should
3446 * just ignoring them. So we mask them out here.
3448 fds[n_poll].events = pollrec->fd->events & ~(G_IO_ERR|G_IO_HUP|G_IO_NVAL);
3449 fds[n_poll].revents = 0;
3452 pollrec = pollrec->next;
3456 context->poll_changed = FALSE;
3460 *timeout = context->timeout;
3462 context->time_is_fresh = FALSE;
3465 UNLOCK_CONTEXT (context);
3471 * g_main_context_check:
3472 * @context: a #GMainContext
3473 * @max_priority: the maximum numerical priority of sources to check
3474 * @fds: (array length=n_fds): array of #GPollFD's that was passed to
3475 * the last call to g_main_context_query()
3476 * @n_fds: return value of g_main_context_query()
3478 * Passes the results of polling back to the main loop.
3480 * Return value: %TRUE if some sources are ready to be dispatched.
3483 g_main_context_check (GMainContext *context,
3494 LOCK_CONTEXT (context);
3496 if (context->in_check_or_prepare)
3498 g_warning ("g_main_context_check() called recursively from within a source's check() or "
3499 "prepare() member.");
3500 UNLOCK_CONTEXT (context);
3504 if (context->wake_up_rec.revents)
3505 g_wakeup_acknowledge (context->wakeup);
3507 /* If the set of poll file descriptors changed, bail out
3508 * and let the main loop rerun
3510 if (context->poll_changed)
3512 UNLOCK_CONTEXT (context);
3516 pollrec = context->poll_records;
3520 if (pollrec->fd->events)
3521 pollrec->fd->revents = fds[i].revents;
3523 pollrec = pollrec->next;
3527 g_source_iter_init (&iter, context, TRUE);
3528 while (g_source_iter_next (&iter, &source))
3530 if (SOURCE_DESTROYED (source) || SOURCE_BLOCKED (source))
3532 if ((n_ready > 0) && (source->priority > max_priority))
3535 if (!(source->flags & G_SOURCE_READY))
3538 gboolean (* check) (GSource *source);
3540 check = source->source_funcs->check;
3544 /* If the check function is set, call it. */
3545 context->in_check_or_prepare++;
3546 UNLOCK_CONTEXT (context);
3548 result = (* check) (source);
3550 LOCK_CONTEXT (context);
3551 context->in_check_or_prepare--;
3556 if (result == FALSE)
3560 /* If not already explicitly flagged ready by ->check()
3561 * (or if we have no check) then we can still be ready if
3562 * any of our fds poll as ready.
3564 for (tmp_list = source->priv->fds; tmp_list; tmp_list = tmp_list->next)
3566 GPollFD *pollfd = tmp_list->data;
3568 if (pollfd->revents)
3576 if (result == FALSE && source->priv->ready_time != -1)
3578 if (!context->time_is_fresh)
3580 context->time = g_get_monotonic_time ();
3581 context->time_is_fresh = TRUE;
3584 if (source->priv->ready_time <= context->time)
3590 GSource *ready_source = source;
3592 while (ready_source)
3594 ready_source->flags |= G_SOURCE_READY;
3595 ready_source = ready_source->priv->parent_source;
3600 if (source->flags & G_SOURCE_READY)
3602 source->ref_count++;
3603 g_ptr_array_add (context->pending_dispatches, source);
3607 /* never dispatch sources with less priority than the first
3608 * one we choose to dispatch
3610 max_priority = source->priority;
3613 g_source_iter_clear (&iter);
3615 UNLOCK_CONTEXT (context);
3621 * g_main_context_dispatch:
3622 * @context: a #GMainContext
3624 * Dispatches all pending sources.
3627 g_main_context_dispatch (GMainContext *context)
3629 LOCK_CONTEXT (context);
3631 if (context->pending_dispatches->len > 0)
3633 g_main_dispatch (context);
3636 UNLOCK_CONTEXT (context);
3639 /* HOLDS context lock */
3641 g_main_context_iterate (GMainContext *context,
3648 gboolean some_ready;
3649 gint nfds, allocated_nfds;
3650 GPollFD *fds = NULL;
3652 UNLOCK_CONTEXT (context);
3654 if (!g_main_context_acquire (context))
3656 gboolean got_ownership;
3658 LOCK_CONTEXT (context);
3663 got_ownership = g_main_context_wait (context,
3671 LOCK_CONTEXT (context);
3673 if (!context->cached_poll_array)
3675 context->cached_poll_array_size = context->n_poll_records;
3676 context->cached_poll_array = g_new (GPollFD, context->n_poll_records);
3679 allocated_nfds = context->cached_poll_array_size;
3680 fds = context->cached_poll_array;
3682 UNLOCK_CONTEXT (context);
3684 g_main_context_prepare (context, &max_priority);
3686 while ((nfds = g_main_context_query (context, max_priority, &timeout, fds,
3687 allocated_nfds)) > allocated_nfds)
3689 LOCK_CONTEXT (context);
3691 context->cached_poll_array_size = allocated_nfds = nfds;
3692 context->cached_poll_array = fds = g_new (GPollFD, nfds);
3693 UNLOCK_CONTEXT (context);
3699 g_main_context_poll (context, timeout, max_priority, fds, nfds);
3701 some_ready = g_main_context_check (context, max_priority, fds, nfds);
3704 g_main_context_dispatch (context);
3706 g_main_context_release (context);
3708 LOCK_CONTEXT (context);
3714 * g_main_context_pending:
3715 * @context: (allow-none): a #GMainContext (if %NULL, the default context will be used)
3717 * Checks if any sources have pending events for the given context.
3719 * Return value: %TRUE if events are pending.
3722 g_main_context_pending (GMainContext *context)
3727 context = g_main_context_default();
3729 LOCK_CONTEXT (context);
3730 retval = g_main_context_iterate (context, FALSE, FALSE, G_THREAD_SELF);
3731 UNLOCK_CONTEXT (context);
3737 * g_main_context_iteration:
3738 * @context: (allow-none): a #GMainContext (if %NULL, the default context will be used)
3739 * @may_block: whether the call may block.
3741 * Runs a single iteration for the given main loop. This involves
3742 * checking to see if any event sources are ready to be processed,
3743 * then if no events sources are ready and @may_block is %TRUE, waiting
3744 * for a source to become ready, then dispatching the highest priority
3745 * events sources that are ready. Otherwise, if @may_block is %FALSE
3746 * sources are not waited to become ready, only those highest priority
3747 * events sources will be dispatched (if any), that are ready at this
3748 * given moment without further waiting.
3750 * Note that even when @may_block is %TRUE, it is still possible for
3751 * g_main_context_iteration() to return %FALSE, since the wait may
3752 * be interrupted for other reasons than an event source becoming ready.
3754 * Return value: %TRUE if events were dispatched.
3757 g_main_context_iteration (GMainContext *context, gboolean may_block)
3762 context = g_main_context_default();
3764 LOCK_CONTEXT (context);
3765 retval = g_main_context_iterate (context, may_block, TRUE, G_THREAD_SELF);
3766 UNLOCK_CONTEXT (context);
3773 * @context: (allow-none): a #GMainContext (if %NULL, the default context will be used).
3774 * @is_running: set to %TRUE to indicate that the loop is running. This
3775 * is not very important since calling g_main_loop_run() will set this to
3778 * Creates a new #GMainLoop structure.
3780 * Return value: a new #GMainLoop.
3783 g_main_loop_new (GMainContext *context,
3784 gboolean is_running)
3789 context = g_main_context_default();
3791 g_main_context_ref (context);
3793 loop = g_new0 (GMainLoop, 1);
3794 loop->context = context;
3795 loop->is_running = is_running != FALSE;
3796 loop->ref_count = 1;
3803 * @loop: a #GMainLoop
3805 * Increases the reference count on a #GMainLoop object by one.
3807 * Return value: @loop
3810 g_main_loop_ref (GMainLoop *loop)
3812 g_return_val_if_fail (loop != NULL, NULL);
3813 g_return_val_if_fail (g_atomic_int_get (&loop->ref_count) > 0, NULL);
3815 g_atomic_int_inc (&loop->ref_count);
3821 * g_main_loop_unref:
3822 * @loop: a #GMainLoop
3824 * Decreases the reference count on a #GMainLoop object by one. If
3825 * the result is zero, free the loop and free all associated memory.
3828 g_main_loop_unref (GMainLoop *loop)
3830 g_return_if_fail (loop != NULL);
3831 g_return_if_fail (g_atomic_int_get (&loop->ref_count) > 0);
3833 if (!g_atomic_int_dec_and_test (&loop->ref_count))
3836 g_main_context_unref (loop->context);
3842 * @loop: a #GMainLoop
3844 * Runs a main loop until g_main_loop_quit() is called on the loop.
3845 * If this is called for the thread of the loop's #GMainContext,
3846 * it will process events from the loop, otherwise it will
3850 g_main_loop_run (GMainLoop *loop)
3852 GThread *self = G_THREAD_SELF;
3854 g_return_if_fail (loop != NULL);
3855 g_return_if_fail (g_atomic_int_get (&loop->ref_count) > 0);
3857 if (!g_main_context_acquire (loop->context))
3859 gboolean got_ownership = FALSE;
3861 /* Another thread owns this context */
3862 LOCK_CONTEXT (loop->context);
3864 g_atomic_int_inc (&loop->ref_count);
3866 if (!loop->is_running)
3867 loop->is_running = TRUE;
3869 while (loop->is_running && !got_ownership)
3870 got_ownership = g_main_context_wait (loop->context,
3871 &loop->context->cond,
3872 &loop->context->mutex);
3874 if (!loop->is_running)
3876 UNLOCK_CONTEXT (loop->context);
3878 g_main_context_release (loop->context);
3879 g_main_loop_unref (loop);
3883 g_assert (got_ownership);
3886 LOCK_CONTEXT (loop->context);
3888 if (loop->context->in_check_or_prepare)
3890 g_warning ("g_main_loop_run(): called recursively from within a source's "
3891 "check() or prepare() member, iteration not possible.");
3895 g_atomic_int_inc (&loop->ref_count);
3896 loop->is_running = TRUE;
3897 while (loop->is_running)
3898 g_main_context_iterate (loop->context, TRUE, TRUE, self);
3900 UNLOCK_CONTEXT (loop->context);
3902 g_main_context_release (loop->context);
3904 g_main_loop_unref (loop);
3909 * @loop: a #GMainLoop
3911 * Stops a #GMainLoop from running. Any calls to g_main_loop_run()
3912 * for the loop will return.
3914 * Note that sources that have already been dispatched when
3915 * g_main_loop_quit() is called will still be executed.
3918 g_main_loop_quit (GMainLoop *loop)
3920 g_return_if_fail (loop != NULL);
3921 g_return_if_fail (g_atomic_int_get (&loop->ref_count) > 0);
3923 LOCK_CONTEXT (loop->context);
3924 loop->is_running = FALSE;
3925 g_wakeup_signal (loop->context->wakeup);
3927 g_cond_broadcast (&loop->context->cond);
3929 UNLOCK_CONTEXT (loop->context);
3933 * g_main_loop_is_running:
3934 * @loop: a #GMainLoop.
3936 * Checks to see if the main loop is currently being run via g_main_loop_run().
3938 * Return value: %TRUE if the mainloop is currently being run.
3941 g_main_loop_is_running (GMainLoop *loop)
3943 g_return_val_if_fail (loop != NULL, FALSE);
3944 g_return_val_if_fail (g_atomic_int_get (&loop->ref_count) > 0, FALSE);
3946 return loop->is_running;
3950 * g_main_loop_get_context:
3951 * @loop: a #GMainLoop.
3953 * Returns the #GMainContext of @loop.
3955 * Return value: (transfer none): the #GMainContext of @loop
3958 g_main_loop_get_context (GMainLoop *loop)
3960 g_return_val_if_fail (loop != NULL, NULL);
3961 g_return_val_if_fail (g_atomic_int_get (&loop->ref_count) > 0, NULL);
3963 return loop->context;
3966 /* HOLDS: context's lock */
3968 g_main_context_poll (GMainContext *context,
3974 #ifdef G_MAIN_POLL_DEBUG
3980 GPollFunc poll_func;
3982 if (n_fds || timeout != 0)
3984 #ifdef G_MAIN_POLL_DEBUG
3985 if (_g_main_poll_debug)
3987 g_print ("polling context=%p n=%d timeout=%d\n",
3988 context, n_fds, timeout);
3989 poll_timer = g_timer_new ();
3993 LOCK_CONTEXT (context);
3995 poll_func = context->poll_func;
3997 UNLOCK_CONTEXT (context);
3998 if ((*poll_func) (fds, n_fds, timeout) < 0 && errno != EINTR)
4001 g_warning ("poll(2) failed due to: %s.",
4002 g_strerror (errno));
4004 /* If g_poll () returns -1, it has already called g_warning() */
4008 #ifdef G_MAIN_POLL_DEBUG
4009 if (_g_main_poll_debug)
4011 LOCK_CONTEXT (context);
4013 g_print ("g_main_poll(%d) timeout: %d - elapsed %12.10f seconds",
4016 g_timer_elapsed (poll_timer, NULL));
4017 g_timer_destroy (poll_timer);
4018 pollrec = context->poll_records;
4020 while (pollrec != NULL)
4025 if (fds[i].fd == pollrec->fd->fd &&
4026 pollrec->fd->events &&
4029 g_print (" [" G_POLLFD_FORMAT " :", fds[i].fd);
4030 if (fds[i].revents & G_IO_IN)
4032 if (fds[i].revents & G_IO_OUT)
4034 if (fds[i].revents & G_IO_PRI)
4036 if (fds[i].revents & G_IO_ERR)
4038 if (fds[i].revents & G_IO_HUP)
4040 if (fds[i].revents & G_IO_NVAL)
4046 pollrec = pollrec->next;
4050 UNLOCK_CONTEXT (context);
4053 } /* if (n_fds || timeout != 0) */
4057 * g_main_context_add_poll:
4058 * @context: (allow-none): a #GMainContext (or %NULL for the default context)
4059 * @fd: a #GPollFD structure holding information about a file
4060 * descriptor to watch.
4061 * @priority: the priority for this file descriptor which should be
4062 * the same as the priority used for g_source_attach() to ensure that the
4063 * file descriptor is polled whenever the results may be needed.
4065 * Adds a file descriptor to the set of file descriptors polled for
4066 * this context. This will very seldom be used directly. Instead
4067 * a typical event source will use g_source_add_unix_fd() instead.
4070 g_main_context_add_poll (GMainContext *context,
4075 context = g_main_context_default ();
4077 g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
4078 g_return_if_fail (fd);
4080 LOCK_CONTEXT (context);
4081 g_main_context_add_poll_unlocked (context, priority, fd);
4082 UNLOCK_CONTEXT (context);
4085 /* HOLDS: main_loop_lock */
4087 g_main_context_add_poll_unlocked (GMainContext *context,
4091 GPollRec *prevrec, *nextrec;
4092 GPollRec *newrec = g_slice_new (GPollRec);
4094 /* This file descriptor may be checked before we ever poll */
4097 newrec->priority = priority;
4099 prevrec = context->poll_records_tail;
4101 while (prevrec && priority < prevrec->priority)
4104 prevrec = prevrec->prev;
4108 prevrec->next = newrec;
4110 context->poll_records = newrec;
4112 newrec->prev = prevrec;
4113 newrec->next = nextrec;
4116 nextrec->prev = newrec;
4118 context->poll_records_tail = newrec;
4120 context->n_poll_records++;
4122 context->poll_changed = TRUE;
4124 /* Now wake up the main loop if it is waiting in the poll() */
4125 g_wakeup_signal (context->wakeup);
4129 * g_main_context_remove_poll:
4130 * @context:a #GMainContext
4131 * @fd: a #GPollFD descriptor previously added with g_main_context_add_poll()
4133 * Removes file descriptor from the set of file descriptors to be
4134 * polled for a particular context.
4137 g_main_context_remove_poll (GMainContext *context,
4141 context = g_main_context_default ();
4143 g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
4144 g_return_if_fail (fd);
4146 LOCK_CONTEXT (context);
4147 g_main_context_remove_poll_unlocked (context, fd);
4148 UNLOCK_CONTEXT (context);
4152 g_main_context_remove_poll_unlocked (GMainContext *context,
4155 GPollRec *pollrec, *prevrec, *nextrec;
4158 pollrec = context->poll_records;
4162 nextrec = pollrec->next;
4163 if (pollrec->fd == fd)
4165 if (prevrec != NULL)
4166 prevrec->next = nextrec;
4168 context->poll_records = nextrec;
4170 if (nextrec != NULL)
4171 nextrec->prev = prevrec;
4173 context->poll_records_tail = prevrec;
4175 g_slice_free (GPollRec, pollrec);
4177 context->n_poll_records--;
4184 context->poll_changed = TRUE;
4186 /* Now wake up the main loop if it is waiting in the poll() */
4187 g_wakeup_signal (context->wakeup);
4191 * g_source_get_current_time:
4192 * @source: a #GSource
4193 * @timeval: #GTimeVal structure in which to store current time.
4195 * This function ignores @source and is otherwise the same as
4196 * g_get_current_time().
4198 * Deprecated: 2.28: use g_source_get_time() instead
4201 g_source_get_current_time (GSource *source,
4204 g_get_current_time (timeval);
4208 * g_source_get_time:
4209 * @source: a #GSource
4211 * Gets the time to be used when checking this source. The advantage of
4212 * calling this function over calling g_get_monotonic_time() directly is
4213 * that when checking multiple sources, GLib can cache a single value
4214 * instead of having to repeatedly get the system monotonic time.
4216 * The time here is the system monotonic time, if available, or some
4217 * other reasonable alternative otherwise. See g_get_monotonic_time().
4219 * Returns: the monotonic time in microseconds
4224 g_source_get_time (GSource *source)
4226 GMainContext *context;
4229 g_return_val_if_fail (source->context != NULL, 0);
4231 context = source->context;
4233 LOCK_CONTEXT (context);
4235 if (!context->time_is_fresh)
4237 context->time = g_get_monotonic_time ();
4238 context->time_is_fresh = TRUE;
4241 result = context->time;
4243 UNLOCK_CONTEXT (context);
4249 * g_main_context_set_poll_func:
4250 * @context: a #GMainContext
4251 * @func: the function to call to poll all file descriptors
4253 * Sets the function to use to handle polling of file descriptors. It
4254 * will be used instead of the poll() system call
4255 * (or GLib's replacement function, which is used where
4256 * poll() isn't available).
4258 * This function could possibly be used to integrate the GLib event
4259 * loop with an external event loop.
4262 g_main_context_set_poll_func (GMainContext *context,
4266 context = g_main_context_default ();
4268 g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
4270 LOCK_CONTEXT (context);
4273 context->poll_func = func;
4275 context->poll_func = g_poll;
4277 UNLOCK_CONTEXT (context);
4281 * g_main_context_get_poll_func:
4282 * @context: a #GMainContext
4284 * Gets the poll function set by g_main_context_set_poll_func().
4286 * Return value: the poll function
4289 g_main_context_get_poll_func (GMainContext *context)
4294 context = g_main_context_default ();
4296 g_return_val_if_fail (g_atomic_int_get (&context->ref_count) > 0, NULL);
4298 LOCK_CONTEXT (context);
4299 result = context->poll_func;
4300 UNLOCK_CONTEXT (context);
4306 * g_main_context_wakeup:
4307 * @context: a #GMainContext
4309 * If @context is currently blocking in g_main_context_iteration()
4310 * waiting for a source to become ready, cause it to stop blocking
4311 * and return. Otherwise, cause the next invocation of
4312 * g_main_context_iteration() to return without blocking.
4314 * This API is useful for low-level control over #GMainContext; for
4315 * example, integrating it with main loop implementations such as
4318 * Another related use for this function is when implementing a main
4319 * loop with a termination condition, computed from multiple threads:
4322 * #define NUM_TASKS 10
4323 * static volatile gint tasks_remaining = NUM_TASKS;
4326 * while (g_atomic_int_get (&tasks_remaining) != 0)
4327 * g_main_context_iteration (NULL, TRUE);
4334 * if (g_atomic_int_dec_and_test (&tasks_remaining))
4335 * g_main_context_wakeup (NULL);
4339 g_main_context_wakeup (GMainContext *context)
4342 context = g_main_context_default ();
4344 g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
4346 g_wakeup_signal (context->wakeup);
4350 * g_main_context_is_owner:
4351 * @context: a #GMainContext
4353 * Determines whether this thread holds the (recursive)
4354 * ownership of this #GMainContext. This is useful to
4355 * know before waiting on another thread that may be
4356 * blocking to get ownership of @context.
4358 * Returns: %TRUE if current thread is owner of @context.
4363 g_main_context_is_owner (GMainContext *context)
4368 context = g_main_context_default ();
4370 LOCK_CONTEXT (context);
4371 is_owner = context->owner == G_THREAD_SELF;
4372 UNLOCK_CONTEXT (context);
4380 g_timeout_set_expiration (GTimeoutSource *timeout_source,
4381 gint64 current_time)
4385 expiration = current_time + (guint64) timeout_source->interval * 1000;
4387 if (timeout_source->seconds)
4390 static gint timer_perturb = -1;
4392 if (timer_perturb == -1)
4395 * we want a per machine/session unique 'random' value; try the dbus
4396 * address first, that has a UUID in it. If there is no dbus, use the
4397 * hostname for hashing.
4399 const char *session_bus_address = g_getenv ("DBUS_SESSION_BUS_ADDRESS");
4400 if (!session_bus_address)
4401 session_bus_address = g_getenv ("HOSTNAME");
4402 if (session_bus_address)
4403 timer_perturb = ABS ((gint) g_str_hash (session_bus_address)) % 1000000;
4408 /* We want the microseconds part of the timeout to land on the
4409 * 'timer_perturb' mark, but we need to make sure we don't try to
4410 * set the timeout in the past. We do this by ensuring that we
4411 * always only *increase* the expiration time by adding a full
4412 * second in the case that the microsecond portion decreases.
4414 expiration -= timer_perturb;
4416 remainder = expiration % 1000000;
4417 if (remainder >= 1000000/4)
4418 expiration += 1000000;
4420 expiration -= remainder;
4421 expiration += timer_perturb;
4424 g_source_set_ready_time ((GSource *) timeout_source, expiration);
4428 g_timeout_dispatch (GSource *source,
4429 GSourceFunc callback,
4432 GTimeoutSource *timeout_source = (GTimeoutSource *)source;
4437 g_warning ("Timeout source dispatched without callback\n"
4438 "You must call g_source_set_callback().");
4442 again = callback (user_data);
4445 g_timeout_set_expiration (timeout_source, g_source_get_time (source));
4451 * g_timeout_source_new:
4452 * @interval: the timeout interval in milliseconds.
4454 * Creates a new timeout source.
4456 * The source will not initially be associated with any #GMainContext
4457 * and must be added to one with g_source_attach() before it will be
4460 * The interval given is in terms of monotonic time, not wall clock
4461 * time. See g_get_monotonic_time().
4463 * Return value: the newly-created timeout source
4466 g_timeout_source_new (guint interval)
4468 GSource *source = g_source_new (&g_timeout_funcs, sizeof (GTimeoutSource));
4469 GTimeoutSource *timeout_source = (GTimeoutSource *)source;
4471 timeout_source->interval = interval;
4472 g_timeout_set_expiration (timeout_source, g_get_monotonic_time ());
4478 * g_timeout_source_new_seconds:
4479 * @interval: the timeout interval in seconds
4481 * Creates a new timeout source.
4483 * The source will not initially be associated with any #GMainContext
4484 * and must be added to one with g_source_attach() before it will be
4487 * The scheduling granularity/accuracy of this timeout source will be
4490 * The interval given in terms of monotonic time, not wall clock time.
4491 * See g_get_monotonic_time().
4493 * Return value: the newly-created timeout source
4498 g_timeout_source_new_seconds (guint interval)
4500 GSource *source = g_source_new (&g_timeout_funcs, sizeof (GTimeoutSource));
4501 GTimeoutSource *timeout_source = (GTimeoutSource *)source;
4503 timeout_source->interval = 1000 * interval;
4504 timeout_source->seconds = TRUE;
4506 g_timeout_set_expiration (timeout_source, g_get_monotonic_time ());
4513 * g_timeout_add_full:
4514 * @priority: the priority of the timeout source. Typically this will be in
4515 * the range between #G_PRIORITY_DEFAULT and #G_PRIORITY_HIGH.
4516 * @interval: the time between calls to the function, in milliseconds
4517 * (1/1000ths of a second)
4518 * @function: function to call
4519 * @data: data to pass to @function
4520 * @notify: (allow-none): function to call when the timeout is removed, or %NULL
4522 * Sets a function to be called at regular intervals, with the given
4523 * priority. The function is called repeatedly until it returns
4524 * %FALSE, at which point the timeout is automatically destroyed and
4525 * the function will not be called again. The @notify function is
4526 * called when the timeout is destroyed. The first call to the
4527 * function will be at the end of the first @interval.
4529 * Note that timeout functions may be delayed, due to the processing of other
4530 * event sources. Thus they should not be relied on for precise timing.
4531 * After each call to the timeout function, the time of the next
4532 * timeout is recalculated based on the current time and the given interval
4533 * (it does not try to 'catch up' time lost in delays).
4535 * This internally creates a main loop source using g_timeout_source_new()
4536 * and attaches it to the main loop context using g_source_attach(). You can
4537 * do these steps manually if you need greater control.
4539 * The interval given in terms of monotonic time, not wall clock time.
4540 * See g_get_monotonic_time().
4542 * Return value: the ID (greater than 0) of the event source.
4543 * Rename to: g_timeout_add
4546 g_timeout_add_full (gint priority,
4548 GSourceFunc function,
4550 GDestroyNotify notify)
4555 g_return_val_if_fail (function != NULL, 0);
4557 source = g_timeout_source_new (interval);
4559 if (priority != G_PRIORITY_DEFAULT)
4560 g_source_set_priority (source, priority);
4562 g_source_set_callback (source, function, data, notify);
4563 id = g_source_attach (source, NULL);
4564 g_source_unref (source);
4571 * @interval: the time between calls to the function, in milliseconds
4572 * (1/1000ths of a second)
4573 * @function: function to call
4574 * @data: data to pass to @function
4576 * Sets a function to be called at regular intervals, with the default
4577 * priority, #G_PRIORITY_DEFAULT. The function is called repeatedly
4578 * until it returns %FALSE, at which point the timeout is automatically
4579 * destroyed and the function will not be called again. The first call
4580 * to the function will be at the end of the first @interval.
4582 * Note that timeout functions may be delayed, due to the processing of other
4583 * event sources. Thus they should not be relied on for precise timing.
4584 * After each call to the timeout function, the time of the next
4585 * timeout is recalculated based on the current time and the given interval
4586 * (it does not try to 'catch up' time lost in delays).
4588 * If you want to have a timer in the "seconds" range and do not care
4589 * about the exact time of the first call of the timer, use the
4590 * g_timeout_add_seconds() function; this function allows for more
4591 * optimizations and more efficient system power usage.
4593 * This internally creates a main loop source using g_timeout_source_new()
4594 * and attaches it to the main loop context using g_source_attach(). You can
4595 * do these steps manually if you need greater control.
4597 * The interval given is in terms of monotonic time, not wall clock
4598 * time. See g_get_monotonic_time().
4600 * Return value: the ID (greater than 0) of the event source.
4603 g_timeout_add (guint32 interval,
4604 GSourceFunc function,
4607 return g_timeout_add_full (G_PRIORITY_DEFAULT,
4608 interval, function, data, NULL);
4612 * g_timeout_add_seconds_full:
4613 * @priority: the priority of the timeout source. Typically this will be in
4614 * the range between #G_PRIORITY_DEFAULT and #G_PRIORITY_HIGH.
4615 * @interval: the time between calls to the function, in seconds
4616 * @function: function to call
4617 * @data: data to pass to @function
4618 * @notify: (allow-none): function to call when the timeout is removed, or %NULL
4620 * Sets a function to be called at regular intervals, with @priority.
4621 * The function is called repeatedly until it returns %FALSE, at which
4622 * point the timeout is automatically destroyed and the function will
4623 * not be called again.
4625 * Unlike g_timeout_add(), this function operates at whole second granularity.
4626 * The initial starting point of the timer is determined by the implementation
4627 * and the implementation is expected to group multiple timers together so that
4628 * they fire all at the same time.
4629 * To allow this grouping, the @interval to the first timer is rounded
4630 * and can deviate up to one second from the specified interval.
4631 * Subsequent timer iterations will generally run at the specified interval.
4633 * Note that timeout functions may be delayed, due to the processing of other
4634 * event sources. Thus they should not be relied on for precise timing.
4635 * After each call to the timeout function, the time of the next
4636 * timeout is recalculated based on the current time and the given @interval
4638 * If you want timing more precise than whole seconds, use g_timeout_add()
4641 * The grouping of timers to fire at the same time results in a more power
4642 * and CPU efficient behavior so if your timer is in multiples of seconds
4643 * and you don't require the first timer exactly one second from now, the
4644 * use of g_timeout_add_seconds() is preferred over g_timeout_add().
4646 * This internally creates a main loop source using
4647 * g_timeout_source_new_seconds() and attaches it to the main loop context
4648 * using g_source_attach(). You can do these steps manually if you need
4651 * The interval given is in terms of monotonic time, not wall clock
4652 * time. See g_get_monotonic_time().
4654 * Return value: the ID (greater than 0) of the event source.
4656 * Rename to: g_timeout_add_seconds
4660 g_timeout_add_seconds_full (gint priority,
4662 GSourceFunc function,
4664 GDestroyNotify notify)
4669 g_return_val_if_fail (function != NULL, 0);
4671 source = g_timeout_source_new_seconds (interval);
4673 if (priority != G_PRIORITY_DEFAULT)
4674 g_source_set_priority (source, priority);
4676 g_source_set_callback (source, function, data, notify);
4677 id = g_source_attach (source, NULL);
4678 g_source_unref (source);
4684 * g_timeout_add_seconds:
4685 * @interval: the time between calls to the function, in seconds
4686 * @function: function to call
4687 * @data: data to pass to @function
4689 * Sets a function to be called at regular intervals with the default
4690 * priority, #G_PRIORITY_DEFAULT. The function is called repeatedly until
4691 * it returns %FALSE, at which point the timeout is automatically destroyed
4692 * and the function will not be called again.
4694 * This internally creates a main loop source using
4695 * g_timeout_source_new_seconds() and attaches it to the main loop context
4696 * using g_source_attach(). You can do these steps manually if you need
4697 * greater control. Also see g_timeout_add_seconds_full().
4699 * Note that the first call of the timer may not be precise for timeouts
4700 * of one second. If you need finer precision and have such a timeout,
4701 * you may want to use g_timeout_add() instead.
4703 * The interval given is in terms of monotonic time, not wall clock
4704 * time. See g_get_monotonic_time().
4706 * Return value: the ID (greater than 0) of the event source.
4711 g_timeout_add_seconds (guint interval,
4712 GSourceFunc function,
4715 g_return_val_if_fail (function != NULL, 0);
4717 return g_timeout_add_seconds_full (G_PRIORITY_DEFAULT, interval, function, data, NULL);
4720 /* Child watch functions */
4725 g_child_watch_prepare (GSource *source,
4733 g_child_watch_check (GSource *source)
4735 GChildWatchSource *child_watch_source;
4736 gboolean child_exited;
4738 child_watch_source = (GChildWatchSource *) source;
4740 child_exited = child_watch_source->poll.revents & G_IO_IN;
4747 * Note: We do _not_ check for the special value of STILL_ACTIVE
4748 * since we know that the process has exited and doing so runs into
4749 * problems if the child process "happens to return STILL_ACTIVE(259)"
4750 * as Microsoft's Platform SDK puts it.
4752 if (!GetExitCodeProcess (child_watch_source->pid, &child_status))
4754 gchar *emsg = g_win32_error_message (GetLastError ());
4755 g_warning (G_STRLOC ": GetExitCodeProcess() failed: %s", emsg);
4758 child_watch_source->child_status = -1;
4761 child_watch_source->child_status = child_status;
4764 return child_exited;
4768 g_child_watch_finalize (GSource *source)
4772 #else /* G_OS_WIN32 */
4775 wake_source (GSource *source)
4777 GMainContext *context;
4779 /* This should be thread-safe:
4781 * - if the source is currently being added to a context, that
4782 * context will be woken up anyway
4784 * - if the source is currently being destroyed, we simply need not
4787 * - the memory for the source will remain valid until after the
4788 * source finalize function was called (which would remove the
4789 * source from the global list which we are currently holding the
4792 * - the GMainContext will either be NULL or point to a live
4795 * - the GMainContext will remain valid since we hold the
4796 * main_context_list lock
4798 * Since we are holding a lot of locks here, don't try to enter any
4799 * more GMainContext functions for fear of dealock -- just hit the
4800 * GWakeup and run. Even if that's safe now, it could easily become
4801 * unsafe with some very minor changes in the future, and signal
4802 * handling is not the most well-tested codepath.
4804 G_LOCK(main_context_list);
4805 context = source->context;
4807 g_wakeup_signal (context->wakeup);
4808 G_UNLOCK(main_context_list);
4812 dispatch_unix_signals (void)
4816 /* clear this first incase another one arrives while we're processing */
4817 any_unix_signal_pending = FALSE;
4819 G_LOCK(unix_signal_lock);
4821 /* handle GChildWatchSource instances */
4822 if (unix_signal_pending[SIGCHLD])
4824 /* The only way we can do this is to scan all of the children.
4826 * The docs promise that we will not reap children that we are not
4827 * explicitly watching, so that ties our hands from calling
4828 * waitpid(-1). We also can't use siginfo's si_pid field since if
4829 * multiple SIGCHLD arrive at the same time, one of them can be
4830 * dropped (since a given UNIX signal can only be pending once).
4832 for (node = unix_child_watches; node; node = node->next)
4834 GChildWatchSource *source = node->data;
4836 if (!source->child_exited)
4841 pid = waitpid (source->pid, &source->child_status, WNOHANG);
4844 source->child_exited = TRUE;
4845 wake_source ((GSource *) source);
4847 else if (pid == -1 && errno == ECHILD)
4849 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.");
4850 source->child_exited = TRUE;
4851 source->child_status = 0;
4852 wake_source ((GSource *) source);
4855 while (pid == -1 && errno == EINTR);
4860 /* handle GUnixSignalWatchSource instances */
4861 for (node = unix_signal_watches; node; node = node->next)
4863 GUnixSignalWatchSource *source = node->data;
4865 if (!source->pending)
4867 if (unix_signal_pending[source->signum])
4869 source->pending = TRUE;
4871 wake_source ((GSource *) source);
4876 memset ((void*)unix_signal_pending, 0, sizeof (unix_signal_pending));
4878 G_UNLOCK(unix_signal_lock);
4882 g_child_watch_prepare (GSource *source,
4885 GChildWatchSource *child_watch_source;
4887 child_watch_source = (GChildWatchSource *) source;
4889 return child_watch_source->child_exited;
4893 g_child_watch_check (GSource *source)
4895 GChildWatchSource *child_watch_source;
4897 child_watch_source = (GChildWatchSource *) source;
4899 return child_watch_source->child_exited;
4903 g_unix_signal_watch_prepare (GSource *source,
4906 GUnixSignalWatchSource *unix_signal_source;
4908 unix_signal_source = (GUnixSignalWatchSource *) source;
4910 return unix_signal_source->pending;
4914 g_unix_signal_watch_check (GSource *source)
4916 GUnixSignalWatchSource *unix_signal_source;
4918 unix_signal_source = (GUnixSignalWatchSource *) source;
4920 return unix_signal_source->pending;
4924 g_unix_signal_watch_dispatch (GSource *source,
4925 GSourceFunc callback,
4928 GUnixSignalWatchSource *unix_signal_source;
4931 unix_signal_source = (GUnixSignalWatchSource *) source;
4935 g_warning ("Unix signal source dispatched without callback\n"
4936 "You must call g_source_set_callback().");
4940 again = (callback) (user_data);
4942 unix_signal_source->pending = FALSE;
4948 ref_unix_signal_handler_unlocked (int signum)
4950 /* Ensure we have the worker context */
4951 g_get_worker_context ();
4952 unix_signal_refcount[signum]++;
4953 if (unix_signal_refcount[signum] == 1)
4955 struct sigaction action;
4956 action.sa_handler = g_unix_signal_handler;
4957 sigemptyset (&action.sa_mask);
4959 action.sa_flags = SA_RESTART | SA_NOCLDSTOP;
4961 action.sa_flags = SA_NOCLDSTOP;
4963 sigaction (signum, &action, NULL);
4968 unref_unix_signal_handler_unlocked (int signum)
4970 unix_signal_refcount[signum]--;
4971 if (unix_signal_refcount[signum] == 0)
4973 struct sigaction action;
4974 action.sa_handler = SIG_DFL;
4975 sigemptyset (&action.sa_mask);
4976 sigaction (signum, &action, NULL);
4981 _g_main_create_unix_signal_watch (int signum)
4984 GUnixSignalWatchSource *unix_signal_source;
4986 source = g_source_new (&g_unix_signal_funcs, sizeof (GUnixSignalWatchSource));
4987 unix_signal_source = (GUnixSignalWatchSource *) source;
4989 unix_signal_source->signum = signum;
4990 unix_signal_source->pending = FALSE;
4992 G_LOCK (unix_signal_lock);
4993 ref_unix_signal_handler_unlocked (signum);
4994 unix_signal_watches = g_slist_prepend (unix_signal_watches, unix_signal_source);
4995 if (unix_signal_pending[signum])
4996 unix_signal_source->pending = TRUE;
4997 G_UNLOCK (unix_signal_lock);
5003 g_unix_signal_watch_finalize (GSource *source)
5005 GUnixSignalWatchSource *unix_signal_source;
5007 unix_signal_source = (GUnixSignalWatchSource *) source;
5009 G_LOCK (unix_signal_lock);
5010 unref_unix_signal_handler_unlocked (unix_signal_source->signum);
5011 unix_signal_watches = g_slist_remove (unix_signal_watches, source);
5012 G_UNLOCK (unix_signal_lock);
5016 g_child_watch_finalize (GSource *source)
5018 G_LOCK (unix_signal_lock);
5019 unix_child_watches = g_slist_remove (unix_child_watches, source);
5020 unref_unix_signal_handler_unlocked (SIGCHLD);
5021 G_UNLOCK (unix_signal_lock);
5024 #endif /* G_OS_WIN32 */
5027 g_child_watch_dispatch (GSource *source,
5028 GSourceFunc callback,
5031 GChildWatchSource *child_watch_source;
5032 GChildWatchFunc child_watch_callback = (GChildWatchFunc) callback;
5034 child_watch_source = (GChildWatchSource *) source;
5038 g_warning ("Child watch source dispatched without callback\n"
5039 "You must call g_source_set_callback().");
5043 (child_watch_callback) (child_watch_source->pid, child_watch_source->child_status, user_data);
5045 /* We never keep a child watch source around as the child is gone */
5052 g_unix_signal_handler (int signum)
5054 unix_signal_pending[signum] = TRUE;
5055 any_unix_signal_pending = TRUE;
5057 g_wakeup_signal (glib_worker_context->wakeup);
5060 #endif /* !G_OS_WIN32 */
5063 * g_child_watch_source_new:
5064 * @pid: process to watch. On POSIX the pid of a child process. On
5065 * Windows a handle for a process (which doesn't have to be a child).
5067 * Creates a new child_watch source.
5069 * The source will not initially be associated with any #GMainContext
5070 * and must be added to one with g_source_attach() before it will be
5073 * Note that child watch sources can only be used in conjunction with
5074 * <literal>g_spawn...</literal> when the %G_SPAWN_DO_NOT_REAP_CHILD
5077 * Note that on platforms where #GPid must be explicitly closed
5078 * (see g_spawn_close_pid()) @pid must not be closed while the
5079 * source is still active. Typically, you will want to call
5080 * g_spawn_close_pid() in the callback function for the source.
5082 * Note further that using g_child_watch_source_new() is not
5083 * compatible with calling <literal>waitpid</literal> with a
5084 * nonpositive first argument in the application. Calling waitpid()
5085 * for individual pids will still work fine.
5087 * Return value: the newly-created child watch source
5092 g_child_watch_source_new (GPid pid)
5094 GSource *source = g_source_new (&g_child_watch_funcs, sizeof (GChildWatchSource));
5095 GChildWatchSource *child_watch_source = (GChildWatchSource *)source;
5097 child_watch_source->pid = pid;
5100 child_watch_source->poll.fd = (gintptr) pid;
5101 child_watch_source->poll.events = G_IO_IN;
5103 g_source_add_poll (source, &child_watch_source->poll);
5104 #else /* G_OS_WIN32 */
5105 G_LOCK (unix_signal_lock);
5106 ref_unix_signal_handler_unlocked (SIGCHLD);
5107 unix_child_watches = g_slist_prepend (unix_child_watches, child_watch_source);
5108 if (waitpid (pid, &child_watch_source->child_status, WNOHANG) > 0)
5109 child_watch_source->child_exited = TRUE;
5110 G_UNLOCK (unix_signal_lock);
5111 #endif /* G_OS_WIN32 */
5117 * g_child_watch_add_full:
5118 * @priority: the priority of the idle source. Typically this will be in the
5119 * range between #G_PRIORITY_DEFAULT_IDLE and #G_PRIORITY_HIGH_IDLE.
5120 * @pid: process to watch. On POSIX the pid of a child process. On
5121 * Windows a handle for a process (which doesn't have to be a child).
5122 * @function: function to call
5123 * @data: data to pass to @function
5124 * @notify: (allow-none): function to call when the idle is removed, or %NULL
5126 * Sets a function to be called when the child indicated by @pid
5127 * exits, at the priority @priority.
5129 * If you obtain @pid from g_spawn_async() or g_spawn_async_with_pipes()
5130 * you will need to pass #G_SPAWN_DO_NOT_REAP_CHILD as flag to
5131 * the spawn function for the child watching to work.
5133 * In many programs, you will want to call g_spawn_check_exit_status()
5134 * in the callback to determine whether or not the child exited
5137 * Also, note that on platforms where #GPid must be explicitly closed
5138 * (see g_spawn_close_pid()) @pid must not be closed while the source
5139 * is still active. Typically, you should invoke g_spawn_close_pid()
5140 * in the callback function for the source.
5142 * GLib supports only a single callback per process id.
5144 * This internally creates a main loop source using
5145 * g_child_watch_source_new() and attaches it to the main loop context
5146 * using g_source_attach(). You can do these steps manually if you
5147 * need greater control.
5149 * Return value: the ID (greater than 0) of the event source.
5151 * Rename to: g_child_watch_add
5155 g_child_watch_add_full (gint priority,
5157 GChildWatchFunc function,
5159 GDestroyNotify notify)
5164 g_return_val_if_fail (function != NULL, 0);
5166 source = g_child_watch_source_new (pid);
5168 if (priority != G_PRIORITY_DEFAULT)
5169 g_source_set_priority (source, priority);
5171 g_source_set_callback (source, (GSourceFunc) function, data, notify);
5172 id = g_source_attach (source, NULL);
5173 g_source_unref (source);
5179 * g_child_watch_add:
5180 * @pid: process id to watch. On POSIX the pid of a child process. On
5181 * Windows a handle for a process (which doesn't have to be a child).
5182 * @function: function to call
5183 * @data: data to pass to @function
5185 * Sets a function to be called when the child indicated by @pid
5186 * exits, at a default priority, #G_PRIORITY_DEFAULT.
5188 * If you obtain @pid from g_spawn_async() or g_spawn_async_with_pipes()
5189 * you will need to pass #G_SPAWN_DO_NOT_REAP_CHILD as flag to
5190 * the spawn function for the child watching to work.
5192 * Note that on platforms where #GPid must be explicitly closed
5193 * (see g_spawn_close_pid()) @pid must not be closed while the
5194 * source is still active. Typically, you will want to call
5195 * g_spawn_close_pid() in the callback function for the source.
5197 * GLib supports only a single callback per process id.
5199 * This internally creates a main loop source using
5200 * g_child_watch_source_new() and attaches it to the main loop context
5201 * using g_source_attach(). You can do these steps manually if you
5202 * need greater control.
5204 * Return value: the ID (greater than 0) of the event source.
5209 g_child_watch_add (GPid pid,
5210 GChildWatchFunc function,
5213 return g_child_watch_add_full (G_PRIORITY_DEFAULT, pid, function, data, NULL);
5217 /* Idle functions */
5220 g_idle_prepare (GSource *source,
5229 g_idle_check (GSource *source)
5235 g_idle_dispatch (GSource *source,
5236 GSourceFunc callback,
5241 g_warning ("Idle source dispatched without callback\n"
5242 "You must call g_source_set_callback().");
5246 return callback (user_data);
5250 * g_idle_source_new:
5252 * Creates a new idle source.
5254 * The source will not initially be associated with any #GMainContext
5255 * and must be added to one with g_source_attach() before it will be
5256 * executed. Note that the default priority for idle sources is
5257 * %G_PRIORITY_DEFAULT_IDLE, as compared to other sources which
5258 * have a default priority of %G_PRIORITY_DEFAULT.
5260 * Return value: the newly-created idle source
5263 g_idle_source_new (void)
5267 source = g_source_new (&g_idle_funcs, sizeof (GSource));
5268 g_source_set_priority (source, G_PRIORITY_DEFAULT_IDLE);
5275 * @priority: the priority of the idle source. Typically this will be in the
5276 * range between #G_PRIORITY_DEFAULT_IDLE and #G_PRIORITY_HIGH_IDLE.
5277 * @function: function to call
5278 * @data: data to pass to @function
5279 * @notify: (allow-none): function to call when the idle is removed, or %NULL
5281 * Adds a function to be called whenever there are no higher priority
5282 * events pending. If the function returns %FALSE it is automatically
5283 * removed from the list of event sources and will not be called again.
5285 * This internally creates a main loop source using g_idle_source_new()
5286 * and attaches it to the main loop context using g_source_attach().
5287 * You can do these steps manually if you need greater control.
5289 * Return value: the ID (greater than 0) of the event source.
5290 * Rename to: g_idle_add
5293 g_idle_add_full (gint priority,
5294 GSourceFunc function,
5296 GDestroyNotify notify)
5301 g_return_val_if_fail (function != NULL, 0);
5303 source = g_idle_source_new ();
5305 if (priority != G_PRIORITY_DEFAULT_IDLE)
5306 g_source_set_priority (source, priority);
5308 g_source_set_callback (source, function, data, notify);
5309 id = g_source_attach (source, NULL);
5310 g_source_unref (source);
5317 * @function: function to call
5318 * @data: data to pass to @function.
5320 * Adds a function to be called whenever there are no higher priority
5321 * events pending to the default main loop. The function is given the
5322 * default idle priority, #G_PRIORITY_DEFAULT_IDLE. If the function
5323 * returns %FALSE it is automatically removed from the list of event
5324 * sources and will not be called again.
5326 * This internally creates a main loop source using g_idle_source_new()
5327 * and attaches it to the main loop context using g_source_attach().
5328 * You can do these steps manually if you need greater control.
5330 * Return value: the ID (greater than 0) of the event source.
5333 g_idle_add (GSourceFunc function,
5336 return g_idle_add_full (G_PRIORITY_DEFAULT_IDLE, function, data, NULL);
5340 * g_idle_remove_by_data:
5341 * @data: the data for the idle source's callback.
5343 * Removes the idle function with the given data.
5345 * Return value: %TRUE if an idle source was found and removed.
5348 g_idle_remove_by_data (gpointer data)
5350 return g_source_remove_by_funcs_user_data (&g_idle_funcs, data);
5354 * g_main_context_invoke:
5355 * @context: (allow-none): a #GMainContext, or %NULL
5356 * @function: function to call
5357 * @data: data to pass to @function
5359 * Invokes a function in such a way that @context is owned during the
5360 * invocation of @function.
5362 * If @context is %NULL then the global default main context — as
5363 * returned by g_main_context_default() — is used.
5365 * If @context is owned by the current thread, @function is called
5366 * directly. Otherwise, if @context is the thread-default main context
5367 * of the current thread and g_main_context_acquire() succeeds, then
5368 * @function is called and g_main_context_release() is called
5371 * In any other case, an idle source is created to call @function and
5372 * that source is attached to @context (presumably to be run in another
5373 * thread). The idle source is attached with #G_PRIORITY_DEFAULT
5374 * priority. If you want a different priority, use
5375 * g_main_context_invoke_full().
5377 * Note that, as with normal idle functions, @function should probably
5378 * return %FALSE. If it returns %TRUE, it will be continuously run in a
5379 * loop (and may prevent this call from returning).
5384 g_main_context_invoke (GMainContext *context,
5385 GSourceFunc function,
5388 g_main_context_invoke_full (context,
5390 function, data, NULL);
5394 * g_main_context_invoke_full:
5395 * @context: (allow-none): a #GMainContext, or %NULL
5396 * @priority: the priority at which to run @function
5397 * @function: function to call
5398 * @data: data to pass to @function
5399 * @notify: (allow-none): a function to call when @data is no longer in use, or %NULL.
5401 * Invokes a function in such a way that @context is owned during the
5402 * invocation of @function.
5404 * This function is the same as g_main_context_invoke() except that it
5405 * lets you specify the priority incase @function ends up being
5406 * scheduled as an idle and also lets you give a #GDestroyNotify for @data.
5408 * @notify should not assume that it is called from any particular
5409 * thread or with any particular context acquired.
5414 g_main_context_invoke_full (GMainContext *context,
5416 GSourceFunc function,
5418 GDestroyNotify notify)
5420 g_return_if_fail (function != NULL);
5423 context = g_main_context_default ();
5425 if (g_main_context_is_owner (context))
5427 while (function (data));
5434 GMainContext *thread_default;
5436 thread_default = g_main_context_get_thread_default ();
5438 if (!thread_default)
5439 thread_default = g_main_context_default ();
5441 if (thread_default == context && g_main_context_acquire (context))
5443 while (function (data));
5445 g_main_context_release (context);
5454 source = g_idle_source_new ();
5455 g_source_set_priority (source, priority);
5456 g_source_set_callback (source, function, data, notify);
5457 g_source_attach (source, context);
5458 g_source_unref (source);
5464 glib_worker_main (gpointer data)
5468 g_main_context_iteration (glib_worker_context, TRUE);
5471 if (any_unix_signal_pending)
5472 dispatch_unix_signals ();
5476 return NULL; /* worst GCC warning message ever... */
5480 g_get_worker_context (void)
5482 static gsize initialised;
5484 if (g_once_init_enter (&initialised))
5486 /* mask all signals in the worker thread */
5492 pthread_sigmask (SIG_SETMASK, &all, &prev_mask);
5494 glib_worker_context = g_main_context_new ();
5495 g_thread_new ("gmain", glib_worker_main, NULL);
5497 pthread_sigmask (SIG_SETMASK, &prev_mask, NULL);
5499 g_once_init_leave (&initialised, TRUE);
5502 return glib_worker_context;