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-private.h"
105 * @title: The Main Event Loop
106 * @short_description: manages all available sources of events
108 * The main event loop manages all the available sources of events for
109 * GLib and GTK+ applications. These events can come from any number of
110 * different types of sources such as file descriptors (plain files,
111 * pipes or sockets) and timeouts. New types of event sources can also
112 * be added using g_source_attach().
114 * To allow multiple independent sets of sources to be handled in
115 * different threads, each source is associated with a #GMainContext.
116 * A GMainContext can only be running in a single thread, but
117 * sources can be added to it and removed from it from other threads.
119 * Each event source is assigned a priority. The default priority,
120 * #G_PRIORITY_DEFAULT, is 0. Values less than 0 denote higher priorities.
121 * Values greater than 0 denote lower priorities. Events from high priority
122 * sources are always processed before events from lower priority sources.
124 * Idle functions can also be added, and assigned a priority. These will
125 * be run whenever no events with a higher priority are ready to be processed.
127 * The #GMainLoop data type represents a main event loop. A GMainLoop is
128 * created with g_main_loop_new(). After adding the initial event sources,
129 * g_main_loop_run() is called. This continuously checks for new events from
130 * each of the event sources and dispatches them. Finally, the processing of
131 * an event from one of the sources leads to a call to g_main_loop_quit() to
132 * exit the main loop, and g_main_loop_run() returns.
134 * It is possible to create new instances of #GMainLoop recursively.
135 * This is often used in GTK+ applications when showing modal dialog
136 * boxes. Note that event sources are associated with a particular
137 * #GMainContext, and will be checked and dispatched for all main
138 * loops associated with that GMainContext.
140 * GTK+ contains wrappers of some of these functions, e.g. gtk_main(),
141 * gtk_main_quit() and gtk_events_pending().
143 * <refsect2><title>Creating new source types</title>
144 * <para>One of the unusual features of the #GMainLoop functionality
145 * is that new types of event source can be created and used in
146 * addition to the builtin type of event source. A new event source
147 * type is used for handling GDK events. A new source type is created
148 * by <firstterm>deriving</firstterm> from the #GSource structure.
149 * The derived type of source is represented by a structure that has
150 * the #GSource structure as a first element, and other elements specific
151 * to the new source type. To create an instance of the new source type,
152 * call g_source_new() passing in the size of the derived structure and
153 * a table of functions. These #GSourceFuncs determine the behavior of
154 * the new source type.</para>
155 * <para>New source types basically interact with the main context
156 * in two ways. Their prepare function in #GSourceFuncs can set a timeout
157 * to determine the maximum amount of time that the main loop will sleep
158 * before checking the source again. In addition, or as well, the source
159 * can add file descriptors to the set that the main context checks using
160 * g_source_add_poll().</para>
162 * <refsect2><title>Customizing the main loop iteration</title>
163 * <para>Single iterations of a #GMainContext can be run with
164 * g_main_context_iteration(). In some cases, more detailed control
165 * of exactly how the details of the main loop work is desired, for
166 * instance, when integrating the #GMainLoop with an external main loop.
167 * In such cases, you can call the component functions of
168 * g_main_context_iteration() directly. These functions are
169 * g_main_context_prepare(), g_main_context_query(),
170 * g_main_context_check() and g_main_context_dispatch().</para>
171 * <para>The operation of these functions can best be seen in terms
172 * of a state diagram, as shown in <xref linkend="mainloop-states"/>.</para>
173 * <figure id="mainloop-states"><title>States of a Main Context</title>
174 * <graphic fileref="mainloop-states.gif" format="GIF"></graphic>
178 * On Unix, the GLib mainloop is incompatible with fork(). Any program
179 * using the mainloop must either exec() or exit() from the child
180 * without returning to the mainloop.
185 typedef struct _GTimeoutSource GTimeoutSource;
186 typedef struct _GChildWatchSource GChildWatchSource;
187 typedef struct _GUnixSignalWatchSource GUnixSignalWatchSource;
188 typedef struct _GPollRec GPollRec;
189 typedef struct _GSourceCallback GSourceCallback;
193 G_SOURCE_READY = 1 << G_HOOK_FLAG_USER_SHIFT,
194 G_SOURCE_CAN_RECURSE = 1 << (G_HOOK_FLAG_USER_SHIFT + 1),
195 G_SOURCE_BLOCKED = 1 << (G_HOOK_FLAG_USER_SHIFT + 2)
198 typedef struct _GSourceList GSourceList;
202 GSource *head, *tail;
206 typedef struct _GMainWaiter GMainWaiter;
214 typedef struct _GMainDispatch GMainDispatch;
216 struct _GMainDispatch
219 GSList *dispatching_sources; /* stack of current sources */
222 #ifdef G_MAIN_POLL_DEBUG
223 gboolean _g_main_poll_debug = FALSE;
228 /* The following lock is used for both the list of sources
229 * and the list of poll records
239 GPtrArray *pending_dispatches;
240 gint timeout; /* Timeout for current iteration */
243 GHashTable *overflow_used_source_ids; /* set<guint> */
245 gint in_check_or_prepare;
247 GPollRec *poll_records, *poll_records_tail;
248 guint n_poll_records;
249 GPollFD *cached_poll_array;
250 guint cached_poll_array_size;
256 /* Flag indicating whether the set of fd's changed during a poll */
257 gboolean poll_changed;
262 gboolean time_is_fresh;
265 struct _GSourceCallback
270 GDestroyNotify notify;
275 GMainContext *context;
280 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;
321 typedef struct _GSourceIter
323 GMainContext *context;
329 #define LOCK_CONTEXT(context) g_mutex_lock (&context->mutex)
330 #define UNLOCK_CONTEXT(context) g_mutex_unlock (&context->mutex)
331 #define G_THREAD_SELF g_thread_self ()
333 #define SOURCE_DESTROYED(source) (((source)->flags & G_HOOK_FLAG_ACTIVE) == 0)
334 #define SOURCE_BLOCKED(source) (((source)->flags & G_SOURCE_BLOCKED) != 0)
336 #define SOURCE_UNREF(source, context) \
338 if ((source)->ref_count > 1) \
339 (source)->ref_count--; \
341 g_source_unref_internal ((source), (context), TRUE); \
345 /* Forward declarations */
347 static void g_source_unref_internal (GSource *source,
348 GMainContext *context,
350 static void g_source_destroy_internal (GSource *source,
351 GMainContext *context,
353 static void g_source_set_priority_unlocked (GSource *source,
354 GMainContext *context,
356 static void g_child_source_remove_internal (GSource *child_source,
357 GMainContext *context);
359 static void g_main_context_poll (GMainContext *context,
364 static void g_main_context_add_poll_unlocked (GMainContext *context,
367 static void g_main_context_remove_poll_unlocked (GMainContext *context,
370 static void g_source_iter_init (GSourceIter *iter,
371 GMainContext *context,
372 gboolean may_modify);
373 static gboolean g_source_iter_next (GSourceIter *iter,
375 static void g_source_iter_clear (GSourceIter *iter);
377 static gboolean g_timeout_prepare (GSource *source,
379 static gboolean g_timeout_check (GSource *source);
380 static gboolean g_timeout_dispatch (GSource *source,
381 GSourceFunc callback,
383 static gboolean g_child_watch_prepare (GSource *source,
385 static gboolean g_child_watch_check (GSource *source);
386 static gboolean g_child_watch_dispatch (GSource *source,
387 GSourceFunc callback,
389 static void g_child_watch_finalize (GSource *source);
391 static void g_unix_signal_handler (int signum);
392 static gboolean g_unix_signal_watch_prepare (GSource *source,
394 static gboolean g_unix_signal_watch_check (GSource *source);
395 static gboolean g_unix_signal_watch_dispatch (GSource *source,
396 GSourceFunc callback,
398 static void g_unix_signal_watch_finalize (GSource *source);
400 static gboolean g_idle_prepare (GSource *source,
402 static gboolean g_idle_check (GSource *source);
403 static gboolean g_idle_dispatch (GSource *source,
404 GSourceFunc callback,
407 static void block_source (GSource *source);
409 static GMainContext *glib_worker_context;
411 G_LOCK_DEFINE_STATIC (main_loop);
412 static GMainContext *default_main_context;
417 /* UNIX signals work by marking one of these variables then waking the
418 * worker context to check on them and dispatch accordingly.
420 #ifdef HAVE_SIG_ATOMIC_T
421 static volatile sig_atomic_t unix_signal_pending[NSIG];
422 static volatile sig_atomic_t any_unix_signal_pending;
424 static volatile int unix_signal_pending[NSIG];
425 static volatile int any_unix_signal_pending;
428 /* Guards all the data below */
429 G_LOCK_DEFINE_STATIC (unix_signal_lock);
430 static GSList *unix_signal_watches;
431 static GSList *unix_child_watches;
433 static GSourceFuncs g_unix_signal_funcs =
435 g_unix_signal_watch_prepare,
436 g_unix_signal_watch_check,
437 g_unix_signal_watch_dispatch,
438 g_unix_signal_watch_finalize
440 #endif /* !G_OS_WIN32 */
441 G_LOCK_DEFINE_STATIC (main_context_list);
442 static GSList *main_context_list = NULL;
444 GSourceFuncs g_timeout_funcs =
452 GSourceFuncs g_child_watch_funcs =
454 g_child_watch_prepare,
456 g_child_watch_dispatch,
457 g_child_watch_finalize
460 GSourceFuncs g_idle_funcs =
469 * g_main_context_ref:
470 * @context: a #GMainContext
472 * Increases the reference count on a #GMainContext object by one.
474 * Returns: the @context that was passed in (since 2.6)
477 g_main_context_ref (GMainContext *context)
479 g_return_val_if_fail (context != NULL, NULL);
480 g_return_val_if_fail (g_atomic_int_get (&context->ref_count) > 0, NULL);
482 g_atomic_int_inc (&context->ref_count);
488 poll_rec_list_free (GMainContext *context,
491 g_slice_free_chain (GPollRec, list, next);
495 * g_main_context_unref:
496 * @context: a #GMainContext
498 * Decreases the reference count on a #GMainContext object by one. If
499 * the result is zero, free the context and free all associated memory.
502 g_main_context_unref (GMainContext *context)
509 g_return_if_fail (context != NULL);
510 g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
512 if (!g_atomic_int_dec_and_test (&context->ref_count))
515 G_LOCK (main_context_list);
516 main_context_list = g_slist_remove (main_context_list, context);
517 G_UNLOCK (main_context_list);
519 g_source_iter_init (&iter, context, TRUE);
520 while (g_source_iter_next (&iter, &source))
522 source->context = NULL;
523 g_source_destroy_internal (source, context, FALSE);
525 for (sl_iter = context->source_lists; sl_iter; sl_iter = sl_iter->next)
527 list = sl_iter->data;
528 g_slice_free (GSourceList, list);
530 g_list_free (context->source_lists);
532 if (context->overflow_used_source_ids)
533 g_hash_table_destroy (context->overflow_used_source_ids);
535 g_mutex_clear (&context->mutex);
537 g_ptr_array_free (context->pending_dispatches, TRUE);
538 g_free (context->cached_poll_array);
540 poll_rec_list_free (context, context->poll_records);
542 g_wakeup_free (context->wakeup);
543 g_cond_clear (&context->cond);
548 /* Helper function used by mainloop/overflow test.
551 g_main_context_new_with_next_id (guint next_id)
553 GMainContext *ret = g_main_context_new ();
555 ret->next_id = next_id;
561 * g_main_context_new:
563 * Creates a new #GMainContext structure.
565 * Return value: the new #GMainContext
568 g_main_context_new (void)
570 static gsize initialised;
571 GMainContext *context;
573 if (g_once_init_enter (&initialised))
575 #ifdef G_MAIN_POLL_DEBUG
576 if (getenv ("G_MAIN_POLL_DEBUG") != NULL)
577 _g_main_poll_debug = TRUE;
580 g_once_init_leave (&initialised, TRUE);
583 context = g_new0 (GMainContext, 1);
585 g_mutex_init (&context->mutex);
586 g_cond_init (&context->cond);
588 context->owner = NULL;
589 context->waiters = NULL;
591 context->ref_count = 1;
593 context->next_id = 1;
595 context->source_lists = NULL;
597 context->poll_func = g_poll;
599 context->cached_poll_array = NULL;
600 context->cached_poll_array_size = 0;
602 context->pending_dispatches = g_ptr_array_new ();
604 context->time_is_fresh = FALSE;
606 context->wakeup = g_wakeup_new ();
607 g_wakeup_get_pollfd (context->wakeup, &context->wake_up_rec);
608 g_main_context_add_poll_unlocked (context, 0, &context->wake_up_rec);
610 G_LOCK (main_context_list);
611 main_context_list = g_slist_append (main_context_list, context);
613 #ifdef G_MAIN_POLL_DEBUG
614 if (_g_main_poll_debug)
615 g_print ("created context=%p\n", context);
618 G_UNLOCK (main_context_list);
624 * g_main_context_default:
626 * Returns the global default main context. This is the main context
627 * used for main loop functions when a main loop is not explicitly
628 * specified, and corresponds to the "main" main loop. See also
629 * g_main_context_get_thread_default().
631 * Return value: (transfer none): the global default main context.
634 g_main_context_default (void)
640 if (!default_main_context)
642 default_main_context = g_main_context_new ();
643 #ifdef G_MAIN_POLL_DEBUG
644 if (_g_main_poll_debug)
645 g_print ("default context=%p\n", default_main_context);
649 G_UNLOCK (main_loop);
651 return default_main_context;
655 free_context (gpointer data)
657 GMainContext *context = data;
659 g_main_context_release (context);
661 g_main_context_unref (context);
665 free_context_stack (gpointer data)
667 g_queue_free_full((GQueue *) data, (GDestroyNotify) free_context);
670 static GPrivate thread_context_stack = G_PRIVATE_INIT (free_context_stack);
673 * g_main_context_push_thread_default:
674 * @context: (allow-none): a #GMainContext, or %NULL for the global default context
676 * Acquires @context and sets it as the thread-default context for the
677 * current thread. This will cause certain asynchronous operations
678 * (such as most <link linkend="gio">gio</link>-based I/O) which are
679 * started in this thread to run under @context and deliver their
680 * results to its main loop, rather than running under the global
681 * default context in the main thread. Note that calling this function
682 * changes the context returned by
683 * g_main_context_get_thread_default(), <emphasis>not</emphasis> the
684 * one returned by g_main_context_default(), so it does not affect the
685 * context used by functions like g_idle_add().
687 * Normally you would call this function shortly after creating a new
688 * thread, passing it a #GMainContext which will be run by a
689 * #GMainLoop in that thread, to set a new default context for all
690 * async operations in that thread. (In this case, you don't need to
691 * ever call g_main_context_pop_thread_default().) In some cases
692 * however, you may want to schedule a single operation in a
693 * non-default context, or temporarily use a non-default context in
694 * the main thread. In that case, you can wrap the call to the
695 * asynchronous operation inside a
696 * g_main_context_push_thread_default() /
697 * g_main_context_pop_thread_default() pair, but it is up to you to
698 * ensure that no other asynchronous operations accidentally get
699 * started while the non-default context is active.
701 * Beware that libraries that predate this function may not correctly
702 * handle being used from a thread with a thread-default context. Eg,
703 * see g_file_supports_thread_contexts().
708 g_main_context_push_thread_default (GMainContext *context)
711 gboolean acquired_context;
713 acquired_context = g_main_context_acquire (context);
714 g_return_if_fail (acquired_context);
716 if (context == g_main_context_default ())
719 g_main_context_ref (context);
721 stack = g_private_get (&thread_context_stack);
724 stack = g_queue_new ();
725 g_private_set (&thread_context_stack, stack);
728 g_queue_push_head (stack, context);
732 * g_main_context_pop_thread_default:
733 * @context: (allow-none): a #GMainContext object, or %NULL
735 * Pops @context off the thread-default context stack (verifying that
736 * it was on the top of the stack).
741 g_main_context_pop_thread_default (GMainContext *context)
745 if (context == g_main_context_default ())
748 stack = g_private_get (&thread_context_stack);
750 g_return_if_fail (stack != NULL);
751 g_return_if_fail (g_queue_peek_head (stack) == context);
753 g_queue_pop_head (stack);
755 g_main_context_release (context);
757 g_main_context_unref (context);
761 * g_main_context_get_thread_default:
763 * Gets the thread-default #GMainContext for this thread. Asynchronous
764 * operations that want to be able to be run in contexts other than
765 * the default one should call this method or
766 * g_main_context_ref_thread_default() to get a #GMainContext to add
767 * their #GSource<!-- -->s to. (Note that even in single-threaded
768 * programs applications may sometimes want to temporarily push a
769 * non-default context, so it is not safe to assume that this will
770 * always return %NULL if you are running in the default thread.)
772 * If you need to hold a reference on the context, use
773 * g_main_context_ref_thread_default() instead.
775 * Returns: (transfer none): the thread-default #GMainContext, or
776 * %NULL if the thread-default context is the global default context.
781 g_main_context_get_thread_default (void)
785 stack = g_private_get (&thread_context_stack);
787 return g_queue_peek_head (stack);
793 * g_main_context_ref_thread_default:
795 * Gets the thread-default #GMainContext for this thread, as with
796 * g_main_context_get_thread_default(), but also adds a reference to
797 * it with g_main_context_ref(). In addition, unlike
798 * g_main_context_get_thread_default(), if the thread-default context
799 * is the global default context, this will return that #GMainContext
800 * (with a ref added to it) rather than returning %NULL.
802 * Returns: (transfer full): the thread-default #GMainContext. Unref
803 * with g_main_context_unref() when you are done with it.
808 g_main_context_ref_thread_default (void)
810 GMainContext *context;
812 context = g_main_context_get_thread_default ();
814 context = g_main_context_default ();
815 return g_main_context_ref (context);
818 /* Hooks for adding to the main loop */
822 * @source_funcs: structure containing functions that implement
823 * the sources behavior.
824 * @struct_size: size of the #GSource structure to create.
826 * Creates a new #GSource structure. The size is specified to
827 * allow creating structures derived from #GSource that contain
828 * additional data. The size passed in must be at least
829 * <literal>sizeof (GSource)</literal>.
831 * The source will not initially be associated with any #GMainContext
832 * and must be added to one with g_source_attach() before it will be
835 * Return value: the newly-created #GSource.
838 g_source_new (GSourceFuncs *source_funcs,
843 g_return_val_if_fail (source_funcs != NULL, NULL);
844 g_return_val_if_fail (struct_size >= sizeof (GSource), NULL);
846 source = (GSource*) g_malloc0 (struct_size);
847 source->priv = g_slice_new0 (GSourcePrivate);
848 source->source_funcs = source_funcs;
849 source->ref_count = 1;
851 source->priority = G_PRIORITY_DEFAULT;
853 source->flags = G_HOOK_FLAG_ACTIVE;
855 /* NULL/0 initialization for all other fields */
860 /* Holds context's lock */
862 g_source_iter_init (GSourceIter *iter,
863 GMainContext *context,
866 iter->context = context;
867 iter->current_list = NULL;
869 iter->may_modify = may_modify;
872 /* Holds context's lock */
874 g_source_iter_next (GSourceIter *iter, GSource **source)
876 GSource *next_source;
879 next_source = iter->source->next;
885 if (iter->current_list)
886 iter->current_list = iter->current_list->next;
888 iter->current_list = iter->context->source_lists;
890 if (iter->current_list)
892 GSourceList *source_list = iter->current_list->data;
894 next_source = source_list->head;
898 /* Note: unreffing iter->source could potentially cause its
899 * GSourceList to be removed from source_lists (if iter->source is
900 * the only source in its list, and it is destroyed), so we have to
901 * keep it reffed until after we advance iter->current_list, above.
904 if (iter->source && iter->may_modify)
905 SOURCE_UNREF (iter->source, iter->context);
906 iter->source = next_source;
907 if (iter->source && iter->may_modify)
908 iter->source->ref_count++;
910 *source = iter->source;
911 return *source != NULL;
914 /* Holds context's lock. Only necessary to call if you broke out of
915 * the g_source_iter_next() loop early.
918 g_source_iter_clear (GSourceIter *iter)
920 if (iter->source && iter->may_modify)
922 SOURCE_UNREF (iter->source, iter->context);
927 /* Holds context's lock
930 find_source_list_for_priority (GMainContext *context,
935 GSourceList *source_list;
938 for (iter = context->source_lists; iter != NULL; last = iter, iter = iter->next)
940 source_list = iter->data;
942 if (source_list->priority == priority)
945 if (source_list->priority > priority)
950 source_list = g_slice_new0 (GSourceList);
951 source_list->priority = priority;
952 context->source_lists = g_list_insert_before (context->source_lists,
962 source_list = g_slice_new0 (GSourceList);
963 source_list->priority = priority;
966 context->source_lists = g_list_append (NULL, source_list);
969 /* This just appends source_list to the end of
970 * context->source_lists without having to walk the list again.
972 last = g_list_append (last, source_list);
977 /* Holds context's lock
980 source_add_to_context (GSource *source,
981 GMainContext *context)
983 GSourceList *source_list;
984 GSource *prev, *next;
986 source_list = find_source_list_for_priority (context, source->priority, TRUE);
988 if (source->priv->parent_source)
990 g_assert (source_list->head != NULL);
992 /* Put the source immediately before its parent */
993 prev = source->priv->parent_source->prev;
994 next = source->priv->parent_source;
998 prev = source_list->tail;
1002 source->next = next;
1004 next->prev = source;
1006 source_list->tail = source;
1008 source->prev = prev;
1010 prev->next = source;
1012 source_list->head = source;
1015 /* Holds context's lock
1018 source_remove_from_context (GSource *source,
1019 GMainContext *context)
1021 GSourceList *source_list;
1023 source_list = find_source_list_for_priority (context, source->priority, FALSE);
1024 g_return_if_fail (source_list != NULL);
1027 source->prev->next = source->next;
1029 source_list->head = source->next;
1032 source->next->prev = source->prev;
1034 source_list->tail = source->prev;
1036 source->prev = NULL;
1037 source->next = NULL;
1039 if (source_list->head == NULL)
1041 context->source_lists = g_list_remove (context->source_lists, source_list);
1042 g_slice_free (GSourceList, source_list);
1045 if (context->overflow_used_source_ids)
1046 g_hash_table_remove (context->overflow_used_source_ids,
1047 GUINT_TO_POINTER (source->source_id));
1052 assign_source_id_unlocked (GMainContext *context,
1057 /* Are we about to overflow back to 0?
1058 * See https://bugzilla.gnome.org/show_bug.cgi?id=687098
1060 if (G_UNLIKELY (context->next_id == G_MAXUINT &&
1061 context->overflow_used_source_ids == NULL))
1066 context->overflow_used_source_ids = g_hash_table_new (NULL, NULL);
1068 g_source_iter_init (&iter, context, FALSE);
1069 while (g_source_iter_next (&iter, &source))
1071 g_hash_table_add (context->overflow_used_source_ids,
1072 GUINT_TO_POINTER (source->source_id));
1076 else if (context->overflow_used_source_ids == NULL)
1078 id = context->next_id++;
1083 * If we overran G_MAXUINT, we fall back to randomly probing the
1084 * source ids for the current context. This will be slower the more
1085 * sources there are, but we're mainly concerned right now about
1086 * correctness and code size. There's time for a more clever solution
1090 id = g_random_int ();
1092 g_hash_table_contains (context->overflow_used_source_ids,
1093 GUINT_TO_POINTER (id)));
1094 g_hash_table_add (context->overflow_used_source_ids, GUINT_TO_POINTER (id));
1097 source->source_id = id;
1101 g_source_attach_unlocked (GSource *source,
1102 GMainContext *context)
1106 source->context = context;
1107 assign_source_id_unlocked (context, source);
1108 source->ref_count++;
1109 source_add_to_context (source, context);
1111 tmp_list = source->poll_fds;
1114 g_main_context_add_poll_unlocked (context, source->priority, tmp_list->data);
1115 tmp_list = tmp_list->next;
1118 tmp_list = source->priv->child_sources;
1121 g_source_attach_unlocked (tmp_list->data, context);
1122 tmp_list = tmp_list->next;
1125 return source->source_id;
1130 * @source: a #GSource
1131 * @context: (allow-none): a #GMainContext (if %NULL, the default context will be used)
1133 * Adds a #GSource to a @context so that it will be executed within
1134 * that context. Remove it by calling g_source_destroy().
1136 * Return value: the ID (greater than 0) for the source within the
1140 g_source_attach (GSource *source,
1141 GMainContext *context)
1145 g_return_val_if_fail (source->context == NULL, 0);
1146 g_return_val_if_fail (!SOURCE_DESTROYED (source), 0);
1149 context = g_main_context_default ();
1151 LOCK_CONTEXT (context);
1153 result = g_source_attach_unlocked (source, context);
1155 /* If another thread has acquired the context, wake it up since it
1156 * might be in poll() right now.
1158 if (context->owner && context->owner != G_THREAD_SELF)
1159 g_wakeup_signal (context->wakeup);
1161 UNLOCK_CONTEXT (context);
1167 g_source_destroy_internal (GSource *source,
1168 GMainContext *context,
1172 LOCK_CONTEXT (context);
1174 if (!SOURCE_DESTROYED (source))
1177 gpointer old_cb_data;
1178 GSourceCallbackFuncs *old_cb_funcs;
1180 source->flags &= ~G_HOOK_FLAG_ACTIVE;
1182 old_cb_data = source->callback_data;
1183 old_cb_funcs = source->callback_funcs;
1185 source->callback_data = NULL;
1186 source->callback_funcs = NULL;
1190 UNLOCK_CONTEXT (context);
1191 old_cb_funcs->unref (old_cb_data);
1192 LOCK_CONTEXT (context);
1195 if (!SOURCE_BLOCKED (source))
1197 tmp_list = source->poll_fds;
1200 g_main_context_remove_poll_unlocked (context, tmp_list->data);
1201 tmp_list = tmp_list->next;
1205 while (source->priv->child_sources)
1206 g_child_source_remove_internal (source->priv->child_sources->data, context);
1208 if (source->priv->parent_source)
1209 g_child_source_remove_internal (source, context);
1211 g_source_unref_internal (source, context, TRUE);
1215 UNLOCK_CONTEXT (context);
1220 * @source: a #GSource
1222 * Removes a source from its #GMainContext, if any, and mark it as
1223 * destroyed. The source cannot be subsequently added to another
1227 g_source_destroy (GSource *source)
1229 GMainContext *context;
1231 g_return_if_fail (source != NULL);
1233 context = source->context;
1236 g_source_destroy_internal (source, context, FALSE);
1238 source->flags &= ~G_HOOK_FLAG_ACTIVE;
1243 * @source: a #GSource
1245 * Returns the numeric ID for a particular source. The ID of a source
1246 * is a positive integer which is unique within a particular main loop
1247 * context. The reverse
1248 * mapping from ID to source is done by g_main_context_find_source_by_id().
1250 * Return value: the ID (greater than 0) for the source
1253 g_source_get_id (GSource *source)
1257 g_return_val_if_fail (source != NULL, 0);
1258 g_return_val_if_fail (source->context != NULL, 0);
1260 LOCK_CONTEXT (source->context);
1261 result = source->source_id;
1262 UNLOCK_CONTEXT (source->context);
1268 * g_source_get_context:
1269 * @source: a #GSource
1271 * Gets the #GMainContext with which the source is associated.
1273 * You can call this on a source that has been destroyed, provided
1274 * that the #GMainContext it was attached to still exists (in which
1275 * case it will return that #GMainContext). In particular, you can
1276 * always call this function on the source returned from
1277 * g_main_current_source(). But calling this function on a source
1278 * whose #GMainContext has been destroyed is an error.
1280 * Return value: (transfer none) (allow-none): the #GMainContext with which the
1281 * source is associated, or %NULL if the context has not
1282 * yet been added to a source.
1285 g_source_get_context (GSource *source)
1287 g_return_val_if_fail (source->context != NULL || !SOURCE_DESTROYED (source), NULL);
1289 return source->context;
1293 * g_source_add_poll:
1294 * @source:a #GSource
1295 * @fd: a #GPollFD structure holding information about a file
1296 * descriptor to watch.
1298 * Adds a file descriptor to the set of file descriptors polled for
1299 * this source. This is usually combined with g_source_new() to add an
1300 * event source. The event source's check function will typically test
1301 * the @revents field in the #GPollFD struct and return %TRUE if events need
1305 g_source_add_poll (GSource *source,
1308 GMainContext *context;
1310 g_return_if_fail (source != NULL);
1311 g_return_if_fail (fd != NULL);
1312 g_return_if_fail (!SOURCE_DESTROYED (source));
1314 context = source->context;
1317 LOCK_CONTEXT (context);
1319 source->poll_fds = g_slist_prepend (source->poll_fds, fd);
1323 if (!SOURCE_BLOCKED (source))
1324 g_main_context_add_poll_unlocked (context, source->priority, fd);
1325 UNLOCK_CONTEXT (context);
1330 * g_source_remove_poll:
1331 * @source:a #GSource
1332 * @fd: a #GPollFD structure previously passed to g_source_add_poll().
1334 * Removes a file descriptor from the set of file descriptors polled for
1338 g_source_remove_poll (GSource *source,
1341 GMainContext *context;
1343 g_return_if_fail (source != NULL);
1344 g_return_if_fail (fd != NULL);
1345 g_return_if_fail (!SOURCE_DESTROYED (source));
1347 context = source->context;
1350 LOCK_CONTEXT (context);
1352 source->poll_fds = g_slist_remove (source->poll_fds, fd);
1356 if (!SOURCE_BLOCKED (source))
1357 g_main_context_remove_poll_unlocked (context, fd);
1358 UNLOCK_CONTEXT (context);
1363 * g_source_add_child_source:
1364 * @source:a #GSource
1365 * @child_source: a second #GSource that @source should "poll"
1367 * Adds @child_source to @source as a "polled" source; when @source is
1368 * added to a #GMainContext, @child_source will be automatically added
1369 * with the same priority, when @child_source is triggered, it will
1370 * cause @source to dispatch (in addition to calling its own
1371 * callback), and when @source is destroyed, it will destroy
1372 * @child_source as well. (@source will also still be dispatched if
1373 * its own prepare/check functions indicate that it is ready.)
1375 * If you don't need @child_source to do anything on its own when it
1376 * triggers, you can call g_source_set_dummy_callback() on it to set a
1377 * callback that does nothing (except return %TRUE if appropriate).
1379 * @source will hold a reference on @child_source while @child_source
1380 * is attached to it.
1385 g_source_add_child_source (GSource *source,
1386 GSource *child_source)
1388 GMainContext *context;
1390 g_return_if_fail (source != NULL);
1391 g_return_if_fail (child_source != NULL);
1392 g_return_if_fail (!SOURCE_DESTROYED (source));
1393 g_return_if_fail (!SOURCE_DESTROYED (child_source));
1394 g_return_if_fail (child_source->context == NULL);
1395 g_return_if_fail (child_source->priv->parent_source == NULL);
1397 context = source->context;
1400 LOCK_CONTEXT (context);
1402 source->priv->child_sources = g_slist_prepend (source->priv->child_sources,
1403 g_source_ref (child_source));
1404 child_source->priv->parent_source = source;
1405 g_source_set_priority_unlocked (child_source, NULL, source->priority);
1406 if (SOURCE_BLOCKED (source))
1407 block_source (child_source);
1411 UNLOCK_CONTEXT (context);
1412 g_source_attach (child_source, context);
1417 g_child_source_remove_internal (GSource *child_source,
1418 GMainContext *context)
1420 GSource *parent_source = child_source->priv->parent_source;
1422 parent_source->priv->child_sources =
1423 g_slist_remove (parent_source->priv->child_sources, child_source);
1424 child_source->priv->parent_source = NULL;
1426 g_source_destroy_internal (child_source, context, TRUE);
1427 g_source_unref_internal (child_source, context, TRUE);
1431 * g_source_remove_child_source:
1432 * @source:a #GSource
1433 * @child_source: a #GSource previously passed to
1434 * g_source_add_child_source().
1436 * Detaches @child_source from @source and destroys it.
1441 g_source_remove_child_source (GSource *source,
1442 GSource *child_source)
1444 GMainContext *context;
1446 g_return_if_fail (source != NULL);
1447 g_return_if_fail (child_source != NULL);
1448 g_return_if_fail (child_source->priv->parent_source == source);
1449 g_return_if_fail (!SOURCE_DESTROYED (source));
1450 g_return_if_fail (!SOURCE_DESTROYED (child_source));
1452 context = source->context;
1455 LOCK_CONTEXT (context);
1457 g_child_source_remove_internal (child_source, context);
1460 UNLOCK_CONTEXT (context);
1464 * g_source_set_callback_indirect:
1465 * @source: the source
1466 * @callback_data: pointer to callback data "object"
1467 * @callback_funcs: functions for reference counting @callback_data
1468 * and getting the callback and data
1470 * Sets the callback function storing the data as a refcounted callback
1471 * "object". This is used internally. Note that calling
1472 * g_source_set_callback_indirect() assumes
1473 * an initial reference count on @callback_data, and thus
1474 * @callback_funcs->unref will eventually be called once more
1475 * than @callback_funcs->ref.
1478 g_source_set_callback_indirect (GSource *source,
1479 gpointer callback_data,
1480 GSourceCallbackFuncs *callback_funcs)
1482 GMainContext *context;
1483 gpointer old_cb_data;
1484 GSourceCallbackFuncs *old_cb_funcs;
1486 g_return_if_fail (source != NULL);
1487 g_return_if_fail (callback_funcs != NULL || callback_data == NULL);
1489 context = source->context;
1492 LOCK_CONTEXT (context);
1494 old_cb_data = source->callback_data;
1495 old_cb_funcs = source->callback_funcs;
1497 source->callback_data = callback_data;
1498 source->callback_funcs = callback_funcs;
1501 UNLOCK_CONTEXT (context);
1504 old_cb_funcs->unref (old_cb_data);
1508 g_source_callback_ref (gpointer cb_data)
1510 GSourceCallback *callback = cb_data;
1512 callback->ref_count++;
1517 g_source_callback_unref (gpointer cb_data)
1519 GSourceCallback *callback = cb_data;
1521 callback->ref_count--;
1522 if (callback->ref_count == 0)
1524 if (callback->notify)
1525 callback->notify (callback->data);
1531 g_source_callback_get (gpointer cb_data,
1536 GSourceCallback *callback = cb_data;
1538 *func = callback->func;
1539 *data = callback->data;
1542 static GSourceCallbackFuncs g_source_callback_funcs = {
1543 g_source_callback_ref,
1544 g_source_callback_unref,
1545 g_source_callback_get,
1549 * g_source_set_callback:
1550 * @source: the source
1551 * @func: a callback function
1552 * @data: the data to pass to callback function
1553 * @notify: (allow-none): a function to call when @data is no longer in use, or %NULL.
1555 * Sets the callback function for a source. The callback for a source is
1556 * called from the source's dispatch function.
1558 * The exact type of @func depends on the type of source; ie. you
1559 * should not count on @func being called with @data as its first
1562 * Typically, you won't use this function. Instead use functions specific
1563 * to the type of source you are using.
1566 g_source_set_callback (GSource *source,
1569 GDestroyNotify notify)
1571 GSourceCallback *new_callback;
1573 g_return_if_fail (source != NULL);
1575 new_callback = g_new (GSourceCallback, 1);
1577 new_callback->ref_count = 1;
1578 new_callback->func = func;
1579 new_callback->data = data;
1580 new_callback->notify = notify;
1582 g_source_set_callback_indirect (source, new_callback, &g_source_callback_funcs);
1587 * g_source_set_funcs:
1588 * @source: a #GSource
1589 * @funcs: the new #GSourceFuncs
1591 * Sets the source functions (can be used to override
1592 * default implementations) of an unattached source.
1597 g_source_set_funcs (GSource *source,
1598 GSourceFuncs *funcs)
1600 g_return_if_fail (source != NULL);
1601 g_return_if_fail (source->context == NULL);
1602 g_return_if_fail (source->ref_count > 0);
1603 g_return_if_fail (funcs != NULL);
1605 source->source_funcs = funcs;
1609 g_source_set_priority_unlocked (GSource *source,
1610 GMainContext *context,
1615 g_return_if_fail (source->priv->parent_source == NULL ||
1616 source->priv->parent_source->priority == priority);
1620 /* Remove the source from the context's source and then
1621 * add it back after so it is sorted in the correct place
1623 source_remove_from_context (source, source->context);
1626 source->priority = priority;
1630 source_add_to_context (source, source->context);
1632 if (!SOURCE_BLOCKED (source))
1634 tmp_list = source->poll_fds;
1637 g_main_context_remove_poll_unlocked (context, tmp_list->data);
1638 g_main_context_add_poll_unlocked (context, priority, tmp_list->data);
1640 tmp_list = tmp_list->next;
1645 if (source->priv->child_sources)
1647 tmp_list = source->priv->child_sources;
1650 g_source_set_priority_unlocked (tmp_list->data, context, priority);
1651 tmp_list = tmp_list->next;
1657 * g_source_set_priority:
1658 * @source: a #GSource
1659 * @priority: the new priority.
1661 * Sets the priority of a source. While the main loop is being run, a
1662 * source will be dispatched if it is ready to be dispatched and no
1663 * sources at a higher (numerically smaller) priority are ready to be
1667 g_source_set_priority (GSource *source,
1670 GMainContext *context;
1672 g_return_if_fail (source != NULL);
1674 context = source->context;
1677 LOCK_CONTEXT (context);
1678 g_source_set_priority_unlocked (source, context, priority);
1680 UNLOCK_CONTEXT (source->context);
1684 * g_source_get_priority:
1685 * @source: a #GSource
1687 * Gets the priority of a source.
1689 * Return value: the priority of the source
1692 g_source_get_priority (GSource *source)
1694 g_return_val_if_fail (source != NULL, 0);
1696 return source->priority;
1700 * g_source_set_can_recurse:
1701 * @source: a #GSource
1702 * @can_recurse: whether recursion is allowed for this source
1704 * Sets whether a source can be called recursively. If @can_recurse is
1705 * %TRUE, then while the source is being dispatched then this source
1706 * will be processed normally. Otherwise, all processing of this
1707 * source is blocked until the dispatch function returns.
1710 g_source_set_can_recurse (GSource *source,
1711 gboolean can_recurse)
1713 GMainContext *context;
1715 g_return_if_fail (source != NULL);
1717 context = source->context;
1720 LOCK_CONTEXT (context);
1723 source->flags |= G_SOURCE_CAN_RECURSE;
1725 source->flags &= ~G_SOURCE_CAN_RECURSE;
1728 UNLOCK_CONTEXT (context);
1732 * g_source_get_can_recurse:
1733 * @source: a #GSource
1735 * Checks whether a source is allowed to be called recursively.
1736 * see g_source_set_can_recurse().
1738 * Return value: whether recursion is allowed.
1741 g_source_get_can_recurse (GSource *source)
1743 g_return_val_if_fail (source != NULL, FALSE);
1745 return (source->flags & G_SOURCE_CAN_RECURSE) != 0;
1750 * g_source_set_name:
1751 * @source: a #GSource
1752 * @name: debug name for the source
1754 * Sets a name for the source, used in debugging and profiling.
1755 * The name defaults to #NULL.
1757 * The source name should describe in a human-readable way
1758 * what the source does. For example, "X11 event queue"
1759 * or "GTK+ repaint idle handler" or whatever it is.
1761 * It is permitted to call this function multiple times, but is not
1762 * recommended due to the potential performance impact. For example,
1763 * one could change the name in the "check" function of a #GSourceFuncs
1764 * to include details like the event type in the source name.
1769 g_source_set_name (GSource *source,
1772 g_return_if_fail (source != NULL);
1774 /* setting back to NULL is allowed, just because it's
1775 * weird if get_name can return NULL but you can't
1779 g_free (source->name);
1780 source->name = g_strdup (name);
1784 * g_source_get_name:
1785 * @source: a #GSource
1787 * Gets a name for the source, used in debugging and profiling.
1788 * The name may be #NULL if it has never been set with
1789 * g_source_set_name().
1791 * Return value: the name of the source
1795 g_source_get_name (GSource *source)
1797 g_return_val_if_fail (source != NULL, NULL);
1799 return source->name;
1803 * g_source_set_name_by_id:
1804 * @tag: a #GSource ID
1805 * @name: debug name for the source
1807 * Sets the name of a source using its ID.
1809 * This is a convenience utility to set source names from the return
1810 * value of g_idle_add(), g_timeout_add(), etc.
1815 g_source_set_name_by_id (guint tag,
1820 g_return_if_fail (tag > 0);
1822 source = g_main_context_find_source_by_id (NULL, tag);
1826 g_source_set_name (source, name);
1832 * @source: a #GSource
1834 * Increases the reference count on a source by one.
1836 * Return value: @source
1839 g_source_ref (GSource *source)
1841 GMainContext *context;
1843 g_return_val_if_fail (source != NULL, NULL);
1845 context = source->context;
1848 LOCK_CONTEXT (context);
1850 source->ref_count++;
1853 UNLOCK_CONTEXT (context);
1858 /* g_source_unref() but possible to call within context lock
1861 g_source_unref_internal (GSource *source,
1862 GMainContext *context,
1865 gpointer old_cb_data = NULL;
1866 GSourceCallbackFuncs *old_cb_funcs = NULL;
1868 g_return_if_fail (source != NULL);
1870 if (!have_lock && context)
1871 LOCK_CONTEXT (context);
1873 source->ref_count--;
1874 if (source->ref_count == 0)
1876 old_cb_data = source->callback_data;
1877 old_cb_funcs = source->callback_funcs;
1879 source->callback_data = NULL;
1880 source->callback_funcs = NULL;
1884 if (!SOURCE_DESTROYED (source))
1885 g_warning (G_STRLOC ": ref_count == 0, but source was still attached to a context!");
1886 source_remove_from_context (source, context);
1889 if (source->source_funcs->finalize)
1892 UNLOCK_CONTEXT (context);
1893 source->source_funcs->finalize (source);
1895 LOCK_CONTEXT (context);
1898 g_free (source->name);
1899 source->name = NULL;
1901 g_slist_free (source->poll_fds);
1902 source->poll_fds = NULL;
1904 g_slice_free (GSourcePrivate, source->priv);
1905 source->priv = NULL;
1910 if (!have_lock && context)
1911 UNLOCK_CONTEXT (context);
1916 UNLOCK_CONTEXT (context);
1918 old_cb_funcs->unref (old_cb_data);
1921 LOCK_CONTEXT (context);
1927 * @source: a #GSource
1929 * Decreases the reference count of a source by one. If the
1930 * resulting reference count is zero the source and associated
1931 * memory will be destroyed.
1934 g_source_unref (GSource *source)
1936 g_return_if_fail (source != NULL);
1938 g_source_unref_internal (source, source->context, FALSE);
1942 * g_main_context_find_source_by_id:
1943 * @context: (allow-none): a #GMainContext (if %NULL, the default context will be used)
1944 * @source_id: the source ID, as returned by g_source_get_id().
1946 * Finds a #GSource given a pair of context and ID.
1948 * Return value: (transfer none): the #GSource if found, otherwise, %NULL
1951 g_main_context_find_source_by_id (GMainContext *context,
1957 g_return_val_if_fail (source_id > 0, NULL);
1959 if (context == NULL)
1960 context = g_main_context_default ();
1962 LOCK_CONTEXT (context);
1964 g_source_iter_init (&iter, context, FALSE);
1965 while (g_source_iter_next (&iter, &source))
1967 if (!SOURCE_DESTROYED (source) &&
1968 source->source_id == source_id)
1971 g_source_iter_clear (&iter);
1973 UNLOCK_CONTEXT (context);
1979 * g_main_context_find_source_by_funcs_user_data:
1980 * @context: (allow-none): a #GMainContext (if %NULL, the default context will be used).
1981 * @funcs: the @source_funcs passed to g_source_new().
1982 * @user_data: the user data from the callback.
1984 * Finds a source with the given source functions and user data. If
1985 * multiple sources exist with the same source function and user data,
1986 * the first one found will be returned.
1988 * Return value: (transfer none): the source, if one was found, otherwise %NULL
1991 g_main_context_find_source_by_funcs_user_data (GMainContext *context,
1992 GSourceFuncs *funcs,
1998 g_return_val_if_fail (funcs != NULL, NULL);
2000 if (context == NULL)
2001 context = g_main_context_default ();
2003 LOCK_CONTEXT (context);
2005 g_source_iter_init (&iter, context, FALSE);
2006 while (g_source_iter_next (&iter, &source))
2008 if (!SOURCE_DESTROYED (source) &&
2009 source->source_funcs == funcs &&
2010 source->callback_funcs)
2012 GSourceFunc callback;
2013 gpointer callback_data;
2015 source->callback_funcs->get (source->callback_data, source, &callback, &callback_data);
2017 if (callback_data == user_data)
2021 g_source_iter_clear (&iter);
2023 UNLOCK_CONTEXT (context);
2029 * g_main_context_find_source_by_user_data:
2030 * @context: a #GMainContext
2031 * @user_data: the user_data for the callback.
2033 * Finds a source with the given user data for the callback. If
2034 * multiple sources exist with the same user data, the first
2035 * one found will be returned.
2037 * Return value: (transfer none): the source, if one was found, otherwise %NULL
2040 g_main_context_find_source_by_user_data (GMainContext *context,
2046 if (context == NULL)
2047 context = g_main_context_default ();
2049 LOCK_CONTEXT (context);
2051 g_source_iter_init (&iter, context, FALSE);
2052 while (g_source_iter_next (&iter, &source))
2054 if (!SOURCE_DESTROYED (source) &&
2055 source->callback_funcs)
2057 GSourceFunc callback;
2058 gpointer callback_data = NULL;
2060 source->callback_funcs->get (source->callback_data, source, &callback, &callback_data);
2062 if (callback_data == user_data)
2066 g_source_iter_clear (&iter);
2068 UNLOCK_CONTEXT (context);
2075 * @tag: the ID of the source to remove.
2077 * Removes the source with the given id from the default main context.
2079 * a #GSource is given by g_source_get_id(), or will be returned by the
2080 * functions g_source_attach(), g_idle_add(), g_idle_add_full(),
2081 * g_timeout_add(), g_timeout_add_full(), g_child_watch_add(),
2082 * g_child_watch_add_full(), g_io_add_watch(), and g_io_add_watch_full().
2084 * See also g_source_destroy(). You must use g_source_destroy() for sources
2085 * added to a non-default main context.
2087 * Return value: %TRUE if the source was found and removed.
2090 g_source_remove (guint tag)
2094 g_return_val_if_fail (tag > 0, FALSE);
2096 source = g_main_context_find_source_by_id (NULL, tag);
2098 g_source_destroy (source);
2100 return source != NULL;
2104 * g_source_remove_by_user_data:
2105 * @user_data: the user_data for the callback.
2107 * Removes a source from the default main loop context given the user
2108 * data for the callback. If multiple sources exist with the same user
2109 * data, only one will be destroyed.
2111 * Return value: %TRUE if a source was found and removed.
2114 g_source_remove_by_user_data (gpointer user_data)
2118 source = g_main_context_find_source_by_user_data (NULL, user_data);
2121 g_source_destroy (source);
2129 * g_source_remove_by_funcs_user_data:
2130 * @funcs: The @source_funcs passed to g_source_new()
2131 * @user_data: the user data for the callback
2133 * Removes a source from the default main loop context given the
2134 * source functions and user data. If multiple sources exist with the
2135 * same source functions and user data, only one will be destroyed.
2137 * Return value: %TRUE if a source was found and removed.
2140 g_source_remove_by_funcs_user_data (GSourceFuncs *funcs,
2145 g_return_val_if_fail (funcs != NULL, FALSE);
2147 source = g_main_context_find_source_by_funcs_user_data (NULL, funcs, user_data);
2150 g_source_destroy (source);
2158 * g_get_current_time:
2159 * @result: #GTimeVal structure in which to store current time.
2161 * Equivalent to the UNIX gettimeofday() function, but portable.
2163 * You may find g_get_real_time() to be more convenient.
2166 g_get_current_time (GTimeVal *result)
2171 g_return_if_fail (result != NULL);
2173 /*this is required on alpha, there the timeval structs are int's
2174 not longs and a cast only would fail horribly*/
2175 gettimeofday (&r, NULL);
2176 result->tv_sec = r.tv_sec;
2177 result->tv_usec = r.tv_usec;
2182 g_return_if_fail (result != NULL);
2184 GetSystemTimeAsFileTime (&ft);
2185 memmove (&time64, &ft, sizeof (FILETIME));
2187 /* Convert from 100s of nanoseconds since 1601-01-01
2188 * to Unix epoch. Yes, this is Y2038 unsafe.
2190 time64 -= G_GINT64_CONSTANT (116444736000000000);
2193 result->tv_sec = time64 / 1000000;
2194 result->tv_usec = time64 % 1000000;
2201 * Queries the system wall-clock time.
2203 * This call is functionally equivalent to g_get_current_time() except
2204 * that the return value is often more convenient than dealing with a
2207 * You should only use this call if you are actually interested in the real
2208 * wall-clock time. g_get_monotonic_time() is probably more useful for
2209 * measuring intervals.
2211 * Returns: the number of microseconds since January 1, 1970 UTC.
2216 g_get_real_time (void)
2220 g_get_current_time (&tv);
2222 return (((gint64) tv.tv_sec) * 1000000) + tv.tv_usec;
2226 static ULONGLONG (*g_GetTickCount64) (void) = NULL;
2227 static guint32 g_win32_tick_epoch = 0;
2229 G_GNUC_INTERNAL void
2230 g_clock_win32_init (void)
2234 g_GetTickCount64 = NULL;
2235 kernel32 = GetModuleHandle ("KERNEL32.DLL");
2236 if (kernel32 != NULL)
2237 g_GetTickCount64 = (void *) GetProcAddress (kernel32, "GetTickCount64");
2238 g_win32_tick_epoch = ((guint32)GetTickCount()) >> 31;
2243 * g_get_monotonic_time:
2245 * Queries the system monotonic time, if available.
2247 * On POSIX systems with clock_gettime() and <literal>CLOCK_MONOTONIC</literal> this call
2248 * is a very shallow wrapper for that. Otherwise, we make a best effort
2249 * that probably involves returning the wall clock time (with at least
2250 * microsecond accuracy, subject to the limitations of the OS kernel).
2252 * It's important to note that POSIX <literal>CLOCK_MONOTONIC</literal> does
2253 * not count time spent while the machine is suspended.
2255 * On Windows, "limitations of the OS kernel" is a rather substantial
2256 * statement. Depending on the configuration of the system, the wall
2257 * clock time is updated as infrequently as 64 times a second (which
2258 * is approximately every 16ms). Also, on XP (but not on Vista or later)
2259 * the monotonic clock is locally monotonic, but may differ in exact
2260 * value between processes due to timer wrap handling.
2262 * Returns: the monotonic time, in microseconds
2267 g_get_monotonic_time (void)
2269 #ifdef HAVE_CLOCK_GETTIME
2270 /* librt clock_gettime() is our first choice */
2273 #ifdef CLOCK_MONOTONIC
2274 clock_gettime (CLOCK_MONOTONIC, &ts);
2276 clock_gettime (CLOCK_REALTIME, &ts);
2279 /* In theory monotonic time can have any epoch.
2281 * glib presently assumes the following:
2283 * 1) The epoch comes some time after the birth of Jesus of Nazareth, but
2284 * not more than 10000 years later.
2286 * 2) The current time also falls sometime within this range.
2288 * These two reasonable assumptions leave us with a maximum deviation from
2289 * the epoch of 10000 years, or 315569520000000000 seconds.
2291 * If we restrict ourselves to this range then the number of microseconds
2292 * will always fit well inside the constraints of a int64 (by a factor of
2295 * If you actually hit the following assertion, probably you should file a
2296 * bug against your operating system for being excessively silly.
2298 g_assert (G_GINT64_CONSTANT (-315569520000000000) < ts.tv_sec &&
2299 ts.tv_sec < G_GINT64_CONSTANT (315569520000000000));
2301 return (((gint64) ts.tv_sec) * 1000000) + (ts.tv_nsec / 1000);
2303 #elif defined (G_OS_WIN32)
2307 /* There are four sources for the monotonic time on Windows:
2309 * Three are based on a (1 msec accuracy, but only read periodically) clock chip:
2310 * - GetTickCount (GTC)
2311 * 32bit msec counter, updated each ~15msec, wraps in ~50 days
2312 * - GetTickCount64 (GTC64)
2313 * Same as GetTickCount, but extended to 64bit, so no wrap
2314 * Only available in Vista or later
2315 * - timeGetTime (TGT)
2316 * similar to GetTickCount by default: 15msec, 50 day wrap.
2317 * available in winmm.dll (thus known as the multimedia timers)
2318 * However apps can raise the system timer clock frequency using timeBeginPeriod()
2319 * increasing the accuracy up to 1 msec, at a cost in general system performance
2322 * One is based on high precision clocks:
2323 * - QueryPrecisionCounter (QPC)
2324 * This has much higher accuracy, but is not guaranteed monotonic, and
2325 * has lots of complications like clock jumps and different times on different
2326 * CPUs. It also has lower long term accuracy (i.e. it will drift compared to
2327 * the low precision clocks.
2329 * Additionally, the precision available in the timer-based wakeup such as
2330 * MsgWaitForMultipleObjectsEx (which is what the mainloop is based on) is based
2331 * on the TGT resolution, so by default it is ~15msec, but can be increased by apps.
2333 * The QPC timer has too many issues to be used as is. The only way it could be used
2334 * is to use it to interpolate the lower precision clocks. Firefox does something like
2336 * https://bugzilla.mozilla.org/show_bug.cgi?id=363258
2338 * However this seems quite complicated, so we're not doing this right now.
2340 * The approach we take instead is to use the TGT timer, extending it to 64bit
2341 * either by using the GTC64 value, or if that is not available, a process local
2342 * time epoch that we increment when we detect a timer wrap (assumes that we read
2343 * the time at least once every 50 days).
2346 * - We have a globally consistent monotonic clock on Vista and later
2347 * - We have a locally monotonic clock on XP
2348 * - Apps that need higher precision in timeouts and clock reads can call
2349 * timeBeginPeriod() to increase it as much as they want
2352 if (g_GetTickCount64 != NULL)
2354 guint32 ticks_as_32bit;
2356 ticks = g_GetTickCount64 ();
2357 ticks32 = timeGetTime();
2359 /* GTC64 and TGT are sampled at different times, however they
2360 * have the same base and source (msecs since system boot).
2361 * They can differ by as much as -16 to +16 msecs.
2362 * We can't just inject the low bits into the 64bit counter
2363 * as one of the counters can have wrapped in 32bit space and
2364 * the other not. Instead we calculate the signed difference
2365 * in 32bit space and apply that difference to the 64bit counter.
2367 ticks_as_32bit = (guint32)ticks;
2369 /* We could do some 2's complement hack, but we play it safe */
2370 if (ticks32 - ticks_as_32bit <= G_MAXINT32)
2371 ticks += ticks32 - ticks_as_32bit;
2373 ticks -= ticks_as_32bit - ticks32;
2379 epoch = g_atomic_int_get (&g_win32_tick_epoch);
2381 /* Must read ticks after the epoch. Then we're guaranteed
2382 * that the ticks value we read is higher or equal to any
2383 * previous ones that lead to the writing of the epoch.
2385 ticks32 = timeGetTime();
2387 /* We store the MSB of the current time as the LSB
2388 * of the epoch. Comparing these bits lets us detect when
2389 * the 32bit counter has wrapped so we can increase the
2392 * This will work as long as this function is called at
2393 * least once every ~24 days, which is half the wrap time
2394 * of a 32bit msec counter. I think this is pretty likely.
2396 * Note that g_win32_tick_epoch is a process local state,
2397 * so the monotonic clock will not be the same between
2400 if ((ticks32 >> 31) != (epoch & 1))
2403 g_atomic_int_set (&g_win32_tick_epoch, epoch);
2407 ticks = (guint64)ticks32 | ((guint64)epoch) << 31;
2410 return ticks * 1000;
2412 #else /* !HAVE_CLOCK_GETTIME && ! G_OS_WIN32*/
2416 g_get_current_time (&tv);
2418 return (((gint64) tv.tv_sec) * 1000000) + tv.tv_usec;
2423 g_main_dispatch_free (gpointer dispatch)
2425 g_slice_free (GMainDispatch, dispatch);
2428 /* Running the main loop */
2430 static GMainDispatch *
2433 static GPrivate depth_private = G_PRIVATE_INIT (g_main_dispatch_free);
2434 GMainDispatch *dispatch;
2436 dispatch = g_private_get (&depth_private);
2440 dispatch = g_slice_new0 (GMainDispatch);
2441 g_private_set (&depth_private, dispatch);
2450 * Returns the depth of the stack of calls to
2451 * g_main_context_dispatch() on any #GMainContext in the current thread.
2452 * That is, when called from the toplevel, it gives 0. When
2453 * called from within a callback from g_main_context_iteration()
2454 * (or g_main_loop_run(), etc.) it returns 1. When called from within
2455 * a callback to a recursive call to g_main_context_iteration(),
2456 * it returns 2. And so forth.
2458 * This function is useful in a situation like the following:
2459 * Imagine an extremely simple "garbage collected" system.
2462 * static GList *free_list;
2465 * allocate_memory (gsize size)
2467 * gpointer result = g_malloc (size);
2468 * free_list = g_list_prepend (free_list, result);
2473 * free_allocated_memory (void)
2476 * for (l = free_list; l; l = l->next);
2478 * g_list_free (free_list);
2486 * g_main_context_iteration (NULL, TRUE);
2487 * free_allocated_memory();
2491 * This works from an application, however, if you want to do the same
2492 * thing from a library, it gets more difficult, since you no longer
2493 * control the main loop. You might think you can simply use an idle
2494 * function to make the call to free_allocated_memory(), but that
2495 * doesn't work, since the idle function could be called from a
2496 * recursive callback. This can be fixed by using g_main_depth()
2500 * allocate_memory (gsize size)
2502 * FreeListBlock *block = g_new (FreeListBlock, 1);
2503 * block->mem = g_malloc (size);
2504 * block->depth = g_main_depth ();
2505 * free_list = g_list_prepend (free_list, block);
2506 * return block->mem;
2510 * free_allocated_memory (void)
2514 * int depth = g_main_depth ();
2515 * for (l = free_list; l; );
2517 * GList *next = l->next;
2518 * FreeListBlock *block = l->data;
2519 * if (block->depth > depth)
2521 * g_free (block->mem);
2523 * free_list = g_list_delete_link (free_list, l);
2531 * There is a temptation to use g_main_depth() to solve
2532 * problems with reentrancy. For instance, while waiting for data
2533 * to be received from the network in response to a menu item,
2534 * the menu item might be selected again. It might seem that
2535 * one could make the menu item's callback return immediately
2536 * and do nothing if g_main_depth() returns a value greater than 1.
2537 * However, this should be avoided since the user then sees selecting
2538 * the menu item do nothing. Furthermore, you'll find yourself adding
2539 * these checks all over your code, since there are doubtless many,
2540 * many things that the user could do. Instead, you can use the
2541 * following techniques:
2546 * Use gtk_widget_set_sensitive() or modal dialogs to prevent
2547 * the user from interacting with elements while the main
2548 * loop is recursing.
2553 * Avoid main loop recursion in situations where you can't handle
2554 * arbitrary callbacks. Instead, structure your code so that you
2555 * simply return to the main loop and then get called again when
2556 * there is more work to do.
2561 * Return value: The main loop recursion level in the current thread
2566 GMainDispatch *dispatch = get_dispatch ();
2567 return dispatch->depth;
2571 * g_main_current_source:
2573 * Returns the currently firing source for this thread.
2575 * Return value: (transfer none): The currently firing source or %NULL.
2580 g_main_current_source (void)
2582 GMainDispatch *dispatch = get_dispatch ();
2583 return dispatch->dispatching_sources ? dispatch->dispatching_sources->data : NULL;
2587 * g_source_is_destroyed:
2588 * @source: a #GSource
2590 * Returns whether @source has been destroyed.
2592 * This is important when you operate upon your objects
2593 * from within idle handlers, but may have freed the object
2594 * before the dispatch of your idle handler.
2598 * idle_callback (gpointer data)
2600 * SomeWidget *self = data;
2602 * GDK_THREADS_ENTER (<!-- -->);
2603 * /<!-- -->* do stuff with self *<!-- -->/
2604 * self->idle_id = 0;
2605 * GDK_THREADS_LEAVE (<!-- -->);
2607 * return G_SOURCE_REMOVE;
2611 * some_widget_do_stuff_later (SomeWidget *self)
2613 * self->idle_id = g_idle_add (idle_callback, self);
2617 * some_widget_finalize (GObject *object)
2619 * SomeWidget *self = SOME_WIDGET (object);
2621 * if (self->idle_id)
2622 * g_source_remove (self->idle_id);
2624 * G_OBJECT_CLASS (parent_class)->finalize (object);
2628 * This will fail in a multi-threaded application if the
2629 * widget is destroyed before the idle handler fires due
2630 * to the use after free in the callback. A solution, to
2631 * this particular problem, is to check to if the source
2632 * has already been destroy within the callback.
2636 * idle_callback (gpointer data)
2638 * SomeWidget *self = data;
2640 * GDK_THREADS_ENTER ();
2641 * if (!g_source_is_destroyed (g_main_current_source ()))
2643 * /<!-- -->* do stuff with self *<!-- -->/
2645 * GDK_THREADS_LEAVE ();
2651 * Return value: %TRUE if the source has been destroyed
2656 g_source_is_destroyed (GSource *source)
2658 return SOURCE_DESTROYED (source);
2661 /* Temporarily remove all this source's file descriptors from the
2662 * poll(), so that if data comes available for one of the file descriptors
2663 * we don't continually spin in the poll()
2665 /* HOLDS: source->context's lock */
2667 block_source (GSource *source)
2671 g_return_if_fail (!SOURCE_BLOCKED (source));
2673 source->flags |= G_SOURCE_BLOCKED;
2675 tmp_list = source->poll_fds;
2678 g_main_context_remove_poll_unlocked (source->context, tmp_list->data);
2679 tmp_list = tmp_list->next;
2682 if (source->priv && source->priv->child_sources)
2684 tmp_list = source->priv->child_sources;
2687 block_source (tmp_list->data);
2688 tmp_list = tmp_list->next;
2693 /* HOLDS: source->context's lock */
2695 unblock_source (GSource *source)
2699 g_return_if_fail (SOURCE_BLOCKED (source)); /* Source already unblocked */
2700 g_return_if_fail (!SOURCE_DESTROYED (source));
2702 source->flags &= ~G_SOURCE_BLOCKED;
2704 tmp_list = source->poll_fds;
2707 g_main_context_add_poll_unlocked (source->context, source->priority, tmp_list->data);
2708 tmp_list = tmp_list->next;
2711 if (source->priv && source->priv->child_sources)
2713 tmp_list = source->priv->child_sources;
2716 unblock_source (tmp_list->data);
2717 tmp_list = tmp_list->next;
2722 /* HOLDS: context's lock */
2724 g_main_dispatch (GMainContext *context)
2726 GMainDispatch *current = get_dispatch ();
2729 for (i = 0; i < context->pending_dispatches->len; i++)
2731 GSource *source = context->pending_dispatches->pdata[i];
2733 context->pending_dispatches->pdata[i] = NULL;
2736 source->flags &= ~G_SOURCE_READY;
2738 if (!SOURCE_DESTROYED (source))
2740 gboolean was_in_call;
2741 gpointer user_data = NULL;
2742 GSourceFunc callback = NULL;
2743 GSourceCallbackFuncs *cb_funcs;
2745 gboolean need_destroy;
2747 gboolean (*dispatch) (GSource *,
2750 GSList current_source_link;
2752 dispatch = source->source_funcs->dispatch;
2753 cb_funcs = source->callback_funcs;
2754 cb_data = source->callback_data;
2757 cb_funcs->ref (cb_data);
2759 if ((source->flags & G_SOURCE_CAN_RECURSE) == 0)
2760 block_source (source);
2762 was_in_call = source->flags & G_HOOK_FLAG_IN_CALL;
2763 source->flags |= G_HOOK_FLAG_IN_CALL;
2766 cb_funcs->get (cb_data, source, &callback, &user_data);
2768 UNLOCK_CONTEXT (context);
2771 /* The on-stack allocation of the GSList is unconventional, but
2772 * we know that the lifetime of the link is bounded to this
2773 * function as the link is kept in a thread specific list and
2774 * not manipulated outside of this function and its descendants.
2775 * Avoiding the overhead of a g_slist_alloc() is useful as many
2776 * applications do little more than dispatch events.
2778 * This is a performance hack - do not revert to g_slist_prepend()!
2780 current_source_link.data = source;
2781 current_source_link.next = current->dispatching_sources;
2782 current->dispatching_sources = ¤t_source_link;
2783 need_destroy = ! dispatch (source,
2786 g_assert (current->dispatching_sources == ¤t_source_link);
2787 current->dispatching_sources = current_source_link.next;
2791 cb_funcs->unref (cb_data);
2793 LOCK_CONTEXT (context);
2796 source->flags &= ~G_HOOK_FLAG_IN_CALL;
2798 if (SOURCE_BLOCKED (source) && !SOURCE_DESTROYED (source))
2799 unblock_source (source);
2801 /* Note: this depends on the fact that we can't switch
2802 * sources from one main context to another
2804 if (need_destroy && !SOURCE_DESTROYED (source))
2806 g_assert (source->context == context);
2807 g_source_destroy_internal (source, context, TRUE);
2811 SOURCE_UNREF (source, context);
2814 g_ptr_array_set_size (context->pending_dispatches, 0);
2818 * g_main_context_acquire:
2819 * @context: a #GMainContext
2821 * Tries to become the owner of the specified context.
2822 * If some other thread is the owner of the context,
2823 * returns %FALSE immediately. Ownership is properly
2824 * recursive: the owner can require ownership again
2825 * and will release ownership when g_main_context_release()
2826 * is called as many times as g_main_context_acquire().
2828 * You must be the owner of a context before you
2829 * can call g_main_context_prepare(), g_main_context_query(),
2830 * g_main_context_check(), g_main_context_dispatch().
2832 * Return value: %TRUE if the operation succeeded, and
2833 * this thread is now the owner of @context.
2836 g_main_context_acquire (GMainContext *context)
2838 gboolean result = FALSE;
2839 GThread *self = G_THREAD_SELF;
2841 if (context == NULL)
2842 context = g_main_context_default ();
2844 LOCK_CONTEXT (context);
2846 if (!context->owner)
2848 context->owner = self;
2849 g_assert (context->owner_count == 0);
2852 if (context->owner == self)
2854 context->owner_count++;
2858 UNLOCK_CONTEXT (context);
2864 * g_main_context_release:
2865 * @context: a #GMainContext
2867 * Releases ownership of a context previously acquired by this thread
2868 * with g_main_context_acquire(). If the context was acquired multiple
2869 * times, the ownership will be released only when g_main_context_release()
2870 * is called as many times as it was acquired.
2873 g_main_context_release (GMainContext *context)
2875 if (context == NULL)
2876 context = g_main_context_default ();
2878 LOCK_CONTEXT (context);
2880 context->owner_count--;
2881 if (context->owner_count == 0)
2883 context->owner = NULL;
2885 if (context->waiters)
2887 GMainWaiter *waiter = context->waiters->data;
2888 gboolean loop_internal_waiter = (waiter->mutex == &context->mutex);
2889 context->waiters = g_slist_delete_link (context->waiters,
2891 if (!loop_internal_waiter)
2892 g_mutex_lock (waiter->mutex);
2894 g_cond_signal (waiter->cond);
2896 if (!loop_internal_waiter)
2897 g_mutex_unlock (waiter->mutex);
2901 UNLOCK_CONTEXT (context);
2905 * g_main_context_wait:
2906 * @context: a #GMainContext
2907 * @cond: a condition variable
2908 * @mutex: a mutex, currently held
2910 * Tries to become the owner of the specified context,
2911 * as with g_main_context_acquire(). But if another thread
2912 * is the owner, atomically drop @mutex and wait on @cond until
2913 * that owner releases ownership or until @cond is signaled, then
2914 * try again (once) to become the owner.
2916 * Return value: %TRUE if the operation succeeded, and
2917 * this thread is now the owner of @context.
2920 g_main_context_wait (GMainContext *context,
2924 gboolean result = FALSE;
2925 GThread *self = G_THREAD_SELF;
2926 gboolean loop_internal_waiter;
2928 if (context == NULL)
2929 context = g_main_context_default ();
2931 loop_internal_waiter = (mutex == &context->mutex);
2933 if (!loop_internal_waiter)
2934 LOCK_CONTEXT (context);
2936 if (context->owner && context->owner != self)
2941 waiter.mutex = mutex;
2943 context->waiters = g_slist_append (context->waiters, &waiter);
2945 if (!loop_internal_waiter)
2946 UNLOCK_CONTEXT (context);
2947 g_cond_wait (cond, mutex);
2948 if (!loop_internal_waiter)
2949 LOCK_CONTEXT (context);
2951 context->waiters = g_slist_remove (context->waiters, &waiter);
2954 if (!context->owner)
2956 context->owner = self;
2957 g_assert (context->owner_count == 0);
2960 if (context->owner == self)
2962 context->owner_count++;
2966 if (!loop_internal_waiter)
2967 UNLOCK_CONTEXT (context);
2973 * g_main_context_prepare:
2974 * @context: a #GMainContext
2975 * @priority: location to store priority of highest priority
2976 * source already ready.
2978 * Prepares to poll sources within a main loop. The resulting information
2979 * for polling is determined by calling g_main_context_query ().
2981 * Return value: %TRUE if some source is ready to be dispatched
2985 g_main_context_prepare (GMainContext *context,
2990 gint current_priority = G_MAXINT;
2994 if (context == NULL)
2995 context = g_main_context_default ();
2997 LOCK_CONTEXT (context);
2999 context->time_is_fresh = FALSE;
3001 if (context->in_check_or_prepare)
3003 g_warning ("g_main_context_prepare() called recursively from within a source's check() or "
3004 "prepare() member.");
3005 UNLOCK_CONTEXT (context);
3010 /* If recursing, finish up current dispatch, before starting over */
3011 if (context->pending_dispatches)
3014 g_main_dispatch (context, ¤t_time);
3016 UNLOCK_CONTEXT (context);
3021 /* If recursing, clear list of pending dispatches */
3023 for (i = 0; i < context->pending_dispatches->len; i++)
3025 if (context->pending_dispatches->pdata[i])
3026 SOURCE_UNREF ((GSource *)context->pending_dispatches->pdata[i], context);
3028 g_ptr_array_set_size (context->pending_dispatches, 0);
3030 /* Prepare all sources */
3032 context->timeout = -1;
3034 g_source_iter_init (&iter, context, TRUE);
3035 while (g_source_iter_next (&iter, &source))
3037 gint source_timeout = -1;
3039 if (SOURCE_DESTROYED (source) || SOURCE_BLOCKED (source))
3041 if ((n_ready > 0) && (source->priority > current_priority))
3044 if (!(source->flags & G_SOURCE_READY))
3047 gboolean (*prepare) (GSource *source,
3050 prepare = source->source_funcs->prepare;
3051 context->in_check_or_prepare++;
3052 UNLOCK_CONTEXT (context);
3054 result = (*prepare) (source, &source_timeout);
3056 LOCK_CONTEXT (context);
3057 context->in_check_or_prepare--;
3061 GSource *ready_source = source;
3063 while (ready_source)
3065 ready_source->flags |= G_SOURCE_READY;
3066 ready_source = ready_source->priv->parent_source;
3071 if (source->flags & G_SOURCE_READY)
3074 current_priority = source->priority;
3075 context->timeout = 0;
3078 if (source_timeout >= 0)
3080 if (context->timeout < 0)
3081 context->timeout = source_timeout;
3083 context->timeout = MIN (context->timeout, source_timeout);
3086 g_source_iter_clear (&iter);
3088 UNLOCK_CONTEXT (context);
3091 *priority = current_priority;
3093 return (n_ready > 0);
3097 * g_main_context_query:
3098 * @context: a #GMainContext
3099 * @max_priority: maximum priority source to check
3100 * @timeout_: (out): location to store timeout to be used in polling
3101 * @fds: (out caller-allocates) (array length=n_fds): location to
3102 * store #GPollFD records that need to be polled.
3103 * @n_fds: length of @fds.
3105 * Determines information necessary to poll this main loop.
3107 * Return value: the number of records actually stored in @fds,
3108 * or, if more than @n_fds records need to be stored, the number
3109 * of records that need to be stored.
3112 g_main_context_query (GMainContext *context,
3121 LOCK_CONTEXT (context);
3123 pollrec = context->poll_records;
3125 while (pollrec && max_priority >= pollrec->priority)
3127 /* We need to include entries with fd->events == 0 in the array because
3128 * otherwise if the application changes fd->events behind our back and
3129 * makes it non-zero, we'll be out of sync when we check the fds[] array.
3130 * (Changing fd->events after adding an FD wasn't an anticipated use of
3131 * this API, but it occurs in practice.) */
3134 fds[n_poll].fd = pollrec->fd->fd;
3135 /* In direct contradiction to the Unix98 spec, IRIX runs into
3136 * difficulty if you pass in POLLERR, POLLHUP or POLLNVAL
3137 * flags in the events field of the pollfd while it should
3138 * just ignoring them. So we mask them out here.
3140 fds[n_poll].events = pollrec->fd->events & ~(G_IO_ERR|G_IO_HUP|G_IO_NVAL);
3141 fds[n_poll].revents = 0;
3144 pollrec = pollrec->next;
3148 context->poll_changed = FALSE;
3152 *timeout = context->timeout;
3154 context->time_is_fresh = FALSE;
3157 UNLOCK_CONTEXT (context);
3163 * g_main_context_check:
3164 * @context: a #GMainContext
3165 * @max_priority: the maximum numerical priority of sources to check
3166 * @fds: (array length=n_fds): array of #GPollFD's that was passed to
3167 * the last call to g_main_context_query()
3168 * @n_fds: return value of g_main_context_query()
3170 * Passes the results of polling back to the main loop.
3172 * Return value: %TRUE if some sources are ready to be dispatched.
3175 g_main_context_check (GMainContext *context,
3186 LOCK_CONTEXT (context);
3188 if (context->in_check_or_prepare)
3190 g_warning ("g_main_context_check() called recursively from within a source's check() or "
3191 "prepare() member.");
3192 UNLOCK_CONTEXT (context);
3196 if (context->wake_up_rec.revents)
3197 g_wakeup_acknowledge (context->wakeup);
3199 /* If the set of poll file descriptors changed, bail out
3200 * and let the main loop rerun
3202 if (context->poll_changed)
3204 UNLOCK_CONTEXT (context);
3208 pollrec = context->poll_records;
3212 if (pollrec->fd->events)
3213 pollrec->fd->revents = fds[i].revents;
3215 pollrec = pollrec->next;
3219 g_source_iter_init (&iter, context, TRUE);
3220 while (g_source_iter_next (&iter, &source))
3222 if (SOURCE_DESTROYED (source) || SOURCE_BLOCKED (source))
3224 if ((n_ready > 0) && (source->priority > max_priority))
3227 if (!(source->flags & G_SOURCE_READY))
3230 gboolean (*check) (GSource *source);
3232 check = source->source_funcs->check;
3234 context->in_check_or_prepare++;
3235 UNLOCK_CONTEXT (context);
3237 result = (*check) (source);
3239 LOCK_CONTEXT (context);
3240 context->in_check_or_prepare--;
3244 GSource *ready_source = source;
3246 while (ready_source)
3248 ready_source->flags |= G_SOURCE_READY;
3249 ready_source = ready_source->priv->parent_source;
3254 if (source->flags & G_SOURCE_READY)
3256 source->ref_count++;
3257 g_ptr_array_add (context->pending_dispatches, source);
3261 /* never dispatch sources with less priority than the first
3262 * one we choose to dispatch
3264 max_priority = source->priority;
3267 g_source_iter_clear (&iter);
3269 UNLOCK_CONTEXT (context);
3275 * g_main_context_dispatch:
3276 * @context: a #GMainContext
3278 * Dispatches all pending sources.
3281 g_main_context_dispatch (GMainContext *context)
3283 LOCK_CONTEXT (context);
3285 if (context->pending_dispatches->len > 0)
3287 g_main_dispatch (context);
3290 UNLOCK_CONTEXT (context);
3293 /* HOLDS context lock */
3295 g_main_context_iterate (GMainContext *context,
3302 gboolean some_ready;
3303 gint nfds, allocated_nfds;
3304 GPollFD *fds = NULL;
3306 UNLOCK_CONTEXT (context);
3308 if (!g_main_context_acquire (context))
3310 gboolean got_ownership;
3312 LOCK_CONTEXT (context);
3317 got_ownership = g_main_context_wait (context,
3325 LOCK_CONTEXT (context);
3327 if (!context->cached_poll_array)
3329 context->cached_poll_array_size = context->n_poll_records;
3330 context->cached_poll_array = g_new (GPollFD, context->n_poll_records);
3333 allocated_nfds = context->cached_poll_array_size;
3334 fds = context->cached_poll_array;
3336 UNLOCK_CONTEXT (context);
3338 g_main_context_prepare (context, &max_priority);
3340 while ((nfds = g_main_context_query (context, max_priority, &timeout, fds,
3341 allocated_nfds)) > allocated_nfds)
3343 LOCK_CONTEXT (context);
3345 context->cached_poll_array_size = allocated_nfds = nfds;
3346 context->cached_poll_array = fds = g_new (GPollFD, nfds);
3347 UNLOCK_CONTEXT (context);
3353 g_main_context_poll (context, timeout, max_priority, fds, nfds);
3355 some_ready = g_main_context_check (context, max_priority, fds, nfds);
3358 g_main_context_dispatch (context);
3360 g_main_context_release (context);
3362 LOCK_CONTEXT (context);
3368 * g_main_context_pending:
3369 * @context: (allow-none): a #GMainContext (if %NULL, the default context will be used)
3371 * Checks if any sources have pending events for the given context.
3373 * Return value: %TRUE if events are pending.
3376 g_main_context_pending (GMainContext *context)
3381 context = g_main_context_default();
3383 LOCK_CONTEXT (context);
3384 retval = g_main_context_iterate (context, FALSE, FALSE, G_THREAD_SELF);
3385 UNLOCK_CONTEXT (context);
3391 * g_main_context_iteration:
3392 * @context: (allow-none): a #GMainContext (if %NULL, the default context will be used)
3393 * @may_block: whether the call may block.
3395 * Runs a single iteration for the given main loop. This involves
3396 * checking to see if any event sources are ready to be processed,
3397 * then if no events sources are ready and @may_block is %TRUE, waiting
3398 * for a source to become ready, then dispatching the highest priority
3399 * events sources that are ready. Otherwise, if @may_block is %FALSE
3400 * sources are not waited to become ready, only those highest priority
3401 * events sources will be dispatched (if any), that are ready at this
3402 * given moment without further waiting.
3404 * Note that even when @may_block is %TRUE, it is still possible for
3405 * g_main_context_iteration() to return %FALSE, since the wait may
3406 * be interrupted for other reasons than an event source becoming ready.
3408 * Return value: %TRUE if events were dispatched.
3411 g_main_context_iteration (GMainContext *context, gboolean may_block)
3416 context = g_main_context_default();
3418 LOCK_CONTEXT (context);
3419 retval = g_main_context_iterate (context, may_block, TRUE, G_THREAD_SELF);
3420 UNLOCK_CONTEXT (context);
3427 * @context: (allow-none): a #GMainContext (if %NULL, the default context will be used).
3428 * @is_running: set to %TRUE to indicate that the loop is running. This
3429 * is not very important since calling g_main_loop_run() will set this to
3432 * Creates a new #GMainLoop structure.
3434 * Return value: a new #GMainLoop.
3437 g_main_loop_new (GMainContext *context,
3438 gboolean is_running)
3443 context = g_main_context_default();
3445 g_main_context_ref (context);
3447 loop = g_new0 (GMainLoop, 1);
3448 loop->context = context;
3449 loop->is_running = is_running != FALSE;
3450 loop->ref_count = 1;
3457 * @loop: a #GMainLoop
3459 * Increases the reference count on a #GMainLoop object by one.
3461 * Return value: @loop
3464 g_main_loop_ref (GMainLoop *loop)
3466 g_return_val_if_fail (loop != NULL, NULL);
3467 g_return_val_if_fail (g_atomic_int_get (&loop->ref_count) > 0, NULL);
3469 g_atomic_int_inc (&loop->ref_count);
3475 * g_main_loop_unref:
3476 * @loop: a #GMainLoop
3478 * Decreases the reference count on a #GMainLoop object by one. If
3479 * the result is zero, free the loop and free all associated memory.
3482 g_main_loop_unref (GMainLoop *loop)
3484 g_return_if_fail (loop != NULL);
3485 g_return_if_fail (g_atomic_int_get (&loop->ref_count) > 0);
3487 if (!g_atomic_int_dec_and_test (&loop->ref_count))
3490 g_main_context_unref (loop->context);
3496 * @loop: a #GMainLoop
3498 * Runs a main loop until g_main_loop_quit() is called on the loop.
3499 * If this is called for the thread of the loop's #GMainContext,
3500 * it will process events from the loop, otherwise it will
3504 g_main_loop_run (GMainLoop *loop)
3506 GThread *self = G_THREAD_SELF;
3508 g_return_if_fail (loop != NULL);
3509 g_return_if_fail (g_atomic_int_get (&loop->ref_count) > 0);
3511 if (!g_main_context_acquire (loop->context))
3513 gboolean got_ownership = FALSE;
3515 /* Another thread owns this context */
3516 LOCK_CONTEXT (loop->context);
3518 g_atomic_int_inc (&loop->ref_count);
3520 if (!loop->is_running)
3521 loop->is_running = TRUE;
3523 while (loop->is_running && !got_ownership)
3524 got_ownership = g_main_context_wait (loop->context,
3525 &loop->context->cond,
3526 &loop->context->mutex);
3528 if (!loop->is_running)
3530 UNLOCK_CONTEXT (loop->context);
3532 g_main_context_release (loop->context);
3533 g_main_loop_unref (loop);
3537 g_assert (got_ownership);
3540 LOCK_CONTEXT (loop->context);
3542 if (loop->context->in_check_or_prepare)
3544 g_warning ("g_main_loop_run(): called recursively from within a source's "
3545 "check() or prepare() member, iteration not possible.");
3549 g_atomic_int_inc (&loop->ref_count);
3550 loop->is_running = TRUE;
3551 while (loop->is_running)
3552 g_main_context_iterate (loop->context, TRUE, TRUE, self);
3554 UNLOCK_CONTEXT (loop->context);
3556 g_main_context_release (loop->context);
3558 g_main_loop_unref (loop);
3563 * @loop: a #GMainLoop
3565 * Stops a #GMainLoop from running. Any calls to g_main_loop_run()
3566 * for the loop will return.
3568 * Note that sources that have already been dispatched when
3569 * g_main_loop_quit() is called will still be executed.
3572 g_main_loop_quit (GMainLoop *loop)
3574 g_return_if_fail (loop != NULL);
3575 g_return_if_fail (g_atomic_int_get (&loop->ref_count) > 0);
3577 LOCK_CONTEXT (loop->context);
3578 loop->is_running = FALSE;
3579 g_wakeup_signal (loop->context->wakeup);
3581 g_cond_broadcast (&loop->context->cond);
3583 UNLOCK_CONTEXT (loop->context);
3587 * g_main_loop_is_running:
3588 * @loop: a #GMainLoop.
3590 * Checks to see if the main loop is currently being run via g_main_loop_run().
3592 * Return value: %TRUE if the mainloop is currently being run.
3595 g_main_loop_is_running (GMainLoop *loop)
3597 g_return_val_if_fail (loop != NULL, FALSE);
3598 g_return_val_if_fail (g_atomic_int_get (&loop->ref_count) > 0, FALSE);
3600 return loop->is_running;
3604 * g_main_loop_get_context:
3605 * @loop: a #GMainLoop.
3607 * Returns the #GMainContext of @loop.
3609 * Return value: (transfer none): the #GMainContext of @loop
3612 g_main_loop_get_context (GMainLoop *loop)
3614 g_return_val_if_fail (loop != NULL, NULL);
3615 g_return_val_if_fail (g_atomic_int_get (&loop->ref_count) > 0, NULL);
3617 return loop->context;
3620 /* HOLDS: context's lock */
3622 g_main_context_poll (GMainContext *context,
3628 #ifdef G_MAIN_POLL_DEBUG
3634 GPollFunc poll_func;
3636 if (n_fds || timeout != 0)
3638 #ifdef G_MAIN_POLL_DEBUG
3639 if (_g_main_poll_debug)
3641 g_print ("polling context=%p n=%d timeout=%d\n",
3642 context, n_fds, timeout);
3643 poll_timer = g_timer_new ();
3647 LOCK_CONTEXT (context);
3649 poll_func = context->poll_func;
3651 UNLOCK_CONTEXT (context);
3652 if ((*poll_func) (fds, n_fds, timeout) < 0 && errno != EINTR)
3655 g_warning ("poll(2) failed due to: %s.",
3656 g_strerror (errno));
3658 /* If g_poll () returns -1, it has already called g_warning() */
3662 #ifdef G_MAIN_POLL_DEBUG
3663 if (_g_main_poll_debug)
3665 LOCK_CONTEXT (context);
3667 g_print ("g_main_poll(%d) timeout: %d - elapsed %12.10f seconds",
3670 g_timer_elapsed (poll_timer, NULL));
3671 g_timer_destroy (poll_timer);
3672 pollrec = context->poll_records;
3674 while (pollrec != NULL)
3679 if (fds[i].fd == pollrec->fd->fd &&
3680 pollrec->fd->events &&
3683 g_print (" [" G_POLLFD_FORMAT " :", fds[i].fd);
3684 if (fds[i].revents & G_IO_IN)
3686 if (fds[i].revents & G_IO_OUT)
3688 if (fds[i].revents & G_IO_PRI)
3690 if (fds[i].revents & G_IO_ERR)
3692 if (fds[i].revents & G_IO_HUP)
3694 if (fds[i].revents & G_IO_NVAL)
3700 pollrec = pollrec->next;
3704 UNLOCK_CONTEXT (context);
3707 } /* if (n_fds || timeout != 0) */
3711 * g_main_context_add_poll:
3712 * @context: (allow-none): a #GMainContext (or %NULL for the default context)
3713 * @fd: a #GPollFD structure holding information about a file
3714 * descriptor to watch.
3715 * @priority: the priority for this file descriptor which should be
3716 * the same as the priority used for g_source_attach() to ensure that the
3717 * file descriptor is polled whenever the results may be needed.
3719 * Adds a file descriptor to the set of file descriptors polled for
3720 * this context. This will very seldom be used directly. Instead
3721 * a typical event source will use g_source_add_poll() instead.
3724 g_main_context_add_poll (GMainContext *context,
3729 context = g_main_context_default ();
3731 g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
3732 g_return_if_fail (fd);
3734 LOCK_CONTEXT (context);
3735 g_main_context_add_poll_unlocked (context, priority, fd);
3736 UNLOCK_CONTEXT (context);
3739 /* HOLDS: main_loop_lock */
3741 g_main_context_add_poll_unlocked (GMainContext *context,
3745 GPollRec *prevrec, *nextrec;
3746 GPollRec *newrec = g_slice_new (GPollRec);
3748 /* This file descriptor may be checked before we ever poll */
3751 newrec->priority = priority;
3753 prevrec = context->poll_records_tail;
3755 while (prevrec && priority < prevrec->priority)
3758 prevrec = prevrec->prev;
3762 prevrec->next = newrec;
3764 context->poll_records = newrec;
3766 newrec->prev = prevrec;
3767 newrec->next = nextrec;
3770 nextrec->prev = newrec;
3772 context->poll_records_tail = newrec;
3774 context->n_poll_records++;
3776 context->poll_changed = TRUE;
3778 /* Now wake up the main loop if it is waiting in the poll() */
3779 g_wakeup_signal (context->wakeup);
3783 * g_main_context_remove_poll:
3784 * @context:a #GMainContext
3785 * @fd: a #GPollFD descriptor previously added with g_main_context_add_poll()
3787 * Removes file descriptor from the set of file descriptors to be
3788 * polled for a particular context.
3791 g_main_context_remove_poll (GMainContext *context,
3795 context = g_main_context_default ();
3797 g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
3798 g_return_if_fail (fd);
3800 LOCK_CONTEXT (context);
3801 g_main_context_remove_poll_unlocked (context, fd);
3802 UNLOCK_CONTEXT (context);
3806 g_main_context_remove_poll_unlocked (GMainContext *context,
3809 GPollRec *pollrec, *prevrec, *nextrec;
3812 pollrec = context->poll_records;
3816 nextrec = pollrec->next;
3817 if (pollrec->fd == fd)
3819 if (prevrec != NULL)
3820 prevrec->next = nextrec;
3822 context->poll_records = nextrec;
3824 if (nextrec != NULL)
3825 nextrec->prev = prevrec;
3827 context->poll_records_tail = prevrec;
3829 g_slice_free (GPollRec, pollrec);
3831 context->n_poll_records--;
3838 context->poll_changed = TRUE;
3840 /* Now wake up the main loop if it is waiting in the poll() */
3841 g_wakeup_signal (context->wakeup);
3845 * g_source_get_current_time:
3846 * @source: a #GSource
3847 * @timeval: #GTimeVal structure in which to store current time.
3849 * This function ignores @source and is otherwise the same as
3850 * g_get_current_time().
3852 * Deprecated: 2.28: use g_source_get_time() instead
3855 g_source_get_current_time (GSource *source,
3858 g_get_current_time (timeval);
3862 * g_source_get_time:
3863 * @source: a #GSource
3865 * Gets the time to be used when checking this source. The advantage of
3866 * calling this function over calling g_get_monotonic_time() directly is
3867 * that when checking multiple sources, GLib can cache a single value
3868 * instead of having to repeatedly get the system monotonic time.
3870 * The time here is the system monotonic time, if available, or some
3871 * other reasonable alternative otherwise. See g_get_monotonic_time().
3873 * Returns: the monotonic time in microseconds
3878 g_source_get_time (GSource *source)
3880 GMainContext *context;
3883 g_return_val_if_fail (source->context != NULL, 0);
3885 context = source->context;
3887 LOCK_CONTEXT (context);
3889 if (!context->time_is_fresh)
3891 context->time = g_get_monotonic_time ();
3892 context->time_is_fresh = TRUE;
3895 result = context->time;
3897 UNLOCK_CONTEXT (context);
3903 * g_main_context_set_poll_func:
3904 * @context: a #GMainContext
3905 * @func: the function to call to poll all file descriptors
3907 * Sets the function to use to handle polling of file descriptors. It
3908 * will be used instead of the poll() system call
3909 * (or GLib's replacement function, which is used where
3910 * poll() isn't available).
3912 * This function could possibly be used to integrate the GLib event
3913 * loop with an external event loop.
3916 g_main_context_set_poll_func (GMainContext *context,
3920 context = g_main_context_default ();
3922 g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
3924 LOCK_CONTEXT (context);
3927 context->poll_func = func;
3929 context->poll_func = g_poll;
3931 UNLOCK_CONTEXT (context);
3935 * g_main_context_get_poll_func:
3936 * @context: a #GMainContext
3938 * Gets the poll function set by g_main_context_set_poll_func().
3940 * Return value: the poll function
3943 g_main_context_get_poll_func (GMainContext *context)
3948 context = g_main_context_default ();
3950 g_return_val_if_fail (g_atomic_int_get (&context->ref_count) > 0, NULL);
3952 LOCK_CONTEXT (context);
3953 result = context->poll_func;
3954 UNLOCK_CONTEXT (context);
3960 * g_main_context_wakeup:
3961 * @context: a #GMainContext
3963 * If @context is currently waiting in a poll(), interrupt
3964 * the poll(), and continue the iteration process.
3967 g_main_context_wakeup (GMainContext *context)
3970 context = g_main_context_default ();
3972 g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
3974 g_wakeup_signal (context->wakeup);
3978 * g_main_context_is_owner:
3979 * @context: a #GMainContext
3981 * Determines whether this thread holds the (recursive)
3982 * ownership of this #GMainContext. This is useful to
3983 * know before waiting on another thread that may be
3984 * blocking to get ownership of @context.
3986 * Returns: %TRUE if current thread is owner of @context.
3991 g_main_context_is_owner (GMainContext *context)
3996 context = g_main_context_default ();
3998 LOCK_CONTEXT (context);
3999 is_owner = context->owner == G_THREAD_SELF;
4000 UNLOCK_CONTEXT (context);
4008 g_timeout_set_expiration (GTimeoutSource *timeout_source,
4009 gint64 current_time)
4011 timeout_source->expiration = current_time +
4012 (guint64) timeout_source->interval * 1000;
4014 if (timeout_source->seconds)
4017 static gint timer_perturb = -1;
4019 if (timer_perturb == -1)
4022 * we want a per machine/session unique 'random' value; try the dbus
4023 * address first, that has a UUID in it. If there is no dbus, use the
4024 * hostname for hashing.
4026 const char *session_bus_address = g_getenv ("DBUS_SESSION_BUS_ADDRESS");
4027 if (!session_bus_address)
4028 session_bus_address = g_getenv ("HOSTNAME");
4029 if (session_bus_address)
4030 timer_perturb = ABS ((gint) g_str_hash (session_bus_address)) % 1000000;
4035 /* We want the microseconds part of the timeout to land on the
4036 * 'timer_perturb' mark, but we need to make sure we don't try to
4037 * set the timeout in the past. We do this by ensuring that we
4038 * always only *increase* the expiration time by adding a full
4039 * second in the case that the microsecond portion decreases.
4041 timeout_source->expiration -= timer_perturb;
4043 remainder = timeout_source->expiration % 1000000;
4044 if (remainder >= 1000000/4)
4045 timeout_source->expiration += 1000000;
4047 timeout_source->expiration -= remainder;
4048 timeout_source->expiration += timer_perturb;
4053 g_timeout_prepare (GSource *source,
4056 GTimeoutSource *timeout_source = (GTimeoutSource *) source;
4057 gint64 now = g_source_get_time (source);
4059 if (now < timeout_source->expiration)
4061 /* Round up to ensure that we don't try again too early */
4062 *timeout = (timeout_source->expiration - now + 999) / 1000;
4071 g_timeout_check (GSource *source)
4073 GTimeoutSource *timeout_source = (GTimeoutSource *) source;
4074 gint64 now = g_source_get_time (source);
4076 return timeout_source->expiration <= now;
4080 g_timeout_dispatch (GSource *source,
4081 GSourceFunc callback,
4084 GTimeoutSource *timeout_source = (GTimeoutSource *)source;
4089 g_warning ("Timeout source dispatched without callback\n"
4090 "You must call g_source_set_callback().");
4094 again = callback (user_data);
4097 g_timeout_set_expiration (timeout_source, g_source_get_time (source));
4103 * g_timeout_source_new:
4104 * @interval: the timeout interval in milliseconds.
4106 * Creates a new timeout source.
4108 * The source will not initially be associated with any #GMainContext
4109 * and must be added to one with g_source_attach() before it will be
4112 * The interval given is in terms of monotonic time, not wall clock
4113 * time. See g_get_monotonic_time().
4115 * Return value: the newly-created timeout source
4118 g_timeout_source_new (guint interval)
4120 GSource *source = g_source_new (&g_timeout_funcs, sizeof (GTimeoutSource));
4121 GTimeoutSource *timeout_source = (GTimeoutSource *)source;
4123 timeout_source->interval = interval;
4124 g_timeout_set_expiration (timeout_source, g_get_monotonic_time ());
4130 * g_timeout_source_new_seconds:
4131 * @interval: the timeout interval in seconds
4133 * Creates a new timeout source.
4135 * The source will not initially be associated with any #GMainContext
4136 * and must be added to one with g_source_attach() before it will be
4139 * The scheduling granularity/accuracy of this timeout source will be
4142 * The interval given in terms of monotonic time, not wall clock time.
4143 * See g_get_monotonic_time().
4145 * Return value: the newly-created timeout source
4150 g_timeout_source_new_seconds (guint interval)
4152 GSource *source = g_source_new (&g_timeout_funcs, sizeof (GTimeoutSource));
4153 GTimeoutSource *timeout_source = (GTimeoutSource *)source;
4155 timeout_source->interval = 1000 * interval;
4156 timeout_source->seconds = TRUE;
4158 g_timeout_set_expiration (timeout_source, g_get_monotonic_time ());
4165 * g_timeout_add_full:
4166 * @priority: the priority of the timeout source. Typically this will be in
4167 * the range between #G_PRIORITY_DEFAULT and #G_PRIORITY_HIGH.
4168 * @interval: the time between calls to the function, in milliseconds
4169 * (1/1000ths of a second)
4170 * @function: function to call
4171 * @data: data to pass to @function
4172 * @notify: (allow-none): function to call when the timeout is removed, or %NULL
4174 * Sets a function to be called at regular intervals, with the given
4175 * priority. The function is called repeatedly until it returns
4176 * %FALSE, at which point the timeout is automatically destroyed and
4177 * the function will not be called again. The @notify function is
4178 * called when the timeout is destroyed. The first call to the
4179 * function will be at the end of the first @interval.
4181 * Note that timeout functions may be delayed, due to the processing of other
4182 * event sources. Thus they should not be relied on for precise timing.
4183 * After each call to the timeout function, the time of the next
4184 * timeout is recalculated based on the current time and the given interval
4185 * (it does not try to 'catch up' time lost in delays).
4187 * This internally creates a main loop source using g_timeout_source_new()
4188 * and attaches it to the main loop context using g_source_attach(). You can
4189 * do these steps manually if you need greater control.
4191 * The interval given in terms of monotonic time, not wall clock time.
4192 * See g_get_monotonic_time().
4194 * Return value: the ID (greater than 0) of the event source.
4195 * Rename to: g_timeout_add
4198 g_timeout_add_full (gint priority,
4200 GSourceFunc function,
4202 GDestroyNotify notify)
4207 g_return_val_if_fail (function != NULL, 0);
4209 source = g_timeout_source_new (interval);
4211 if (priority != G_PRIORITY_DEFAULT)
4212 g_source_set_priority (source, priority);
4214 g_source_set_callback (source, function, data, notify);
4215 id = g_source_attach (source, NULL);
4216 g_source_unref (source);
4223 * @interval: the time between calls to the function, in milliseconds
4224 * (1/1000ths of a second)
4225 * @function: function to call
4226 * @data: data to pass to @function
4228 * Sets a function to be called at regular intervals, with the default
4229 * priority, #G_PRIORITY_DEFAULT. The function is called repeatedly
4230 * until it returns %FALSE, at which point the timeout is automatically
4231 * destroyed and the function will not be called again. The first call
4232 * to the function will be at the end of the first @interval.
4234 * Note that timeout functions may be delayed, due to the processing of other
4235 * event sources. Thus they should not be relied on for precise timing.
4236 * After each call to the timeout function, the time of the next
4237 * timeout is recalculated based on the current time and the given interval
4238 * (it does not try to 'catch up' time lost in delays).
4240 * If you want to have a timer in the "seconds" range and do not care
4241 * about the exact time of the first call of the timer, use the
4242 * g_timeout_add_seconds() function; this function allows for more
4243 * optimizations and more efficient system power usage.
4245 * This internally creates a main loop source using g_timeout_source_new()
4246 * and attaches it to the main loop context using g_source_attach(). You can
4247 * do these steps manually if you need greater control.
4249 * The interval given is in terms of monotonic time, not wall clock
4250 * time. See g_get_monotonic_time().
4252 * Return value: the ID (greater than 0) of the event source.
4255 g_timeout_add (guint32 interval,
4256 GSourceFunc function,
4259 return g_timeout_add_full (G_PRIORITY_DEFAULT,
4260 interval, function, data, NULL);
4264 * g_timeout_add_seconds_full:
4265 * @priority: the priority of the timeout source. Typically this will be in
4266 * the range between #G_PRIORITY_DEFAULT and #G_PRIORITY_HIGH.
4267 * @interval: the time between calls to the function, in seconds
4268 * @function: function to call
4269 * @data: data to pass to @function
4270 * @notify: (allow-none): function to call when the timeout is removed, or %NULL
4272 * Sets a function to be called at regular intervals, with @priority.
4273 * The function is called repeatedly until it returns %FALSE, at which
4274 * point the timeout is automatically destroyed and the function will
4275 * not be called again.
4277 * Unlike g_timeout_add(), this function operates at whole second granularity.
4278 * The initial starting point of the timer is determined by the implementation
4279 * and the implementation is expected to group multiple timers together so that
4280 * they fire all at the same time.
4281 * To allow this grouping, the @interval to the first timer is rounded
4282 * and can deviate up to one second from the specified interval.
4283 * Subsequent timer iterations will generally run at the specified interval.
4285 * Note that timeout functions may be delayed, due to the processing of other
4286 * event sources. Thus they should not be relied on for precise timing.
4287 * After each call to the timeout function, the time of the next
4288 * timeout is recalculated based on the current time and the given @interval
4290 * If you want timing more precise than whole seconds, use g_timeout_add()
4293 * The grouping of timers to fire at the same time results in a more power
4294 * and CPU efficient behavior so if your timer is in multiples of seconds
4295 * and you don't require the first timer exactly one second from now, the
4296 * use of g_timeout_add_seconds() is preferred over g_timeout_add().
4298 * This internally creates a main loop source using
4299 * g_timeout_source_new_seconds() and attaches it to the main loop context
4300 * using g_source_attach(). You can do these steps manually if you need
4303 * The interval given is in terms of monotonic time, not wall clock
4304 * time. See g_get_monotonic_time().
4306 * Return value: the ID (greater than 0) of the event source.
4308 * Rename to: g_timeout_add_seconds
4312 g_timeout_add_seconds_full (gint priority,
4314 GSourceFunc function,
4316 GDestroyNotify notify)
4321 g_return_val_if_fail (function != NULL, 0);
4323 source = g_timeout_source_new_seconds (interval);
4325 if (priority != G_PRIORITY_DEFAULT)
4326 g_source_set_priority (source, priority);
4328 g_source_set_callback (source, function, data, notify);
4329 id = g_source_attach (source, NULL);
4330 g_source_unref (source);
4336 * g_timeout_add_seconds:
4337 * @interval: the time between calls to the function, in seconds
4338 * @function: function to call
4339 * @data: data to pass to @function
4341 * Sets a function to be called at regular intervals with the default
4342 * priority, #G_PRIORITY_DEFAULT. The function is called repeatedly until
4343 * it returns %FALSE, at which point the timeout is automatically destroyed
4344 * and the function will not be called again.
4346 * This internally creates a main loop source using
4347 * g_timeout_source_new_seconds() and attaches it to the main loop context
4348 * using g_source_attach(). You can do these steps manually if you need
4349 * greater control. Also see g_timeout_add_seconds_full().
4351 * Note that the first call of the timer may not be precise for timeouts
4352 * of one second. If you need finer precision and have such a timeout,
4353 * you may want to use g_timeout_add() instead.
4355 * The interval given is in terms of monotonic time, not wall clock
4356 * time. See g_get_monotonic_time().
4358 * Return value: the ID (greater than 0) of the event source.
4363 g_timeout_add_seconds (guint interval,
4364 GSourceFunc function,
4367 g_return_val_if_fail (function != NULL, 0);
4369 return g_timeout_add_seconds_full (G_PRIORITY_DEFAULT, interval, function, data, NULL);
4372 /* Child watch functions */
4377 g_child_watch_prepare (GSource *source,
4385 g_child_watch_check (GSource *source)
4387 GChildWatchSource *child_watch_source;
4388 gboolean child_exited;
4390 child_watch_source = (GChildWatchSource *) source;
4392 child_exited = child_watch_source->poll.revents & G_IO_IN;
4399 * Note: We do _not_ check for the special value of STILL_ACTIVE
4400 * since we know that the process has exited and doing so runs into
4401 * problems if the child process "happens to return STILL_ACTIVE(259)"
4402 * as Microsoft's Platform SDK puts it.
4404 if (!GetExitCodeProcess (child_watch_source->pid, &child_status))
4406 gchar *emsg = g_win32_error_message (GetLastError ());
4407 g_warning (G_STRLOC ": GetExitCodeProcess() failed: %s", emsg);
4410 child_watch_source->child_status = -1;
4413 child_watch_source->child_status = child_status;
4416 return child_exited;
4420 g_child_watch_finalize (GSource *source)
4424 #else /* G_OS_WIN32 */
4427 wake_source (GSource *source)
4429 GMainContext *context;
4431 /* This should be thread-safe:
4433 * - if the source is currently being added to a context, that
4434 * context will be woken up anyway
4436 * - if the source is currently being destroyed, we simply need not
4439 * - the memory for the source will remain valid until after the
4440 * source finalize function was called (which would remove the
4441 * source from the global list which we are currently holding the
4444 * - the GMainContext will either be NULL or point to a live
4447 * - the GMainContext will remain valid since we hold the
4448 * main_context_list lock
4450 * Since we are holding a lot of locks here, don't try to enter any
4451 * more GMainContext functions for fear of dealock -- just hit the
4452 * GWakeup and run. Even if that's safe now, it could easily become
4453 * unsafe with some very minor changes in the future, and signal
4454 * handling is not the most well-tested codepath.
4456 G_LOCK(main_context_list);
4457 context = source->context;
4459 g_wakeup_signal (context->wakeup);
4460 G_UNLOCK(main_context_list);
4464 dispatch_unix_signals (void)
4468 /* clear this first incase another one arrives while we're processing */
4469 any_unix_signal_pending = FALSE;
4471 G_LOCK(unix_signal_lock);
4473 /* handle GChildWatchSource instances */
4474 if (unix_signal_pending[SIGCHLD])
4476 unix_signal_pending[SIGCHLD] = FALSE;
4478 /* The only way we can do this is to scan all of the children.
4480 * The docs promise that we will not reap children that we are not
4481 * explicitly watching, so that ties our hands from calling
4482 * waitpid(-1). We also can't use siginfo's si_pid field since if
4483 * multiple SIGCHLD arrive at the same time, one of them can be
4484 * dropped (since a given UNIX signal can only be pending once).
4486 for (node = unix_child_watches; node; node = node->next)
4488 GChildWatchSource *source = node->data;
4490 if (!source->child_exited)
4495 pid = waitpid (source->pid, &source->child_status, WNOHANG);
4498 source->child_exited = TRUE;
4499 wake_source ((GSource *) source);
4501 else if (pid == -1 && errno == ECHILD)
4503 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.");
4504 source->child_exited = TRUE;
4505 source->child_status = 0;
4506 wake_source ((GSource *) source);
4509 while (pid == -1 && errno == EINTR);
4514 /* handle GUnixSignalWatchSource instances */
4515 for (node = unix_signal_watches; node; node = node->next)
4517 GUnixSignalWatchSource *source = node->data;
4519 if (!source->pending)
4521 if (unix_signal_pending[source->signum])
4523 unix_signal_pending[source->signum] = FALSE;
4524 source->pending = TRUE;
4526 wake_source ((GSource *) source);
4531 G_UNLOCK(unix_signal_lock);
4535 g_child_watch_prepare (GSource *source,
4538 GChildWatchSource *child_watch_source;
4540 child_watch_source = (GChildWatchSource *) source;
4542 return child_watch_source->child_exited;
4546 g_child_watch_check (GSource *source)
4548 GChildWatchSource *child_watch_source;
4550 child_watch_source = (GChildWatchSource *) source;
4552 return child_watch_source->child_exited;
4556 g_unix_signal_watch_prepare (GSource *source,
4559 GUnixSignalWatchSource *unix_signal_source;
4561 unix_signal_source = (GUnixSignalWatchSource *) source;
4563 return unix_signal_source->pending;
4567 g_unix_signal_watch_check (GSource *source)
4569 GUnixSignalWatchSource *unix_signal_source;
4571 unix_signal_source = (GUnixSignalWatchSource *) source;
4573 return unix_signal_source->pending;
4577 g_unix_signal_watch_dispatch (GSource *source,
4578 GSourceFunc callback,
4581 GUnixSignalWatchSource *unix_signal_source;
4584 unix_signal_source = (GUnixSignalWatchSource *) source;
4588 g_warning ("Unix signal source dispatched without callback\n"
4589 "You must call g_source_set_callback().");
4593 again = (callback) (user_data);
4595 unix_signal_source->pending = FALSE;
4601 ensure_unix_signal_handler_installed_unlocked (int signum)
4603 static sigset_t installed_signal_mask;
4604 static gboolean initialized;
4605 struct sigaction action;
4609 sigemptyset (&installed_signal_mask);
4610 g_get_worker_context ();
4614 if (sigismember (&installed_signal_mask, signum))
4617 sigaddset (&installed_signal_mask, signum);
4619 action.sa_handler = g_unix_signal_handler;
4620 sigemptyset (&action.sa_mask);
4621 action.sa_flags = SA_RESTART | SA_NOCLDSTOP;
4622 sigaction (signum, &action, NULL);
4626 _g_main_create_unix_signal_watch (int signum)
4629 GUnixSignalWatchSource *unix_signal_source;
4631 source = g_source_new (&g_unix_signal_funcs, sizeof (GUnixSignalWatchSource));
4632 unix_signal_source = (GUnixSignalWatchSource *) source;
4634 unix_signal_source->signum = signum;
4635 unix_signal_source->pending = FALSE;
4637 G_LOCK (unix_signal_lock);
4638 ensure_unix_signal_handler_installed_unlocked (signum);
4639 unix_signal_watches = g_slist_prepend (unix_signal_watches, unix_signal_source);
4640 if (unix_signal_pending[signum])
4641 unix_signal_source->pending = TRUE;
4642 unix_signal_pending[signum] = FALSE;
4643 G_UNLOCK (unix_signal_lock);
4649 g_unix_signal_watch_finalize (GSource *source)
4651 G_LOCK (unix_signal_lock);
4652 unix_signal_watches = g_slist_remove (unix_signal_watches, source);
4653 G_UNLOCK (unix_signal_lock);
4657 g_child_watch_finalize (GSource *source)
4659 G_LOCK (unix_signal_lock);
4660 unix_child_watches = g_slist_remove (unix_child_watches, source);
4661 G_UNLOCK (unix_signal_lock);
4664 #endif /* G_OS_WIN32 */
4667 g_child_watch_dispatch (GSource *source,
4668 GSourceFunc callback,
4671 GChildWatchSource *child_watch_source;
4672 GChildWatchFunc child_watch_callback = (GChildWatchFunc) callback;
4674 child_watch_source = (GChildWatchSource *) source;
4678 g_warning ("Child watch source dispatched without callback\n"
4679 "You must call g_source_set_callback().");
4683 (child_watch_callback) (child_watch_source->pid, child_watch_source->child_status, user_data);
4685 /* We never keep a child watch source around as the child is gone */
4692 g_unix_signal_handler (int signum)
4694 unix_signal_pending[signum] = TRUE;
4695 any_unix_signal_pending = TRUE;
4697 g_wakeup_signal (glib_worker_context->wakeup);
4700 #endif /* !G_OS_WIN32 */
4703 * g_child_watch_source_new:
4704 * @pid: process to watch. On POSIX the pid of a child process. On
4705 * Windows a handle for a process (which doesn't have to be a child).
4707 * Creates a new child_watch source.
4709 * The source will not initially be associated with any #GMainContext
4710 * and must be added to one with g_source_attach() before it will be
4713 * Note that child watch sources can only be used in conjunction with
4714 * <literal>g_spawn...</literal> when the %G_SPAWN_DO_NOT_REAP_CHILD
4717 * Note that on platforms where #GPid must be explicitly closed
4718 * (see g_spawn_close_pid()) @pid must not be closed while the
4719 * source is still active. Typically, you will want to call
4720 * g_spawn_close_pid() in the callback function for the source.
4722 * Note further that using g_child_watch_source_new() is not
4723 * compatible with calling <literal>waitpid</literal> with a
4724 * nonpositive first argument in the application. Calling waitpid()
4725 * for individual pids will still work fine.
4727 * Return value: the newly-created child watch source
4732 g_child_watch_source_new (GPid pid)
4734 GSource *source = g_source_new (&g_child_watch_funcs, sizeof (GChildWatchSource));
4735 GChildWatchSource *child_watch_source = (GChildWatchSource *)source;
4737 child_watch_source->pid = pid;
4740 child_watch_source->poll.fd = (gintptr) pid;
4741 child_watch_source->poll.events = G_IO_IN;
4743 g_source_add_poll (source, &child_watch_source->poll);
4744 #else /* G_OS_WIN32 */
4745 G_LOCK (unix_signal_lock);
4746 ensure_unix_signal_handler_installed_unlocked (SIGCHLD);
4747 unix_child_watches = g_slist_prepend (unix_child_watches, child_watch_source);
4748 if (waitpid (pid, &child_watch_source->child_status, WNOHANG) > 0)
4749 child_watch_source->child_exited = TRUE;
4750 G_UNLOCK (unix_signal_lock);
4751 #endif /* G_OS_WIN32 */
4757 * g_child_watch_add_full:
4758 * @priority: the priority of the idle source. Typically this will be in the
4759 * range between #G_PRIORITY_DEFAULT_IDLE and #G_PRIORITY_HIGH_IDLE.
4760 * @pid: process to watch. On POSIX the pid of a child process. On
4761 * Windows a handle for a process (which doesn't have to be a child).
4762 * @function: function to call
4763 * @data: data to pass to @function
4764 * @notify: (allow-none): function to call when the idle is removed, or %NULL
4766 * Sets a function to be called when the child indicated by @pid
4767 * exits, at the priority @priority.
4769 * If you obtain @pid from g_spawn_async() or g_spawn_async_with_pipes()
4770 * you will need to pass #G_SPAWN_DO_NOT_REAP_CHILD as flag to
4771 * the spawn function for the child watching to work.
4773 * In many programs, you will want to call g_spawn_check_exit_status()
4774 * in the callback to determine whether or not the child exited
4777 * Also, note that on platforms where #GPid must be explicitly closed
4778 * (see g_spawn_close_pid()) @pid must not be closed while the source
4779 * is still active. Typically, you should invoke g_spawn_close_pid()
4780 * in the callback function for the source.
4782 * GLib supports only a single callback per process id.
4784 * This internally creates a main loop source using
4785 * g_child_watch_source_new() and attaches it to the main loop context
4786 * using g_source_attach(). You can do these steps manually if you
4787 * need greater control.
4789 * Return value: the ID (greater than 0) of the event source.
4791 * Rename to: g_child_watch_add
4795 g_child_watch_add_full (gint priority,
4797 GChildWatchFunc function,
4799 GDestroyNotify notify)
4804 g_return_val_if_fail (function != NULL, 0);
4806 source = g_child_watch_source_new (pid);
4808 if (priority != G_PRIORITY_DEFAULT)
4809 g_source_set_priority (source, priority);
4811 g_source_set_callback (source, (GSourceFunc) function, data, notify);
4812 id = g_source_attach (source, NULL);
4813 g_source_unref (source);
4819 * g_child_watch_add:
4820 * @pid: process id to watch. On POSIX the pid of a child process. On
4821 * Windows a handle for a process (which doesn't have to be a child).
4822 * @function: function to call
4823 * @data: data to pass to @function
4825 * Sets a function to be called when the child indicated by @pid
4826 * exits, at a default priority, #G_PRIORITY_DEFAULT.
4828 * If you obtain @pid from g_spawn_async() or g_spawn_async_with_pipes()
4829 * you will need to pass #G_SPAWN_DO_NOT_REAP_CHILD as flag to
4830 * the spawn function for the child watching to work.
4832 * Note that on platforms where #GPid must be explicitly closed
4833 * (see g_spawn_close_pid()) @pid must not be closed while the
4834 * source is still active. Typically, you will want to call
4835 * g_spawn_close_pid() in the callback function for the source.
4837 * GLib supports only a single callback per process id.
4839 * This internally creates a main loop source using
4840 * g_child_watch_source_new() and attaches it to the main loop context
4841 * using g_source_attach(). You can do these steps manually if you
4842 * need greater control.
4844 * Return value: the ID (greater than 0) of the event source.
4849 g_child_watch_add (GPid pid,
4850 GChildWatchFunc function,
4853 return g_child_watch_add_full (G_PRIORITY_DEFAULT, pid, function, data, NULL);
4857 /* Idle functions */
4860 g_idle_prepare (GSource *source,
4869 g_idle_check (GSource *source)
4875 g_idle_dispatch (GSource *source,
4876 GSourceFunc callback,
4881 g_warning ("Idle source dispatched without callback\n"
4882 "You must call g_source_set_callback().");
4886 return callback (user_data);
4890 * g_idle_source_new:
4892 * Creates a new idle source.
4894 * The source will not initially be associated with any #GMainContext
4895 * and must be added to one with g_source_attach() before it will be
4896 * executed. Note that the default priority for idle sources is
4897 * %G_PRIORITY_DEFAULT_IDLE, as compared to other sources which
4898 * have a default priority of %G_PRIORITY_DEFAULT.
4900 * Return value: the newly-created idle source
4903 g_idle_source_new (void)
4907 source = g_source_new (&g_idle_funcs, sizeof (GSource));
4908 g_source_set_priority (source, G_PRIORITY_DEFAULT_IDLE);
4915 * @priority: the priority of the idle source. Typically this will be in the
4916 * range between #G_PRIORITY_DEFAULT_IDLE and #G_PRIORITY_HIGH_IDLE.
4917 * @function: function to call
4918 * @data: data to pass to @function
4919 * @notify: (allow-none): function to call when the idle is removed, or %NULL
4921 * Adds a function to be called whenever there are no higher priority
4922 * events pending. If the function returns %FALSE it is automatically
4923 * removed from the list of event sources and will not be called again.
4925 * This internally creates a main loop source using g_idle_source_new()
4926 * and attaches it to the main loop context using g_source_attach().
4927 * You can do these steps manually if you need greater control.
4929 * Return value: the ID (greater than 0) of the event source.
4930 * Rename to: g_idle_add
4933 g_idle_add_full (gint priority,
4934 GSourceFunc function,
4936 GDestroyNotify notify)
4941 g_return_val_if_fail (function != NULL, 0);
4943 source = g_idle_source_new ();
4945 if (priority != G_PRIORITY_DEFAULT_IDLE)
4946 g_source_set_priority (source, priority);
4948 g_source_set_callback (source, function, data, notify);
4949 id = g_source_attach (source, NULL);
4950 g_source_unref (source);
4957 * @function: function to call
4958 * @data: data to pass to @function.
4960 * Adds a function to be called whenever there are no higher priority
4961 * events pending to the default main loop. The function is given the
4962 * default idle priority, #G_PRIORITY_DEFAULT_IDLE. If the function
4963 * returns %FALSE it is automatically removed from the list of event
4964 * sources and will not be called again.
4966 * This internally creates a main loop source using g_idle_source_new()
4967 * and attaches it to the main loop context using g_source_attach().
4968 * You can do these steps manually if you need greater control.
4970 * Return value: the ID (greater than 0) of the event source.
4973 g_idle_add (GSourceFunc function,
4976 return g_idle_add_full (G_PRIORITY_DEFAULT_IDLE, function, data, NULL);
4980 * g_idle_remove_by_data:
4981 * @data: the data for the idle source's callback.
4983 * Removes the idle function with the given data.
4985 * Return value: %TRUE if an idle source was found and removed.
4988 g_idle_remove_by_data (gpointer data)
4990 return g_source_remove_by_funcs_user_data (&g_idle_funcs, data);
4994 * g_main_context_invoke:
4995 * @context: (allow-none): a #GMainContext, or %NULL
4996 * @function: function to call
4997 * @data: data to pass to @function
4999 * Invokes a function in such a way that @context is owned during the
5000 * invocation of @function.
5002 * If @context is %NULL then the global default main context — as
5003 * returned by g_main_context_default() — is used.
5005 * If @context is owned by the current thread, @function is called
5006 * directly. Otherwise, if @context is the thread-default main context
5007 * of the current thread and g_main_context_acquire() succeeds, then
5008 * @function is called and g_main_context_release() is called
5011 * In any other case, an idle source is created to call @function and
5012 * that source is attached to @context (presumably to be run in another
5013 * thread). The idle source is attached with #G_PRIORITY_DEFAULT
5014 * priority. If you want a different priority, use
5015 * g_main_context_invoke_full().
5017 * Note that, as with normal idle functions, @function should probably
5018 * return %FALSE. If it returns %TRUE, it will be continuously run in a
5019 * loop (and may prevent this call from returning).
5024 g_main_context_invoke (GMainContext *context,
5025 GSourceFunc function,
5028 g_main_context_invoke_full (context,
5030 function, data, NULL);
5034 * g_main_context_invoke_full:
5035 * @context: (allow-none): a #GMainContext, or %NULL
5036 * @priority: the priority at which to run @function
5037 * @function: function to call
5038 * @data: data to pass to @function
5039 * @notify: (allow-none): a function to call when @data is no longer in use, or %NULL.
5041 * Invokes a function in such a way that @context is owned during the
5042 * invocation of @function.
5044 * This function is the same as g_main_context_invoke() except that it
5045 * lets you specify the priority incase @function ends up being
5046 * scheduled as an idle and also lets you give a #GDestroyNotify for @data.
5048 * @notify should not assume that it is called from any particular
5049 * thread or with any particular context acquired.
5054 g_main_context_invoke_full (GMainContext *context,
5056 GSourceFunc function,
5058 GDestroyNotify notify)
5060 g_return_if_fail (function != NULL);
5063 context = g_main_context_default ();
5065 if (g_main_context_is_owner (context))
5067 while (function (data));
5074 GMainContext *thread_default;
5076 thread_default = g_main_context_get_thread_default ();
5078 if (!thread_default)
5079 thread_default = g_main_context_default ();
5081 if (thread_default == context && g_main_context_acquire (context))
5083 while (function (data));
5085 g_main_context_release (context);
5094 source = g_idle_source_new ();
5095 g_source_set_priority (source, priority);
5096 g_source_set_callback (source, function, data, notify);
5097 g_source_attach (source, context);
5098 g_source_unref (source);
5104 glib_worker_main (gpointer data)
5108 g_main_context_iteration (glib_worker_context, TRUE);
5111 if (any_unix_signal_pending)
5112 dispatch_unix_signals ();
5116 return NULL; /* worst GCC warning message ever... */
5120 g_get_worker_context (void)
5122 static gsize initialised;
5124 if (g_once_init_enter (&initialised))
5126 /* mask all signals in the worker thread */
5132 pthread_sigmask (SIG_SETMASK, &all, &prev_mask);
5134 glib_worker_context = g_main_context_new ();
5135 g_thread_new ("gmain", glib_worker_main, NULL);
5137 pthread_sigmask (SIG_SETMASK, &prev_mask, NULL);
5139 g_once_init_leave (&initialised, TRUE);
5142 return glib_worker_context;