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
220 GSList *dispatching_sources; /* stack of current sources */
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;
432 /* Guards all the data below */
433 G_LOCK_DEFINE_STATIC (unix_signal_lock);
434 static GSList *unix_signal_watches;
435 static GSList *unix_child_watches;
437 static GSourceFuncs g_unix_signal_funcs =
439 g_unix_signal_watch_prepare,
440 g_unix_signal_watch_check,
441 g_unix_signal_watch_dispatch,
442 g_unix_signal_watch_finalize
444 #endif /* !G_OS_WIN32 */
445 G_LOCK_DEFINE_STATIC (main_context_list);
446 static GSList *main_context_list = NULL;
448 GSourceFuncs g_timeout_funcs =
456 GSourceFuncs g_child_watch_funcs =
458 g_child_watch_prepare,
460 g_child_watch_dispatch,
461 g_child_watch_finalize
464 GSourceFuncs g_idle_funcs =
473 * g_main_context_ref:
474 * @context: a #GMainContext
476 * Increases the reference count on a #GMainContext object by one.
478 * Returns: the @context that was passed in (since 2.6)
481 g_main_context_ref (GMainContext *context)
483 g_return_val_if_fail (context != NULL, NULL);
484 g_return_val_if_fail (g_atomic_int_get (&context->ref_count) > 0, NULL);
486 g_atomic_int_inc (&context->ref_count);
492 poll_rec_list_free (GMainContext *context,
495 g_slice_free_chain (GPollRec, list, next);
499 * g_main_context_unref:
500 * @context: a #GMainContext
502 * Decreases the reference count on a #GMainContext object by one. If
503 * the result is zero, free the context and free all associated memory.
506 g_main_context_unref (GMainContext *context)
513 g_return_if_fail (context != NULL);
514 g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
516 if (!g_atomic_int_dec_and_test (&context->ref_count))
519 G_LOCK (main_context_list);
520 main_context_list = g_slist_remove (main_context_list, context);
521 G_UNLOCK (main_context_list);
523 g_source_iter_init (&iter, context, TRUE);
524 while (g_source_iter_next (&iter, &source))
526 source->context = NULL;
527 g_source_destroy_internal (source, context, FALSE);
529 for (sl_iter = context->source_lists; sl_iter; sl_iter = sl_iter->next)
531 list = sl_iter->data;
532 g_slice_free (GSourceList, list);
534 g_list_free (context->source_lists);
536 if (context->overflow_used_source_ids)
537 g_hash_table_destroy (context->overflow_used_source_ids);
539 g_mutex_clear (&context->mutex);
541 g_ptr_array_free (context->pending_dispatches, TRUE);
542 g_free (context->cached_poll_array);
544 poll_rec_list_free (context, context->poll_records);
546 g_wakeup_free (context->wakeup);
547 g_cond_clear (&context->cond);
552 /* Helper function used by mainloop/overflow test.
555 g_main_context_new_with_next_id (guint next_id)
557 GMainContext *ret = g_main_context_new ();
559 ret->next_id = next_id;
565 * g_main_context_new:
567 * Creates a new #GMainContext structure.
569 * Return value: the new #GMainContext
572 g_main_context_new (void)
574 static gsize initialised;
575 GMainContext *context;
577 if (g_once_init_enter (&initialised))
579 #ifdef G_MAIN_POLL_DEBUG
580 if (getenv ("G_MAIN_POLL_DEBUG") != NULL)
581 _g_main_poll_debug = TRUE;
584 g_once_init_leave (&initialised, TRUE);
587 context = g_new0 (GMainContext, 1);
589 g_mutex_init (&context->mutex);
590 g_cond_init (&context->cond);
592 context->owner = NULL;
593 context->waiters = NULL;
595 context->ref_count = 1;
597 context->next_id = 1;
599 context->source_lists = NULL;
601 context->poll_func = g_poll;
603 context->cached_poll_array = NULL;
604 context->cached_poll_array_size = 0;
606 context->pending_dispatches = g_ptr_array_new ();
608 context->time_is_fresh = FALSE;
610 context->wakeup = g_wakeup_new ();
611 g_wakeup_get_pollfd (context->wakeup, &context->wake_up_rec);
612 g_main_context_add_poll_unlocked (context, 0, &context->wake_up_rec);
614 G_LOCK (main_context_list);
615 main_context_list = g_slist_append (main_context_list, context);
617 #ifdef G_MAIN_POLL_DEBUG
618 if (_g_main_poll_debug)
619 g_print ("created context=%p\n", context);
622 G_UNLOCK (main_context_list);
628 * g_main_context_default:
630 * Returns the global default main context. This is the main context
631 * used for main loop functions when a main loop is not explicitly
632 * specified, and corresponds to the "main" main loop. See also
633 * g_main_context_get_thread_default().
635 * Return value: (transfer none): the global default main context.
638 g_main_context_default (void)
644 if (!default_main_context)
646 default_main_context = g_main_context_new ();
647 #ifdef G_MAIN_POLL_DEBUG
648 if (_g_main_poll_debug)
649 g_print ("default context=%p\n", default_main_context);
653 G_UNLOCK (main_loop);
655 return default_main_context;
659 free_context (gpointer data)
661 GMainContext *context = data;
663 g_main_context_release (context);
665 g_main_context_unref (context);
669 free_context_stack (gpointer data)
671 g_queue_free_full((GQueue *) data, (GDestroyNotify) free_context);
674 static GPrivate thread_context_stack = G_PRIVATE_INIT (free_context_stack);
677 * g_main_context_push_thread_default:
678 * @context: (allow-none): a #GMainContext, or %NULL for the global default context
680 * Acquires @context and sets it as the thread-default context for the
681 * current thread. This will cause certain asynchronous operations
682 * (such as most <link linkend="gio">gio</link>-based I/O) which are
683 * started in this thread to run under @context and deliver their
684 * results to its main loop, rather than running under the global
685 * default context in the main thread. Note that calling this function
686 * changes the context returned by
687 * g_main_context_get_thread_default(), <emphasis>not</emphasis> the
688 * one returned by g_main_context_default(), so it does not affect the
689 * context used by functions like g_idle_add().
691 * Normally you would call this function shortly after creating a new
692 * thread, passing it a #GMainContext which will be run by a
693 * #GMainLoop in that thread, to set a new default context for all
694 * async operations in that thread. (In this case, you don't need to
695 * ever call g_main_context_pop_thread_default().) In some cases
696 * however, you may want to schedule a single operation in a
697 * non-default context, or temporarily use a non-default context in
698 * the main thread. In that case, you can wrap the call to the
699 * asynchronous operation inside a
700 * g_main_context_push_thread_default() /
701 * g_main_context_pop_thread_default() pair, but it is up to you to
702 * ensure that no other asynchronous operations accidentally get
703 * started while the non-default context is active.
705 * Beware that libraries that predate this function may not correctly
706 * handle being used from a thread with a thread-default context. Eg,
707 * see g_file_supports_thread_contexts().
712 g_main_context_push_thread_default (GMainContext *context)
715 gboolean acquired_context;
717 acquired_context = g_main_context_acquire (context);
718 g_return_if_fail (acquired_context);
720 if (context == g_main_context_default ())
723 g_main_context_ref (context);
725 stack = g_private_get (&thread_context_stack);
728 stack = g_queue_new ();
729 g_private_set (&thread_context_stack, stack);
732 g_queue_push_head (stack, context);
736 * g_main_context_pop_thread_default:
737 * @context: (allow-none): a #GMainContext object, or %NULL
739 * Pops @context off the thread-default context stack (verifying that
740 * it was on the top of the stack).
745 g_main_context_pop_thread_default (GMainContext *context)
749 if (context == g_main_context_default ())
752 stack = g_private_get (&thread_context_stack);
754 g_return_if_fail (stack != NULL);
755 g_return_if_fail (g_queue_peek_head (stack) == context);
757 g_queue_pop_head (stack);
759 g_main_context_release (context);
761 g_main_context_unref (context);
765 * g_main_context_get_thread_default:
767 * Gets the thread-default #GMainContext for this thread. Asynchronous
768 * operations that want to be able to be run in contexts other than
769 * the default one should call this method or
770 * g_main_context_ref_thread_default() to get a #GMainContext to add
771 * their #GSource<!-- -->s to. (Note that even in single-threaded
772 * programs applications may sometimes want to temporarily push a
773 * non-default context, so it is not safe to assume that this will
774 * always return %NULL if you are running in the default thread.)
776 * If you need to hold a reference on the context, use
777 * g_main_context_ref_thread_default() instead.
779 * Returns: (transfer none): the thread-default #GMainContext, or
780 * %NULL if the thread-default context is the global default context.
785 g_main_context_get_thread_default (void)
789 stack = g_private_get (&thread_context_stack);
791 return g_queue_peek_head (stack);
797 * g_main_context_ref_thread_default:
799 * Gets the thread-default #GMainContext for this thread, as with
800 * g_main_context_get_thread_default(), but also adds a reference to
801 * it with g_main_context_ref(). In addition, unlike
802 * g_main_context_get_thread_default(), if the thread-default context
803 * is the global default context, this will return that #GMainContext
804 * (with a ref added to it) rather than returning %NULL.
806 * Returns: (transfer full): the thread-default #GMainContext. Unref
807 * with g_main_context_unref() when you are done with it.
812 g_main_context_ref_thread_default (void)
814 GMainContext *context;
816 context = g_main_context_get_thread_default ();
818 context = g_main_context_default ();
819 return g_main_context_ref (context);
822 /* Hooks for adding to the main loop */
826 * @source_funcs: structure containing functions that implement
827 * the sources behavior.
828 * @struct_size: size of the #GSource structure to create.
830 * Creates a new #GSource structure. The size is specified to
831 * allow creating structures derived from #GSource that contain
832 * additional data. The size passed in must be at least
833 * <literal>sizeof (GSource)</literal>.
835 * The source will not initially be associated with any #GMainContext
836 * and must be added to one with g_source_attach() before it will be
839 * Return value: the newly-created #GSource.
842 g_source_new (GSourceFuncs *source_funcs,
847 g_return_val_if_fail (source_funcs != NULL, NULL);
848 g_return_val_if_fail (struct_size >= sizeof (GSource), NULL);
850 source = (GSource*) g_malloc0 (struct_size);
851 source->priv = g_slice_new0 (GSourcePrivate);
852 source->source_funcs = source_funcs;
853 source->ref_count = 1;
855 source->priority = G_PRIORITY_DEFAULT;
857 source->flags = G_HOOK_FLAG_ACTIVE;
859 source->priv->ready_time = -1;
861 /* NULL/0 initialization for all other fields */
866 /* Holds context's lock */
868 g_source_iter_init (GSourceIter *iter,
869 GMainContext *context,
872 iter->context = context;
873 iter->current_list = NULL;
875 iter->may_modify = may_modify;
878 /* Holds context's lock */
880 g_source_iter_next (GSourceIter *iter, GSource **source)
882 GSource *next_source;
885 next_source = iter->source->next;
891 if (iter->current_list)
892 iter->current_list = iter->current_list->next;
894 iter->current_list = iter->context->source_lists;
896 if (iter->current_list)
898 GSourceList *source_list = iter->current_list->data;
900 next_source = source_list->head;
904 /* Note: unreffing iter->source could potentially cause its
905 * GSourceList to be removed from source_lists (if iter->source is
906 * the only source in its list, and it is destroyed), so we have to
907 * keep it reffed until after we advance iter->current_list, above.
910 if (iter->source && iter->may_modify)
911 SOURCE_UNREF (iter->source, iter->context);
912 iter->source = next_source;
913 if (iter->source && iter->may_modify)
914 iter->source->ref_count++;
916 *source = iter->source;
917 return *source != NULL;
920 /* Holds context's lock. Only necessary to call if you broke out of
921 * the g_source_iter_next() loop early.
924 g_source_iter_clear (GSourceIter *iter)
926 if (iter->source && iter->may_modify)
928 SOURCE_UNREF (iter->source, iter->context);
933 /* Holds context's lock
936 find_source_list_for_priority (GMainContext *context,
941 GSourceList *source_list;
944 for (iter = context->source_lists; iter != NULL; last = iter, iter = iter->next)
946 source_list = iter->data;
948 if (source_list->priority == priority)
951 if (source_list->priority > priority)
956 source_list = g_slice_new0 (GSourceList);
957 source_list->priority = priority;
958 context->source_lists = g_list_insert_before (context->source_lists,
968 source_list = g_slice_new0 (GSourceList);
969 source_list->priority = priority;
972 context->source_lists = g_list_append (NULL, source_list);
975 /* This just appends source_list to the end of
976 * context->source_lists without having to walk the list again.
978 last = g_list_append (last, source_list);
983 /* Holds context's lock
986 source_add_to_context (GSource *source,
987 GMainContext *context)
989 GSourceList *source_list;
990 GSource *prev, *next;
992 source_list = find_source_list_for_priority (context, source->priority, TRUE);
994 if (source->priv->parent_source)
996 g_assert (source_list->head != NULL);
998 /* Put the source immediately before its parent */
999 prev = source->priv->parent_source->prev;
1000 next = source->priv->parent_source;
1004 prev = source_list->tail;
1008 source->next = next;
1010 next->prev = source;
1012 source_list->tail = source;
1014 source->prev = prev;
1016 prev->next = source;
1018 source_list->head = source;
1021 /* Holds context's lock
1024 source_remove_from_context (GSource *source,
1025 GMainContext *context)
1027 GSourceList *source_list;
1029 source_list = find_source_list_for_priority (context, source->priority, FALSE);
1030 g_return_if_fail (source_list != NULL);
1033 source->prev->next = source->next;
1035 source_list->head = source->next;
1038 source->next->prev = source->prev;
1040 source_list->tail = source->prev;
1042 source->prev = NULL;
1043 source->next = NULL;
1045 if (source_list->head == NULL)
1047 context->source_lists = g_list_remove (context->source_lists, source_list);
1048 g_slice_free (GSourceList, source_list);
1051 if (context->overflow_used_source_ids)
1052 g_hash_table_remove (context->overflow_used_source_ids,
1053 GUINT_TO_POINTER (source->source_id));
1058 assign_source_id_unlocked (GMainContext *context,
1063 /* Are we about to overflow back to 0?
1064 * See https://bugzilla.gnome.org/show_bug.cgi?id=687098
1066 if (G_UNLIKELY (context->next_id == G_MAXUINT &&
1067 context->overflow_used_source_ids == NULL))
1072 context->overflow_used_source_ids = g_hash_table_new (NULL, NULL);
1074 g_source_iter_init (&iter, context, FALSE);
1075 while (g_source_iter_next (&iter, &source))
1077 g_hash_table_add (context->overflow_used_source_ids,
1078 GUINT_TO_POINTER (source->source_id));
1082 else if (context->overflow_used_source_ids == NULL)
1084 id = context->next_id++;
1089 * If we overran G_MAXUINT, we fall back to randomly probing the
1090 * source ids for the current context. This will be slower the more
1091 * sources there are, but we're mainly concerned right now about
1092 * correctness and code size. There's time for a more clever solution
1096 id = g_random_int ();
1098 g_hash_table_contains (context->overflow_used_source_ids,
1099 GUINT_TO_POINTER (id)));
1100 g_hash_table_add (context->overflow_used_source_ids, GUINT_TO_POINTER (id));
1103 source->source_id = id;
1107 g_source_attach_unlocked (GSource *source,
1108 GMainContext *context)
1112 source->context = context;
1113 assign_source_id_unlocked (context, source);
1114 source->ref_count++;
1115 source_add_to_context (source, context);
1117 tmp_list = source->poll_fds;
1120 g_main_context_add_poll_unlocked (context, source->priority, tmp_list->data);
1121 tmp_list = tmp_list->next;
1124 for (tmp_list = source->priv->fds; tmp_list; tmp_list = tmp_list->next)
1125 g_main_context_add_poll_unlocked (context, source->priority, tmp_list->data);
1127 tmp_list = source->priv->child_sources;
1130 g_source_attach_unlocked (tmp_list->data, context);
1131 tmp_list = tmp_list->next;
1134 return source->source_id;
1139 * @source: a #GSource
1140 * @context: (allow-none): a #GMainContext (if %NULL, the default context will be used)
1142 * Adds a #GSource to a @context so that it will be executed within
1143 * that context. Remove it by calling g_source_destroy().
1145 * Return value: the ID (greater than 0) for the source within the
1149 g_source_attach (GSource *source,
1150 GMainContext *context)
1154 g_return_val_if_fail (source->context == NULL, 0);
1155 g_return_val_if_fail (!SOURCE_DESTROYED (source), 0);
1158 context = g_main_context_default ();
1160 LOCK_CONTEXT (context);
1162 result = g_source_attach_unlocked (source, context);
1164 /* If another thread has acquired the context, wake it up since it
1165 * might be in poll() right now.
1167 if (context->owner && context->owner != G_THREAD_SELF)
1168 g_wakeup_signal (context->wakeup);
1170 UNLOCK_CONTEXT (context);
1176 g_source_destroy_internal (GSource *source,
1177 GMainContext *context,
1181 LOCK_CONTEXT (context);
1183 if (!SOURCE_DESTROYED (source))
1186 gpointer old_cb_data;
1187 GSourceCallbackFuncs *old_cb_funcs;
1189 source->flags &= ~G_HOOK_FLAG_ACTIVE;
1191 old_cb_data = source->callback_data;
1192 old_cb_funcs = source->callback_funcs;
1194 source->callback_data = NULL;
1195 source->callback_funcs = NULL;
1199 UNLOCK_CONTEXT (context);
1200 old_cb_funcs->unref (old_cb_data);
1201 LOCK_CONTEXT (context);
1204 if (!SOURCE_BLOCKED (source))
1206 tmp_list = source->poll_fds;
1209 g_main_context_remove_poll_unlocked (context, tmp_list->data);
1210 tmp_list = tmp_list->next;
1213 for (tmp_list = source->priv->fds; tmp_list; tmp_list = tmp_list->next)
1214 g_main_context_remove_poll_unlocked (context, tmp_list->data);
1217 while (source->priv->child_sources)
1218 g_child_source_remove_internal (source->priv->child_sources->data, context);
1220 if (source->priv->parent_source)
1221 g_child_source_remove_internal (source, context);
1223 g_source_unref_internal (source, context, TRUE);
1227 UNLOCK_CONTEXT (context);
1232 * @source: a #GSource
1234 * Removes a source from its #GMainContext, if any, and mark it as
1235 * destroyed. The source cannot be subsequently added to another
1239 g_source_destroy (GSource *source)
1241 GMainContext *context;
1243 g_return_if_fail (source != NULL);
1245 context = source->context;
1248 g_source_destroy_internal (source, context, FALSE);
1250 source->flags &= ~G_HOOK_FLAG_ACTIVE;
1255 * @source: a #GSource
1257 * Returns the numeric ID for a particular source. The ID of a source
1258 * is a positive integer which is unique within a particular main loop
1259 * context. The reverse
1260 * mapping from ID to source is done by g_main_context_find_source_by_id().
1262 * Return value: the ID (greater than 0) for the source
1265 g_source_get_id (GSource *source)
1269 g_return_val_if_fail (source != NULL, 0);
1270 g_return_val_if_fail (source->context != NULL, 0);
1272 LOCK_CONTEXT (source->context);
1273 result = source->source_id;
1274 UNLOCK_CONTEXT (source->context);
1280 * g_source_get_context:
1281 * @source: a #GSource
1283 * Gets the #GMainContext with which the source is associated.
1285 * You can call this on a source that has been destroyed, provided
1286 * that the #GMainContext it was attached to still exists (in which
1287 * case it will return that #GMainContext). In particular, you can
1288 * always call this function on the source returned from
1289 * g_main_current_source(). But calling this function on a source
1290 * whose #GMainContext has been destroyed is an error.
1292 * Return value: (transfer none) (allow-none): the #GMainContext with which the
1293 * source is associated, or %NULL if the context has not
1294 * yet been added to a source.
1297 g_source_get_context (GSource *source)
1299 g_return_val_if_fail (source->context != NULL || !SOURCE_DESTROYED (source), NULL);
1301 return source->context;
1305 * g_source_add_poll:
1306 * @source:a #GSource
1307 * @fd: a #GPollFD structure holding information about a file
1308 * descriptor to watch.
1310 * Adds a file descriptor to the set of file descriptors polled for
1311 * this source. This is usually combined with g_source_new() to add an
1312 * event source. The event source's check function will typically test
1313 * the @revents field in the #GPollFD struct and return %TRUE if events need
1316 * Using this API forces the linear scanning of event sources on each
1317 * main loop iteration. Newly-written event sources should try to use
1318 * g_source_add_unix_fd() instead of this API.
1321 g_source_add_poll (GSource *source,
1324 GMainContext *context;
1326 g_return_if_fail (source != NULL);
1327 g_return_if_fail (fd != NULL);
1328 g_return_if_fail (!SOURCE_DESTROYED (source));
1330 context = source->context;
1333 LOCK_CONTEXT (context);
1335 source->poll_fds = g_slist_prepend (source->poll_fds, fd);
1339 if (!SOURCE_BLOCKED (source))
1340 g_main_context_add_poll_unlocked (context, source->priority, fd);
1341 UNLOCK_CONTEXT (context);
1346 * g_source_remove_poll:
1347 * @source:a #GSource
1348 * @fd: a #GPollFD structure previously passed to g_source_add_poll().
1350 * Removes a file descriptor from the set of file descriptors polled for
1354 g_source_remove_poll (GSource *source,
1357 GMainContext *context;
1359 g_return_if_fail (source != NULL);
1360 g_return_if_fail (fd != NULL);
1361 g_return_if_fail (!SOURCE_DESTROYED (source));
1363 context = source->context;
1366 LOCK_CONTEXT (context);
1368 source->poll_fds = g_slist_remove (source->poll_fds, fd);
1372 if (!SOURCE_BLOCKED (source))
1373 g_main_context_remove_poll_unlocked (context, fd);
1374 UNLOCK_CONTEXT (context);
1379 * g_source_add_child_source:
1380 * @source:a #GSource
1381 * @child_source: a second #GSource that @source should "poll"
1383 * Adds @child_source to @source as a "polled" source; when @source is
1384 * added to a #GMainContext, @child_source will be automatically added
1385 * with the same priority, when @child_source is triggered, it will
1386 * cause @source to dispatch (in addition to calling its own
1387 * callback), and when @source is destroyed, it will destroy
1388 * @child_source as well. (@source will also still be dispatched if
1389 * its own prepare/check functions indicate that it is ready.)
1391 * If you don't need @child_source to do anything on its own when it
1392 * triggers, you can call g_source_set_dummy_callback() on it to set a
1393 * callback that does nothing (except return %TRUE if appropriate).
1395 * @source will hold a reference on @child_source while @child_source
1396 * is attached to it.
1401 g_source_add_child_source (GSource *source,
1402 GSource *child_source)
1404 GMainContext *context;
1406 g_return_if_fail (source != NULL);
1407 g_return_if_fail (child_source != NULL);
1408 g_return_if_fail (!SOURCE_DESTROYED (source));
1409 g_return_if_fail (!SOURCE_DESTROYED (child_source));
1410 g_return_if_fail (child_source->context == NULL);
1411 g_return_if_fail (child_source->priv->parent_source == NULL);
1413 context = source->context;
1416 LOCK_CONTEXT (context);
1418 source->priv->child_sources = g_slist_prepend (source->priv->child_sources,
1419 g_source_ref (child_source));
1420 child_source->priv->parent_source = source;
1421 g_source_set_priority_unlocked (child_source, NULL, source->priority);
1422 if (SOURCE_BLOCKED (source))
1423 block_source (child_source);
1427 UNLOCK_CONTEXT (context);
1428 g_source_attach (child_source, context);
1433 g_child_source_remove_internal (GSource *child_source,
1434 GMainContext *context)
1436 GSource *parent_source = child_source->priv->parent_source;
1438 parent_source->priv->child_sources =
1439 g_slist_remove (parent_source->priv->child_sources, child_source);
1440 child_source->priv->parent_source = NULL;
1442 g_source_destroy_internal (child_source, context, TRUE);
1443 g_source_unref_internal (child_source, context, TRUE);
1447 * g_source_remove_child_source:
1448 * @source:a #GSource
1449 * @child_source: a #GSource previously passed to
1450 * g_source_add_child_source().
1452 * Detaches @child_source from @source and destroys it.
1457 g_source_remove_child_source (GSource *source,
1458 GSource *child_source)
1460 GMainContext *context;
1462 g_return_if_fail (source != NULL);
1463 g_return_if_fail (child_source != NULL);
1464 g_return_if_fail (child_source->priv->parent_source == source);
1465 g_return_if_fail (!SOURCE_DESTROYED (source));
1466 g_return_if_fail (!SOURCE_DESTROYED (child_source));
1468 context = source->context;
1471 LOCK_CONTEXT (context);
1473 g_child_source_remove_internal (child_source, context);
1476 UNLOCK_CONTEXT (context);
1480 * g_source_set_callback_indirect:
1481 * @source: the source
1482 * @callback_data: pointer to callback data "object"
1483 * @callback_funcs: functions for reference counting @callback_data
1484 * and getting the callback and data
1486 * Sets the callback function storing the data as a refcounted callback
1487 * "object". This is used internally. Note that calling
1488 * g_source_set_callback_indirect() assumes
1489 * an initial reference count on @callback_data, and thus
1490 * @callback_funcs->unref will eventually be called once more
1491 * than @callback_funcs->ref.
1494 g_source_set_callback_indirect (GSource *source,
1495 gpointer callback_data,
1496 GSourceCallbackFuncs *callback_funcs)
1498 GMainContext *context;
1499 gpointer old_cb_data;
1500 GSourceCallbackFuncs *old_cb_funcs;
1502 g_return_if_fail (source != NULL);
1503 g_return_if_fail (callback_funcs != NULL || callback_data == NULL);
1505 context = source->context;
1508 LOCK_CONTEXT (context);
1510 old_cb_data = source->callback_data;
1511 old_cb_funcs = source->callback_funcs;
1513 source->callback_data = callback_data;
1514 source->callback_funcs = callback_funcs;
1517 UNLOCK_CONTEXT (context);
1520 old_cb_funcs->unref (old_cb_data);
1524 g_source_callback_ref (gpointer cb_data)
1526 GSourceCallback *callback = cb_data;
1528 callback->ref_count++;
1533 g_source_callback_unref (gpointer cb_data)
1535 GSourceCallback *callback = cb_data;
1537 callback->ref_count--;
1538 if (callback->ref_count == 0)
1540 if (callback->notify)
1541 callback->notify (callback->data);
1547 g_source_callback_get (gpointer cb_data,
1552 GSourceCallback *callback = cb_data;
1554 *func = callback->func;
1555 *data = callback->data;
1558 static GSourceCallbackFuncs g_source_callback_funcs = {
1559 g_source_callback_ref,
1560 g_source_callback_unref,
1561 g_source_callback_get,
1565 * g_source_set_callback:
1566 * @source: the source
1567 * @func: a callback function
1568 * @data: the data to pass to callback function
1569 * @notify: (allow-none): a function to call when @data is no longer in use, or %NULL.
1571 * Sets the callback function for a source. The callback for a source is
1572 * called from the source's dispatch function.
1574 * The exact type of @func depends on the type of source; ie. you
1575 * should not count on @func being called with @data as its first
1578 * Typically, you won't use this function. Instead use functions specific
1579 * to the type of source you are using.
1582 g_source_set_callback (GSource *source,
1585 GDestroyNotify notify)
1587 GSourceCallback *new_callback;
1589 g_return_if_fail (source != NULL);
1591 new_callback = g_new (GSourceCallback, 1);
1593 new_callback->ref_count = 1;
1594 new_callback->func = func;
1595 new_callback->data = data;
1596 new_callback->notify = notify;
1598 g_source_set_callback_indirect (source, new_callback, &g_source_callback_funcs);
1603 * g_source_set_funcs:
1604 * @source: a #GSource
1605 * @funcs: the new #GSourceFuncs
1607 * Sets the source functions (can be used to override
1608 * default implementations) of an unattached source.
1613 g_source_set_funcs (GSource *source,
1614 GSourceFuncs *funcs)
1616 g_return_if_fail (source != NULL);
1617 g_return_if_fail (source->context == NULL);
1618 g_return_if_fail (source->ref_count > 0);
1619 g_return_if_fail (funcs != NULL);
1621 source->source_funcs = funcs;
1625 g_source_set_priority_unlocked (GSource *source,
1626 GMainContext *context,
1631 g_return_if_fail (source->priv->parent_source == NULL ||
1632 source->priv->parent_source->priority == priority);
1636 /* Remove the source from the context's source and then
1637 * add it back after so it is sorted in the correct place
1639 source_remove_from_context (source, source->context);
1642 source->priority = priority;
1646 source_add_to_context (source, source->context);
1648 if (!SOURCE_BLOCKED (source))
1650 tmp_list = source->poll_fds;
1653 g_main_context_remove_poll_unlocked (context, tmp_list->data);
1654 g_main_context_add_poll_unlocked (context, priority, tmp_list->data);
1656 tmp_list = tmp_list->next;
1659 for (tmp_list = source->priv->fds; tmp_list; tmp_list = tmp_list->next)
1661 g_main_context_remove_poll_unlocked (context, tmp_list->data);
1662 g_main_context_add_poll_unlocked (context, priority, tmp_list->data);
1667 if (source->priv->child_sources)
1669 tmp_list = source->priv->child_sources;
1672 g_source_set_priority_unlocked (tmp_list->data, context, priority);
1673 tmp_list = tmp_list->next;
1679 * g_source_set_priority:
1680 * @source: a #GSource
1681 * @priority: the new priority.
1683 * Sets the priority of a source. While the main loop is being run, a
1684 * source will be dispatched if it is ready to be dispatched and no
1685 * sources at a higher (numerically smaller) priority are ready to be
1689 g_source_set_priority (GSource *source,
1692 GMainContext *context;
1694 g_return_if_fail (source != NULL);
1696 context = source->context;
1699 LOCK_CONTEXT (context);
1700 g_source_set_priority_unlocked (source, context, priority);
1702 UNLOCK_CONTEXT (source->context);
1706 * g_source_get_priority:
1707 * @source: a #GSource
1709 * Gets the priority of a source.
1711 * Return value: the priority of the source
1714 g_source_get_priority (GSource *source)
1716 g_return_val_if_fail (source != NULL, 0);
1718 return source->priority;
1722 * g_source_set_ready_time:
1723 * @source: a #GSource
1724 * @ready_time: the monotonic time at which the source will be ready,
1725 * 0 for "immediately", -1 for "never"
1727 * Sets a #GSource to be dispatched when the given monotonic time is
1728 * reached (or passed). If the monotonic time is in the past (as it
1729 * always will be if @ready_time is 0) then the source will be
1730 * dispatched immediately.
1732 * If @ready_time is -1 then the source is never woken up on the basis
1733 * of the passage of time.
1735 * Dispatching the source does not reset the ready time. You should do
1736 * so yourself, from the source dispatch function.
1741 g_source_set_ready_time (GSource *source,
1744 GMainContext *context;
1746 g_return_if_fail (source != NULL);
1747 g_return_if_fail (source->ref_count > 0);
1749 if (source->priv->ready_time == ready_time)
1752 context = source->context;
1755 LOCK_CONTEXT (context);
1757 source->priv->ready_time = ready_time;
1761 /* Quite likely that we need to change the timeout on the poll */
1762 if (!SOURCE_BLOCKED (source))
1763 g_wakeup_signal (context->wakeup);
1764 UNLOCK_CONTEXT (context);
1769 * g_source_get_ready_time:
1770 * @source: a #GSource
1772 * Gets the "ready time" of @source, as set by
1773 * g_source_set_ready_time().
1775 * Any time before the current monotonic time (including 0) is an
1776 * indication that the source will fire immediately.
1778 * Returns: the monotonic ready time, -1 for "never"
1781 g_source_get_ready_time (GSource *source)
1783 g_return_val_if_fail (source != NULL, -1);
1785 return source->priv->ready_time;
1789 * g_source_set_can_recurse:
1790 * @source: a #GSource
1791 * @can_recurse: whether recursion is allowed for this source
1793 * Sets whether a source can be called recursively. If @can_recurse is
1794 * %TRUE, then while the source is being dispatched then this source
1795 * will be processed normally. Otherwise, all processing of this
1796 * source is blocked until the dispatch function returns.
1799 g_source_set_can_recurse (GSource *source,
1800 gboolean can_recurse)
1802 GMainContext *context;
1804 g_return_if_fail (source != NULL);
1806 context = source->context;
1809 LOCK_CONTEXT (context);
1812 source->flags |= G_SOURCE_CAN_RECURSE;
1814 source->flags &= ~G_SOURCE_CAN_RECURSE;
1817 UNLOCK_CONTEXT (context);
1821 * g_source_get_can_recurse:
1822 * @source: a #GSource
1824 * Checks whether a source is allowed to be called recursively.
1825 * see g_source_set_can_recurse().
1827 * Return value: whether recursion is allowed.
1830 g_source_get_can_recurse (GSource *source)
1832 g_return_val_if_fail (source != NULL, FALSE);
1834 return (source->flags & G_SOURCE_CAN_RECURSE) != 0;
1839 * g_source_set_name:
1840 * @source: a #GSource
1841 * @name: debug name for the source
1843 * Sets a name for the source, used in debugging and profiling.
1844 * The name defaults to #NULL.
1846 * The source name should describe in a human-readable way
1847 * what the source does. For example, "X11 event queue"
1848 * or "GTK+ repaint idle handler" or whatever it is.
1850 * It is permitted to call this function multiple times, but is not
1851 * recommended due to the potential performance impact. For example,
1852 * one could change the name in the "check" function of a #GSourceFuncs
1853 * to include details like the event type in the source name.
1858 g_source_set_name (GSource *source,
1861 g_return_if_fail (source != NULL);
1863 /* setting back to NULL is allowed, just because it's
1864 * weird if get_name can return NULL but you can't
1868 g_free (source->name);
1869 source->name = g_strdup (name);
1873 * g_source_get_name:
1874 * @source: a #GSource
1876 * Gets a name for the source, used in debugging and profiling.
1877 * The name may be #NULL if it has never been set with
1878 * g_source_set_name().
1880 * Return value: the name of the source
1884 g_source_get_name (GSource *source)
1886 g_return_val_if_fail (source != NULL, NULL);
1888 return source->name;
1892 * g_source_set_name_by_id:
1893 * @tag: a #GSource ID
1894 * @name: debug name for the source
1896 * Sets the name of a source using its ID.
1898 * This is a convenience utility to set source names from the return
1899 * value of g_idle_add(), g_timeout_add(), etc.
1904 g_source_set_name_by_id (guint tag,
1909 g_return_if_fail (tag > 0);
1911 source = g_main_context_find_source_by_id (NULL, tag);
1915 g_source_set_name (source, name);
1921 * @source: a #GSource
1923 * Increases the reference count on a source by one.
1925 * Return value: @source
1928 g_source_ref (GSource *source)
1930 GMainContext *context;
1932 g_return_val_if_fail (source != NULL, NULL);
1934 context = source->context;
1937 LOCK_CONTEXT (context);
1939 source->ref_count++;
1942 UNLOCK_CONTEXT (context);
1947 /* g_source_unref() but possible to call within context lock
1950 g_source_unref_internal (GSource *source,
1951 GMainContext *context,
1954 gpointer old_cb_data = NULL;
1955 GSourceCallbackFuncs *old_cb_funcs = NULL;
1957 g_return_if_fail (source != NULL);
1959 if (!have_lock && context)
1960 LOCK_CONTEXT (context);
1962 source->ref_count--;
1963 if (source->ref_count == 0)
1965 old_cb_data = source->callback_data;
1966 old_cb_funcs = source->callback_funcs;
1968 source->callback_data = NULL;
1969 source->callback_funcs = NULL;
1973 if (!SOURCE_DESTROYED (source))
1974 g_warning (G_STRLOC ": ref_count == 0, but source was still attached to a context!");
1975 source_remove_from_context (source, context);
1978 if (source->source_funcs->finalize)
1981 UNLOCK_CONTEXT (context);
1982 source->source_funcs->finalize (source);
1984 LOCK_CONTEXT (context);
1987 g_free (source->name);
1988 source->name = NULL;
1990 g_slist_free (source->poll_fds);
1991 source->poll_fds = NULL;
1993 g_slist_free_full (source->priv->fds, g_free);
1995 g_slice_free (GSourcePrivate, source->priv);
1996 source->priv = NULL;
2001 if (!have_lock && context)
2002 UNLOCK_CONTEXT (context);
2007 UNLOCK_CONTEXT (context);
2009 old_cb_funcs->unref (old_cb_data);
2012 LOCK_CONTEXT (context);
2018 * @source: a #GSource
2020 * Decreases the reference count of a source by one. If the
2021 * resulting reference count is zero the source and associated
2022 * memory will be destroyed.
2025 g_source_unref (GSource *source)
2027 g_return_if_fail (source != NULL);
2029 g_source_unref_internal (source, source->context, FALSE);
2033 * g_main_context_find_source_by_id:
2034 * @context: (allow-none): a #GMainContext (if %NULL, the default context will be used)
2035 * @source_id: the source ID, as returned by g_source_get_id().
2037 * Finds a #GSource given a pair of context and ID.
2039 * Return value: (transfer none): the #GSource if found, otherwise, %NULL
2042 g_main_context_find_source_by_id (GMainContext *context,
2048 g_return_val_if_fail (source_id > 0, NULL);
2050 if (context == NULL)
2051 context = g_main_context_default ();
2053 LOCK_CONTEXT (context);
2055 g_source_iter_init (&iter, context, FALSE);
2056 while (g_source_iter_next (&iter, &source))
2058 if (!SOURCE_DESTROYED (source) &&
2059 source->source_id == source_id)
2062 g_source_iter_clear (&iter);
2064 UNLOCK_CONTEXT (context);
2070 * g_main_context_find_source_by_funcs_user_data:
2071 * @context: (allow-none): a #GMainContext (if %NULL, the default context will be used).
2072 * @funcs: the @source_funcs passed to g_source_new().
2073 * @user_data: the user data from the callback.
2075 * Finds a source with the given source functions and user data. If
2076 * multiple sources exist with the same source function and user data,
2077 * the first one found will be returned.
2079 * Return value: (transfer none): the source, if one was found, otherwise %NULL
2082 g_main_context_find_source_by_funcs_user_data (GMainContext *context,
2083 GSourceFuncs *funcs,
2089 g_return_val_if_fail (funcs != NULL, NULL);
2091 if (context == NULL)
2092 context = g_main_context_default ();
2094 LOCK_CONTEXT (context);
2096 g_source_iter_init (&iter, context, FALSE);
2097 while (g_source_iter_next (&iter, &source))
2099 if (!SOURCE_DESTROYED (source) &&
2100 source->source_funcs == funcs &&
2101 source->callback_funcs)
2103 GSourceFunc callback;
2104 gpointer callback_data;
2106 source->callback_funcs->get (source->callback_data, source, &callback, &callback_data);
2108 if (callback_data == user_data)
2112 g_source_iter_clear (&iter);
2114 UNLOCK_CONTEXT (context);
2120 * g_main_context_find_source_by_user_data:
2121 * @context: a #GMainContext
2122 * @user_data: the user_data for the callback.
2124 * Finds a source with the given user data for the callback. If
2125 * multiple sources exist with the same user data, the first
2126 * one found will be returned.
2128 * Return value: (transfer none): the source, if one was found, otherwise %NULL
2131 g_main_context_find_source_by_user_data (GMainContext *context,
2137 if (context == NULL)
2138 context = g_main_context_default ();
2140 LOCK_CONTEXT (context);
2142 g_source_iter_init (&iter, context, FALSE);
2143 while (g_source_iter_next (&iter, &source))
2145 if (!SOURCE_DESTROYED (source) &&
2146 source->callback_funcs)
2148 GSourceFunc callback;
2149 gpointer callback_data = NULL;
2151 source->callback_funcs->get (source->callback_data, source, &callback, &callback_data);
2153 if (callback_data == user_data)
2157 g_source_iter_clear (&iter);
2159 UNLOCK_CONTEXT (context);
2166 * @tag: the ID of the source to remove.
2168 * Removes the source with the given id from the default main context.
2170 * a #GSource is given by g_source_get_id(), or will be returned by the
2171 * functions g_source_attach(), g_idle_add(), g_idle_add_full(),
2172 * g_timeout_add(), g_timeout_add_full(), g_child_watch_add(),
2173 * g_child_watch_add_full(), g_io_add_watch(), and g_io_add_watch_full().
2175 * See also g_source_destroy(). You must use g_source_destroy() for sources
2176 * added to a non-default main context.
2178 * Return value: %TRUE if the source was found and removed.
2181 g_source_remove (guint tag)
2185 g_return_val_if_fail (tag > 0, FALSE);
2187 source = g_main_context_find_source_by_id (NULL, tag);
2189 g_source_destroy (source);
2191 return source != NULL;
2195 * g_source_remove_by_user_data:
2196 * @user_data: the user_data for the callback.
2198 * Removes a source from the default main loop context given the user
2199 * data for the callback. If multiple sources exist with the same user
2200 * data, only one will be destroyed.
2202 * Return value: %TRUE if a source was found and removed.
2205 g_source_remove_by_user_data (gpointer user_data)
2209 source = g_main_context_find_source_by_user_data (NULL, user_data);
2212 g_source_destroy (source);
2220 * g_source_remove_by_funcs_user_data:
2221 * @funcs: The @source_funcs passed to g_source_new()
2222 * @user_data: the user data for the callback
2224 * Removes a source from the default main loop context given the
2225 * source functions and user data. If multiple sources exist with the
2226 * same source functions and user data, only one will be destroyed.
2228 * Return value: %TRUE if a source was found and removed.
2231 g_source_remove_by_funcs_user_data (GSourceFuncs *funcs,
2236 g_return_val_if_fail (funcs != NULL, FALSE);
2238 source = g_main_context_find_source_by_funcs_user_data (NULL, funcs, user_data);
2241 g_source_destroy (source);
2250 * g_source_add_unix_fd:
2251 * @source: a #GSource
2252 * @fd: the fd to monitor
2253 * @events: an event mask
2255 * Monitors @fd for the IO events in @events.
2257 * The tag returned by this function can be used to remove or modify the
2258 * monitoring of the fd using g_source_remove_unix_fd() or
2259 * g_source_modify_unix_fd().
2261 * It is not necessary to remove the fd before destroying the source; it
2262 * will be cleaned up automatically.
2264 * As the name suggests, this function is not available on Windows.
2266 * Returns: an opaque tag
2271 g_source_add_unix_fd (GSource *source,
2273 GIOCondition events)
2275 GMainContext *context;
2278 g_return_val_if_fail (source != NULL, NULL);
2279 g_return_val_if_fail (!SOURCE_DESTROYED (source), NULL);
2281 poll_fd = g_new (GPollFD, 1);
2283 poll_fd->events = events;
2284 poll_fd->revents = 0;
2286 context = source->context;
2289 LOCK_CONTEXT (context);
2291 source->priv->fds = g_slist_prepend (source->priv->fds, poll_fd);
2295 if (!SOURCE_BLOCKED (source))
2296 g_main_context_add_poll_unlocked (context, source->priority, poll_fd);
2297 UNLOCK_CONTEXT (context);
2304 * g_source_modify_unix_fd:
2305 * @source: a #GSource
2306 * @tag: the tag from g_source_add_unix_fd()
2307 * @new_events: the new event mask to watch
2309 * Updates the event mask to watch for the fd identified by @tag.
2311 * @tag is the tag returned from g_source_add_unix_fd().
2313 * If you want to remove a fd, don't set its event mask to zero.
2314 * Instead, call g_source_remove_unix_fd().
2316 * As the name suggests, this function is not available on Windows.
2321 g_source_modify_unix_fd (GSource *source,
2323 GIOCondition new_events)
2325 GMainContext *context;
2328 g_return_if_fail (source != NULL);
2329 g_return_if_fail (g_slist_find (source->priv->fds, tag));
2331 context = source->context;
2334 poll_fd->events = new_events;
2337 g_main_context_wakeup (context);
2341 * g_source_remove_unix_fd:
2342 * @source: a #GSource
2343 * @tag: the tag from g_source_add_unix_fd()
2345 * Reverses the effect of a previous call to g_source_add_unix_fd().
2347 * You only need to call this if you want to remove an fd from being
2348 * watched while keeping the same source around. In the normal case you
2349 * will just want to destroy the source.
2351 * As the name suggests, this function is not available on Windows.
2356 g_source_remove_unix_fd (GSource *source,
2359 GMainContext *context;
2362 g_return_if_fail (source != NULL);
2363 g_return_if_fail (g_slist_find (source->priv->fds, tag));
2365 context = source->context;
2369 LOCK_CONTEXT (context);
2371 source->priv->fds = g_slist_remove (source->priv->fds, poll_fd);
2375 if (!SOURCE_BLOCKED (source))
2376 g_main_context_remove_poll_unlocked (context, poll_fd);
2378 UNLOCK_CONTEXT (context);
2385 * g_source_query_unix_fd:
2386 * @source: a #GSource
2387 * @tag: the tag from g_source_add_unix_fd()
2389 * Queries the events reported for the fd corresponding to @tag on
2390 * @source during the last poll.
2392 * The return value of this function is only defined when the function
2393 * is called from the check or dispatch functions for @source.
2395 * As the name suggests, this function is not available on Windows.
2397 * Returns: the conditions reported on the fd
2402 g_source_query_unix_fd (GSource *source,
2407 g_return_val_if_fail (source != NULL, 0);
2408 g_return_val_if_fail (g_slist_find (source->priv->fds, tag), 0);
2412 return poll_fd->revents;
2414 #endif /* G_OS_UNIX */
2417 * g_get_current_time:
2418 * @result: #GTimeVal structure in which to store current time.
2420 * Equivalent to the UNIX gettimeofday() function, but portable.
2422 * You may find g_get_real_time() to be more convenient.
2425 g_get_current_time (GTimeVal *result)
2430 g_return_if_fail (result != NULL);
2432 /*this is required on alpha, there the timeval structs are int's
2433 not longs and a cast only would fail horribly*/
2434 gettimeofday (&r, NULL);
2435 result->tv_sec = r.tv_sec;
2436 result->tv_usec = r.tv_usec;
2441 g_return_if_fail (result != NULL);
2443 GetSystemTimeAsFileTime (&ft);
2444 memmove (&time64, &ft, sizeof (FILETIME));
2446 /* Convert from 100s of nanoseconds since 1601-01-01
2447 * to Unix epoch. Yes, this is Y2038 unsafe.
2449 time64 -= G_GINT64_CONSTANT (116444736000000000);
2452 result->tv_sec = time64 / 1000000;
2453 result->tv_usec = time64 % 1000000;
2460 * Queries the system wall-clock time.
2462 * This call is functionally equivalent to g_get_current_time() except
2463 * that the return value is often more convenient than dealing with a
2466 * You should only use this call if you are actually interested in the real
2467 * wall-clock time. g_get_monotonic_time() is probably more useful for
2468 * measuring intervals.
2470 * Returns: the number of microseconds since January 1, 1970 UTC.
2475 g_get_real_time (void)
2479 g_get_current_time (&tv);
2481 return (((gint64) tv.tv_sec) * 1000000) + tv.tv_usec;
2485 static ULONGLONG (*g_GetTickCount64) (void) = NULL;
2486 static guint32 g_win32_tick_epoch = 0;
2489 g_clock_win32_init (void)
2493 g_GetTickCount64 = NULL;
2494 kernel32 = GetModuleHandle ("KERNEL32.DLL");
2495 if (kernel32 != NULL)
2496 g_GetTickCount64 = (void *) GetProcAddress (kernel32, "GetTickCount64");
2497 g_win32_tick_epoch = ((guint32)GetTickCount()) >> 31;
2502 * g_get_monotonic_time:
2504 * Queries the system monotonic time, if available.
2506 * On POSIX systems with clock_gettime() and <literal>CLOCK_MONOTONIC</literal> this call
2507 * is a very shallow wrapper for that. Otherwise, we make a best effort
2508 * that probably involves returning the wall clock time (with at least
2509 * microsecond accuracy, subject to the limitations of the OS kernel).
2511 * It's important to note that POSIX <literal>CLOCK_MONOTONIC</literal> does
2512 * not count time spent while the machine is suspended.
2514 * On Windows, "limitations of the OS kernel" is a rather substantial
2515 * statement. Depending on the configuration of the system, the wall
2516 * clock time is updated as infrequently as 64 times a second (which
2517 * is approximately every 16ms). Also, on XP (but not on Vista or later)
2518 * the monotonic clock is locally monotonic, but may differ in exact
2519 * value between processes due to timer wrap handling.
2521 * Returns: the monotonic time, in microseconds
2526 g_get_monotonic_time (void)
2528 #ifdef HAVE_CLOCK_GETTIME
2529 /* librt clock_gettime() is our first choice */
2532 #ifdef CLOCK_MONOTONIC
2533 clock_gettime (CLOCK_MONOTONIC, &ts);
2535 clock_gettime (CLOCK_REALTIME, &ts);
2538 /* In theory monotonic time can have any epoch.
2540 * glib presently assumes the following:
2542 * 1) The epoch comes some time after the birth of Jesus of Nazareth, but
2543 * not more than 10000 years later.
2545 * 2) The current time also falls sometime within this range.
2547 * These two reasonable assumptions leave us with a maximum deviation from
2548 * the epoch of 10000 years, or 315569520000000000 seconds.
2550 * If we restrict ourselves to this range then the number of microseconds
2551 * will always fit well inside the constraints of a int64 (by a factor of
2554 * If you actually hit the following assertion, probably you should file a
2555 * bug against your operating system for being excessively silly.
2557 g_assert (G_GINT64_CONSTANT (-315569520000000000) < ts.tv_sec &&
2558 ts.tv_sec < G_GINT64_CONSTANT (315569520000000000));
2560 return (((gint64) ts.tv_sec) * 1000000) + (ts.tv_nsec / 1000);
2562 #elif defined (G_OS_WIN32)
2566 /* There are four sources for the monotonic time on Windows:
2568 * Three are based on a (1 msec accuracy, but only read periodically) clock chip:
2569 * - GetTickCount (GTC)
2570 * 32bit msec counter, updated each ~15msec, wraps in ~50 days
2571 * - GetTickCount64 (GTC64)
2572 * Same as GetTickCount, but extended to 64bit, so no wrap
2573 * Only available in Vista or later
2574 * - timeGetTime (TGT)
2575 * similar to GetTickCount by default: 15msec, 50 day wrap.
2576 * available in winmm.dll (thus known as the multimedia timers)
2577 * However apps can raise the system timer clock frequency using timeBeginPeriod()
2578 * increasing the accuracy up to 1 msec, at a cost in general system performance
2581 * One is based on high precision clocks:
2582 * - QueryPrecisionCounter (QPC)
2583 * This has much higher accuracy, but is not guaranteed monotonic, and
2584 * has lots of complications like clock jumps and different times on different
2585 * CPUs. It also has lower long term accuracy (i.e. it will drift compared to
2586 * the low precision clocks.
2588 * Additionally, the precision available in the timer-based wakeup such as
2589 * MsgWaitForMultipleObjectsEx (which is what the mainloop is based on) is based
2590 * on the TGT resolution, so by default it is ~15msec, but can be increased by apps.
2592 * The QPC timer has too many issues to be used as is. The only way it could be used
2593 * is to use it to interpolate the lower precision clocks. Firefox does something like
2595 * https://bugzilla.mozilla.org/show_bug.cgi?id=363258
2597 * However this seems quite complicated, so we're not doing this right now.
2599 * The approach we take instead is to use the TGT timer, extending it to 64bit
2600 * either by using the GTC64 value, or if that is not available, a process local
2601 * time epoch that we increment when we detect a timer wrap (assumes that we read
2602 * the time at least once every 50 days).
2605 * - We have a globally consistent monotonic clock on Vista and later
2606 * - We have a locally monotonic clock on XP
2607 * - Apps that need higher precision in timeouts and clock reads can call
2608 * timeBeginPeriod() to increase it as much as they want
2611 if (g_GetTickCount64 != NULL)
2613 guint32 ticks_as_32bit;
2615 ticks = g_GetTickCount64 ();
2616 ticks32 = timeGetTime();
2618 /* GTC64 and TGT are sampled at different times, however they
2619 * have the same base and source (msecs since system boot).
2620 * They can differ by as much as -16 to +16 msecs.
2621 * We can't just inject the low bits into the 64bit counter
2622 * as one of the counters can have wrapped in 32bit space and
2623 * the other not. Instead we calculate the signed difference
2624 * in 32bit space and apply that difference to the 64bit counter.
2626 ticks_as_32bit = (guint32)ticks;
2628 /* We could do some 2's complement hack, but we play it safe */
2629 if (ticks32 - ticks_as_32bit <= G_MAXINT32)
2630 ticks += ticks32 - ticks_as_32bit;
2632 ticks -= ticks_as_32bit - ticks32;
2638 epoch = g_atomic_int_get (&g_win32_tick_epoch);
2640 /* Must read ticks after the epoch. Then we're guaranteed
2641 * that the ticks value we read is higher or equal to any
2642 * previous ones that lead to the writing of the epoch.
2644 ticks32 = timeGetTime();
2646 /* We store the MSB of the current time as the LSB
2647 * of the epoch. Comparing these bits lets us detect when
2648 * the 32bit counter has wrapped so we can increase the
2651 * This will work as long as this function is called at
2652 * least once every ~24 days, which is half the wrap time
2653 * of a 32bit msec counter. I think this is pretty likely.
2655 * Note that g_win32_tick_epoch is a process local state,
2656 * so the monotonic clock will not be the same between
2659 if ((ticks32 >> 31) != (epoch & 1))
2662 g_atomic_int_set (&g_win32_tick_epoch, epoch);
2666 ticks = (guint64)ticks32 | ((guint64)epoch) << 31;
2669 return ticks * 1000;
2671 #else /* !HAVE_CLOCK_GETTIME && ! G_OS_WIN32*/
2675 g_get_current_time (&tv);
2677 return (((gint64) tv.tv_sec) * 1000000) + tv.tv_usec;
2682 g_main_dispatch_free (gpointer dispatch)
2684 g_slice_free (GMainDispatch, dispatch);
2687 /* Running the main loop */
2689 static GMainDispatch *
2692 static GPrivate depth_private = G_PRIVATE_INIT (g_main_dispatch_free);
2693 GMainDispatch *dispatch;
2695 dispatch = g_private_get (&depth_private);
2699 dispatch = g_slice_new0 (GMainDispatch);
2700 g_private_set (&depth_private, dispatch);
2709 * Returns the depth of the stack of calls to
2710 * g_main_context_dispatch() on any #GMainContext in the current thread.
2711 * That is, when called from the toplevel, it gives 0. When
2712 * called from within a callback from g_main_context_iteration()
2713 * (or g_main_loop_run(), etc.) it returns 1. When called from within
2714 * a callback to a recursive call to g_main_context_iteration(),
2715 * it returns 2. And so forth.
2717 * This function is useful in a situation like the following:
2718 * Imagine an extremely simple "garbage collected" system.
2721 * static GList *free_list;
2724 * allocate_memory (gsize size)
2726 * gpointer result = g_malloc (size);
2727 * free_list = g_list_prepend (free_list, result);
2732 * free_allocated_memory (void)
2735 * for (l = free_list; l; l = l->next);
2737 * g_list_free (free_list);
2745 * g_main_context_iteration (NULL, TRUE);
2746 * free_allocated_memory();
2750 * This works from an application, however, if you want to do the same
2751 * thing from a library, it gets more difficult, since you no longer
2752 * control the main loop. You might think you can simply use an idle
2753 * function to make the call to free_allocated_memory(), but that
2754 * doesn't work, since the idle function could be called from a
2755 * recursive callback. This can be fixed by using g_main_depth()
2759 * allocate_memory (gsize size)
2761 * FreeListBlock *block = g_new (FreeListBlock, 1);
2762 * block->mem = g_malloc (size);
2763 * block->depth = g_main_depth ();
2764 * free_list = g_list_prepend (free_list, block);
2765 * return block->mem;
2769 * free_allocated_memory (void)
2773 * int depth = g_main_depth ();
2774 * for (l = free_list; l; );
2776 * GList *next = l->next;
2777 * FreeListBlock *block = l->data;
2778 * if (block->depth > depth)
2780 * g_free (block->mem);
2782 * free_list = g_list_delete_link (free_list, l);
2790 * There is a temptation to use g_main_depth() to solve
2791 * problems with reentrancy. For instance, while waiting for data
2792 * to be received from the network in response to a menu item,
2793 * the menu item might be selected again. It might seem that
2794 * one could make the menu item's callback return immediately
2795 * and do nothing if g_main_depth() returns a value greater than 1.
2796 * However, this should be avoided since the user then sees selecting
2797 * the menu item do nothing. Furthermore, you'll find yourself adding
2798 * these checks all over your code, since there are doubtless many,
2799 * many things that the user could do. Instead, you can use the
2800 * following techniques:
2805 * Use gtk_widget_set_sensitive() or modal dialogs to prevent
2806 * the user from interacting with elements while the main
2807 * loop is recursing.
2812 * Avoid main loop recursion in situations where you can't handle
2813 * arbitrary callbacks. Instead, structure your code so that you
2814 * simply return to the main loop and then get called again when
2815 * there is more work to do.
2820 * Return value: The main loop recursion level in the current thread
2825 GMainDispatch *dispatch = get_dispatch ();
2826 return dispatch->depth;
2830 * g_main_current_source:
2832 * Returns the currently firing source for this thread.
2834 * Return value: (transfer none): The currently firing source or %NULL.
2839 g_main_current_source (void)
2841 GMainDispatch *dispatch = get_dispatch ();
2842 return dispatch->dispatching_sources ? dispatch->dispatching_sources->data : NULL;
2846 * g_source_is_destroyed:
2847 * @source: a #GSource
2849 * Returns whether @source has been destroyed.
2851 * This is important when you operate upon your objects
2852 * from within idle handlers, but may have freed the object
2853 * before the dispatch of your idle handler.
2857 * idle_callback (gpointer data)
2859 * SomeWidget *self = data;
2861 * GDK_THREADS_ENTER (<!-- -->);
2862 * /<!-- -->* do stuff with self *<!-- -->/
2863 * self->idle_id = 0;
2864 * GDK_THREADS_LEAVE (<!-- -->);
2866 * return G_SOURCE_REMOVE;
2870 * some_widget_do_stuff_later (SomeWidget *self)
2872 * self->idle_id = g_idle_add (idle_callback, self);
2876 * some_widget_finalize (GObject *object)
2878 * SomeWidget *self = SOME_WIDGET (object);
2880 * if (self->idle_id)
2881 * g_source_remove (self->idle_id);
2883 * G_OBJECT_CLASS (parent_class)->finalize (object);
2887 * This will fail in a multi-threaded application if the
2888 * widget is destroyed before the idle handler fires due
2889 * to the use after free in the callback. A solution, to
2890 * this particular problem, is to check to if the source
2891 * has already been destroy within the callback.
2895 * idle_callback (gpointer data)
2897 * SomeWidget *self = data;
2899 * GDK_THREADS_ENTER ();
2900 * if (!g_source_is_destroyed (g_main_current_source ()))
2902 * /<!-- -->* do stuff with self *<!-- -->/
2904 * GDK_THREADS_LEAVE ();
2910 * Return value: %TRUE if the source has been destroyed
2915 g_source_is_destroyed (GSource *source)
2917 return SOURCE_DESTROYED (source);
2920 /* Temporarily remove all this source's file descriptors from the
2921 * poll(), so that if data comes available for one of the file descriptors
2922 * we don't continually spin in the poll()
2924 /* HOLDS: source->context's lock */
2926 block_source (GSource *source)
2930 g_return_if_fail (!SOURCE_BLOCKED (source));
2932 source->flags |= G_SOURCE_BLOCKED;
2934 tmp_list = source->poll_fds;
2937 g_main_context_remove_poll_unlocked (source->context, tmp_list->data);
2938 tmp_list = tmp_list->next;
2941 for (tmp_list = source->priv->fds; tmp_list; tmp_list = tmp_list->next)
2942 g_main_context_remove_poll_unlocked (source->context, tmp_list->data);
2944 if (source->priv && source->priv->child_sources)
2946 tmp_list = source->priv->child_sources;
2949 block_source (tmp_list->data);
2950 tmp_list = tmp_list->next;
2955 /* HOLDS: source->context's lock */
2957 unblock_source (GSource *source)
2961 g_return_if_fail (SOURCE_BLOCKED (source)); /* Source already unblocked */
2962 g_return_if_fail (!SOURCE_DESTROYED (source));
2964 source->flags &= ~G_SOURCE_BLOCKED;
2966 tmp_list = source->poll_fds;
2969 g_main_context_add_poll_unlocked (source->context, source->priority, tmp_list->data);
2970 tmp_list = tmp_list->next;
2973 for (tmp_list = source->priv->fds; tmp_list; tmp_list = tmp_list->next)
2974 g_main_context_add_poll_unlocked (source->context, source->priority, tmp_list->data);
2976 if (source->priv && source->priv->child_sources)
2978 tmp_list = source->priv->child_sources;
2981 unblock_source (tmp_list->data);
2982 tmp_list = tmp_list->next;
2987 /* HOLDS: context's lock */
2989 g_main_dispatch (GMainContext *context)
2991 GMainDispatch *current = get_dispatch ();
2994 for (i = 0; i < context->pending_dispatches->len; i++)
2996 GSource *source = context->pending_dispatches->pdata[i];
2998 context->pending_dispatches->pdata[i] = NULL;
3001 source->flags &= ~G_SOURCE_READY;
3003 if (!SOURCE_DESTROYED (source))
3005 gboolean was_in_call;
3006 gpointer user_data = NULL;
3007 GSourceFunc callback = NULL;
3008 GSourceCallbackFuncs *cb_funcs;
3010 gboolean need_destroy;
3012 gboolean (*dispatch) (GSource *,
3015 GSList current_source_link;
3017 dispatch = source->source_funcs->dispatch;
3018 cb_funcs = source->callback_funcs;
3019 cb_data = source->callback_data;
3022 cb_funcs->ref (cb_data);
3024 if ((source->flags & G_SOURCE_CAN_RECURSE) == 0)
3025 block_source (source);
3027 was_in_call = source->flags & G_HOOK_FLAG_IN_CALL;
3028 source->flags |= G_HOOK_FLAG_IN_CALL;
3031 cb_funcs->get (cb_data, source, &callback, &user_data);
3033 UNLOCK_CONTEXT (context);
3036 /* The on-stack allocation of the GSList is unconventional, but
3037 * we know that the lifetime of the link is bounded to this
3038 * function as the link is kept in a thread specific list and
3039 * not manipulated outside of this function and its descendants.
3040 * Avoiding the overhead of a g_slist_alloc() is useful as many
3041 * applications do little more than dispatch events.
3043 * This is a performance hack - do not revert to g_slist_prepend()!
3045 current_source_link.data = source;
3046 current_source_link.next = current->dispatching_sources;
3047 current->dispatching_sources = ¤t_source_link;
3048 need_destroy = ! dispatch (source,
3051 g_assert (current->dispatching_sources == ¤t_source_link);
3052 current->dispatching_sources = current_source_link.next;
3056 cb_funcs->unref (cb_data);
3058 LOCK_CONTEXT (context);
3061 source->flags &= ~G_HOOK_FLAG_IN_CALL;
3063 if (SOURCE_BLOCKED (source) && !SOURCE_DESTROYED (source))
3064 unblock_source (source);
3066 /* Note: this depends on the fact that we can't switch
3067 * sources from one main context to another
3069 if (need_destroy && !SOURCE_DESTROYED (source))
3071 g_assert (source->context == context);
3072 g_source_destroy_internal (source, context, TRUE);
3076 SOURCE_UNREF (source, context);
3079 g_ptr_array_set_size (context->pending_dispatches, 0);
3083 * g_main_context_acquire:
3084 * @context: a #GMainContext
3086 * Tries to become the owner of the specified context.
3087 * If some other thread is the owner of the context,
3088 * returns %FALSE immediately. Ownership is properly
3089 * recursive: the owner can require ownership again
3090 * and will release ownership when g_main_context_release()
3091 * is called as many times as g_main_context_acquire().
3093 * You must be the owner of a context before you
3094 * can call g_main_context_prepare(), g_main_context_query(),
3095 * g_main_context_check(), g_main_context_dispatch().
3097 * Return value: %TRUE if the operation succeeded, and
3098 * this thread is now the owner of @context.
3101 g_main_context_acquire (GMainContext *context)
3103 gboolean result = FALSE;
3104 GThread *self = G_THREAD_SELF;
3106 if (context == NULL)
3107 context = g_main_context_default ();
3109 LOCK_CONTEXT (context);
3111 if (!context->owner)
3113 context->owner = self;
3114 g_assert (context->owner_count == 0);
3117 if (context->owner == self)
3119 context->owner_count++;
3123 UNLOCK_CONTEXT (context);
3129 * g_main_context_release:
3130 * @context: a #GMainContext
3132 * Releases ownership of a context previously acquired by this thread
3133 * with g_main_context_acquire(). If the context was acquired multiple
3134 * times, the ownership will be released only when g_main_context_release()
3135 * is called as many times as it was acquired.
3138 g_main_context_release (GMainContext *context)
3140 if (context == NULL)
3141 context = g_main_context_default ();
3143 LOCK_CONTEXT (context);
3145 context->owner_count--;
3146 if (context->owner_count == 0)
3148 context->owner = NULL;
3150 if (context->waiters)
3152 GMainWaiter *waiter = context->waiters->data;
3153 gboolean loop_internal_waiter = (waiter->mutex == &context->mutex);
3154 context->waiters = g_slist_delete_link (context->waiters,
3156 if (!loop_internal_waiter)
3157 g_mutex_lock (waiter->mutex);
3159 g_cond_signal (waiter->cond);
3161 if (!loop_internal_waiter)
3162 g_mutex_unlock (waiter->mutex);
3166 UNLOCK_CONTEXT (context);
3170 * g_main_context_wait:
3171 * @context: a #GMainContext
3172 * @cond: a condition variable
3173 * @mutex: a mutex, currently held
3175 * Tries to become the owner of the specified context,
3176 * as with g_main_context_acquire(). But if another thread
3177 * is the owner, atomically drop @mutex and wait on @cond until
3178 * that owner releases ownership or until @cond is signaled, then
3179 * try again (once) to become the owner.
3181 * Return value: %TRUE if the operation succeeded, and
3182 * this thread is now the owner of @context.
3185 g_main_context_wait (GMainContext *context,
3189 gboolean result = FALSE;
3190 GThread *self = G_THREAD_SELF;
3191 gboolean loop_internal_waiter;
3193 if (context == NULL)
3194 context = g_main_context_default ();
3196 loop_internal_waiter = (mutex == &context->mutex);
3198 if (!loop_internal_waiter)
3199 LOCK_CONTEXT (context);
3201 if (context->owner && context->owner != self)
3206 waiter.mutex = mutex;
3208 context->waiters = g_slist_append (context->waiters, &waiter);
3210 if (!loop_internal_waiter)
3211 UNLOCK_CONTEXT (context);
3212 g_cond_wait (cond, mutex);
3213 if (!loop_internal_waiter)
3214 LOCK_CONTEXT (context);
3216 context->waiters = g_slist_remove (context->waiters, &waiter);
3219 if (!context->owner)
3221 context->owner = self;
3222 g_assert (context->owner_count == 0);
3225 if (context->owner == self)
3227 context->owner_count++;
3231 if (!loop_internal_waiter)
3232 UNLOCK_CONTEXT (context);
3238 * g_main_context_prepare:
3239 * @context: a #GMainContext
3240 * @priority: location to store priority of highest priority
3241 * source already ready.
3243 * Prepares to poll sources within a main loop. The resulting information
3244 * for polling is determined by calling g_main_context_query ().
3246 * Return value: %TRUE if some source is ready to be dispatched
3250 g_main_context_prepare (GMainContext *context,
3255 gint current_priority = G_MAXINT;
3259 if (context == NULL)
3260 context = g_main_context_default ();
3262 LOCK_CONTEXT (context);
3264 context->time_is_fresh = FALSE;
3266 if (context->in_check_or_prepare)
3268 g_warning ("g_main_context_prepare() called recursively from within a source's check() or "
3269 "prepare() member.");
3270 UNLOCK_CONTEXT (context);
3275 /* If recursing, finish up current dispatch, before starting over */
3276 if (context->pending_dispatches)
3279 g_main_dispatch (context, ¤t_time);
3281 UNLOCK_CONTEXT (context);
3286 /* If recursing, clear list of pending dispatches */
3288 for (i = 0; i < context->pending_dispatches->len; i++)
3290 if (context->pending_dispatches->pdata[i])
3291 SOURCE_UNREF ((GSource *)context->pending_dispatches->pdata[i], context);
3293 g_ptr_array_set_size (context->pending_dispatches, 0);
3295 /* Prepare all sources */
3297 context->timeout = -1;
3299 g_source_iter_init (&iter, context, TRUE);
3300 while (g_source_iter_next (&iter, &source))
3302 gint source_timeout = -1;
3304 if (SOURCE_DESTROYED (source) || SOURCE_BLOCKED (source))
3306 if ((n_ready > 0) && (source->priority > current_priority))
3309 if (!(source->flags & G_SOURCE_READY))
3312 gboolean (* prepare) (GSource *source,
3315 prepare = source->source_funcs->prepare;
3319 context->in_check_or_prepare++;
3320 UNLOCK_CONTEXT (context);
3322 result = (* prepare) (source, &source_timeout);
3324 LOCK_CONTEXT (context);
3325 context->in_check_or_prepare--;
3329 source_timeout = -1;
3333 if (result == FALSE && source->priv->ready_time != -1)
3335 if (!context->time_is_fresh)
3337 context->time = g_get_monotonic_time ();
3338 context->time_is_fresh = TRUE;
3341 if (source->priv->ready_time <= context->time)
3350 /* rounding down will lead to spinning, so always round up */
3351 timeout = (source->priv->ready_time - context->time + 999) / 1000;
3353 if (source_timeout < 0 || timeout < source_timeout)
3354 source_timeout = timeout;
3360 GSource *ready_source = source;
3362 while (ready_source)
3364 ready_source->flags |= G_SOURCE_READY;
3365 ready_source = ready_source->priv->parent_source;
3370 if (source->flags & G_SOURCE_READY)
3373 current_priority = source->priority;
3374 context->timeout = 0;
3377 if (source_timeout >= 0)
3379 if (context->timeout < 0)
3380 context->timeout = source_timeout;
3382 context->timeout = MIN (context->timeout, source_timeout);
3385 g_source_iter_clear (&iter);
3387 UNLOCK_CONTEXT (context);
3390 *priority = current_priority;
3392 return (n_ready > 0);
3396 * g_main_context_query:
3397 * @context: a #GMainContext
3398 * @max_priority: maximum priority source to check
3399 * @timeout_: (out): location to store timeout to be used in polling
3400 * @fds: (out caller-allocates) (array length=n_fds): location to
3401 * store #GPollFD records that need to be polled.
3402 * @n_fds: length of @fds.
3404 * Determines information necessary to poll this main loop.
3406 * Return value: the number of records actually stored in @fds,
3407 * or, if more than @n_fds records need to be stored, the number
3408 * of records that need to be stored.
3411 g_main_context_query (GMainContext *context,
3420 LOCK_CONTEXT (context);
3422 pollrec = context->poll_records;
3424 while (pollrec && max_priority >= pollrec->priority)
3426 /* We need to include entries with fd->events == 0 in the array because
3427 * otherwise if the application changes fd->events behind our back and
3428 * makes it non-zero, we'll be out of sync when we check the fds[] array.
3429 * (Changing fd->events after adding an FD wasn't an anticipated use of
3430 * this API, but it occurs in practice.) */
3433 fds[n_poll].fd = pollrec->fd->fd;
3434 /* In direct contradiction to the Unix98 spec, IRIX runs into
3435 * difficulty if you pass in POLLERR, POLLHUP or POLLNVAL
3436 * flags in the events field of the pollfd while it should
3437 * just ignoring them. So we mask them out here.
3439 fds[n_poll].events = pollrec->fd->events & ~(G_IO_ERR|G_IO_HUP|G_IO_NVAL);
3440 fds[n_poll].revents = 0;
3443 pollrec = pollrec->next;
3447 context->poll_changed = FALSE;
3451 *timeout = context->timeout;
3453 context->time_is_fresh = FALSE;
3456 UNLOCK_CONTEXT (context);
3462 * g_main_context_check:
3463 * @context: a #GMainContext
3464 * @max_priority: the maximum numerical priority of sources to check
3465 * @fds: (array length=n_fds): array of #GPollFD's that was passed to
3466 * the last call to g_main_context_query()
3467 * @n_fds: return value of g_main_context_query()
3469 * Passes the results of polling back to the main loop.
3471 * Return value: %TRUE if some sources are ready to be dispatched.
3474 g_main_context_check (GMainContext *context,
3485 LOCK_CONTEXT (context);
3487 if (context->in_check_or_prepare)
3489 g_warning ("g_main_context_check() called recursively from within a source's check() or "
3490 "prepare() member.");
3491 UNLOCK_CONTEXT (context);
3495 if (context->wake_up_rec.revents)
3496 g_wakeup_acknowledge (context->wakeup);
3498 /* If the set of poll file descriptors changed, bail out
3499 * and let the main loop rerun
3501 if (context->poll_changed)
3503 UNLOCK_CONTEXT (context);
3507 pollrec = context->poll_records;
3511 if (pollrec->fd->events)
3512 pollrec->fd->revents = fds[i].revents;
3514 pollrec = pollrec->next;
3518 g_source_iter_init (&iter, context, TRUE);
3519 while (g_source_iter_next (&iter, &source))
3521 if (SOURCE_DESTROYED (source) || SOURCE_BLOCKED (source))
3523 if ((n_ready > 0) && (source->priority > max_priority))
3526 if (!(source->flags & G_SOURCE_READY))
3529 gboolean (* check) (GSource *source);
3531 check = source->source_funcs->check;
3535 /* If the check function is set, call it. */
3536 context->in_check_or_prepare++;
3537 UNLOCK_CONTEXT (context);
3539 result = (* check) (source);
3541 LOCK_CONTEXT (context);
3542 context->in_check_or_prepare--;
3547 if (result == FALSE)
3551 /* If not already explicitly flagged ready by ->check()
3552 * (or if we have no check) then we can still be ready if
3553 * any of our fds poll as ready.
3555 for (tmp_list = source->priv->fds; tmp_list; tmp_list = tmp_list->next)
3557 GPollFD *pollfd = tmp_list->data;
3559 if (pollfd->revents)
3567 if (result == FALSE && source->priv->ready_time != -1)
3569 if (!context->time_is_fresh)
3571 context->time = g_get_monotonic_time ();
3572 context->time_is_fresh = TRUE;
3575 if (source->priv->ready_time <= context->time)
3581 GSource *ready_source = source;
3583 while (ready_source)
3585 ready_source->flags |= G_SOURCE_READY;
3586 ready_source = ready_source->priv->parent_source;
3591 if (source->flags & G_SOURCE_READY)
3593 source->ref_count++;
3594 g_ptr_array_add (context->pending_dispatches, source);
3598 /* never dispatch sources with less priority than the first
3599 * one we choose to dispatch
3601 max_priority = source->priority;
3604 g_source_iter_clear (&iter);
3606 UNLOCK_CONTEXT (context);
3612 * g_main_context_dispatch:
3613 * @context: a #GMainContext
3615 * Dispatches all pending sources.
3618 g_main_context_dispatch (GMainContext *context)
3620 LOCK_CONTEXT (context);
3622 if (context->pending_dispatches->len > 0)
3624 g_main_dispatch (context);
3627 UNLOCK_CONTEXT (context);
3630 /* HOLDS context lock */
3632 g_main_context_iterate (GMainContext *context,
3639 gboolean some_ready;
3640 gint nfds, allocated_nfds;
3641 GPollFD *fds = NULL;
3643 UNLOCK_CONTEXT (context);
3645 if (!g_main_context_acquire (context))
3647 gboolean got_ownership;
3649 LOCK_CONTEXT (context);
3654 got_ownership = g_main_context_wait (context,
3662 LOCK_CONTEXT (context);
3664 if (!context->cached_poll_array)
3666 context->cached_poll_array_size = context->n_poll_records;
3667 context->cached_poll_array = g_new (GPollFD, context->n_poll_records);
3670 allocated_nfds = context->cached_poll_array_size;
3671 fds = context->cached_poll_array;
3673 UNLOCK_CONTEXT (context);
3675 g_main_context_prepare (context, &max_priority);
3677 while ((nfds = g_main_context_query (context, max_priority, &timeout, fds,
3678 allocated_nfds)) > allocated_nfds)
3680 LOCK_CONTEXT (context);
3682 context->cached_poll_array_size = allocated_nfds = nfds;
3683 context->cached_poll_array = fds = g_new (GPollFD, nfds);
3684 UNLOCK_CONTEXT (context);
3690 g_main_context_poll (context, timeout, max_priority, fds, nfds);
3692 some_ready = g_main_context_check (context, max_priority, fds, nfds);
3695 g_main_context_dispatch (context);
3697 g_main_context_release (context);
3699 LOCK_CONTEXT (context);
3705 * g_main_context_pending:
3706 * @context: (allow-none): a #GMainContext (if %NULL, the default context will be used)
3708 * Checks if any sources have pending events for the given context.
3710 * Return value: %TRUE if events are pending.
3713 g_main_context_pending (GMainContext *context)
3718 context = g_main_context_default();
3720 LOCK_CONTEXT (context);
3721 retval = g_main_context_iterate (context, FALSE, FALSE, G_THREAD_SELF);
3722 UNLOCK_CONTEXT (context);
3728 * g_main_context_iteration:
3729 * @context: (allow-none): a #GMainContext (if %NULL, the default context will be used)
3730 * @may_block: whether the call may block.
3732 * Runs a single iteration for the given main loop. This involves
3733 * checking to see if any event sources are ready to be processed,
3734 * then if no events sources are ready and @may_block is %TRUE, waiting
3735 * for a source to become ready, then dispatching the highest priority
3736 * events sources that are ready. Otherwise, if @may_block is %FALSE
3737 * sources are not waited to become ready, only those highest priority
3738 * events sources will be dispatched (if any), that are ready at this
3739 * given moment without further waiting.
3741 * Note that even when @may_block is %TRUE, it is still possible for
3742 * g_main_context_iteration() to return %FALSE, since the wait may
3743 * be interrupted for other reasons than an event source becoming ready.
3745 * Return value: %TRUE if events were dispatched.
3748 g_main_context_iteration (GMainContext *context, gboolean may_block)
3753 context = g_main_context_default();
3755 LOCK_CONTEXT (context);
3756 retval = g_main_context_iterate (context, may_block, TRUE, G_THREAD_SELF);
3757 UNLOCK_CONTEXT (context);
3764 * @context: (allow-none): a #GMainContext (if %NULL, the default context will be used).
3765 * @is_running: set to %TRUE to indicate that the loop is running. This
3766 * is not very important since calling g_main_loop_run() will set this to
3769 * Creates a new #GMainLoop structure.
3771 * Return value: a new #GMainLoop.
3774 g_main_loop_new (GMainContext *context,
3775 gboolean is_running)
3780 context = g_main_context_default();
3782 g_main_context_ref (context);
3784 loop = g_new0 (GMainLoop, 1);
3785 loop->context = context;
3786 loop->is_running = is_running != FALSE;
3787 loop->ref_count = 1;
3794 * @loop: a #GMainLoop
3796 * Increases the reference count on a #GMainLoop object by one.
3798 * Return value: @loop
3801 g_main_loop_ref (GMainLoop *loop)
3803 g_return_val_if_fail (loop != NULL, NULL);
3804 g_return_val_if_fail (g_atomic_int_get (&loop->ref_count) > 0, NULL);
3806 g_atomic_int_inc (&loop->ref_count);
3812 * g_main_loop_unref:
3813 * @loop: a #GMainLoop
3815 * Decreases the reference count on a #GMainLoop object by one. If
3816 * the result is zero, free the loop and free all associated memory.
3819 g_main_loop_unref (GMainLoop *loop)
3821 g_return_if_fail (loop != NULL);
3822 g_return_if_fail (g_atomic_int_get (&loop->ref_count) > 0);
3824 if (!g_atomic_int_dec_and_test (&loop->ref_count))
3827 g_main_context_unref (loop->context);
3833 * @loop: a #GMainLoop
3835 * Runs a main loop until g_main_loop_quit() is called on the loop.
3836 * If this is called for the thread of the loop's #GMainContext,
3837 * it will process events from the loop, otherwise it will
3841 g_main_loop_run (GMainLoop *loop)
3843 GThread *self = G_THREAD_SELF;
3845 g_return_if_fail (loop != NULL);
3846 g_return_if_fail (g_atomic_int_get (&loop->ref_count) > 0);
3848 if (!g_main_context_acquire (loop->context))
3850 gboolean got_ownership = FALSE;
3852 /* Another thread owns this context */
3853 LOCK_CONTEXT (loop->context);
3855 g_atomic_int_inc (&loop->ref_count);
3857 if (!loop->is_running)
3858 loop->is_running = TRUE;
3860 while (loop->is_running && !got_ownership)
3861 got_ownership = g_main_context_wait (loop->context,
3862 &loop->context->cond,
3863 &loop->context->mutex);
3865 if (!loop->is_running)
3867 UNLOCK_CONTEXT (loop->context);
3869 g_main_context_release (loop->context);
3870 g_main_loop_unref (loop);
3874 g_assert (got_ownership);
3877 LOCK_CONTEXT (loop->context);
3879 if (loop->context->in_check_or_prepare)
3881 g_warning ("g_main_loop_run(): called recursively from within a source's "
3882 "check() or prepare() member, iteration not possible.");
3886 g_atomic_int_inc (&loop->ref_count);
3887 loop->is_running = TRUE;
3888 while (loop->is_running)
3889 g_main_context_iterate (loop->context, TRUE, TRUE, self);
3891 UNLOCK_CONTEXT (loop->context);
3893 g_main_context_release (loop->context);
3895 g_main_loop_unref (loop);
3900 * @loop: a #GMainLoop
3902 * Stops a #GMainLoop from running. Any calls to g_main_loop_run()
3903 * for the loop will return.
3905 * Note that sources that have already been dispatched when
3906 * g_main_loop_quit() is called will still be executed.
3909 g_main_loop_quit (GMainLoop *loop)
3911 g_return_if_fail (loop != NULL);
3912 g_return_if_fail (g_atomic_int_get (&loop->ref_count) > 0);
3914 LOCK_CONTEXT (loop->context);
3915 loop->is_running = FALSE;
3916 g_wakeup_signal (loop->context->wakeup);
3918 g_cond_broadcast (&loop->context->cond);
3920 UNLOCK_CONTEXT (loop->context);
3924 * g_main_loop_is_running:
3925 * @loop: a #GMainLoop.
3927 * Checks to see if the main loop is currently being run via g_main_loop_run().
3929 * Return value: %TRUE if the mainloop is currently being run.
3932 g_main_loop_is_running (GMainLoop *loop)
3934 g_return_val_if_fail (loop != NULL, FALSE);
3935 g_return_val_if_fail (g_atomic_int_get (&loop->ref_count) > 0, FALSE);
3937 return loop->is_running;
3941 * g_main_loop_get_context:
3942 * @loop: a #GMainLoop.
3944 * Returns the #GMainContext of @loop.
3946 * Return value: (transfer none): the #GMainContext of @loop
3949 g_main_loop_get_context (GMainLoop *loop)
3951 g_return_val_if_fail (loop != NULL, NULL);
3952 g_return_val_if_fail (g_atomic_int_get (&loop->ref_count) > 0, NULL);
3954 return loop->context;
3957 /* HOLDS: context's lock */
3959 g_main_context_poll (GMainContext *context,
3965 #ifdef G_MAIN_POLL_DEBUG
3971 GPollFunc poll_func;
3973 if (n_fds || timeout != 0)
3975 #ifdef G_MAIN_POLL_DEBUG
3976 if (_g_main_poll_debug)
3978 g_print ("polling context=%p n=%d timeout=%d\n",
3979 context, n_fds, timeout);
3980 poll_timer = g_timer_new ();
3984 LOCK_CONTEXT (context);
3986 poll_func = context->poll_func;
3988 UNLOCK_CONTEXT (context);
3989 if ((*poll_func) (fds, n_fds, timeout) < 0 && errno != EINTR)
3992 g_warning ("poll(2) failed due to: %s.",
3993 g_strerror (errno));
3995 /* If g_poll () returns -1, it has already called g_warning() */
3999 #ifdef G_MAIN_POLL_DEBUG
4000 if (_g_main_poll_debug)
4002 LOCK_CONTEXT (context);
4004 g_print ("g_main_poll(%d) timeout: %d - elapsed %12.10f seconds",
4007 g_timer_elapsed (poll_timer, NULL));
4008 g_timer_destroy (poll_timer);
4009 pollrec = context->poll_records;
4011 while (pollrec != NULL)
4016 if (fds[i].fd == pollrec->fd->fd &&
4017 pollrec->fd->events &&
4020 g_print (" [" G_POLLFD_FORMAT " :", fds[i].fd);
4021 if (fds[i].revents & G_IO_IN)
4023 if (fds[i].revents & G_IO_OUT)
4025 if (fds[i].revents & G_IO_PRI)
4027 if (fds[i].revents & G_IO_ERR)
4029 if (fds[i].revents & G_IO_HUP)
4031 if (fds[i].revents & G_IO_NVAL)
4037 pollrec = pollrec->next;
4041 UNLOCK_CONTEXT (context);
4044 } /* if (n_fds || timeout != 0) */
4048 * g_main_context_add_poll:
4049 * @context: (allow-none): a #GMainContext (or %NULL for the default context)
4050 * @fd: a #GPollFD structure holding information about a file
4051 * descriptor to watch.
4052 * @priority: the priority for this file descriptor which should be
4053 * the same as the priority used for g_source_attach() to ensure that the
4054 * file descriptor is polled whenever the results may be needed.
4056 * Adds a file descriptor to the set of file descriptors polled for
4057 * this context. This will very seldom be used directly. Instead
4058 * a typical event source will use g_source_add_unix_fd() instead.
4061 g_main_context_add_poll (GMainContext *context,
4066 context = g_main_context_default ();
4068 g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
4069 g_return_if_fail (fd);
4071 LOCK_CONTEXT (context);
4072 g_main_context_add_poll_unlocked (context, priority, fd);
4073 UNLOCK_CONTEXT (context);
4076 /* HOLDS: main_loop_lock */
4078 g_main_context_add_poll_unlocked (GMainContext *context,
4082 GPollRec *prevrec, *nextrec;
4083 GPollRec *newrec = g_slice_new (GPollRec);
4085 /* This file descriptor may be checked before we ever poll */
4088 newrec->priority = priority;
4090 prevrec = context->poll_records_tail;
4092 while (prevrec && priority < prevrec->priority)
4095 prevrec = prevrec->prev;
4099 prevrec->next = newrec;
4101 context->poll_records = newrec;
4103 newrec->prev = prevrec;
4104 newrec->next = nextrec;
4107 nextrec->prev = newrec;
4109 context->poll_records_tail = newrec;
4111 context->n_poll_records++;
4113 context->poll_changed = TRUE;
4115 /* Now wake up the main loop if it is waiting in the poll() */
4116 g_wakeup_signal (context->wakeup);
4120 * g_main_context_remove_poll:
4121 * @context:a #GMainContext
4122 * @fd: a #GPollFD descriptor previously added with g_main_context_add_poll()
4124 * Removes file descriptor from the set of file descriptors to be
4125 * polled for a particular context.
4128 g_main_context_remove_poll (GMainContext *context,
4132 context = g_main_context_default ();
4134 g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
4135 g_return_if_fail (fd);
4137 LOCK_CONTEXT (context);
4138 g_main_context_remove_poll_unlocked (context, fd);
4139 UNLOCK_CONTEXT (context);
4143 g_main_context_remove_poll_unlocked (GMainContext *context,
4146 GPollRec *pollrec, *prevrec, *nextrec;
4149 pollrec = context->poll_records;
4153 nextrec = pollrec->next;
4154 if (pollrec->fd == fd)
4156 if (prevrec != NULL)
4157 prevrec->next = nextrec;
4159 context->poll_records = nextrec;
4161 if (nextrec != NULL)
4162 nextrec->prev = prevrec;
4164 context->poll_records_tail = prevrec;
4166 g_slice_free (GPollRec, pollrec);
4168 context->n_poll_records--;
4175 context->poll_changed = TRUE;
4177 /* Now wake up the main loop if it is waiting in the poll() */
4178 g_wakeup_signal (context->wakeup);
4182 * g_source_get_current_time:
4183 * @source: a #GSource
4184 * @timeval: #GTimeVal structure in which to store current time.
4186 * This function ignores @source and is otherwise the same as
4187 * g_get_current_time().
4189 * Deprecated: 2.28: use g_source_get_time() instead
4192 g_source_get_current_time (GSource *source,
4195 g_get_current_time (timeval);
4199 * g_source_get_time:
4200 * @source: a #GSource
4202 * Gets the time to be used when checking this source. The advantage of
4203 * calling this function over calling g_get_monotonic_time() directly is
4204 * that when checking multiple sources, GLib can cache a single value
4205 * instead of having to repeatedly get the system monotonic time.
4207 * The time here is the system monotonic time, if available, or some
4208 * other reasonable alternative otherwise. See g_get_monotonic_time().
4210 * Returns: the monotonic time in microseconds
4215 g_source_get_time (GSource *source)
4217 GMainContext *context;
4220 g_return_val_if_fail (source->context != NULL, 0);
4222 context = source->context;
4224 LOCK_CONTEXT (context);
4226 if (!context->time_is_fresh)
4228 context->time = g_get_monotonic_time ();
4229 context->time_is_fresh = TRUE;
4232 result = context->time;
4234 UNLOCK_CONTEXT (context);
4240 * g_main_context_set_poll_func:
4241 * @context: a #GMainContext
4242 * @func: the function to call to poll all file descriptors
4244 * Sets the function to use to handle polling of file descriptors. It
4245 * will be used instead of the poll() system call
4246 * (or GLib's replacement function, which is used where
4247 * poll() isn't available).
4249 * This function could possibly be used to integrate the GLib event
4250 * loop with an external event loop.
4253 g_main_context_set_poll_func (GMainContext *context,
4257 context = g_main_context_default ();
4259 g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
4261 LOCK_CONTEXT (context);
4264 context->poll_func = func;
4266 context->poll_func = g_poll;
4268 UNLOCK_CONTEXT (context);
4272 * g_main_context_get_poll_func:
4273 * @context: a #GMainContext
4275 * Gets the poll function set by g_main_context_set_poll_func().
4277 * Return value: the poll function
4280 g_main_context_get_poll_func (GMainContext *context)
4285 context = g_main_context_default ();
4287 g_return_val_if_fail (g_atomic_int_get (&context->ref_count) > 0, NULL);
4289 LOCK_CONTEXT (context);
4290 result = context->poll_func;
4291 UNLOCK_CONTEXT (context);
4297 * g_main_context_wakeup:
4298 * @context: a #GMainContext
4300 * If @context is currently waiting in a poll(), interrupt
4301 * the poll(), and continue the iteration process.
4304 g_main_context_wakeup (GMainContext *context)
4307 context = g_main_context_default ();
4309 g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
4311 g_wakeup_signal (context->wakeup);
4315 * g_main_context_is_owner:
4316 * @context: a #GMainContext
4318 * Determines whether this thread holds the (recursive)
4319 * ownership of this #GMainContext. This is useful to
4320 * know before waiting on another thread that may be
4321 * blocking to get ownership of @context.
4323 * Returns: %TRUE if current thread is owner of @context.
4328 g_main_context_is_owner (GMainContext *context)
4333 context = g_main_context_default ();
4335 LOCK_CONTEXT (context);
4336 is_owner = context->owner == G_THREAD_SELF;
4337 UNLOCK_CONTEXT (context);
4345 g_timeout_set_expiration (GTimeoutSource *timeout_source,
4346 gint64 current_time)
4350 expiration = current_time + (guint64) timeout_source->interval * 1000;
4352 if (timeout_source->seconds)
4355 static gint timer_perturb = -1;
4357 if (timer_perturb == -1)
4360 * we want a per machine/session unique 'random' value; try the dbus
4361 * address first, that has a UUID in it. If there is no dbus, use the
4362 * hostname for hashing.
4364 const char *session_bus_address = g_getenv ("DBUS_SESSION_BUS_ADDRESS");
4365 if (!session_bus_address)
4366 session_bus_address = g_getenv ("HOSTNAME");
4367 if (session_bus_address)
4368 timer_perturb = ABS ((gint) g_str_hash (session_bus_address)) % 1000000;
4373 /* We want the microseconds part of the timeout to land on the
4374 * 'timer_perturb' mark, but we need to make sure we don't try to
4375 * set the timeout in the past. We do this by ensuring that we
4376 * always only *increase* the expiration time by adding a full
4377 * second in the case that the microsecond portion decreases.
4379 expiration -= timer_perturb;
4381 remainder = expiration % 1000000;
4382 if (remainder >= 1000000/4)
4383 expiration += 1000000;
4385 expiration -= remainder;
4386 expiration += timer_perturb;
4389 g_source_set_ready_time ((GSource *) timeout_source, expiration);
4393 g_timeout_dispatch (GSource *source,
4394 GSourceFunc callback,
4397 GTimeoutSource *timeout_source = (GTimeoutSource *)source;
4402 g_warning ("Timeout source dispatched without callback\n"
4403 "You must call g_source_set_callback().");
4407 again = callback (user_data);
4410 g_timeout_set_expiration (timeout_source, g_source_get_time (source));
4416 * g_timeout_source_new:
4417 * @interval: the timeout interval in milliseconds.
4419 * Creates a new timeout source.
4421 * The source will not initially be associated with any #GMainContext
4422 * and must be added to one with g_source_attach() before it will be
4425 * The interval given is in terms of monotonic time, not wall clock
4426 * time. See g_get_monotonic_time().
4428 * Return value: the newly-created timeout source
4431 g_timeout_source_new (guint interval)
4433 GSource *source = g_source_new (&g_timeout_funcs, sizeof (GTimeoutSource));
4434 GTimeoutSource *timeout_source = (GTimeoutSource *)source;
4436 timeout_source->interval = interval;
4437 g_timeout_set_expiration (timeout_source, g_get_monotonic_time ());
4443 * g_timeout_source_new_seconds:
4444 * @interval: the timeout interval in seconds
4446 * Creates a new timeout source.
4448 * The source will not initially be associated with any #GMainContext
4449 * and must be added to one with g_source_attach() before it will be
4452 * The scheduling granularity/accuracy of this timeout source will be
4455 * The interval given in terms of monotonic time, not wall clock time.
4456 * See g_get_monotonic_time().
4458 * Return value: the newly-created timeout source
4463 g_timeout_source_new_seconds (guint interval)
4465 GSource *source = g_source_new (&g_timeout_funcs, sizeof (GTimeoutSource));
4466 GTimeoutSource *timeout_source = (GTimeoutSource *)source;
4468 timeout_source->interval = 1000 * interval;
4469 timeout_source->seconds = TRUE;
4471 g_timeout_set_expiration (timeout_source, g_get_monotonic_time ());
4478 * g_timeout_add_full:
4479 * @priority: the priority of the timeout source. Typically this will be in
4480 * the range between #G_PRIORITY_DEFAULT and #G_PRIORITY_HIGH.
4481 * @interval: the time between calls to the function, in milliseconds
4482 * (1/1000ths of a second)
4483 * @function: function to call
4484 * @data: data to pass to @function
4485 * @notify: (allow-none): function to call when the timeout is removed, or %NULL
4487 * Sets a function to be called at regular intervals, with the given
4488 * priority. The function is called repeatedly until it returns
4489 * %FALSE, at which point the timeout is automatically destroyed and
4490 * the function will not be called again. The @notify function is
4491 * called when the timeout is destroyed. The first call to the
4492 * function will be at the end of the first @interval.
4494 * Note that timeout functions may be delayed, due to the processing of other
4495 * event sources. Thus they should not be relied on for precise timing.
4496 * After each call to the timeout function, the time of the next
4497 * timeout is recalculated based on the current time and the given interval
4498 * (it does not try to 'catch up' time lost in delays).
4500 * This internally creates a main loop source using g_timeout_source_new()
4501 * and attaches it to the main loop context using g_source_attach(). You can
4502 * do these steps manually if you need greater control.
4504 * The interval given in terms of monotonic time, not wall clock time.
4505 * See g_get_monotonic_time().
4507 * Return value: the ID (greater than 0) of the event source.
4508 * Rename to: g_timeout_add
4511 g_timeout_add_full (gint priority,
4513 GSourceFunc function,
4515 GDestroyNotify notify)
4520 g_return_val_if_fail (function != NULL, 0);
4522 source = g_timeout_source_new (interval);
4524 if (priority != G_PRIORITY_DEFAULT)
4525 g_source_set_priority (source, priority);
4527 g_source_set_callback (source, function, data, notify);
4528 id = g_source_attach (source, NULL);
4529 g_source_unref (source);
4536 * @interval: the time between calls to the function, in milliseconds
4537 * (1/1000ths of a second)
4538 * @function: function to call
4539 * @data: data to pass to @function
4541 * Sets a function to be called at regular intervals, with the default
4542 * priority, #G_PRIORITY_DEFAULT. The function is called repeatedly
4543 * until it returns %FALSE, at which point the timeout is automatically
4544 * destroyed and the function will not be called again. The first call
4545 * to the function will be at the end of the first @interval.
4547 * Note that timeout functions may be delayed, due to the processing of other
4548 * event sources. Thus they should not be relied on for precise timing.
4549 * After each call to the timeout function, the time of the next
4550 * timeout is recalculated based on the current time and the given interval
4551 * (it does not try to 'catch up' time lost in delays).
4553 * If you want to have a timer in the "seconds" range and do not care
4554 * about the exact time of the first call of the timer, use the
4555 * g_timeout_add_seconds() function; this function allows for more
4556 * optimizations and more efficient system power usage.
4558 * This internally creates a main loop source using g_timeout_source_new()
4559 * and attaches it to the main loop context using g_source_attach(). You can
4560 * do these steps manually if you need greater control.
4562 * The interval given is in terms of monotonic time, not wall clock
4563 * time. See g_get_monotonic_time().
4565 * Return value: the ID (greater than 0) of the event source.
4568 g_timeout_add (guint32 interval,
4569 GSourceFunc function,
4572 return g_timeout_add_full (G_PRIORITY_DEFAULT,
4573 interval, function, data, NULL);
4577 * g_timeout_add_seconds_full:
4578 * @priority: the priority of the timeout source. Typically this will be in
4579 * the range between #G_PRIORITY_DEFAULT and #G_PRIORITY_HIGH.
4580 * @interval: the time between calls to the function, in seconds
4581 * @function: function to call
4582 * @data: data to pass to @function
4583 * @notify: (allow-none): function to call when the timeout is removed, or %NULL
4585 * Sets a function to be called at regular intervals, with @priority.
4586 * The function is called repeatedly until it returns %FALSE, at which
4587 * point the timeout is automatically destroyed and the function will
4588 * not be called again.
4590 * Unlike g_timeout_add(), this function operates at whole second granularity.
4591 * The initial starting point of the timer is determined by the implementation
4592 * and the implementation is expected to group multiple timers together so that
4593 * they fire all at the same time.
4594 * To allow this grouping, the @interval to the first timer is rounded
4595 * and can deviate up to one second from the specified interval.
4596 * Subsequent timer iterations will generally run at the specified interval.
4598 * Note that timeout functions may be delayed, due to the processing of other
4599 * event sources. Thus they should not be relied on for precise timing.
4600 * After each call to the timeout function, the time of the next
4601 * timeout is recalculated based on the current time and the given @interval
4603 * If you want timing more precise than whole seconds, use g_timeout_add()
4606 * The grouping of timers to fire at the same time results in a more power
4607 * and CPU efficient behavior so if your timer is in multiples of seconds
4608 * and you don't require the first timer exactly one second from now, the
4609 * use of g_timeout_add_seconds() is preferred over g_timeout_add().
4611 * This internally creates a main loop source using
4612 * g_timeout_source_new_seconds() and attaches it to the main loop context
4613 * using g_source_attach(). You can do these steps manually if you need
4616 * The interval given is in terms of monotonic time, not wall clock
4617 * time. See g_get_monotonic_time().
4619 * Return value: the ID (greater than 0) of the event source.
4621 * Rename to: g_timeout_add_seconds
4625 g_timeout_add_seconds_full (gint priority,
4627 GSourceFunc function,
4629 GDestroyNotify notify)
4634 g_return_val_if_fail (function != NULL, 0);
4636 source = g_timeout_source_new_seconds (interval);
4638 if (priority != G_PRIORITY_DEFAULT)
4639 g_source_set_priority (source, priority);
4641 g_source_set_callback (source, function, data, notify);
4642 id = g_source_attach (source, NULL);
4643 g_source_unref (source);
4649 * g_timeout_add_seconds:
4650 * @interval: the time between calls to the function, in seconds
4651 * @function: function to call
4652 * @data: data to pass to @function
4654 * Sets a function to be called at regular intervals with the default
4655 * priority, #G_PRIORITY_DEFAULT. The function is called repeatedly until
4656 * it returns %FALSE, at which point the timeout is automatically destroyed
4657 * and the function will not be called again.
4659 * This internally creates a main loop source using
4660 * g_timeout_source_new_seconds() and attaches it to the main loop context
4661 * using g_source_attach(). You can do these steps manually if you need
4662 * greater control. Also see g_timeout_add_seconds_full().
4664 * Note that the first call of the timer may not be precise for timeouts
4665 * of one second. If you need finer precision and have such a timeout,
4666 * you may want to use g_timeout_add() instead.
4668 * The interval given is in terms of monotonic time, not wall clock
4669 * time. See g_get_monotonic_time().
4671 * Return value: the ID (greater than 0) of the event source.
4676 g_timeout_add_seconds (guint interval,
4677 GSourceFunc function,
4680 g_return_val_if_fail (function != NULL, 0);
4682 return g_timeout_add_seconds_full (G_PRIORITY_DEFAULT, interval, function, data, NULL);
4685 /* Child watch functions */
4690 g_child_watch_prepare (GSource *source,
4698 g_child_watch_check (GSource *source)
4700 GChildWatchSource *child_watch_source;
4701 gboolean child_exited;
4703 child_watch_source = (GChildWatchSource *) source;
4705 child_exited = child_watch_source->poll.revents & G_IO_IN;
4712 * Note: We do _not_ check for the special value of STILL_ACTIVE
4713 * since we know that the process has exited and doing so runs into
4714 * problems if the child process "happens to return STILL_ACTIVE(259)"
4715 * as Microsoft's Platform SDK puts it.
4717 if (!GetExitCodeProcess (child_watch_source->pid, &child_status))
4719 gchar *emsg = g_win32_error_message (GetLastError ());
4720 g_warning (G_STRLOC ": GetExitCodeProcess() failed: %s", emsg);
4723 child_watch_source->child_status = -1;
4726 child_watch_source->child_status = child_status;
4729 return child_exited;
4733 g_child_watch_finalize (GSource *source)
4737 #else /* G_OS_WIN32 */
4740 wake_source (GSource *source)
4742 GMainContext *context;
4744 /* This should be thread-safe:
4746 * - if the source is currently being added to a context, that
4747 * context will be woken up anyway
4749 * - if the source is currently being destroyed, we simply need not
4752 * - the memory for the source will remain valid until after the
4753 * source finalize function was called (which would remove the
4754 * source from the global list which we are currently holding the
4757 * - the GMainContext will either be NULL or point to a live
4760 * - the GMainContext will remain valid since we hold the
4761 * main_context_list lock
4763 * Since we are holding a lot of locks here, don't try to enter any
4764 * more GMainContext functions for fear of dealock -- just hit the
4765 * GWakeup and run. Even if that's safe now, it could easily become
4766 * unsafe with some very minor changes in the future, and signal
4767 * handling is not the most well-tested codepath.
4769 G_LOCK(main_context_list);
4770 context = source->context;
4772 g_wakeup_signal (context->wakeup);
4773 G_UNLOCK(main_context_list);
4777 dispatch_unix_signals (void)
4781 /* clear this first incase another one arrives while we're processing */
4782 any_unix_signal_pending = FALSE;
4784 G_LOCK(unix_signal_lock);
4786 /* handle GChildWatchSource instances */
4787 if (unix_signal_pending[SIGCHLD])
4789 unix_signal_pending[SIGCHLD] = FALSE;
4791 /* The only way we can do this is to scan all of the children.
4793 * The docs promise that we will not reap children that we are not
4794 * explicitly watching, so that ties our hands from calling
4795 * waitpid(-1). We also can't use siginfo's si_pid field since if
4796 * multiple SIGCHLD arrive at the same time, one of them can be
4797 * dropped (since a given UNIX signal can only be pending once).
4799 for (node = unix_child_watches; node; node = node->next)
4801 GChildWatchSource *source = node->data;
4803 if (!source->child_exited)
4808 pid = waitpid (source->pid, &source->child_status, WNOHANG);
4811 source->child_exited = TRUE;
4812 wake_source ((GSource *) source);
4814 else if (pid == -1 && errno == ECHILD)
4816 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.");
4817 source->child_exited = TRUE;
4818 source->child_status = 0;
4819 wake_source ((GSource *) source);
4822 while (pid == -1 && errno == EINTR);
4827 /* handle GUnixSignalWatchSource instances */
4828 for (node = unix_signal_watches; node; node = node->next)
4830 GUnixSignalWatchSource *source = node->data;
4832 if (!source->pending)
4834 if (unix_signal_pending[source->signum])
4836 unix_signal_pending[source->signum] = FALSE;
4837 source->pending = TRUE;
4839 wake_source ((GSource *) source);
4844 G_UNLOCK(unix_signal_lock);
4848 g_child_watch_prepare (GSource *source,
4851 GChildWatchSource *child_watch_source;
4853 child_watch_source = (GChildWatchSource *) source;
4855 return child_watch_source->child_exited;
4859 g_child_watch_check (GSource *source)
4861 GChildWatchSource *child_watch_source;
4863 child_watch_source = (GChildWatchSource *) source;
4865 return child_watch_source->child_exited;
4869 g_unix_signal_watch_prepare (GSource *source,
4872 GUnixSignalWatchSource *unix_signal_source;
4874 unix_signal_source = (GUnixSignalWatchSource *) source;
4876 return unix_signal_source->pending;
4880 g_unix_signal_watch_check (GSource *source)
4882 GUnixSignalWatchSource *unix_signal_source;
4884 unix_signal_source = (GUnixSignalWatchSource *) source;
4886 return unix_signal_source->pending;
4890 g_unix_signal_watch_dispatch (GSource *source,
4891 GSourceFunc callback,
4894 GUnixSignalWatchSource *unix_signal_source;
4897 unix_signal_source = (GUnixSignalWatchSource *) source;
4901 g_warning ("Unix signal source dispatched without callback\n"
4902 "You must call g_source_set_callback().");
4906 again = (callback) (user_data);
4908 unix_signal_source->pending = FALSE;
4914 ensure_unix_signal_handler_installed_unlocked (int signum)
4916 static sigset_t installed_signal_mask;
4917 static gboolean initialized;
4918 struct sigaction action;
4922 sigemptyset (&installed_signal_mask);
4923 g_get_worker_context ();
4927 if (sigismember (&installed_signal_mask, signum))
4930 sigaddset (&installed_signal_mask, signum);
4932 action.sa_handler = g_unix_signal_handler;
4933 sigemptyset (&action.sa_mask);
4934 action.sa_flags = SA_RESTART | SA_NOCLDSTOP;
4935 sigaction (signum, &action, NULL);
4939 _g_main_create_unix_signal_watch (int signum)
4942 GUnixSignalWatchSource *unix_signal_source;
4944 source = g_source_new (&g_unix_signal_funcs, sizeof (GUnixSignalWatchSource));
4945 unix_signal_source = (GUnixSignalWatchSource *) source;
4947 unix_signal_source->signum = signum;
4948 unix_signal_source->pending = FALSE;
4950 G_LOCK (unix_signal_lock);
4951 ensure_unix_signal_handler_installed_unlocked (signum);
4952 unix_signal_watches = g_slist_prepend (unix_signal_watches, unix_signal_source);
4953 if (unix_signal_pending[signum])
4954 unix_signal_source->pending = TRUE;
4955 unix_signal_pending[signum] = FALSE;
4956 G_UNLOCK (unix_signal_lock);
4962 g_unix_signal_watch_finalize (GSource *source)
4964 G_LOCK (unix_signal_lock);
4965 unix_signal_watches = g_slist_remove (unix_signal_watches, source);
4966 G_UNLOCK (unix_signal_lock);
4970 g_child_watch_finalize (GSource *source)
4972 G_LOCK (unix_signal_lock);
4973 unix_child_watches = g_slist_remove (unix_child_watches, source);
4974 G_UNLOCK (unix_signal_lock);
4977 #endif /* G_OS_WIN32 */
4980 g_child_watch_dispatch (GSource *source,
4981 GSourceFunc callback,
4984 GChildWatchSource *child_watch_source;
4985 GChildWatchFunc child_watch_callback = (GChildWatchFunc) callback;
4987 child_watch_source = (GChildWatchSource *) source;
4991 g_warning ("Child watch source dispatched without callback\n"
4992 "You must call g_source_set_callback().");
4996 (child_watch_callback) (child_watch_source->pid, child_watch_source->child_status, user_data);
4998 /* We never keep a child watch source around as the child is gone */
5005 g_unix_signal_handler (int signum)
5007 unix_signal_pending[signum] = TRUE;
5008 any_unix_signal_pending = TRUE;
5010 g_wakeup_signal (glib_worker_context->wakeup);
5013 #endif /* !G_OS_WIN32 */
5016 * g_child_watch_source_new:
5017 * @pid: process to watch. On POSIX the pid of a child process. On
5018 * Windows a handle for a process (which doesn't have to be a child).
5020 * Creates a new child_watch source.
5022 * The source will not initially be associated with any #GMainContext
5023 * and must be added to one with g_source_attach() before it will be
5026 * Note that child watch sources can only be used in conjunction with
5027 * <literal>g_spawn...</literal> when the %G_SPAWN_DO_NOT_REAP_CHILD
5030 * Note that on platforms where #GPid must be explicitly closed
5031 * (see g_spawn_close_pid()) @pid must not be closed while the
5032 * source is still active. Typically, you will want to call
5033 * g_spawn_close_pid() in the callback function for the source.
5035 * Note further that using g_child_watch_source_new() is not
5036 * compatible with calling <literal>waitpid</literal> with a
5037 * nonpositive first argument in the application. Calling waitpid()
5038 * for individual pids will still work fine.
5040 * Return value: the newly-created child watch source
5045 g_child_watch_source_new (GPid pid)
5047 GSource *source = g_source_new (&g_child_watch_funcs, sizeof (GChildWatchSource));
5048 GChildWatchSource *child_watch_source = (GChildWatchSource *)source;
5050 child_watch_source->pid = pid;
5053 child_watch_source->poll.fd = (gintptr) pid;
5054 child_watch_source->poll.events = G_IO_IN;
5056 g_source_add_poll (source, &child_watch_source->poll);
5057 #else /* G_OS_WIN32 */
5058 G_LOCK (unix_signal_lock);
5059 ensure_unix_signal_handler_installed_unlocked (SIGCHLD);
5060 unix_child_watches = g_slist_prepend (unix_child_watches, child_watch_source);
5061 if (waitpid (pid, &child_watch_source->child_status, WNOHANG) > 0)
5062 child_watch_source->child_exited = TRUE;
5063 G_UNLOCK (unix_signal_lock);
5064 #endif /* G_OS_WIN32 */
5070 * g_child_watch_add_full:
5071 * @priority: the priority of the idle source. Typically this will be in the
5072 * range between #G_PRIORITY_DEFAULT_IDLE and #G_PRIORITY_HIGH_IDLE.
5073 * @pid: process to watch. On POSIX the pid of a child process. On
5074 * Windows a handle for a process (which doesn't have to be a child).
5075 * @function: function to call
5076 * @data: data to pass to @function
5077 * @notify: (allow-none): function to call when the idle is removed, or %NULL
5079 * Sets a function to be called when the child indicated by @pid
5080 * exits, at the priority @priority.
5082 * If you obtain @pid from g_spawn_async() or g_spawn_async_with_pipes()
5083 * you will need to pass #G_SPAWN_DO_NOT_REAP_CHILD as flag to
5084 * the spawn function for the child watching to work.
5086 * In many programs, you will want to call g_spawn_check_exit_status()
5087 * in the callback to determine whether or not the child exited
5090 * Also, note that on platforms where #GPid must be explicitly closed
5091 * (see g_spawn_close_pid()) @pid must not be closed while the source
5092 * is still active. Typically, you should invoke g_spawn_close_pid()
5093 * in the callback function for the source.
5095 * GLib supports only a single callback per process id.
5097 * This internally creates a main loop source using
5098 * g_child_watch_source_new() and attaches it to the main loop context
5099 * using g_source_attach(). You can do these steps manually if you
5100 * need greater control.
5102 * Return value: the ID (greater than 0) of the event source.
5104 * Rename to: g_child_watch_add
5108 g_child_watch_add_full (gint priority,
5110 GChildWatchFunc function,
5112 GDestroyNotify notify)
5117 g_return_val_if_fail (function != NULL, 0);
5119 source = g_child_watch_source_new (pid);
5121 if (priority != G_PRIORITY_DEFAULT)
5122 g_source_set_priority (source, priority);
5124 g_source_set_callback (source, (GSourceFunc) function, data, notify);
5125 id = g_source_attach (source, NULL);
5126 g_source_unref (source);
5132 * g_child_watch_add:
5133 * @pid: process id to watch. On POSIX the pid of a child process. On
5134 * Windows a handle for a process (which doesn't have to be a child).
5135 * @function: function to call
5136 * @data: data to pass to @function
5138 * Sets a function to be called when the child indicated by @pid
5139 * exits, at a default priority, #G_PRIORITY_DEFAULT.
5141 * If you obtain @pid from g_spawn_async() or g_spawn_async_with_pipes()
5142 * you will need to pass #G_SPAWN_DO_NOT_REAP_CHILD as flag to
5143 * the spawn function for the child watching to work.
5145 * Note that on platforms where #GPid must be explicitly closed
5146 * (see g_spawn_close_pid()) @pid must not be closed while the
5147 * source is still active. Typically, you will want to call
5148 * g_spawn_close_pid() in the callback function for the source.
5150 * GLib supports only a single callback per process id.
5152 * This internally creates a main loop source using
5153 * g_child_watch_source_new() and attaches it to the main loop context
5154 * using g_source_attach(). You can do these steps manually if you
5155 * need greater control.
5157 * Return value: the ID (greater than 0) of the event source.
5162 g_child_watch_add (GPid pid,
5163 GChildWatchFunc function,
5166 return g_child_watch_add_full (G_PRIORITY_DEFAULT, pid, function, data, NULL);
5170 /* Idle functions */
5173 g_idle_prepare (GSource *source,
5182 g_idle_check (GSource *source)
5188 g_idle_dispatch (GSource *source,
5189 GSourceFunc callback,
5194 g_warning ("Idle source dispatched without callback\n"
5195 "You must call g_source_set_callback().");
5199 return callback (user_data);
5203 * g_idle_source_new:
5205 * Creates a new idle source.
5207 * The source will not initially be associated with any #GMainContext
5208 * and must be added to one with g_source_attach() before it will be
5209 * executed. Note that the default priority for idle sources is
5210 * %G_PRIORITY_DEFAULT_IDLE, as compared to other sources which
5211 * have a default priority of %G_PRIORITY_DEFAULT.
5213 * Return value: the newly-created idle source
5216 g_idle_source_new (void)
5220 source = g_source_new (&g_idle_funcs, sizeof (GSource));
5221 g_source_set_priority (source, G_PRIORITY_DEFAULT_IDLE);
5228 * @priority: the priority of the idle source. Typically this will be in the
5229 * range between #G_PRIORITY_DEFAULT_IDLE and #G_PRIORITY_HIGH_IDLE.
5230 * @function: function to call
5231 * @data: data to pass to @function
5232 * @notify: (allow-none): function to call when the idle is removed, or %NULL
5234 * Adds a function to be called whenever there are no higher priority
5235 * events pending. If the function returns %FALSE it is automatically
5236 * removed from the list of event sources and will not be called again.
5238 * This internally creates a main loop source using g_idle_source_new()
5239 * and attaches it to the main loop context using g_source_attach().
5240 * You can do these steps manually if you need greater control.
5242 * Return value: the ID (greater than 0) of the event source.
5243 * Rename to: g_idle_add
5246 g_idle_add_full (gint priority,
5247 GSourceFunc function,
5249 GDestroyNotify notify)
5254 g_return_val_if_fail (function != NULL, 0);
5256 source = g_idle_source_new ();
5258 if (priority != G_PRIORITY_DEFAULT_IDLE)
5259 g_source_set_priority (source, priority);
5261 g_source_set_callback (source, function, data, notify);
5262 id = g_source_attach (source, NULL);
5263 g_source_unref (source);
5270 * @function: function to call
5271 * @data: data to pass to @function.
5273 * Adds a function to be called whenever there are no higher priority
5274 * events pending to the default main loop. The function is given the
5275 * default idle priority, #G_PRIORITY_DEFAULT_IDLE. If the function
5276 * returns %FALSE it is automatically removed from the list of event
5277 * sources and will not be called again.
5279 * This internally creates a main loop source using g_idle_source_new()
5280 * and attaches it to the main loop context using g_source_attach().
5281 * You can do these steps manually if you need greater control.
5283 * Return value: the ID (greater than 0) of the event source.
5286 g_idle_add (GSourceFunc function,
5289 return g_idle_add_full (G_PRIORITY_DEFAULT_IDLE, function, data, NULL);
5293 * g_idle_remove_by_data:
5294 * @data: the data for the idle source's callback.
5296 * Removes the idle function with the given data.
5298 * Return value: %TRUE if an idle source was found and removed.
5301 g_idle_remove_by_data (gpointer data)
5303 return g_source_remove_by_funcs_user_data (&g_idle_funcs, data);
5307 * g_main_context_invoke:
5308 * @context: (allow-none): a #GMainContext, or %NULL
5309 * @function: function to call
5310 * @data: data to pass to @function
5312 * Invokes a function in such a way that @context is owned during the
5313 * invocation of @function.
5315 * If @context is %NULL then the global default main context — as
5316 * returned by g_main_context_default() — is used.
5318 * If @context is owned by the current thread, @function is called
5319 * directly. Otherwise, if @context is the thread-default main context
5320 * of the current thread and g_main_context_acquire() succeeds, then
5321 * @function is called and g_main_context_release() is called
5324 * In any other case, an idle source is created to call @function and
5325 * that source is attached to @context (presumably to be run in another
5326 * thread). The idle source is attached with #G_PRIORITY_DEFAULT
5327 * priority. If you want a different priority, use
5328 * g_main_context_invoke_full().
5330 * Note that, as with normal idle functions, @function should probably
5331 * return %FALSE. If it returns %TRUE, it will be continuously run in a
5332 * loop (and may prevent this call from returning).
5337 g_main_context_invoke (GMainContext *context,
5338 GSourceFunc function,
5341 g_main_context_invoke_full (context,
5343 function, data, NULL);
5347 * g_main_context_invoke_full:
5348 * @context: (allow-none): a #GMainContext, or %NULL
5349 * @priority: the priority at which to run @function
5350 * @function: function to call
5351 * @data: data to pass to @function
5352 * @notify: (allow-none): a function to call when @data is no longer in use, or %NULL.
5354 * Invokes a function in such a way that @context is owned during the
5355 * invocation of @function.
5357 * This function is the same as g_main_context_invoke() except that it
5358 * lets you specify the priority incase @function ends up being
5359 * scheduled as an idle and also lets you give a #GDestroyNotify for @data.
5361 * @notify should not assume that it is called from any particular
5362 * thread or with any particular context acquired.
5367 g_main_context_invoke_full (GMainContext *context,
5369 GSourceFunc function,
5371 GDestroyNotify notify)
5373 g_return_if_fail (function != NULL);
5376 context = g_main_context_default ();
5378 if (g_main_context_is_owner (context))
5380 while (function (data));
5387 GMainContext *thread_default;
5389 thread_default = g_main_context_get_thread_default ();
5391 if (!thread_default)
5392 thread_default = g_main_context_default ();
5394 if (thread_default == context && g_main_context_acquire (context))
5396 while (function (data));
5398 g_main_context_release (context);
5407 source = g_idle_source_new ();
5408 g_source_set_priority (source, priority);
5409 g_source_set_callback (source, function, data, notify);
5410 g_source_attach (source, context);
5411 g_source_unref (source);
5417 glib_worker_main (gpointer data)
5421 g_main_context_iteration (glib_worker_context, TRUE);
5424 if (any_unix_signal_pending)
5425 dispatch_unix_signals ();
5429 return NULL; /* worst GCC warning message ever... */
5433 g_get_worker_context (void)
5435 static gsize initialised;
5437 if (g_once_init_enter (&initialised))
5439 /* mask all signals in the worker thread */
5445 pthread_sigmask (SIG_SETMASK, &all, &prev_mask);
5447 glib_worker_context = g_main_context_new ();
5448 g_thread_new ("gmain", glib_worker_main, NULL);
5450 pthread_sigmask (SIG_SETMASK, &prev_mask, NULL);
5452 g_once_init_leave (&initialised, TRUE);
5455 return glib_worker_context;