1 /* GLIB - Library of useful routines for C programming
2 * Copyright (C) 1995-1997 Peter Mattis, Spencer Kimball and Josh MacDonald
4 * gmain.c: Main loop abstraction, timeouts, and idle functions
5 * Copyright 1998 Owen Taylor
7 * This library is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU Lesser General Public
9 * License as published by the Free Software Foundation; either
10 * version 2 of the License, or (at your option) any later version.
12 * This library is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 * Lesser General Public License for more details.
17 * You should have received a copy of the GNU Lesser General Public
18 * License along with this library; if not, write to the
19 * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
20 * Boston, MA 02111-1307, USA.
24 * Modified by the GLib Team and others 1997-2000. See the AUTHORS
25 * file for a list of people on the GLib Team. See the ChangeLog
26 * files for a list of changes. These files are distributed with
27 * GLib at ftp://ftp.gtk.org/pub/gtk/.
35 #include "glibconfig.h"
37 /* Uncomment the next line (and the corresponding line in gpoll.c) to
38 * enable debugging printouts if the environment variable
39 * G_MAIN_POLL_DEBUG is set to some value.
41 /* #define G_MAIN_POLL_DEBUG */
44 /* Always enable debugging printout on Windows, as it is more often
47 #define G_MAIN_POLL_DEBUG
51 #include "glib-unix.h"
54 #include <sys/eventfd.h>
59 #include <sys/types.h>
62 #ifdef HAVE_SYS_TIME_H
64 #endif /* HAVE_SYS_TIME_H */
67 #endif /* HAVE_UNISTD_H */
74 #endif /* G_OS_WIN32 */
77 #include <sys/socket.h>
79 #endif /* G_OS_BEOS */
84 #include "giochannel.h"
88 #include "gstrfuncs.h"
89 #include "gtestutils.h"
95 #ifdef G_MAIN_POLL_DEBUG
100 #include "gmain-internal.h"
101 #include "glib-init.h"
102 #include "glib-private.h"
106 * @title: The Main Event Loop
107 * @short_description: manages all available sources of events
109 * The main event loop manages all the available sources of events for
110 * GLib and GTK+ applications. These events can come from any number of
111 * different types of sources such as file descriptors (plain files,
112 * pipes or sockets) and timeouts. New types of event sources can also
113 * be added using g_source_attach().
115 * To allow multiple independent sets of sources to be handled in
116 * different threads, each source is associated with a #GMainContext.
117 * A GMainContext can only be running in a single thread, but
118 * sources can be added to it and removed from it from other threads.
120 * Each event source is assigned a priority. The default priority,
121 * #G_PRIORITY_DEFAULT, is 0. Values less than 0 denote higher priorities.
122 * Values greater than 0 denote lower priorities. Events from high priority
123 * sources are always processed before events from lower priority sources.
125 * Idle functions can also be added, and assigned a priority. These will
126 * be run whenever no events with a higher priority are ready to be processed.
128 * The #GMainLoop data type represents a main event loop. A GMainLoop is
129 * created with g_main_loop_new(). After adding the initial event sources,
130 * g_main_loop_run() is called. This continuously checks for new events from
131 * each of the event sources and dispatches them. Finally, the processing of
132 * an event from one of the sources leads to a call to g_main_loop_quit() to
133 * exit the main loop, and g_main_loop_run() returns.
135 * It is possible to create new instances of #GMainLoop recursively.
136 * This is often used in GTK+ applications when showing modal dialog
137 * boxes. Note that event sources are associated with a particular
138 * #GMainContext, and will be checked and dispatched for all main
139 * loops associated with that GMainContext.
141 * GTK+ contains wrappers of some of these functions, e.g. gtk_main(),
142 * gtk_main_quit() and gtk_events_pending().
144 * <refsect2><title>Creating new source types</title>
145 * <para>One of the unusual features of the #GMainLoop functionality
146 * is that new types of event source can be created and used in
147 * addition to the builtin type of event source. A new event source
148 * type is used for handling GDK events. A new source type is created
149 * by <firstterm>deriving</firstterm> from the #GSource structure.
150 * The derived type of source is represented by a structure that has
151 * the #GSource structure as a first element, and other elements specific
152 * to the new source type. To create an instance of the new source type,
153 * call g_source_new() passing in the size of the derived structure and
154 * a table of functions. These #GSourceFuncs determine the behavior of
155 * the new source type.</para>
156 * <para>New source types basically interact with the main context
157 * in two ways. Their prepare function in #GSourceFuncs can set a timeout
158 * to determine the maximum amount of time that the main loop will sleep
159 * before checking the source again. In addition, or as well, the source
160 * can add file descriptors to the set that the main context checks using
161 * g_source_add_poll().</para>
163 * <refsect2><title>Customizing the main loop iteration</title>
164 * <para>Single iterations of a #GMainContext can be run with
165 * g_main_context_iteration(). In some cases, more detailed control
166 * of exactly how the details of the main loop work is desired, for
167 * instance, when integrating the #GMainLoop with an external main loop.
168 * In such cases, you can call the component functions of
169 * g_main_context_iteration() directly. These functions are
170 * g_main_context_prepare(), g_main_context_query(),
171 * g_main_context_check() and g_main_context_dispatch().</para>
172 * <para>The operation of these functions can best be seen in terms
173 * of a state diagram, as shown in <xref linkend="mainloop-states"/>.</para>
174 * <figure id="mainloop-states"><title>States of a Main Context</title>
175 * <graphic fileref="mainloop-states.gif" format="GIF"></graphic>
179 * On Unix, the GLib mainloop is incompatible with fork(). Any program
180 * using the mainloop must either exec() or exit() from the child
181 * without returning to the mainloop.
186 typedef struct _GTimeoutSource GTimeoutSource;
187 typedef struct _GChildWatchSource GChildWatchSource;
188 typedef struct _GUnixSignalWatchSource GUnixSignalWatchSource;
189 typedef struct _GPollRec GPollRec;
190 typedef struct _GSourceCallback GSourceCallback;
194 G_SOURCE_READY = 1 << G_HOOK_FLAG_USER_SHIFT,
195 G_SOURCE_CAN_RECURSE = 1 << (G_HOOK_FLAG_USER_SHIFT + 1),
196 G_SOURCE_BLOCKED = 1 << (G_HOOK_FLAG_USER_SHIFT + 2)
199 typedef struct _GSourceList GSourceList;
203 GSource *head, *tail;
207 typedef struct _GMainWaiter GMainWaiter;
215 typedef struct _GMainDispatch GMainDispatch;
217 struct _GMainDispatch
220 GSList *dispatching_sources; /* stack of current sources */
223 #ifdef G_MAIN_POLL_DEBUG
224 gboolean _g_main_poll_debug = FALSE;
229 /* The following lock is used for both the list of sources
230 * and the list of poll records
240 GPtrArray *pending_dispatches;
241 gint timeout; /* Timeout for current iteration */
244 GHashTable *overflow_used_source_ids; /* set<guint> */
246 gint in_check_or_prepare;
248 GPollRec *poll_records, *poll_records_tail;
249 guint n_poll_records;
250 GPollFD *cached_poll_array;
251 guint cached_poll_array_size;
257 /* Flag indicating whether the set of fd's changed during a poll */
258 gboolean poll_changed;
263 gboolean time_is_fresh;
266 struct _GSourceCallback
271 GDestroyNotify notify;
276 GMainContext *context;
281 struct _GTimeoutSource
289 struct _GChildWatchSource
296 #else /* G_OS_WIN32 */
297 gboolean child_exited;
298 #endif /* G_OS_WIN32 */
301 struct _GUnixSignalWatchSource
316 struct _GSourcePrivate
318 GSList *child_sources;
319 GSource *parent_source;
322 typedef struct _GSourceIter
324 GMainContext *context;
330 #define LOCK_CONTEXT(context) g_mutex_lock (&context->mutex)
331 #define UNLOCK_CONTEXT(context) g_mutex_unlock (&context->mutex)
332 #define G_THREAD_SELF g_thread_self ()
334 #define SOURCE_DESTROYED(source) (((source)->flags & G_HOOK_FLAG_ACTIVE) == 0)
335 #define SOURCE_BLOCKED(source) (((source)->flags & G_SOURCE_BLOCKED) != 0)
337 #define SOURCE_UNREF(source, context) \
339 if ((source)->ref_count > 1) \
340 (source)->ref_count--; \
342 g_source_unref_internal ((source), (context), TRUE); \
346 /* Forward declarations */
348 static void g_source_unref_internal (GSource *source,
349 GMainContext *context,
351 static void g_source_destroy_internal (GSource *source,
352 GMainContext *context,
354 static void g_source_set_priority_unlocked (GSource *source,
355 GMainContext *context,
357 static void g_child_source_remove_internal (GSource *child_source,
358 GMainContext *context);
360 static void g_main_context_poll (GMainContext *context,
365 static void g_main_context_add_poll_unlocked (GMainContext *context,
368 static void g_main_context_remove_poll_unlocked (GMainContext *context,
371 static void g_source_iter_init (GSourceIter *iter,
372 GMainContext *context,
373 gboolean may_modify);
374 static gboolean g_source_iter_next (GSourceIter *iter,
376 static void g_source_iter_clear (GSourceIter *iter);
378 static gboolean g_timeout_prepare (GSource *source,
380 static gboolean g_timeout_check (GSource *source);
381 static gboolean g_timeout_dispatch (GSource *source,
382 GSourceFunc callback,
384 static gboolean g_child_watch_prepare (GSource *source,
386 static gboolean g_child_watch_check (GSource *source);
387 static gboolean g_child_watch_dispatch (GSource *source,
388 GSourceFunc callback,
390 static void g_child_watch_finalize (GSource *source);
392 static void g_unix_signal_handler (int signum);
393 static gboolean g_unix_signal_watch_prepare (GSource *source,
395 static gboolean g_unix_signal_watch_check (GSource *source);
396 static gboolean g_unix_signal_watch_dispatch (GSource *source,
397 GSourceFunc callback,
399 static void g_unix_signal_watch_finalize (GSource *source);
401 static gboolean g_idle_prepare (GSource *source,
403 static gboolean g_idle_check (GSource *source);
404 static gboolean g_idle_dispatch (GSource *source,
405 GSourceFunc callback,
408 static void block_source (GSource *source);
410 static GMainContext *glib_worker_context;
412 G_LOCK_DEFINE_STATIC (main_loop);
413 static GMainContext *default_main_context;
418 /* UNIX signals work by marking one of these variables then waking the
419 * worker context to check on them and dispatch accordingly.
421 #ifdef HAVE_SIG_ATOMIC_T
422 static volatile sig_atomic_t unix_signal_pending[NSIG];
423 static volatile sig_atomic_t any_unix_signal_pending;
425 static volatile int unix_signal_pending[NSIG];
426 static volatile int any_unix_signal_pending;
429 /* Guards all the data below */
430 G_LOCK_DEFINE_STATIC (unix_signal_lock);
431 static GSList *unix_signal_watches;
432 static GSList *unix_child_watches;
434 static GSourceFuncs g_unix_signal_funcs =
436 g_unix_signal_watch_prepare,
437 g_unix_signal_watch_check,
438 g_unix_signal_watch_dispatch,
439 g_unix_signal_watch_finalize
441 #endif /* !G_OS_WIN32 */
442 G_LOCK_DEFINE_STATIC (main_context_list);
443 static GSList *main_context_list = NULL;
445 GSourceFuncs g_timeout_funcs =
453 GSourceFuncs g_child_watch_funcs =
455 g_child_watch_prepare,
457 g_child_watch_dispatch,
458 g_child_watch_finalize
461 GSourceFuncs g_idle_funcs =
470 * g_main_context_ref:
471 * @context: a #GMainContext
473 * Increases the reference count on a #GMainContext object by one.
475 * Returns: the @context that was passed in (since 2.6)
478 g_main_context_ref (GMainContext *context)
480 g_return_val_if_fail (context != NULL, NULL);
481 g_return_val_if_fail (g_atomic_int_get (&context->ref_count) > 0, NULL);
483 g_atomic_int_inc (&context->ref_count);
489 poll_rec_list_free (GMainContext *context,
492 g_slice_free_chain (GPollRec, list, next);
496 * g_main_context_unref:
497 * @context: a #GMainContext
499 * Decreases the reference count on a #GMainContext object by one. If
500 * the result is zero, free the context and free all associated memory.
503 g_main_context_unref (GMainContext *context)
510 g_return_if_fail (context != NULL);
511 g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
513 if (!g_atomic_int_dec_and_test (&context->ref_count))
516 G_LOCK (main_context_list);
517 main_context_list = g_slist_remove (main_context_list, context);
518 G_UNLOCK (main_context_list);
520 g_source_iter_init (&iter, context, TRUE);
521 while (g_source_iter_next (&iter, &source))
523 source->context = NULL;
524 g_source_destroy_internal (source, context, FALSE);
526 for (sl_iter = context->source_lists; sl_iter; sl_iter = sl_iter->next)
528 list = sl_iter->data;
529 g_slice_free (GSourceList, list);
531 g_list_free (context->source_lists);
533 if (context->overflow_used_source_ids)
534 g_hash_table_destroy (context->overflow_used_source_ids);
536 g_mutex_clear (&context->mutex);
538 g_ptr_array_free (context->pending_dispatches, TRUE);
539 g_free (context->cached_poll_array);
541 poll_rec_list_free (context, context->poll_records);
543 g_wakeup_free (context->wakeup);
544 g_cond_clear (&context->cond);
549 /* Helper function used by mainloop/overflow test.
552 g_main_context_new_with_next_id (guint next_id)
554 GMainContext *ret = g_main_context_new ();
556 ret->next_id = next_id;
562 * g_main_context_new:
564 * Creates a new #GMainContext structure.
566 * Return value: the new #GMainContext
569 g_main_context_new (void)
571 static gsize initialised;
572 GMainContext *context;
574 if (g_once_init_enter (&initialised))
576 #ifdef G_MAIN_POLL_DEBUG
577 if (getenv ("G_MAIN_POLL_DEBUG") != NULL)
578 _g_main_poll_debug = TRUE;
581 g_once_init_leave (&initialised, TRUE);
584 context = g_new0 (GMainContext, 1);
586 g_mutex_init (&context->mutex);
587 g_cond_init (&context->cond);
589 context->owner = NULL;
590 context->waiters = NULL;
592 context->ref_count = 1;
594 context->next_id = 1;
596 context->source_lists = NULL;
598 context->poll_func = g_poll;
600 context->cached_poll_array = NULL;
601 context->cached_poll_array_size = 0;
603 context->pending_dispatches = g_ptr_array_new ();
605 context->time_is_fresh = FALSE;
607 context->wakeup = g_wakeup_new ();
608 g_wakeup_get_pollfd (context->wakeup, &context->wake_up_rec);
609 g_main_context_add_poll_unlocked (context, 0, &context->wake_up_rec);
611 G_LOCK (main_context_list);
612 main_context_list = g_slist_append (main_context_list, context);
614 #ifdef G_MAIN_POLL_DEBUG
615 if (_g_main_poll_debug)
616 g_print ("created context=%p\n", context);
619 G_UNLOCK (main_context_list);
625 * g_main_context_default:
627 * Returns the global default main context. This is the main context
628 * used for main loop functions when a main loop is not explicitly
629 * specified, and corresponds to the "main" main loop. See also
630 * g_main_context_get_thread_default().
632 * Return value: (transfer none): the global default main context.
635 g_main_context_default (void)
641 if (!default_main_context)
643 default_main_context = g_main_context_new ();
644 #ifdef G_MAIN_POLL_DEBUG
645 if (_g_main_poll_debug)
646 g_print ("default context=%p\n", default_main_context);
650 G_UNLOCK (main_loop);
652 return default_main_context;
656 free_context (gpointer data)
658 GMainContext *context = data;
660 g_main_context_release (context);
662 g_main_context_unref (context);
666 free_context_stack (gpointer data)
668 g_queue_free_full((GQueue *) data, (GDestroyNotify) free_context);
671 static GPrivate thread_context_stack = G_PRIVATE_INIT (free_context_stack);
674 * g_main_context_push_thread_default:
675 * @context: (allow-none): a #GMainContext, or %NULL for the global default context
677 * Acquires @context and sets it as the thread-default context for the
678 * current thread. This will cause certain asynchronous operations
679 * (such as most <link linkend="gio">gio</link>-based I/O) which are
680 * started in this thread to run under @context and deliver their
681 * results to its main loop, rather than running under the global
682 * default context in the main thread. Note that calling this function
683 * changes the context returned by
684 * g_main_context_get_thread_default(), <emphasis>not</emphasis> the
685 * one returned by g_main_context_default(), so it does not affect the
686 * context used by functions like g_idle_add().
688 * Normally you would call this function shortly after creating a new
689 * thread, passing it a #GMainContext which will be run by a
690 * #GMainLoop in that thread, to set a new default context for all
691 * async operations in that thread. (In this case, you don't need to
692 * ever call g_main_context_pop_thread_default().) In some cases
693 * however, you may want to schedule a single operation in a
694 * non-default context, or temporarily use a non-default context in
695 * the main thread. In that case, you can wrap the call to the
696 * asynchronous operation inside a
697 * g_main_context_push_thread_default() /
698 * g_main_context_pop_thread_default() pair, but it is up to you to
699 * ensure that no other asynchronous operations accidentally get
700 * started while the non-default context is active.
702 * Beware that libraries that predate this function may not correctly
703 * handle being used from a thread with a thread-default context. Eg,
704 * see g_file_supports_thread_contexts().
709 g_main_context_push_thread_default (GMainContext *context)
712 gboolean acquired_context;
714 acquired_context = g_main_context_acquire (context);
715 g_return_if_fail (acquired_context);
717 if (context == g_main_context_default ())
720 g_main_context_ref (context);
722 stack = g_private_get (&thread_context_stack);
725 stack = g_queue_new ();
726 g_private_set (&thread_context_stack, stack);
729 g_queue_push_head (stack, context);
733 * g_main_context_pop_thread_default:
734 * @context: (allow-none): a #GMainContext object, or %NULL
736 * Pops @context off the thread-default context stack (verifying that
737 * it was on the top of the stack).
742 g_main_context_pop_thread_default (GMainContext *context)
746 if (context == g_main_context_default ())
749 stack = g_private_get (&thread_context_stack);
751 g_return_if_fail (stack != NULL);
752 g_return_if_fail (g_queue_peek_head (stack) == context);
754 g_queue_pop_head (stack);
756 g_main_context_release (context);
758 g_main_context_unref (context);
762 * g_main_context_get_thread_default:
764 * Gets the thread-default #GMainContext for this thread. Asynchronous
765 * operations that want to be able to be run in contexts other than
766 * the default one should call this method or
767 * g_main_context_ref_thread_default() to get a #GMainContext to add
768 * their #GSource<!-- -->s to. (Note that even in single-threaded
769 * programs applications may sometimes want to temporarily push a
770 * non-default context, so it is not safe to assume that this will
771 * always return %NULL if you are running in the default thread.)
773 * If you need to hold a reference on the context, use
774 * g_main_context_ref_thread_default() instead.
776 * Returns: (transfer none): the thread-default #GMainContext, or
777 * %NULL if the thread-default context is the global default context.
782 g_main_context_get_thread_default (void)
786 stack = g_private_get (&thread_context_stack);
788 return g_queue_peek_head (stack);
794 * g_main_context_ref_thread_default:
796 * Gets the thread-default #GMainContext for this thread, as with
797 * g_main_context_get_thread_default(), but also adds a reference to
798 * it with g_main_context_ref(). In addition, unlike
799 * g_main_context_get_thread_default(), if the thread-default context
800 * is the global default context, this will return that #GMainContext
801 * (with a ref added to it) rather than returning %NULL.
803 * Returns: (transfer full): the thread-default #GMainContext. Unref
804 * with g_main_context_unref() when you are done with it.
809 g_main_context_ref_thread_default (void)
811 GMainContext *context;
813 context = g_main_context_get_thread_default ();
815 context = g_main_context_default ();
816 return g_main_context_ref (context);
819 /* Hooks for adding to the main loop */
823 * @source_funcs: structure containing functions that implement
824 * the sources behavior.
825 * @struct_size: size of the #GSource structure to create.
827 * Creates a new #GSource structure. The size is specified to
828 * allow creating structures derived from #GSource that contain
829 * additional data. The size passed in must be at least
830 * <literal>sizeof (GSource)</literal>.
832 * The source will not initially be associated with any #GMainContext
833 * and must be added to one with g_source_attach() before it will be
836 * Return value: the newly-created #GSource.
839 g_source_new (GSourceFuncs *source_funcs,
844 g_return_val_if_fail (source_funcs != NULL, NULL);
845 g_return_val_if_fail (struct_size >= sizeof (GSource), NULL);
847 source = (GSource*) g_malloc0 (struct_size);
848 source->priv = g_slice_new0 (GSourcePrivate);
849 source->source_funcs = source_funcs;
850 source->ref_count = 1;
852 source->priority = G_PRIORITY_DEFAULT;
854 source->flags = G_HOOK_FLAG_ACTIVE;
856 /* NULL/0 initialization for all other fields */
861 /* Holds context's lock */
863 g_source_iter_init (GSourceIter *iter,
864 GMainContext *context,
867 iter->context = context;
868 iter->current_list = NULL;
870 iter->may_modify = may_modify;
873 /* Holds context's lock */
875 g_source_iter_next (GSourceIter *iter, GSource **source)
877 GSource *next_source;
880 next_source = iter->source->next;
886 if (iter->current_list)
887 iter->current_list = iter->current_list->next;
889 iter->current_list = iter->context->source_lists;
891 if (iter->current_list)
893 GSourceList *source_list = iter->current_list->data;
895 next_source = source_list->head;
899 /* Note: unreffing iter->source could potentially cause its
900 * GSourceList to be removed from source_lists (if iter->source is
901 * the only source in its list, and it is destroyed), so we have to
902 * keep it reffed until after we advance iter->current_list, above.
905 if (iter->source && iter->may_modify)
906 SOURCE_UNREF (iter->source, iter->context);
907 iter->source = next_source;
908 if (iter->source && iter->may_modify)
909 iter->source->ref_count++;
911 *source = iter->source;
912 return *source != NULL;
915 /* Holds context's lock. Only necessary to call if you broke out of
916 * the g_source_iter_next() loop early.
919 g_source_iter_clear (GSourceIter *iter)
921 if (iter->source && iter->may_modify)
923 SOURCE_UNREF (iter->source, iter->context);
928 /* Holds context's lock
931 find_source_list_for_priority (GMainContext *context,
936 GSourceList *source_list;
939 for (iter = context->source_lists; iter != NULL; last = iter, iter = iter->next)
941 source_list = iter->data;
943 if (source_list->priority == priority)
946 if (source_list->priority > priority)
951 source_list = g_slice_new0 (GSourceList);
952 source_list->priority = priority;
953 context->source_lists = g_list_insert_before (context->source_lists,
963 source_list = g_slice_new0 (GSourceList);
964 source_list->priority = priority;
967 context->source_lists = g_list_append (NULL, source_list);
970 /* This just appends source_list to the end of
971 * context->source_lists without having to walk the list again.
973 last = g_list_append (last, source_list);
978 /* Holds context's lock
981 source_add_to_context (GSource *source,
982 GMainContext *context)
984 GSourceList *source_list;
985 GSource *prev, *next;
987 source_list = find_source_list_for_priority (context, source->priority, TRUE);
989 if (source->priv->parent_source)
991 g_assert (source_list->head != NULL);
993 /* Put the source immediately before its parent */
994 prev = source->priv->parent_source->prev;
995 next = source->priv->parent_source;
999 prev = source_list->tail;
1003 source->next = next;
1005 next->prev = source;
1007 source_list->tail = source;
1009 source->prev = prev;
1011 prev->next = source;
1013 source_list->head = source;
1016 /* Holds context's lock
1019 source_remove_from_context (GSource *source,
1020 GMainContext *context)
1022 GSourceList *source_list;
1024 source_list = find_source_list_for_priority (context, source->priority, FALSE);
1025 g_return_if_fail (source_list != NULL);
1028 source->prev->next = source->next;
1030 source_list->head = source->next;
1033 source->next->prev = source->prev;
1035 source_list->tail = source->prev;
1037 source->prev = NULL;
1038 source->next = NULL;
1040 if (source_list->head == NULL)
1042 context->source_lists = g_list_remove (context->source_lists, source_list);
1043 g_slice_free (GSourceList, source_list);
1046 if (context->overflow_used_source_ids)
1047 g_hash_table_remove (context->overflow_used_source_ids,
1048 GUINT_TO_POINTER (source->source_id));
1053 assign_source_id_unlocked (GMainContext *context,
1058 /* Are we about to overflow back to 0?
1059 * See https://bugzilla.gnome.org/show_bug.cgi?id=687098
1061 if (G_UNLIKELY (context->next_id == G_MAXUINT &&
1062 context->overflow_used_source_ids == NULL))
1067 context->overflow_used_source_ids = g_hash_table_new (NULL, NULL);
1069 g_source_iter_init (&iter, context, FALSE);
1070 while (g_source_iter_next (&iter, &source))
1072 g_hash_table_add (context->overflow_used_source_ids,
1073 GUINT_TO_POINTER (source->source_id));
1077 else if (context->overflow_used_source_ids == NULL)
1079 id = context->next_id++;
1084 * If we overran G_MAXUINT, we fall back to randomly probing the
1085 * source ids for the current context. This will be slower the more
1086 * sources there are, but we're mainly concerned right now about
1087 * correctness and code size. There's time for a more clever solution
1091 id = g_random_int ();
1093 g_hash_table_contains (context->overflow_used_source_ids,
1094 GUINT_TO_POINTER (id)));
1095 g_hash_table_add (context->overflow_used_source_ids, GUINT_TO_POINTER (id));
1098 source->source_id = id;
1102 g_source_attach_unlocked (GSource *source,
1103 GMainContext *context)
1107 source->context = context;
1108 assign_source_id_unlocked (context, source);
1109 source->ref_count++;
1110 source_add_to_context (source, context);
1112 tmp_list = source->poll_fds;
1115 g_main_context_add_poll_unlocked (context, source->priority, tmp_list->data);
1116 tmp_list = tmp_list->next;
1119 tmp_list = source->priv->child_sources;
1122 g_source_attach_unlocked (tmp_list->data, context);
1123 tmp_list = tmp_list->next;
1126 return source->source_id;
1131 * @source: a #GSource
1132 * @context: (allow-none): a #GMainContext (if %NULL, the default context will be used)
1134 * Adds a #GSource to a @context so that it will be executed within
1135 * that context. Remove it by calling g_source_destroy().
1137 * Return value: the ID (greater than 0) for the source within the
1141 g_source_attach (GSource *source,
1142 GMainContext *context)
1146 g_return_val_if_fail (source->context == NULL, 0);
1147 g_return_val_if_fail (!SOURCE_DESTROYED (source), 0);
1150 context = g_main_context_default ();
1152 LOCK_CONTEXT (context);
1154 result = g_source_attach_unlocked (source, context);
1156 /* If another thread has acquired the context, wake it up since it
1157 * might be in poll() right now.
1159 if (context->owner && context->owner != G_THREAD_SELF)
1160 g_wakeup_signal (context->wakeup);
1162 UNLOCK_CONTEXT (context);
1168 g_source_destroy_internal (GSource *source,
1169 GMainContext *context,
1173 LOCK_CONTEXT (context);
1175 if (!SOURCE_DESTROYED (source))
1178 gpointer old_cb_data;
1179 GSourceCallbackFuncs *old_cb_funcs;
1181 source->flags &= ~G_HOOK_FLAG_ACTIVE;
1183 old_cb_data = source->callback_data;
1184 old_cb_funcs = source->callback_funcs;
1186 source->callback_data = NULL;
1187 source->callback_funcs = NULL;
1191 UNLOCK_CONTEXT (context);
1192 old_cb_funcs->unref (old_cb_data);
1193 LOCK_CONTEXT (context);
1196 if (!SOURCE_BLOCKED (source))
1198 tmp_list = source->poll_fds;
1201 g_main_context_remove_poll_unlocked (context, tmp_list->data);
1202 tmp_list = tmp_list->next;
1206 while (source->priv->child_sources)
1207 g_child_source_remove_internal (source->priv->child_sources->data, context);
1209 if (source->priv->parent_source)
1210 g_child_source_remove_internal (source, context);
1212 g_source_unref_internal (source, context, TRUE);
1216 UNLOCK_CONTEXT (context);
1221 * @source: a #GSource
1223 * Removes a source from its #GMainContext, if any, and mark it as
1224 * destroyed. The source cannot be subsequently added to another
1228 g_source_destroy (GSource *source)
1230 GMainContext *context;
1232 g_return_if_fail (source != NULL);
1234 context = source->context;
1237 g_source_destroy_internal (source, context, FALSE);
1239 source->flags &= ~G_HOOK_FLAG_ACTIVE;
1244 * @source: a #GSource
1246 * Returns the numeric ID for a particular source. The ID of a source
1247 * is a positive integer which is unique within a particular main loop
1248 * context. The reverse
1249 * mapping from ID to source is done by g_main_context_find_source_by_id().
1251 * Return value: the ID (greater than 0) for the source
1254 g_source_get_id (GSource *source)
1258 g_return_val_if_fail (source != NULL, 0);
1259 g_return_val_if_fail (source->context != NULL, 0);
1261 LOCK_CONTEXT (source->context);
1262 result = source->source_id;
1263 UNLOCK_CONTEXT (source->context);
1269 * g_source_get_context:
1270 * @source: a #GSource
1272 * Gets the #GMainContext with which the source is associated.
1274 * You can call this on a source that has been destroyed, provided
1275 * that the #GMainContext it was attached to still exists (in which
1276 * case it will return that #GMainContext). In particular, you can
1277 * always call this function on the source returned from
1278 * g_main_current_source(). But calling this function on a source
1279 * whose #GMainContext has been destroyed is an error.
1281 * Return value: (transfer none) (allow-none): the #GMainContext with which the
1282 * source is associated, or %NULL if the context has not
1283 * yet been added to a source.
1286 g_source_get_context (GSource *source)
1288 g_return_val_if_fail (source->context != NULL || !SOURCE_DESTROYED (source), NULL);
1290 return source->context;
1294 * g_source_add_poll:
1295 * @source:a #GSource
1296 * @fd: a #GPollFD structure holding information about a file
1297 * descriptor to watch.
1299 * Adds a file descriptor to the set of file descriptors polled for
1300 * this source. This is usually combined with g_source_new() to add an
1301 * event source. The event source's check function will typically test
1302 * the @revents field in the #GPollFD struct and return %TRUE if events need
1306 g_source_add_poll (GSource *source,
1309 GMainContext *context;
1311 g_return_if_fail (source != NULL);
1312 g_return_if_fail (fd != NULL);
1313 g_return_if_fail (!SOURCE_DESTROYED (source));
1315 context = source->context;
1318 LOCK_CONTEXT (context);
1320 source->poll_fds = g_slist_prepend (source->poll_fds, fd);
1324 if (!SOURCE_BLOCKED (source))
1325 g_main_context_add_poll_unlocked (context, source->priority, fd);
1326 UNLOCK_CONTEXT (context);
1331 * g_source_remove_poll:
1332 * @source:a #GSource
1333 * @fd: a #GPollFD structure previously passed to g_source_add_poll().
1335 * Removes a file descriptor from the set of file descriptors polled for
1339 g_source_remove_poll (GSource *source,
1342 GMainContext *context;
1344 g_return_if_fail (source != NULL);
1345 g_return_if_fail (fd != NULL);
1346 g_return_if_fail (!SOURCE_DESTROYED (source));
1348 context = source->context;
1351 LOCK_CONTEXT (context);
1353 source->poll_fds = g_slist_remove (source->poll_fds, fd);
1357 if (!SOURCE_BLOCKED (source))
1358 g_main_context_remove_poll_unlocked (context, fd);
1359 UNLOCK_CONTEXT (context);
1364 * g_source_add_child_source:
1365 * @source:a #GSource
1366 * @child_source: a second #GSource that @source should "poll"
1368 * Adds @child_source to @source as a "polled" source; when @source is
1369 * added to a #GMainContext, @child_source will be automatically added
1370 * with the same priority, when @child_source is triggered, it will
1371 * cause @source to dispatch (in addition to calling its own
1372 * callback), and when @source is destroyed, it will destroy
1373 * @child_source as well. (@source will also still be dispatched if
1374 * its own prepare/check functions indicate that it is ready.)
1376 * If you don't need @child_source to do anything on its own when it
1377 * triggers, you can call g_source_set_dummy_callback() on it to set a
1378 * callback that does nothing (except return %TRUE if appropriate).
1380 * @source will hold a reference on @child_source while @child_source
1381 * is attached to it.
1386 g_source_add_child_source (GSource *source,
1387 GSource *child_source)
1389 GMainContext *context;
1391 g_return_if_fail (source != NULL);
1392 g_return_if_fail (child_source != NULL);
1393 g_return_if_fail (!SOURCE_DESTROYED (source));
1394 g_return_if_fail (!SOURCE_DESTROYED (child_source));
1395 g_return_if_fail (child_source->context == NULL);
1396 g_return_if_fail (child_source->priv->parent_source == NULL);
1398 context = source->context;
1401 LOCK_CONTEXT (context);
1403 source->priv->child_sources = g_slist_prepend (source->priv->child_sources,
1404 g_source_ref (child_source));
1405 child_source->priv->parent_source = source;
1406 g_source_set_priority_unlocked (child_source, NULL, source->priority);
1407 if (SOURCE_BLOCKED (source))
1408 block_source (child_source);
1412 UNLOCK_CONTEXT (context);
1413 g_source_attach (child_source, context);
1418 g_child_source_remove_internal (GSource *child_source,
1419 GMainContext *context)
1421 GSource *parent_source = child_source->priv->parent_source;
1423 parent_source->priv->child_sources =
1424 g_slist_remove (parent_source->priv->child_sources, child_source);
1425 child_source->priv->parent_source = NULL;
1427 g_source_destroy_internal (child_source, context, TRUE);
1428 g_source_unref_internal (child_source, context, TRUE);
1432 * g_source_remove_child_source:
1433 * @source:a #GSource
1434 * @child_source: a #GSource previously passed to
1435 * g_source_add_child_source().
1437 * Detaches @child_source from @source and destroys it.
1442 g_source_remove_child_source (GSource *source,
1443 GSource *child_source)
1445 GMainContext *context;
1447 g_return_if_fail (source != NULL);
1448 g_return_if_fail (child_source != NULL);
1449 g_return_if_fail (child_source->priv->parent_source == source);
1450 g_return_if_fail (!SOURCE_DESTROYED (source));
1451 g_return_if_fail (!SOURCE_DESTROYED (child_source));
1453 context = source->context;
1456 LOCK_CONTEXT (context);
1458 g_child_source_remove_internal (child_source, context);
1461 UNLOCK_CONTEXT (context);
1465 * g_source_set_callback_indirect:
1466 * @source: the source
1467 * @callback_data: pointer to callback data "object"
1468 * @callback_funcs: functions for reference counting @callback_data
1469 * and getting the callback and data
1471 * Sets the callback function storing the data as a refcounted callback
1472 * "object". This is used internally. Note that calling
1473 * g_source_set_callback_indirect() assumes
1474 * an initial reference count on @callback_data, and thus
1475 * @callback_funcs->unref will eventually be called once more
1476 * than @callback_funcs->ref.
1479 g_source_set_callback_indirect (GSource *source,
1480 gpointer callback_data,
1481 GSourceCallbackFuncs *callback_funcs)
1483 GMainContext *context;
1484 gpointer old_cb_data;
1485 GSourceCallbackFuncs *old_cb_funcs;
1487 g_return_if_fail (source != NULL);
1488 g_return_if_fail (callback_funcs != NULL || callback_data == NULL);
1490 context = source->context;
1493 LOCK_CONTEXT (context);
1495 old_cb_data = source->callback_data;
1496 old_cb_funcs = source->callback_funcs;
1498 source->callback_data = callback_data;
1499 source->callback_funcs = callback_funcs;
1502 UNLOCK_CONTEXT (context);
1505 old_cb_funcs->unref (old_cb_data);
1509 g_source_callback_ref (gpointer cb_data)
1511 GSourceCallback *callback = cb_data;
1513 callback->ref_count++;
1518 g_source_callback_unref (gpointer cb_data)
1520 GSourceCallback *callback = cb_data;
1522 callback->ref_count--;
1523 if (callback->ref_count == 0)
1525 if (callback->notify)
1526 callback->notify (callback->data);
1532 g_source_callback_get (gpointer cb_data,
1537 GSourceCallback *callback = cb_data;
1539 *func = callback->func;
1540 *data = callback->data;
1543 static GSourceCallbackFuncs g_source_callback_funcs = {
1544 g_source_callback_ref,
1545 g_source_callback_unref,
1546 g_source_callback_get,
1550 * g_source_set_callback:
1551 * @source: the source
1552 * @func: a callback function
1553 * @data: the data to pass to callback function
1554 * @notify: (allow-none): a function to call when @data is no longer in use, or %NULL.
1556 * Sets the callback function for a source. The callback for a source is
1557 * called from the source's dispatch function.
1559 * The exact type of @func depends on the type of source; ie. you
1560 * should not count on @func being called with @data as its first
1563 * Typically, you won't use this function. Instead use functions specific
1564 * to the type of source you are using.
1567 g_source_set_callback (GSource *source,
1570 GDestroyNotify notify)
1572 GSourceCallback *new_callback;
1574 g_return_if_fail (source != NULL);
1576 new_callback = g_new (GSourceCallback, 1);
1578 new_callback->ref_count = 1;
1579 new_callback->func = func;
1580 new_callback->data = data;
1581 new_callback->notify = notify;
1583 g_source_set_callback_indirect (source, new_callback, &g_source_callback_funcs);
1588 * g_source_set_funcs:
1589 * @source: a #GSource
1590 * @funcs: the new #GSourceFuncs
1592 * Sets the source functions (can be used to override
1593 * default implementations) of an unattached source.
1598 g_source_set_funcs (GSource *source,
1599 GSourceFuncs *funcs)
1601 g_return_if_fail (source != NULL);
1602 g_return_if_fail (source->context == NULL);
1603 g_return_if_fail (source->ref_count > 0);
1604 g_return_if_fail (funcs != NULL);
1606 source->source_funcs = funcs;
1610 g_source_set_priority_unlocked (GSource *source,
1611 GMainContext *context,
1616 g_return_if_fail (source->priv->parent_source == NULL ||
1617 source->priv->parent_source->priority == priority);
1621 /* Remove the source from the context's source and then
1622 * add it back after so it is sorted in the correct place
1624 source_remove_from_context (source, source->context);
1627 source->priority = priority;
1631 source_add_to_context (source, source->context);
1633 if (!SOURCE_BLOCKED (source))
1635 tmp_list = source->poll_fds;
1638 g_main_context_remove_poll_unlocked (context, tmp_list->data);
1639 g_main_context_add_poll_unlocked (context, priority, tmp_list->data);
1641 tmp_list = tmp_list->next;
1646 if (source->priv->child_sources)
1648 tmp_list = source->priv->child_sources;
1651 g_source_set_priority_unlocked (tmp_list->data, context, priority);
1652 tmp_list = tmp_list->next;
1658 * g_source_set_priority:
1659 * @source: a #GSource
1660 * @priority: the new priority.
1662 * Sets the priority of a source. While the main loop is being run, a
1663 * source will be dispatched if it is ready to be dispatched and no
1664 * sources at a higher (numerically smaller) priority are ready to be
1668 g_source_set_priority (GSource *source,
1671 GMainContext *context;
1673 g_return_if_fail (source != NULL);
1675 context = source->context;
1678 LOCK_CONTEXT (context);
1679 g_source_set_priority_unlocked (source, context, priority);
1681 UNLOCK_CONTEXT (source->context);
1685 * g_source_get_priority:
1686 * @source: a #GSource
1688 * Gets the priority of a source.
1690 * Return value: the priority of the source
1693 g_source_get_priority (GSource *source)
1695 g_return_val_if_fail (source != NULL, 0);
1697 return source->priority;
1701 * g_source_set_can_recurse:
1702 * @source: a #GSource
1703 * @can_recurse: whether recursion is allowed for this source
1705 * Sets whether a source can be called recursively. If @can_recurse is
1706 * %TRUE, then while the source is being dispatched then this source
1707 * will be processed normally. Otherwise, all processing of this
1708 * source is blocked until the dispatch function returns.
1711 g_source_set_can_recurse (GSource *source,
1712 gboolean can_recurse)
1714 GMainContext *context;
1716 g_return_if_fail (source != NULL);
1718 context = source->context;
1721 LOCK_CONTEXT (context);
1724 source->flags |= G_SOURCE_CAN_RECURSE;
1726 source->flags &= ~G_SOURCE_CAN_RECURSE;
1729 UNLOCK_CONTEXT (context);
1733 * g_source_get_can_recurse:
1734 * @source: a #GSource
1736 * Checks whether a source is allowed to be called recursively.
1737 * see g_source_set_can_recurse().
1739 * Return value: whether recursion is allowed.
1742 g_source_get_can_recurse (GSource *source)
1744 g_return_val_if_fail (source != NULL, FALSE);
1746 return (source->flags & G_SOURCE_CAN_RECURSE) != 0;
1751 * g_source_set_name:
1752 * @source: a #GSource
1753 * @name: debug name for the source
1755 * Sets a name for the source, used in debugging and profiling.
1756 * The name defaults to #NULL.
1758 * The source name should describe in a human-readable way
1759 * what the source does. For example, "X11 event queue"
1760 * or "GTK+ repaint idle handler" or whatever it is.
1762 * It is permitted to call this function multiple times, but is not
1763 * recommended due to the potential performance impact. For example,
1764 * one could change the name in the "check" function of a #GSourceFuncs
1765 * to include details like the event type in the source name.
1770 g_source_set_name (GSource *source,
1773 g_return_if_fail (source != NULL);
1775 /* setting back to NULL is allowed, just because it's
1776 * weird if get_name can return NULL but you can't
1780 g_free (source->name);
1781 source->name = g_strdup (name);
1785 * g_source_get_name:
1786 * @source: a #GSource
1788 * Gets a name for the source, used in debugging and profiling.
1789 * The name may be #NULL if it has never been set with
1790 * g_source_set_name().
1792 * Return value: the name of the source
1796 g_source_get_name (GSource *source)
1798 g_return_val_if_fail (source != NULL, NULL);
1800 return source->name;
1804 * g_source_set_name_by_id:
1805 * @tag: a #GSource ID
1806 * @name: debug name for the source
1808 * Sets the name of a source using its ID.
1810 * This is a convenience utility to set source names from the return
1811 * value of g_idle_add(), g_timeout_add(), etc.
1816 g_source_set_name_by_id (guint tag,
1821 g_return_if_fail (tag > 0);
1823 source = g_main_context_find_source_by_id (NULL, tag);
1827 g_source_set_name (source, name);
1833 * @source: a #GSource
1835 * Increases the reference count on a source by one.
1837 * Return value: @source
1840 g_source_ref (GSource *source)
1842 GMainContext *context;
1844 g_return_val_if_fail (source != NULL, NULL);
1846 context = source->context;
1849 LOCK_CONTEXT (context);
1851 source->ref_count++;
1854 UNLOCK_CONTEXT (context);
1859 /* g_source_unref() but possible to call within context lock
1862 g_source_unref_internal (GSource *source,
1863 GMainContext *context,
1866 gpointer old_cb_data = NULL;
1867 GSourceCallbackFuncs *old_cb_funcs = NULL;
1869 g_return_if_fail (source != NULL);
1871 if (!have_lock && context)
1872 LOCK_CONTEXT (context);
1874 source->ref_count--;
1875 if (source->ref_count == 0)
1877 old_cb_data = source->callback_data;
1878 old_cb_funcs = source->callback_funcs;
1880 source->callback_data = NULL;
1881 source->callback_funcs = NULL;
1885 if (!SOURCE_DESTROYED (source))
1886 g_warning (G_STRLOC ": ref_count == 0, but source was still attached to a context!");
1887 source_remove_from_context (source, context);
1890 if (source->source_funcs->finalize)
1893 UNLOCK_CONTEXT (context);
1894 source->source_funcs->finalize (source);
1896 LOCK_CONTEXT (context);
1899 g_free (source->name);
1900 source->name = NULL;
1902 g_slist_free (source->poll_fds);
1903 source->poll_fds = NULL;
1905 g_slice_free (GSourcePrivate, source->priv);
1906 source->priv = NULL;
1911 if (!have_lock && context)
1912 UNLOCK_CONTEXT (context);
1917 UNLOCK_CONTEXT (context);
1919 old_cb_funcs->unref (old_cb_data);
1922 LOCK_CONTEXT (context);
1928 * @source: a #GSource
1930 * Decreases the reference count of a source by one. If the
1931 * resulting reference count is zero the source and associated
1932 * memory will be destroyed.
1935 g_source_unref (GSource *source)
1937 g_return_if_fail (source != NULL);
1939 g_source_unref_internal (source, source->context, FALSE);
1943 * g_main_context_find_source_by_id:
1944 * @context: (allow-none): a #GMainContext (if %NULL, the default context will be used)
1945 * @source_id: the source ID, as returned by g_source_get_id().
1947 * Finds a #GSource given a pair of context and ID.
1949 * Return value: (transfer none): the #GSource if found, otherwise, %NULL
1952 g_main_context_find_source_by_id (GMainContext *context,
1958 g_return_val_if_fail (source_id > 0, NULL);
1960 if (context == NULL)
1961 context = g_main_context_default ();
1963 LOCK_CONTEXT (context);
1965 g_source_iter_init (&iter, context, FALSE);
1966 while (g_source_iter_next (&iter, &source))
1968 if (!SOURCE_DESTROYED (source) &&
1969 source->source_id == source_id)
1972 g_source_iter_clear (&iter);
1974 UNLOCK_CONTEXT (context);
1980 * g_main_context_find_source_by_funcs_user_data:
1981 * @context: (allow-none): a #GMainContext (if %NULL, the default context will be used).
1982 * @funcs: the @source_funcs passed to g_source_new().
1983 * @user_data: the user data from the callback.
1985 * Finds a source with the given source functions and user data. If
1986 * multiple sources exist with the same source function and user data,
1987 * the first one found will be returned.
1989 * Return value: (transfer none): the source, if one was found, otherwise %NULL
1992 g_main_context_find_source_by_funcs_user_data (GMainContext *context,
1993 GSourceFuncs *funcs,
1999 g_return_val_if_fail (funcs != NULL, NULL);
2001 if (context == NULL)
2002 context = g_main_context_default ();
2004 LOCK_CONTEXT (context);
2006 g_source_iter_init (&iter, context, FALSE);
2007 while (g_source_iter_next (&iter, &source))
2009 if (!SOURCE_DESTROYED (source) &&
2010 source->source_funcs == funcs &&
2011 source->callback_funcs)
2013 GSourceFunc callback;
2014 gpointer callback_data;
2016 source->callback_funcs->get (source->callback_data, source, &callback, &callback_data);
2018 if (callback_data == user_data)
2022 g_source_iter_clear (&iter);
2024 UNLOCK_CONTEXT (context);
2030 * g_main_context_find_source_by_user_data:
2031 * @context: a #GMainContext
2032 * @user_data: the user_data for the callback.
2034 * Finds a source with the given user data for the callback. If
2035 * multiple sources exist with the same user data, the first
2036 * one found will be returned.
2038 * Return value: (transfer none): the source, if one was found, otherwise %NULL
2041 g_main_context_find_source_by_user_data (GMainContext *context,
2047 if (context == NULL)
2048 context = g_main_context_default ();
2050 LOCK_CONTEXT (context);
2052 g_source_iter_init (&iter, context, FALSE);
2053 while (g_source_iter_next (&iter, &source))
2055 if (!SOURCE_DESTROYED (source) &&
2056 source->callback_funcs)
2058 GSourceFunc callback;
2059 gpointer callback_data = NULL;
2061 source->callback_funcs->get (source->callback_data, source, &callback, &callback_data);
2063 if (callback_data == user_data)
2067 g_source_iter_clear (&iter);
2069 UNLOCK_CONTEXT (context);
2076 * @tag: the ID of the source to remove.
2078 * Removes the source with the given id from the default main context.
2080 * a #GSource is given by g_source_get_id(), or will be returned by the
2081 * functions g_source_attach(), g_idle_add(), g_idle_add_full(),
2082 * g_timeout_add(), g_timeout_add_full(), g_child_watch_add(),
2083 * g_child_watch_add_full(), g_io_add_watch(), and g_io_add_watch_full().
2085 * See also g_source_destroy(). You must use g_source_destroy() for sources
2086 * added to a non-default main context.
2088 * Return value: %TRUE if the source was found and removed.
2091 g_source_remove (guint tag)
2095 g_return_val_if_fail (tag > 0, FALSE);
2097 source = g_main_context_find_source_by_id (NULL, tag);
2099 g_source_destroy (source);
2101 return source != NULL;
2105 * g_source_remove_by_user_data:
2106 * @user_data: the user_data for the callback.
2108 * Removes a source from the default main loop context given the user
2109 * data for the callback. If multiple sources exist with the same user
2110 * data, only one will be destroyed.
2112 * Return value: %TRUE if a source was found and removed.
2115 g_source_remove_by_user_data (gpointer user_data)
2119 source = g_main_context_find_source_by_user_data (NULL, user_data);
2122 g_source_destroy (source);
2130 * g_source_remove_by_funcs_user_data:
2131 * @funcs: The @source_funcs passed to g_source_new()
2132 * @user_data: the user data for the callback
2134 * Removes a source from the default main loop context given the
2135 * source functions and user data. If multiple sources exist with the
2136 * same source functions and user data, only one will be destroyed.
2138 * Return value: %TRUE if a source was found and removed.
2141 g_source_remove_by_funcs_user_data (GSourceFuncs *funcs,
2146 g_return_val_if_fail (funcs != NULL, FALSE);
2148 source = g_main_context_find_source_by_funcs_user_data (NULL, funcs, user_data);
2151 g_source_destroy (source);
2159 * g_get_current_time:
2160 * @result: #GTimeVal structure in which to store current time.
2162 * Equivalent to the UNIX gettimeofday() function, but portable.
2164 * You may find g_get_real_time() to be more convenient.
2167 g_get_current_time (GTimeVal *result)
2172 g_return_if_fail (result != NULL);
2174 /*this is required on alpha, there the timeval structs are int's
2175 not longs and a cast only would fail horribly*/
2176 gettimeofday (&r, NULL);
2177 result->tv_sec = r.tv_sec;
2178 result->tv_usec = r.tv_usec;
2183 g_return_if_fail (result != NULL);
2185 GetSystemTimeAsFileTime (&ft);
2186 memmove (&time64, &ft, sizeof (FILETIME));
2188 /* Convert from 100s of nanoseconds since 1601-01-01
2189 * to Unix epoch. Yes, this is Y2038 unsafe.
2191 time64 -= G_GINT64_CONSTANT (116444736000000000);
2194 result->tv_sec = time64 / 1000000;
2195 result->tv_usec = time64 % 1000000;
2202 * Queries the system wall-clock time.
2204 * This call is functionally equivalent to g_get_current_time() except
2205 * that the return value is often more convenient than dealing with a
2208 * You should only use this call if you are actually interested in the real
2209 * wall-clock time. g_get_monotonic_time() is probably more useful for
2210 * measuring intervals.
2212 * Returns: the number of microseconds since January 1, 1970 UTC.
2217 g_get_real_time (void)
2221 g_get_current_time (&tv);
2223 return (((gint64) tv.tv_sec) * 1000000) + tv.tv_usec;
2227 static ULONGLONG (*g_GetTickCount64) (void) = NULL;
2228 static guint32 g_win32_tick_epoch = 0;
2230 G_GNUC_INTERNAL void
2231 g_clock_win32_init (void)
2235 g_GetTickCount64 = NULL;
2236 kernel32 = GetModuleHandle ("KERNEL32.DLL");
2237 if (kernel32 != NULL)
2238 g_GetTickCount64 = (void *) GetProcAddress (kernel32, "GetTickCount64");
2239 g_win32_tick_epoch = ((guint32)GetTickCount()) >> 31;
2244 * g_get_monotonic_time:
2246 * Queries the system monotonic time, if available.
2248 * On POSIX systems with clock_gettime() and <literal>CLOCK_MONOTONIC</literal> this call
2249 * is a very shallow wrapper for that. Otherwise, we make a best effort
2250 * that probably involves returning the wall clock time (with at least
2251 * microsecond accuracy, subject to the limitations of the OS kernel).
2253 * It's important to note that POSIX <literal>CLOCK_MONOTONIC</literal> does
2254 * not count time spent while the machine is suspended.
2256 * On Windows, "limitations of the OS kernel" is a rather substantial
2257 * statement. Depending on the configuration of the system, the wall
2258 * clock time is updated as infrequently as 64 times a second (which
2259 * is approximately every 16ms). Also, on XP (but not on Vista or later)
2260 * the monotonic clock is locally monotonic, but may differ in exact
2261 * value between processes due to timer wrap handling.
2263 * Returns: the monotonic time, in microseconds
2268 g_get_monotonic_time (void)
2270 #ifdef HAVE_CLOCK_GETTIME
2271 /* librt clock_gettime() is our first choice */
2274 #ifdef CLOCK_MONOTONIC
2275 clock_gettime (CLOCK_MONOTONIC, &ts);
2277 clock_gettime (CLOCK_REALTIME, &ts);
2280 /* In theory monotonic time can have any epoch.
2282 * glib presently assumes the following:
2284 * 1) The epoch comes some time after the birth of Jesus of Nazareth, but
2285 * not more than 10000 years later.
2287 * 2) The current time also falls sometime within this range.
2289 * These two reasonable assumptions leave us with a maximum deviation from
2290 * the epoch of 10000 years, or 315569520000000000 seconds.
2292 * If we restrict ourselves to this range then the number of microseconds
2293 * will always fit well inside the constraints of a int64 (by a factor of
2296 * If you actually hit the following assertion, probably you should file a
2297 * bug against your operating system for being excessively silly.
2299 g_assert (G_GINT64_CONSTANT (-315569520000000000) < ts.tv_sec &&
2300 ts.tv_sec < G_GINT64_CONSTANT (315569520000000000));
2302 return (((gint64) ts.tv_sec) * 1000000) + (ts.tv_nsec / 1000);
2304 #elif defined (G_OS_WIN32)
2308 /* There are four sources for the monotonic time on Windows:
2310 * Three are based on a (1 msec accuracy, but only read periodically) clock chip:
2311 * - GetTickCount (GTC)
2312 * 32bit msec counter, updated each ~15msec, wraps in ~50 days
2313 * - GetTickCount64 (GTC64)
2314 * Same as GetTickCount, but extended to 64bit, so no wrap
2315 * Only available in Vista or later
2316 * - timeGetTime (TGT)
2317 * similar to GetTickCount by default: 15msec, 50 day wrap.
2318 * available in winmm.dll (thus known as the multimedia timers)
2319 * However apps can raise the system timer clock frequency using timeBeginPeriod()
2320 * increasing the accuracy up to 1 msec, at a cost in general system performance
2323 * One is based on high precision clocks:
2324 * - QueryPrecisionCounter (QPC)
2325 * This has much higher accuracy, but is not guaranteed monotonic, and
2326 * has lots of complications like clock jumps and different times on different
2327 * CPUs. It also has lower long term accuracy (i.e. it will drift compared to
2328 * the low precision clocks.
2330 * Additionally, the precision available in the timer-based wakeup such as
2331 * MsgWaitForMultipleObjectsEx (which is what the mainloop is based on) is based
2332 * on the TGT resolution, so by default it is ~15msec, but can be increased by apps.
2334 * The QPC timer has too many issues to be used as is. The only way it could be used
2335 * is to use it to interpolate the lower precision clocks. Firefox does something like
2337 * https://bugzilla.mozilla.org/show_bug.cgi?id=363258
2339 * However this seems quite complicated, so we're not doing this right now.
2341 * The approach we take instead is to use the TGT timer, extending it to 64bit
2342 * either by using the GTC64 value, or if that is not available, a process local
2343 * time epoch that we increment when we detect a timer wrap (assumes that we read
2344 * the time at least once every 50 days).
2347 * - We have a globally consistent monotonic clock on Vista and later
2348 * - We have a locally monotonic clock on XP
2349 * - Apps that need higher precision in timeouts and clock reads can call
2350 * timeBeginPeriod() to increase it as much as they want
2353 if (g_GetTickCount64 != NULL)
2355 guint32 ticks_as_32bit;
2357 ticks = g_GetTickCount64 ();
2358 ticks32 = timeGetTime();
2360 /* GTC64 and TGT are sampled at different times, however they
2361 * have the same base and source (msecs since system boot).
2362 * They can differ by as much as -16 to +16 msecs.
2363 * We can't just inject the low bits into the 64bit counter
2364 * as one of the counters can have wrapped in 32bit space and
2365 * the other not. Instead we calculate the signed difference
2366 * in 32bit space and apply that difference to the 64bit counter.
2368 ticks_as_32bit = (guint32)ticks;
2370 /* We could do some 2's complement hack, but we play it safe */
2371 if (ticks32 - ticks_as_32bit <= G_MAXINT32)
2372 ticks += ticks32 - ticks_as_32bit;
2374 ticks -= ticks_as_32bit - ticks32;
2380 epoch = g_atomic_int_get (&g_win32_tick_epoch);
2382 /* Must read ticks after the epoch. Then we're guaranteed
2383 * that the ticks value we read is higher or equal to any
2384 * previous ones that lead to the writing of the epoch.
2386 ticks32 = timeGetTime();
2388 /* We store the MSB of the current time as the LSB
2389 * of the epoch. Comparing these bits lets us detect when
2390 * the 32bit counter has wrapped so we can increase the
2393 * This will work as long as this function is called at
2394 * least once every ~24 days, which is half the wrap time
2395 * of a 32bit msec counter. I think this is pretty likely.
2397 * Note that g_win32_tick_epoch is a process local state,
2398 * so the monotonic clock will not be the same between
2401 if ((ticks32 >> 31) != (epoch & 1))
2404 g_atomic_int_set (&g_win32_tick_epoch, epoch);
2408 ticks = (guint64)ticks32 | ((guint64)epoch) << 31;
2411 return ticks * 1000;
2413 #else /* !HAVE_CLOCK_GETTIME && ! G_OS_WIN32*/
2417 g_get_current_time (&tv);
2419 return (((gint64) tv.tv_sec) * 1000000) + tv.tv_usec;
2424 g_main_dispatch_free (gpointer dispatch)
2426 g_slice_free (GMainDispatch, dispatch);
2429 /* Running the main loop */
2431 static GMainDispatch *
2434 static GPrivate depth_private = G_PRIVATE_INIT (g_main_dispatch_free);
2435 GMainDispatch *dispatch;
2437 dispatch = g_private_get (&depth_private);
2441 dispatch = g_slice_new0 (GMainDispatch);
2442 g_private_set (&depth_private, dispatch);
2451 * Returns the depth of the stack of calls to
2452 * g_main_context_dispatch() on any #GMainContext in the current thread.
2453 * That is, when called from the toplevel, it gives 0. When
2454 * called from within a callback from g_main_context_iteration()
2455 * (or g_main_loop_run(), etc.) it returns 1. When called from within
2456 * a callback to a recursive call to g_main_context_iteration(),
2457 * it returns 2. And so forth.
2459 * This function is useful in a situation like the following:
2460 * Imagine an extremely simple "garbage collected" system.
2463 * static GList *free_list;
2466 * allocate_memory (gsize size)
2468 * gpointer result = g_malloc (size);
2469 * free_list = g_list_prepend (free_list, result);
2474 * free_allocated_memory (void)
2477 * for (l = free_list; l; l = l->next);
2479 * g_list_free (free_list);
2487 * g_main_context_iteration (NULL, TRUE);
2488 * free_allocated_memory();
2492 * This works from an application, however, if you want to do the same
2493 * thing from a library, it gets more difficult, since you no longer
2494 * control the main loop. You might think you can simply use an idle
2495 * function to make the call to free_allocated_memory(), but that
2496 * doesn't work, since the idle function could be called from a
2497 * recursive callback. This can be fixed by using g_main_depth()
2501 * allocate_memory (gsize size)
2503 * FreeListBlock *block = g_new (FreeListBlock, 1);
2504 * block->mem = g_malloc (size);
2505 * block->depth = g_main_depth ();
2506 * free_list = g_list_prepend (free_list, block);
2507 * return block->mem;
2511 * free_allocated_memory (void)
2515 * int depth = g_main_depth ();
2516 * for (l = free_list; l; );
2518 * GList *next = l->next;
2519 * FreeListBlock *block = l->data;
2520 * if (block->depth > depth)
2522 * g_free (block->mem);
2524 * free_list = g_list_delete_link (free_list, l);
2532 * There is a temptation to use g_main_depth() to solve
2533 * problems with reentrancy. For instance, while waiting for data
2534 * to be received from the network in response to a menu item,
2535 * the menu item might be selected again. It might seem that
2536 * one could make the menu item's callback return immediately
2537 * and do nothing if g_main_depth() returns a value greater than 1.
2538 * However, this should be avoided since the user then sees selecting
2539 * the menu item do nothing. Furthermore, you'll find yourself adding
2540 * these checks all over your code, since there are doubtless many,
2541 * many things that the user could do. Instead, you can use the
2542 * following techniques:
2547 * Use gtk_widget_set_sensitive() or modal dialogs to prevent
2548 * the user from interacting with elements while the main
2549 * loop is recursing.
2554 * Avoid main loop recursion in situations where you can't handle
2555 * arbitrary callbacks. Instead, structure your code so that you
2556 * simply return to the main loop and then get called again when
2557 * there is more work to do.
2562 * Return value: The main loop recursion level in the current thread
2567 GMainDispatch *dispatch = get_dispatch ();
2568 return dispatch->depth;
2572 * g_main_current_source:
2574 * Returns the currently firing source for this thread.
2576 * Return value: (transfer none): The currently firing source or %NULL.
2581 g_main_current_source (void)
2583 GMainDispatch *dispatch = get_dispatch ();
2584 return dispatch->dispatching_sources ? dispatch->dispatching_sources->data : NULL;
2588 * g_source_is_destroyed:
2589 * @source: a #GSource
2591 * Returns whether @source has been destroyed.
2593 * This is important when you operate upon your objects
2594 * from within idle handlers, but may have freed the object
2595 * before the dispatch of your idle handler.
2599 * idle_callback (gpointer data)
2601 * SomeWidget *self = data;
2603 * GDK_THREADS_ENTER (<!-- -->);
2604 * /<!-- -->* do stuff with self *<!-- -->/
2605 * self->idle_id = 0;
2606 * GDK_THREADS_LEAVE (<!-- -->);
2608 * return G_SOURCE_REMOVE;
2612 * some_widget_do_stuff_later (SomeWidget *self)
2614 * self->idle_id = g_idle_add (idle_callback, self);
2618 * some_widget_finalize (GObject *object)
2620 * SomeWidget *self = SOME_WIDGET (object);
2622 * if (self->idle_id)
2623 * g_source_remove (self->idle_id);
2625 * G_OBJECT_CLASS (parent_class)->finalize (object);
2629 * This will fail in a multi-threaded application if the
2630 * widget is destroyed before the idle handler fires due
2631 * to the use after free in the callback. A solution, to
2632 * this particular problem, is to check to if the source
2633 * has already been destroy within the callback.
2637 * idle_callback (gpointer data)
2639 * SomeWidget *self = data;
2641 * GDK_THREADS_ENTER ();
2642 * if (!g_source_is_destroyed (g_main_current_source ()))
2644 * /<!-- -->* do stuff with self *<!-- -->/
2646 * GDK_THREADS_LEAVE ();
2652 * Return value: %TRUE if the source has been destroyed
2657 g_source_is_destroyed (GSource *source)
2659 return SOURCE_DESTROYED (source);
2662 /* Temporarily remove all this source's file descriptors from the
2663 * poll(), so that if data comes available for one of the file descriptors
2664 * we don't continually spin in the poll()
2666 /* HOLDS: source->context's lock */
2668 block_source (GSource *source)
2672 g_return_if_fail (!SOURCE_BLOCKED (source));
2674 source->flags |= G_SOURCE_BLOCKED;
2676 tmp_list = source->poll_fds;
2679 g_main_context_remove_poll_unlocked (source->context, tmp_list->data);
2680 tmp_list = tmp_list->next;
2683 if (source->priv && source->priv->child_sources)
2685 tmp_list = source->priv->child_sources;
2688 block_source (tmp_list->data);
2689 tmp_list = tmp_list->next;
2694 /* HOLDS: source->context's lock */
2696 unblock_source (GSource *source)
2700 g_return_if_fail (SOURCE_BLOCKED (source)); /* Source already unblocked */
2701 g_return_if_fail (!SOURCE_DESTROYED (source));
2703 source->flags &= ~G_SOURCE_BLOCKED;
2705 tmp_list = source->poll_fds;
2708 g_main_context_add_poll_unlocked (source->context, source->priority, tmp_list->data);
2709 tmp_list = tmp_list->next;
2712 if (source->priv && source->priv->child_sources)
2714 tmp_list = source->priv->child_sources;
2717 unblock_source (tmp_list->data);
2718 tmp_list = tmp_list->next;
2723 /* HOLDS: context's lock */
2725 g_main_dispatch (GMainContext *context)
2727 GMainDispatch *current = get_dispatch ();
2730 for (i = 0; i < context->pending_dispatches->len; i++)
2732 GSource *source = context->pending_dispatches->pdata[i];
2734 context->pending_dispatches->pdata[i] = NULL;
2737 source->flags &= ~G_SOURCE_READY;
2739 if (!SOURCE_DESTROYED (source))
2741 gboolean was_in_call;
2742 gpointer user_data = NULL;
2743 GSourceFunc callback = NULL;
2744 GSourceCallbackFuncs *cb_funcs;
2746 gboolean need_destroy;
2748 gboolean (*dispatch) (GSource *,
2751 GSList current_source_link;
2753 dispatch = source->source_funcs->dispatch;
2754 cb_funcs = source->callback_funcs;
2755 cb_data = source->callback_data;
2758 cb_funcs->ref (cb_data);
2760 if ((source->flags & G_SOURCE_CAN_RECURSE) == 0)
2761 block_source (source);
2763 was_in_call = source->flags & G_HOOK_FLAG_IN_CALL;
2764 source->flags |= G_HOOK_FLAG_IN_CALL;
2767 cb_funcs->get (cb_data, source, &callback, &user_data);
2769 UNLOCK_CONTEXT (context);
2772 /* The on-stack allocation of the GSList is unconventional, but
2773 * we know that the lifetime of the link is bounded to this
2774 * function as the link is kept in a thread specific list and
2775 * not manipulated outside of this function and its descendants.
2776 * Avoiding the overhead of a g_slist_alloc() is useful as many
2777 * applications do little more than dispatch events.
2779 * This is a performance hack - do not revert to g_slist_prepend()!
2781 current_source_link.data = source;
2782 current_source_link.next = current->dispatching_sources;
2783 current->dispatching_sources = ¤t_source_link;
2784 need_destroy = ! dispatch (source,
2787 g_assert (current->dispatching_sources == ¤t_source_link);
2788 current->dispatching_sources = current_source_link.next;
2792 cb_funcs->unref (cb_data);
2794 LOCK_CONTEXT (context);
2797 source->flags &= ~G_HOOK_FLAG_IN_CALL;
2799 if (SOURCE_BLOCKED (source) && !SOURCE_DESTROYED (source))
2800 unblock_source (source);
2802 /* Note: this depends on the fact that we can't switch
2803 * sources from one main context to another
2805 if (need_destroy && !SOURCE_DESTROYED (source))
2807 g_assert (source->context == context);
2808 g_source_destroy_internal (source, context, TRUE);
2812 SOURCE_UNREF (source, context);
2815 g_ptr_array_set_size (context->pending_dispatches, 0);
2819 * g_main_context_acquire:
2820 * @context: a #GMainContext
2822 * Tries to become the owner of the specified context.
2823 * If some other thread is the owner of the context,
2824 * returns %FALSE immediately. Ownership is properly
2825 * recursive: the owner can require ownership again
2826 * and will release ownership when g_main_context_release()
2827 * is called as many times as g_main_context_acquire().
2829 * You must be the owner of a context before you
2830 * can call g_main_context_prepare(), g_main_context_query(),
2831 * g_main_context_check(), g_main_context_dispatch().
2833 * Return value: %TRUE if the operation succeeded, and
2834 * this thread is now the owner of @context.
2837 g_main_context_acquire (GMainContext *context)
2839 gboolean result = FALSE;
2840 GThread *self = G_THREAD_SELF;
2842 if (context == NULL)
2843 context = g_main_context_default ();
2845 LOCK_CONTEXT (context);
2847 if (!context->owner)
2849 context->owner = self;
2850 g_assert (context->owner_count == 0);
2853 if (context->owner == self)
2855 context->owner_count++;
2859 UNLOCK_CONTEXT (context);
2865 * g_main_context_release:
2866 * @context: a #GMainContext
2868 * Releases ownership of a context previously acquired by this thread
2869 * with g_main_context_acquire(). If the context was acquired multiple
2870 * times, the ownership will be released only when g_main_context_release()
2871 * is called as many times as it was acquired.
2874 g_main_context_release (GMainContext *context)
2876 if (context == NULL)
2877 context = g_main_context_default ();
2879 LOCK_CONTEXT (context);
2881 context->owner_count--;
2882 if (context->owner_count == 0)
2884 context->owner = NULL;
2886 if (context->waiters)
2888 GMainWaiter *waiter = context->waiters->data;
2889 gboolean loop_internal_waiter = (waiter->mutex == &context->mutex);
2890 context->waiters = g_slist_delete_link (context->waiters,
2892 if (!loop_internal_waiter)
2893 g_mutex_lock (waiter->mutex);
2895 g_cond_signal (waiter->cond);
2897 if (!loop_internal_waiter)
2898 g_mutex_unlock (waiter->mutex);
2902 UNLOCK_CONTEXT (context);
2906 * g_main_context_wait:
2907 * @context: a #GMainContext
2908 * @cond: a condition variable
2909 * @mutex: a mutex, currently held
2911 * Tries to become the owner of the specified context,
2912 * as with g_main_context_acquire(). But if another thread
2913 * is the owner, atomically drop @mutex and wait on @cond until
2914 * that owner releases ownership or until @cond is signaled, then
2915 * try again (once) to become the owner.
2917 * Return value: %TRUE if the operation succeeded, and
2918 * this thread is now the owner of @context.
2921 g_main_context_wait (GMainContext *context,
2925 gboolean result = FALSE;
2926 GThread *self = G_THREAD_SELF;
2927 gboolean loop_internal_waiter;
2929 if (context == NULL)
2930 context = g_main_context_default ();
2932 loop_internal_waiter = (mutex == &context->mutex);
2934 if (!loop_internal_waiter)
2935 LOCK_CONTEXT (context);
2937 if (context->owner && context->owner != self)
2942 waiter.mutex = mutex;
2944 context->waiters = g_slist_append (context->waiters, &waiter);
2946 if (!loop_internal_waiter)
2947 UNLOCK_CONTEXT (context);
2948 g_cond_wait (cond, mutex);
2949 if (!loop_internal_waiter)
2950 LOCK_CONTEXT (context);
2952 context->waiters = g_slist_remove (context->waiters, &waiter);
2955 if (!context->owner)
2957 context->owner = self;
2958 g_assert (context->owner_count == 0);
2961 if (context->owner == self)
2963 context->owner_count++;
2967 if (!loop_internal_waiter)
2968 UNLOCK_CONTEXT (context);
2974 * g_main_context_prepare:
2975 * @context: a #GMainContext
2976 * @priority: location to store priority of highest priority
2977 * source already ready.
2979 * Prepares to poll sources within a main loop. The resulting information
2980 * for polling is determined by calling g_main_context_query ().
2982 * Return value: %TRUE if some source is ready to be dispatched
2986 g_main_context_prepare (GMainContext *context,
2991 gint current_priority = G_MAXINT;
2995 if (context == NULL)
2996 context = g_main_context_default ();
2998 LOCK_CONTEXT (context);
3000 context->time_is_fresh = FALSE;
3002 if (context->in_check_or_prepare)
3004 g_warning ("g_main_context_prepare() called recursively from within a source's check() or "
3005 "prepare() member.");
3006 UNLOCK_CONTEXT (context);
3011 /* If recursing, finish up current dispatch, before starting over */
3012 if (context->pending_dispatches)
3015 g_main_dispatch (context, ¤t_time);
3017 UNLOCK_CONTEXT (context);
3022 /* If recursing, clear list of pending dispatches */
3024 for (i = 0; i < context->pending_dispatches->len; i++)
3026 if (context->pending_dispatches->pdata[i])
3027 SOURCE_UNREF ((GSource *)context->pending_dispatches->pdata[i], context);
3029 g_ptr_array_set_size (context->pending_dispatches, 0);
3031 /* Prepare all sources */
3033 context->timeout = -1;
3035 g_source_iter_init (&iter, context, TRUE);
3036 while (g_source_iter_next (&iter, &source))
3038 gint source_timeout = -1;
3040 if (SOURCE_DESTROYED (source) || SOURCE_BLOCKED (source))
3042 if ((n_ready > 0) && (source->priority > current_priority))
3045 if (!(source->flags & G_SOURCE_READY))
3048 gboolean (*prepare) (GSource *source,
3051 prepare = source->source_funcs->prepare;
3052 context->in_check_or_prepare++;
3053 UNLOCK_CONTEXT (context);
3055 result = (*prepare) (source, &source_timeout);
3057 LOCK_CONTEXT (context);
3058 context->in_check_or_prepare--;
3062 GSource *ready_source = source;
3064 while (ready_source)
3066 ready_source->flags |= G_SOURCE_READY;
3067 ready_source = ready_source->priv->parent_source;
3072 if (source->flags & G_SOURCE_READY)
3075 current_priority = source->priority;
3076 context->timeout = 0;
3079 if (source_timeout >= 0)
3081 if (context->timeout < 0)
3082 context->timeout = source_timeout;
3084 context->timeout = MIN (context->timeout, source_timeout);
3087 g_source_iter_clear (&iter);
3089 UNLOCK_CONTEXT (context);
3092 *priority = current_priority;
3094 return (n_ready > 0);
3098 * g_main_context_query:
3099 * @context: a #GMainContext
3100 * @max_priority: maximum priority source to check
3101 * @timeout_: (out): location to store timeout to be used in polling
3102 * @fds: (out caller-allocates) (array length=n_fds): location to
3103 * store #GPollFD records that need to be polled.
3104 * @n_fds: length of @fds.
3106 * Determines information necessary to poll this main loop.
3108 * Return value: the number of records actually stored in @fds,
3109 * or, if more than @n_fds records need to be stored, the number
3110 * of records that need to be stored.
3113 g_main_context_query (GMainContext *context,
3122 LOCK_CONTEXT (context);
3124 pollrec = context->poll_records;
3126 while (pollrec && max_priority >= pollrec->priority)
3128 /* We need to include entries with fd->events == 0 in the array because
3129 * otherwise if the application changes fd->events behind our back and
3130 * makes it non-zero, we'll be out of sync when we check the fds[] array.
3131 * (Changing fd->events after adding an FD wasn't an anticipated use of
3132 * this API, but it occurs in practice.) */
3135 fds[n_poll].fd = pollrec->fd->fd;
3136 /* In direct contradiction to the Unix98 spec, IRIX runs into
3137 * difficulty if you pass in POLLERR, POLLHUP or POLLNVAL
3138 * flags in the events field of the pollfd while it should
3139 * just ignoring them. So we mask them out here.
3141 fds[n_poll].events = pollrec->fd->events & ~(G_IO_ERR|G_IO_HUP|G_IO_NVAL);
3142 fds[n_poll].revents = 0;
3145 pollrec = pollrec->next;
3149 context->poll_changed = FALSE;
3153 *timeout = context->timeout;
3155 context->time_is_fresh = FALSE;
3158 UNLOCK_CONTEXT (context);
3164 * g_main_context_check:
3165 * @context: a #GMainContext
3166 * @max_priority: the maximum numerical priority of sources to check
3167 * @fds: (array length=n_fds): array of #GPollFD's that was passed to
3168 * the last call to g_main_context_query()
3169 * @n_fds: return value of g_main_context_query()
3171 * Passes the results of polling back to the main loop.
3173 * Return value: %TRUE if some sources are ready to be dispatched.
3176 g_main_context_check (GMainContext *context,
3187 LOCK_CONTEXT (context);
3189 if (context->in_check_or_prepare)
3191 g_warning ("g_main_context_check() called recursively from within a source's check() or "
3192 "prepare() member.");
3193 UNLOCK_CONTEXT (context);
3197 if (context->wake_up_rec.revents)
3198 g_wakeup_acknowledge (context->wakeup);
3200 /* If the set of poll file descriptors changed, bail out
3201 * and let the main loop rerun
3203 if (context->poll_changed)
3205 UNLOCK_CONTEXT (context);
3209 pollrec = context->poll_records;
3213 if (pollrec->fd->events)
3214 pollrec->fd->revents = fds[i].revents;
3216 pollrec = pollrec->next;
3220 g_source_iter_init (&iter, context, TRUE);
3221 while (g_source_iter_next (&iter, &source))
3223 if (SOURCE_DESTROYED (source) || SOURCE_BLOCKED (source))
3225 if ((n_ready > 0) && (source->priority > max_priority))
3228 if (!(source->flags & G_SOURCE_READY))
3231 gboolean (*check) (GSource *source);
3233 check = source->source_funcs->check;
3235 context->in_check_or_prepare++;
3236 UNLOCK_CONTEXT (context);
3238 result = (*check) (source);
3240 LOCK_CONTEXT (context);
3241 context->in_check_or_prepare--;
3245 GSource *ready_source = source;
3247 while (ready_source)
3249 ready_source->flags |= G_SOURCE_READY;
3250 ready_source = ready_source->priv->parent_source;
3255 if (source->flags & G_SOURCE_READY)
3257 source->ref_count++;
3258 g_ptr_array_add (context->pending_dispatches, source);
3262 /* never dispatch sources with less priority than the first
3263 * one we choose to dispatch
3265 max_priority = source->priority;
3268 g_source_iter_clear (&iter);
3270 UNLOCK_CONTEXT (context);
3276 * g_main_context_dispatch:
3277 * @context: a #GMainContext
3279 * Dispatches all pending sources.
3282 g_main_context_dispatch (GMainContext *context)
3284 LOCK_CONTEXT (context);
3286 if (context->pending_dispatches->len > 0)
3288 g_main_dispatch (context);
3291 UNLOCK_CONTEXT (context);
3294 /* HOLDS context lock */
3296 g_main_context_iterate (GMainContext *context,
3303 gboolean some_ready;
3304 gint nfds, allocated_nfds;
3305 GPollFD *fds = NULL;
3307 UNLOCK_CONTEXT (context);
3309 if (!g_main_context_acquire (context))
3311 gboolean got_ownership;
3313 LOCK_CONTEXT (context);
3318 got_ownership = g_main_context_wait (context,
3326 LOCK_CONTEXT (context);
3328 if (!context->cached_poll_array)
3330 context->cached_poll_array_size = context->n_poll_records;
3331 context->cached_poll_array = g_new (GPollFD, context->n_poll_records);
3334 allocated_nfds = context->cached_poll_array_size;
3335 fds = context->cached_poll_array;
3337 UNLOCK_CONTEXT (context);
3339 g_main_context_prepare (context, &max_priority);
3341 while ((nfds = g_main_context_query (context, max_priority, &timeout, fds,
3342 allocated_nfds)) > allocated_nfds)
3344 LOCK_CONTEXT (context);
3346 context->cached_poll_array_size = allocated_nfds = nfds;
3347 context->cached_poll_array = fds = g_new (GPollFD, nfds);
3348 UNLOCK_CONTEXT (context);
3354 g_main_context_poll (context, timeout, max_priority, fds, nfds);
3356 some_ready = g_main_context_check (context, max_priority, fds, nfds);
3359 g_main_context_dispatch (context);
3361 g_main_context_release (context);
3363 LOCK_CONTEXT (context);
3369 * g_main_context_pending:
3370 * @context: (allow-none): a #GMainContext (if %NULL, the default context will be used)
3372 * Checks if any sources have pending events for the given context.
3374 * Return value: %TRUE if events are pending.
3377 g_main_context_pending (GMainContext *context)
3382 context = g_main_context_default();
3384 LOCK_CONTEXT (context);
3385 retval = g_main_context_iterate (context, FALSE, FALSE, G_THREAD_SELF);
3386 UNLOCK_CONTEXT (context);
3392 * g_main_context_iteration:
3393 * @context: (allow-none): a #GMainContext (if %NULL, the default context will be used)
3394 * @may_block: whether the call may block.
3396 * Runs a single iteration for the given main loop. This involves
3397 * checking to see if any event sources are ready to be processed,
3398 * then if no events sources are ready and @may_block is %TRUE, waiting
3399 * for a source to become ready, then dispatching the highest priority
3400 * events sources that are ready. Otherwise, if @may_block is %FALSE
3401 * sources are not waited to become ready, only those highest priority
3402 * events sources will be dispatched (if any), that are ready at this
3403 * given moment without further waiting.
3405 * Note that even when @may_block is %TRUE, it is still possible for
3406 * g_main_context_iteration() to return %FALSE, since the wait may
3407 * be interrupted for other reasons than an event source becoming ready.
3409 * Return value: %TRUE if events were dispatched.
3412 g_main_context_iteration (GMainContext *context, gboolean may_block)
3417 context = g_main_context_default();
3419 LOCK_CONTEXT (context);
3420 retval = g_main_context_iterate (context, may_block, TRUE, G_THREAD_SELF);
3421 UNLOCK_CONTEXT (context);
3428 * @context: (allow-none): a #GMainContext (if %NULL, the default context will be used).
3429 * @is_running: set to %TRUE to indicate that the loop is running. This
3430 * is not very important since calling g_main_loop_run() will set this to
3433 * Creates a new #GMainLoop structure.
3435 * Return value: a new #GMainLoop.
3438 g_main_loop_new (GMainContext *context,
3439 gboolean is_running)
3444 context = g_main_context_default();
3446 g_main_context_ref (context);
3448 loop = g_new0 (GMainLoop, 1);
3449 loop->context = context;
3450 loop->is_running = is_running != FALSE;
3451 loop->ref_count = 1;
3458 * @loop: a #GMainLoop
3460 * Increases the reference count on a #GMainLoop object by one.
3462 * Return value: @loop
3465 g_main_loop_ref (GMainLoop *loop)
3467 g_return_val_if_fail (loop != NULL, NULL);
3468 g_return_val_if_fail (g_atomic_int_get (&loop->ref_count) > 0, NULL);
3470 g_atomic_int_inc (&loop->ref_count);
3476 * g_main_loop_unref:
3477 * @loop: a #GMainLoop
3479 * Decreases the reference count on a #GMainLoop object by one. If
3480 * the result is zero, free the loop and free all associated memory.
3483 g_main_loop_unref (GMainLoop *loop)
3485 g_return_if_fail (loop != NULL);
3486 g_return_if_fail (g_atomic_int_get (&loop->ref_count) > 0);
3488 if (!g_atomic_int_dec_and_test (&loop->ref_count))
3491 g_main_context_unref (loop->context);
3497 * @loop: a #GMainLoop
3499 * Runs a main loop until g_main_loop_quit() is called on the loop.
3500 * If this is called for the thread of the loop's #GMainContext,
3501 * it will process events from the loop, otherwise it will
3505 g_main_loop_run (GMainLoop *loop)
3507 GThread *self = G_THREAD_SELF;
3509 g_return_if_fail (loop != NULL);
3510 g_return_if_fail (g_atomic_int_get (&loop->ref_count) > 0);
3512 if (!g_main_context_acquire (loop->context))
3514 gboolean got_ownership = FALSE;
3516 /* Another thread owns this context */
3517 LOCK_CONTEXT (loop->context);
3519 g_atomic_int_inc (&loop->ref_count);
3521 if (!loop->is_running)
3522 loop->is_running = TRUE;
3524 while (loop->is_running && !got_ownership)
3525 got_ownership = g_main_context_wait (loop->context,
3526 &loop->context->cond,
3527 &loop->context->mutex);
3529 if (!loop->is_running)
3531 UNLOCK_CONTEXT (loop->context);
3533 g_main_context_release (loop->context);
3534 g_main_loop_unref (loop);
3538 g_assert (got_ownership);
3541 LOCK_CONTEXT (loop->context);
3543 if (loop->context->in_check_or_prepare)
3545 g_warning ("g_main_loop_run(): called recursively from within a source's "
3546 "check() or prepare() member, iteration not possible.");
3550 g_atomic_int_inc (&loop->ref_count);
3551 loop->is_running = TRUE;
3552 while (loop->is_running)
3553 g_main_context_iterate (loop->context, TRUE, TRUE, self);
3555 UNLOCK_CONTEXT (loop->context);
3557 g_main_context_release (loop->context);
3559 g_main_loop_unref (loop);
3564 * @loop: a #GMainLoop
3566 * Stops a #GMainLoop from running. Any calls to g_main_loop_run()
3567 * for the loop will return.
3569 * Note that sources that have already been dispatched when
3570 * g_main_loop_quit() is called will still be executed.
3573 g_main_loop_quit (GMainLoop *loop)
3575 g_return_if_fail (loop != NULL);
3576 g_return_if_fail (g_atomic_int_get (&loop->ref_count) > 0);
3578 LOCK_CONTEXT (loop->context);
3579 loop->is_running = FALSE;
3580 g_wakeup_signal (loop->context->wakeup);
3582 g_cond_broadcast (&loop->context->cond);
3584 UNLOCK_CONTEXT (loop->context);
3588 * g_main_loop_is_running:
3589 * @loop: a #GMainLoop.
3591 * Checks to see if the main loop is currently being run via g_main_loop_run().
3593 * Return value: %TRUE if the mainloop is currently being run.
3596 g_main_loop_is_running (GMainLoop *loop)
3598 g_return_val_if_fail (loop != NULL, FALSE);
3599 g_return_val_if_fail (g_atomic_int_get (&loop->ref_count) > 0, FALSE);
3601 return loop->is_running;
3605 * g_main_loop_get_context:
3606 * @loop: a #GMainLoop.
3608 * Returns the #GMainContext of @loop.
3610 * Return value: (transfer none): the #GMainContext of @loop
3613 g_main_loop_get_context (GMainLoop *loop)
3615 g_return_val_if_fail (loop != NULL, NULL);
3616 g_return_val_if_fail (g_atomic_int_get (&loop->ref_count) > 0, NULL);
3618 return loop->context;
3621 /* HOLDS: context's lock */
3623 g_main_context_poll (GMainContext *context,
3629 #ifdef G_MAIN_POLL_DEBUG
3635 GPollFunc poll_func;
3637 if (n_fds || timeout != 0)
3639 #ifdef G_MAIN_POLL_DEBUG
3640 if (_g_main_poll_debug)
3642 g_print ("polling context=%p n=%d timeout=%d\n",
3643 context, n_fds, timeout);
3644 poll_timer = g_timer_new ();
3648 LOCK_CONTEXT (context);
3650 poll_func = context->poll_func;
3652 UNLOCK_CONTEXT (context);
3653 if ((*poll_func) (fds, n_fds, timeout) < 0 && errno != EINTR)
3656 g_warning ("poll(2) failed due to: %s.",
3657 g_strerror (errno));
3659 /* If g_poll () returns -1, it has already called g_warning() */
3663 #ifdef G_MAIN_POLL_DEBUG
3664 if (_g_main_poll_debug)
3666 LOCK_CONTEXT (context);
3668 g_print ("g_main_poll(%d) timeout: %d - elapsed %12.10f seconds",
3671 g_timer_elapsed (poll_timer, NULL));
3672 g_timer_destroy (poll_timer);
3673 pollrec = context->poll_records;
3675 while (pollrec != NULL)
3680 if (fds[i].fd == pollrec->fd->fd &&
3681 pollrec->fd->events &&
3684 g_print (" [" G_POLLFD_FORMAT " :", fds[i].fd);
3685 if (fds[i].revents & G_IO_IN)
3687 if (fds[i].revents & G_IO_OUT)
3689 if (fds[i].revents & G_IO_PRI)
3691 if (fds[i].revents & G_IO_ERR)
3693 if (fds[i].revents & G_IO_HUP)
3695 if (fds[i].revents & G_IO_NVAL)
3701 pollrec = pollrec->next;
3705 UNLOCK_CONTEXT (context);
3708 } /* if (n_fds || timeout != 0) */
3712 * g_main_context_add_poll:
3713 * @context: (allow-none): a #GMainContext (or %NULL for the default context)
3714 * @fd: a #GPollFD structure holding information about a file
3715 * descriptor to watch.
3716 * @priority: the priority for this file descriptor which should be
3717 * the same as the priority used for g_source_attach() to ensure that the
3718 * file descriptor is polled whenever the results may be needed.
3720 * Adds a file descriptor to the set of file descriptors polled for
3721 * this context. This will very seldom be used directly. Instead
3722 * a typical event source will use g_source_add_poll() instead.
3725 g_main_context_add_poll (GMainContext *context,
3730 context = g_main_context_default ();
3732 g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
3733 g_return_if_fail (fd);
3735 LOCK_CONTEXT (context);
3736 g_main_context_add_poll_unlocked (context, priority, fd);
3737 UNLOCK_CONTEXT (context);
3740 /* HOLDS: main_loop_lock */
3742 g_main_context_add_poll_unlocked (GMainContext *context,
3746 GPollRec *prevrec, *nextrec;
3747 GPollRec *newrec = g_slice_new (GPollRec);
3749 /* This file descriptor may be checked before we ever poll */
3752 newrec->priority = priority;
3754 prevrec = context->poll_records_tail;
3756 while (prevrec && priority < prevrec->priority)
3759 prevrec = prevrec->prev;
3763 prevrec->next = newrec;
3765 context->poll_records = newrec;
3767 newrec->prev = prevrec;
3768 newrec->next = nextrec;
3771 nextrec->prev = newrec;
3773 context->poll_records_tail = newrec;
3775 context->n_poll_records++;
3777 context->poll_changed = TRUE;
3779 /* Now wake up the main loop if it is waiting in the poll() */
3780 g_wakeup_signal (context->wakeup);
3784 * g_main_context_remove_poll:
3785 * @context:a #GMainContext
3786 * @fd: a #GPollFD descriptor previously added with g_main_context_add_poll()
3788 * Removes file descriptor from the set of file descriptors to be
3789 * polled for a particular context.
3792 g_main_context_remove_poll (GMainContext *context,
3796 context = g_main_context_default ();
3798 g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
3799 g_return_if_fail (fd);
3801 LOCK_CONTEXT (context);
3802 g_main_context_remove_poll_unlocked (context, fd);
3803 UNLOCK_CONTEXT (context);
3807 g_main_context_remove_poll_unlocked (GMainContext *context,
3810 GPollRec *pollrec, *prevrec, *nextrec;
3813 pollrec = context->poll_records;
3817 nextrec = pollrec->next;
3818 if (pollrec->fd == fd)
3820 if (prevrec != NULL)
3821 prevrec->next = nextrec;
3823 context->poll_records = nextrec;
3825 if (nextrec != NULL)
3826 nextrec->prev = prevrec;
3828 context->poll_records_tail = prevrec;
3830 g_slice_free (GPollRec, pollrec);
3832 context->n_poll_records--;
3839 context->poll_changed = TRUE;
3841 /* Now wake up the main loop if it is waiting in the poll() */
3842 g_wakeup_signal (context->wakeup);
3846 * g_source_get_current_time:
3847 * @source: a #GSource
3848 * @timeval: #GTimeVal structure in which to store current time.
3850 * This function ignores @source and is otherwise the same as
3851 * g_get_current_time().
3853 * Deprecated: 2.28: use g_source_get_time() instead
3856 g_source_get_current_time (GSource *source,
3859 g_get_current_time (timeval);
3863 * g_source_get_time:
3864 * @source: a #GSource
3866 * Gets the time to be used when checking this source. The advantage of
3867 * calling this function over calling g_get_monotonic_time() directly is
3868 * that when checking multiple sources, GLib can cache a single value
3869 * instead of having to repeatedly get the system monotonic time.
3871 * The time here is the system monotonic time, if available, or some
3872 * other reasonable alternative otherwise. See g_get_monotonic_time().
3874 * Returns: the monotonic time in microseconds
3879 g_source_get_time (GSource *source)
3881 GMainContext *context;
3884 g_return_val_if_fail (source->context != NULL, 0);
3886 context = source->context;
3888 LOCK_CONTEXT (context);
3890 if (!context->time_is_fresh)
3892 context->time = g_get_monotonic_time ();
3893 context->time_is_fresh = TRUE;
3896 result = context->time;
3898 UNLOCK_CONTEXT (context);
3904 * g_main_context_set_poll_func:
3905 * @context: a #GMainContext
3906 * @func: the function to call to poll all file descriptors
3908 * Sets the function to use to handle polling of file descriptors. It
3909 * will be used instead of the poll() system call
3910 * (or GLib's replacement function, which is used where
3911 * poll() isn't available).
3913 * This function could possibly be used to integrate the GLib event
3914 * loop with an external event loop.
3917 g_main_context_set_poll_func (GMainContext *context,
3921 context = g_main_context_default ();
3923 g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
3925 LOCK_CONTEXT (context);
3928 context->poll_func = func;
3930 context->poll_func = g_poll;
3932 UNLOCK_CONTEXT (context);
3936 * g_main_context_get_poll_func:
3937 * @context: a #GMainContext
3939 * Gets the poll function set by g_main_context_set_poll_func().
3941 * Return value: the poll function
3944 g_main_context_get_poll_func (GMainContext *context)
3949 context = g_main_context_default ();
3951 g_return_val_if_fail (g_atomic_int_get (&context->ref_count) > 0, NULL);
3953 LOCK_CONTEXT (context);
3954 result = context->poll_func;
3955 UNLOCK_CONTEXT (context);
3961 * g_main_context_wakeup:
3962 * @context: a #GMainContext
3964 * If @context is currently waiting in a poll(), interrupt
3965 * the poll(), and continue the iteration process.
3968 g_main_context_wakeup (GMainContext *context)
3971 context = g_main_context_default ();
3973 g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
3975 g_wakeup_signal (context->wakeup);
3979 * g_main_context_is_owner:
3980 * @context: a #GMainContext
3982 * Determines whether this thread holds the (recursive)
3983 * ownership of this #GMainContext. This is useful to
3984 * know before waiting on another thread that may be
3985 * blocking to get ownership of @context.
3987 * Returns: %TRUE if current thread is owner of @context.
3992 g_main_context_is_owner (GMainContext *context)
3997 context = g_main_context_default ();
3999 LOCK_CONTEXT (context);
4000 is_owner = context->owner == G_THREAD_SELF;
4001 UNLOCK_CONTEXT (context);
4009 g_timeout_set_expiration (GTimeoutSource *timeout_source,
4010 gint64 current_time)
4012 timeout_source->expiration = current_time +
4013 (guint64) timeout_source->interval * 1000;
4015 if (timeout_source->seconds)
4018 static gint timer_perturb = -1;
4020 if (timer_perturb == -1)
4023 * we want a per machine/session unique 'random' value; try the dbus
4024 * address first, that has a UUID in it. If there is no dbus, use the
4025 * hostname for hashing.
4027 const char *session_bus_address = g_getenv ("DBUS_SESSION_BUS_ADDRESS");
4028 if (!session_bus_address)
4029 session_bus_address = g_getenv ("HOSTNAME");
4030 if (session_bus_address)
4031 timer_perturb = ABS ((gint) g_str_hash (session_bus_address)) % 1000000;
4036 /* We want the microseconds part of the timeout to land on the
4037 * 'timer_perturb' mark, but we need to make sure we don't try to
4038 * set the timeout in the past. We do this by ensuring that we
4039 * always only *increase* the expiration time by adding a full
4040 * second in the case that the microsecond portion decreases.
4042 timeout_source->expiration -= timer_perturb;
4044 remainder = timeout_source->expiration % 1000000;
4045 if (remainder >= 1000000/4)
4046 timeout_source->expiration += 1000000;
4048 timeout_source->expiration -= remainder;
4049 timeout_source->expiration += timer_perturb;
4054 g_timeout_prepare (GSource *source,
4057 GTimeoutSource *timeout_source = (GTimeoutSource *) source;
4058 gint64 now = g_source_get_time (source);
4060 if (now < timeout_source->expiration)
4062 /* Round up to ensure that we don't try again too early */
4063 *timeout = (timeout_source->expiration - now + 999) / 1000;
4072 g_timeout_check (GSource *source)
4074 GTimeoutSource *timeout_source = (GTimeoutSource *) source;
4075 gint64 now = g_source_get_time (source);
4077 return timeout_source->expiration <= now;
4081 g_timeout_dispatch (GSource *source,
4082 GSourceFunc callback,
4085 GTimeoutSource *timeout_source = (GTimeoutSource *)source;
4090 g_warning ("Timeout source dispatched without callback\n"
4091 "You must call g_source_set_callback().");
4095 again = callback (user_data);
4098 g_timeout_set_expiration (timeout_source, g_source_get_time (source));
4104 * g_timeout_source_new:
4105 * @interval: the timeout interval in milliseconds.
4107 * Creates a new timeout source.
4109 * The source will not initially be associated with any #GMainContext
4110 * and must be added to one with g_source_attach() before it will be
4113 * The interval given is in terms of monotonic time, not wall clock
4114 * time. See g_get_monotonic_time().
4116 * Return value: the newly-created timeout source
4119 g_timeout_source_new (guint interval)
4121 GSource *source = g_source_new (&g_timeout_funcs, sizeof (GTimeoutSource));
4122 GTimeoutSource *timeout_source = (GTimeoutSource *)source;
4124 timeout_source->interval = interval;
4125 g_timeout_set_expiration (timeout_source, g_get_monotonic_time ());
4131 * g_timeout_source_new_seconds:
4132 * @interval: the timeout interval in seconds
4134 * Creates a new timeout source.
4136 * The source will not initially be associated with any #GMainContext
4137 * and must be added to one with g_source_attach() before it will be
4140 * The scheduling granularity/accuracy of this timeout source will be
4143 * The interval given in terms of monotonic time, not wall clock time.
4144 * See g_get_monotonic_time().
4146 * Return value: the newly-created timeout source
4151 g_timeout_source_new_seconds (guint interval)
4153 GSource *source = g_source_new (&g_timeout_funcs, sizeof (GTimeoutSource));
4154 GTimeoutSource *timeout_source = (GTimeoutSource *)source;
4156 timeout_source->interval = 1000 * interval;
4157 timeout_source->seconds = TRUE;
4159 g_timeout_set_expiration (timeout_source, g_get_monotonic_time ());
4166 * g_timeout_add_full:
4167 * @priority: the priority of the timeout source. Typically this will be in
4168 * the range between #G_PRIORITY_DEFAULT and #G_PRIORITY_HIGH.
4169 * @interval: the time between calls to the function, in milliseconds
4170 * (1/1000ths of a second)
4171 * @function: function to call
4172 * @data: data to pass to @function
4173 * @notify: (allow-none): function to call when the timeout is removed, or %NULL
4175 * Sets a function to be called at regular intervals, with the given
4176 * priority. The function is called repeatedly until it returns
4177 * %FALSE, at which point the timeout is automatically destroyed and
4178 * the function will not be called again. The @notify function is
4179 * called when the timeout is destroyed. The first call to the
4180 * function will be at the end of the first @interval.
4182 * Note that timeout functions may be delayed, due to the processing of other
4183 * event sources. Thus they should not be relied on for precise timing.
4184 * After each call to the timeout function, the time of the next
4185 * timeout is recalculated based on the current time and the given interval
4186 * (it does not try to 'catch up' time lost in delays).
4188 * This internally creates a main loop source using g_timeout_source_new()
4189 * and attaches it to the main loop context using g_source_attach(). You can
4190 * do these steps manually if you need greater control.
4192 * The interval given in terms of monotonic time, not wall clock time.
4193 * See g_get_monotonic_time().
4195 * Return value: the ID (greater than 0) of the event source.
4196 * Rename to: g_timeout_add
4199 g_timeout_add_full (gint priority,
4201 GSourceFunc function,
4203 GDestroyNotify notify)
4208 g_return_val_if_fail (function != NULL, 0);
4210 source = g_timeout_source_new (interval);
4212 if (priority != G_PRIORITY_DEFAULT)
4213 g_source_set_priority (source, priority);
4215 g_source_set_callback (source, function, data, notify);
4216 id = g_source_attach (source, NULL);
4217 g_source_unref (source);
4224 * @interval: the time between calls to the function, in milliseconds
4225 * (1/1000ths of a second)
4226 * @function: function to call
4227 * @data: data to pass to @function
4229 * Sets a function to be called at regular intervals, with the default
4230 * priority, #G_PRIORITY_DEFAULT. The function is called repeatedly
4231 * until it returns %FALSE, at which point the timeout is automatically
4232 * destroyed and the function will not be called again. The first call
4233 * to the function will be at the end of the first @interval.
4235 * Note that timeout functions may be delayed, due to the processing of other
4236 * event sources. Thus they should not be relied on for precise timing.
4237 * After each call to the timeout function, the time of the next
4238 * timeout is recalculated based on the current time and the given interval
4239 * (it does not try to 'catch up' time lost in delays).
4241 * If you want to have a timer in the "seconds" range and do not care
4242 * about the exact time of the first call of the timer, use the
4243 * g_timeout_add_seconds() function; this function allows for more
4244 * optimizations and more efficient system power usage.
4246 * This internally creates a main loop source using g_timeout_source_new()
4247 * and attaches it to the main loop context using g_source_attach(). You can
4248 * do these steps manually if you need greater control.
4250 * The interval given is in terms of monotonic time, not wall clock
4251 * time. See g_get_monotonic_time().
4253 * Return value: the ID (greater than 0) of the event source.
4256 g_timeout_add (guint32 interval,
4257 GSourceFunc function,
4260 return g_timeout_add_full (G_PRIORITY_DEFAULT,
4261 interval, function, data, NULL);
4265 * g_timeout_add_seconds_full:
4266 * @priority: the priority of the timeout source. Typically this will be in
4267 * the range between #G_PRIORITY_DEFAULT and #G_PRIORITY_HIGH.
4268 * @interval: the time between calls to the function, in seconds
4269 * @function: function to call
4270 * @data: data to pass to @function
4271 * @notify: (allow-none): function to call when the timeout is removed, or %NULL
4273 * Sets a function to be called at regular intervals, with @priority.
4274 * The function is called repeatedly until it returns %FALSE, at which
4275 * point the timeout is automatically destroyed and the function will
4276 * not be called again.
4278 * Unlike g_timeout_add(), this function operates at whole second granularity.
4279 * The initial starting point of the timer is determined by the implementation
4280 * and the implementation is expected to group multiple timers together so that
4281 * they fire all at the same time.
4282 * To allow this grouping, the @interval to the first timer is rounded
4283 * and can deviate up to one second from the specified interval.
4284 * Subsequent timer iterations will generally run at the specified interval.
4286 * Note that timeout functions may be delayed, due to the processing of other
4287 * event sources. Thus they should not be relied on for precise timing.
4288 * After each call to the timeout function, the time of the next
4289 * timeout is recalculated based on the current time and the given @interval
4291 * If you want timing more precise than whole seconds, use g_timeout_add()
4294 * The grouping of timers to fire at the same time results in a more power
4295 * and CPU efficient behavior so if your timer is in multiples of seconds
4296 * and you don't require the first timer exactly one second from now, the
4297 * use of g_timeout_add_seconds() is preferred over g_timeout_add().
4299 * This internally creates a main loop source using
4300 * g_timeout_source_new_seconds() and attaches it to the main loop context
4301 * using g_source_attach(). You can do these steps manually if you need
4304 * The interval given is in terms of monotonic time, not wall clock
4305 * time. See g_get_monotonic_time().
4307 * Return value: the ID (greater than 0) of the event source.
4309 * Rename to: g_timeout_add_seconds
4313 g_timeout_add_seconds_full (gint priority,
4315 GSourceFunc function,
4317 GDestroyNotify notify)
4322 g_return_val_if_fail (function != NULL, 0);
4324 source = g_timeout_source_new_seconds (interval);
4326 if (priority != G_PRIORITY_DEFAULT)
4327 g_source_set_priority (source, priority);
4329 g_source_set_callback (source, function, data, notify);
4330 id = g_source_attach (source, NULL);
4331 g_source_unref (source);
4337 * g_timeout_add_seconds:
4338 * @interval: the time between calls to the function, in seconds
4339 * @function: function to call
4340 * @data: data to pass to @function
4342 * Sets a function to be called at regular intervals with the default
4343 * priority, #G_PRIORITY_DEFAULT. The function is called repeatedly until
4344 * it returns %FALSE, at which point the timeout is automatically destroyed
4345 * and the function will not be called again.
4347 * This internally creates a main loop source using
4348 * g_timeout_source_new_seconds() and attaches it to the main loop context
4349 * using g_source_attach(). You can do these steps manually if you need
4350 * greater control. Also see g_timeout_add_seconds_full().
4352 * Note that the first call of the timer may not be precise for timeouts
4353 * of one second. If you need finer precision and have such a timeout,
4354 * you may want to use g_timeout_add() instead.
4356 * The interval given is in terms of monotonic time, not wall clock
4357 * time. See g_get_monotonic_time().
4359 * Return value: the ID (greater than 0) of the event source.
4364 g_timeout_add_seconds (guint interval,
4365 GSourceFunc function,
4368 g_return_val_if_fail (function != NULL, 0);
4370 return g_timeout_add_seconds_full (G_PRIORITY_DEFAULT, interval, function, data, NULL);
4373 /* Child watch functions */
4378 g_child_watch_prepare (GSource *source,
4386 g_child_watch_check (GSource *source)
4388 GChildWatchSource *child_watch_source;
4389 gboolean child_exited;
4391 child_watch_source = (GChildWatchSource *) source;
4393 child_exited = child_watch_source->poll.revents & G_IO_IN;
4400 * Note: We do _not_ check for the special value of STILL_ACTIVE
4401 * since we know that the process has exited and doing so runs into
4402 * problems if the child process "happens to return STILL_ACTIVE(259)"
4403 * as Microsoft's Platform SDK puts it.
4405 if (!GetExitCodeProcess (child_watch_source->pid, &child_status))
4407 gchar *emsg = g_win32_error_message (GetLastError ());
4408 g_warning (G_STRLOC ": GetExitCodeProcess() failed: %s", emsg);
4411 child_watch_source->child_status = -1;
4414 child_watch_source->child_status = child_status;
4417 return child_exited;
4421 g_child_watch_finalize (GSource *source)
4425 #else /* G_OS_WIN32 */
4428 wake_source (GSource *source)
4430 GMainContext *context;
4432 /* This should be thread-safe:
4434 * - if the source is currently being added to a context, that
4435 * context will be woken up anyway
4437 * - if the source is currently being destroyed, we simply need not
4440 * - the memory for the source will remain valid until after the
4441 * source finalize function was called (which would remove the
4442 * source from the global list which we are currently holding the
4445 * - the GMainContext will either be NULL or point to a live
4448 * - the GMainContext will remain valid since we hold the
4449 * main_context_list lock
4451 * Since we are holding a lot of locks here, don't try to enter any
4452 * more GMainContext functions for fear of dealock -- just hit the
4453 * GWakeup and run. Even if that's safe now, it could easily become
4454 * unsafe with some very minor changes in the future, and signal
4455 * handling is not the most well-tested codepath.
4457 G_LOCK(main_context_list);
4458 context = source->context;
4460 g_wakeup_signal (context->wakeup);
4461 G_UNLOCK(main_context_list);
4465 dispatch_unix_signals (void)
4469 /* clear this first incase another one arrives while we're processing */
4470 any_unix_signal_pending = FALSE;
4472 G_LOCK(unix_signal_lock);
4474 /* handle GChildWatchSource instances */
4475 if (unix_signal_pending[SIGCHLD])
4477 unix_signal_pending[SIGCHLD] = FALSE;
4479 /* The only way we can do this is to scan all of the children.
4481 * The docs promise that we will not reap children that we are not
4482 * explicitly watching, so that ties our hands from calling
4483 * waitpid(-1). We also can't use siginfo's si_pid field since if
4484 * multiple SIGCHLD arrive at the same time, one of them can be
4485 * dropped (since a given UNIX signal can only be pending once).
4487 for (node = unix_child_watches; node; node = node->next)
4489 GChildWatchSource *source = node->data;
4491 if (!source->child_exited)
4496 pid = waitpid (source->pid, &source->child_status, WNOHANG);
4499 source->child_exited = TRUE;
4500 wake_source ((GSource *) source);
4502 else if (pid == -1 && errno == ECHILD)
4504 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.");
4505 source->child_exited = TRUE;
4506 source->child_status = 0;
4507 wake_source ((GSource *) source);
4510 while (pid == -1 && errno == EINTR);
4515 /* handle GUnixSignalWatchSource instances */
4516 for (node = unix_signal_watches; node; node = node->next)
4518 GUnixSignalWatchSource *source = node->data;
4520 if (!source->pending)
4522 if (unix_signal_pending[source->signum])
4524 unix_signal_pending[source->signum] = FALSE;
4525 source->pending = TRUE;
4527 wake_source ((GSource *) source);
4532 G_UNLOCK(unix_signal_lock);
4536 g_child_watch_prepare (GSource *source,
4539 GChildWatchSource *child_watch_source;
4541 child_watch_source = (GChildWatchSource *) source;
4543 return child_watch_source->child_exited;
4547 g_child_watch_check (GSource *source)
4549 GChildWatchSource *child_watch_source;
4551 child_watch_source = (GChildWatchSource *) source;
4553 return child_watch_source->child_exited;
4557 g_unix_signal_watch_prepare (GSource *source,
4560 GUnixSignalWatchSource *unix_signal_source;
4562 unix_signal_source = (GUnixSignalWatchSource *) source;
4564 return unix_signal_source->pending;
4568 g_unix_signal_watch_check (GSource *source)
4570 GUnixSignalWatchSource *unix_signal_source;
4572 unix_signal_source = (GUnixSignalWatchSource *) source;
4574 return unix_signal_source->pending;
4578 g_unix_signal_watch_dispatch (GSource *source,
4579 GSourceFunc callback,
4582 GUnixSignalWatchSource *unix_signal_source;
4585 unix_signal_source = (GUnixSignalWatchSource *) source;
4589 g_warning ("Unix signal source dispatched without callback\n"
4590 "You must call g_source_set_callback().");
4594 again = (callback) (user_data);
4596 unix_signal_source->pending = FALSE;
4602 ensure_unix_signal_handler_installed_unlocked (int signum)
4604 static sigset_t installed_signal_mask;
4605 static gboolean initialized;
4606 struct sigaction action;
4610 sigemptyset (&installed_signal_mask);
4611 g_get_worker_context ();
4615 if (sigismember (&installed_signal_mask, signum))
4618 sigaddset (&installed_signal_mask, signum);
4620 action.sa_handler = g_unix_signal_handler;
4621 sigemptyset (&action.sa_mask);
4622 action.sa_flags = SA_RESTART | SA_NOCLDSTOP;
4623 sigaction (signum, &action, NULL);
4627 _g_main_create_unix_signal_watch (int signum)
4630 GUnixSignalWatchSource *unix_signal_source;
4632 source = g_source_new (&g_unix_signal_funcs, sizeof (GUnixSignalWatchSource));
4633 unix_signal_source = (GUnixSignalWatchSource *) source;
4635 unix_signal_source->signum = signum;
4636 unix_signal_source->pending = FALSE;
4638 G_LOCK (unix_signal_lock);
4639 ensure_unix_signal_handler_installed_unlocked (signum);
4640 unix_signal_watches = g_slist_prepend (unix_signal_watches, unix_signal_source);
4641 if (unix_signal_pending[signum])
4642 unix_signal_source->pending = TRUE;
4643 unix_signal_pending[signum] = FALSE;
4644 G_UNLOCK (unix_signal_lock);
4650 g_unix_signal_watch_finalize (GSource *source)
4652 G_LOCK (unix_signal_lock);
4653 unix_signal_watches = g_slist_remove (unix_signal_watches, source);
4654 G_UNLOCK (unix_signal_lock);
4658 g_child_watch_finalize (GSource *source)
4660 G_LOCK (unix_signal_lock);
4661 unix_child_watches = g_slist_remove (unix_child_watches, source);
4662 G_UNLOCK (unix_signal_lock);
4665 #endif /* G_OS_WIN32 */
4668 g_child_watch_dispatch (GSource *source,
4669 GSourceFunc callback,
4672 GChildWatchSource *child_watch_source;
4673 GChildWatchFunc child_watch_callback = (GChildWatchFunc) callback;
4675 child_watch_source = (GChildWatchSource *) source;
4679 g_warning ("Child watch source dispatched without callback\n"
4680 "You must call g_source_set_callback().");
4684 (child_watch_callback) (child_watch_source->pid, child_watch_source->child_status, user_data);
4686 /* We never keep a child watch source around as the child is gone */
4693 g_unix_signal_handler (int signum)
4695 unix_signal_pending[signum] = TRUE;
4696 any_unix_signal_pending = TRUE;
4698 g_wakeup_signal (glib_worker_context->wakeup);
4701 #endif /* !G_OS_WIN32 */
4704 * g_child_watch_source_new:
4705 * @pid: process to watch. On POSIX the pid of a child process. On
4706 * Windows a handle for a process (which doesn't have to be a child).
4708 * Creates a new child_watch source.
4710 * The source will not initially be associated with any #GMainContext
4711 * and must be added to one with g_source_attach() before it will be
4714 * Note that child watch sources can only be used in conjunction with
4715 * <literal>g_spawn...</literal> when the %G_SPAWN_DO_NOT_REAP_CHILD
4718 * Note that on platforms where #GPid must be explicitly closed
4719 * (see g_spawn_close_pid()) @pid must not be closed while the
4720 * source is still active. Typically, you will want to call
4721 * g_spawn_close_pid() in the callback function for the source.
4723 * Note further that using g_child_watch_source_new() is not
4724 * compatible with calling <literal>waitpid</literal> with a
4725 * nonpositive first argument in the application. Calling waitpid()
4726 * for individual pids will still work fine.
4728 * Return value: the newly-created child watch source
4733 g_child_watch_source_new (GPid pid)
4735 GSource *source = g_source_new (&g_child_watch_funcs, sizeof (GChildWatchSource));
4736 GChildWatchSource *child_watch_source = (GChildWatchSource *)source;
4738 child_watch_source->pid = pid;
4741 child_watch_source->poll.fd = (gintptr) pid;
4742 child_watch_source->poll.events = G_IO_IN;
4744 g_source_add_poll (source, &child_watch_source->poll);
4745 #else /* G_OS_WIN32 */
4746 G_LOCK (unix_signal_lock);
4747 ensure_unix_signal_handler_installed_unlocked (SIGCHLD);
4748 unix_child_watches = g_slist_prepend (unix_child_watches, child_watch_source);
4749 if (waitpid (pid, &child_watch_source->child_status, WNOHANG) > 0)
4750 child_watch_source->child_exited = TRUE;
4751 G_UNLOCK (unix_signal_lock);
4752 #endif /* G_OS_WIN32 */
4758 * g_child_watch_add_full:
4759 * @priority: the priority of the idle source. Typically this will be in the
4760 * range between #G_PRIORITY_DEFAULT_IDLE and #G_PRIORITY_HIGH_IDLE.
4761 * @pid: process to watch. On POSIX the pid of a child process. On
4762 * Windows a handle for a process (which doesn't have to be a child).
4763 * @function: function to call
4764 * @data: data to pass to @function
4765 * @notify: (allow-none): function to call when the idle is removed, or %NULL
4767 * Sets a function to be called when the child indicated by @pid
4768 * exits, at the priority @priority.
4770 * If you obtain @pid from g_spawn_async() or g_spawn_async_with_pipes()
4771 * you will need to pass #G_SPAWN_DO_NOT_REAP_CHILD as flag to
4772 * the spawn function for the child watching to work.
4774 * In many programs, you will want to call g_spawn_check_exit_status()
4775 * in the callback to determine whether or not the child exited
4778 * Also, note that on platforms where #GPid must be explicitly closed
4779 * (see g_spawn_close_pid()) @pid must not be closed while the source
4780 * is still active. Typically, you should invoke g_spawn_close_pid()
4781 * in the callback function for the source.
4783 * GLib supports only a single callback per process id.
4785 * This internally creates a main loop source using
4786 * g_child_watch_source_new() and attaches it to the main loop context
4787 * using g_source_attach(). You can do these steps manually if you
4788 * need greater control.
4790 * Return value: the ID (greater than 0) of the event source.
4792 * Rename to: g_child_watch_add
4796 g_child_watch_add_full (gint priority,
4798 GChildWatchFunc function,
4800 GDestroyNotify notify)
4805 g_return_val_if_fail (function != NULL, 0);
4807 source = g_child_watch_source_new (pid);
4809 if (priority != G_PRIORITY_DEFAULT)
4810 g_source_set_priority (source, priority);
4812 g_source_set_callback (source, (GSourceFunc) function, data, notify);
4813 id = g_source_attach (source, NULL);
4814 g_source_unref (source);
4820 * g_child_watch_add:
4821 * @pid: process id to watch. On POSIX the pid of a child process. On
4822 * Windows a handle for a process (which doesn't have to be a child).
4823 * @function: function to call
4824 * @data: data to pass to @function
4826 * Sets a function to be called when the child indicated by @pid
4827 * exits, at a default priority, #G_PRIORITY_DEFAULT.
4829 * If you obtain @pid from g_spawn_async() or g_spawn_async_with_pipes()
4830 * you will need to pass #G_SPAWN_DO_NOT_REAP_CHILD as flag to
4831 * the spawn function for the child watching to work.
4833 * Note that on platforms where #GPid must be explicitly closed
4834 * (see g_spawn_close_pid()) @pid must not be closed while the
4835 * source is still active. Typically, you will want to call
4836 * g_spawn_close_pid() in the callback function for the source.
4838 * GLib supports only a single callback per process id.
4840 * This internally creates a main loop source using
4841 * g_child_watch_source_new() and attaches it to the main loop context
4842 * using g_source_attach(). You can do these steps manually if you
4843 * need greater control.
4845 * Return value: the ID (greater than 0) of the event source.
4850 g_child_watch_add (GPid pid,
4851 GChildWatchFunc function,
4854 return g_child_watch_add_full (G_PRIORITY_DEFAULT, pid, function, data, NULL);
4858 /* Idle functions */
4861 g_idle_prepare (GSource *source,
4870 g_idle_check (GSource *source)
4876 g_idle_dispatch (GSource *source,
4877 GSourceFunc callback,
4882 g_warning ("Idle source dispatched without callback\n"
4883 "You must call g_source_set_callback().");
4887 return callback (user_data);
4891 * g_idle_source_new:
4893 * Creates a new idle source.
4895 * The source will not initially be associated with any #GMainContext
4896 * and must be added to one with g_source_attach() before it will be
4897 * executed. Note that the default priority for idle sources is
4898 * %G_PRIORITY_DEFAULT_IDLE, as compared to other sources which
4899 * have a default priority of %G_PRIORITY_DEFAULT.
4901 * Return value: the newly-created idle source
4904 g_idle_source_new (void)
4908 source = g_source_new (&g_idle_funcs, sizeof (GSource));
4909 g_source_set_priority (source, G_PRIORITY_DEFAULT_IDLE);
4916 * @priority: the priority of the idle source. Typically this will be in the
4917 * range between #G_PRIORITY_DEFAULT_IDLE and #G_PRIORITY_HIGH_IDLE.
4918 * @function: function to call
4919 * @data: data to pass to @function
4920 * @notify: (allow-none): function to call when the idle is removed, or %NULL
4922 * Adds a function to be called whenever there are no higher priority
4923 * events pending. If the function returns %FALSE it is automatically
4924 * removed from the list of event sources and will not be called again.
4926 * This internally creates a main loop source using g_idle_source_new()
4927 * and attaches it to the main loop context using g_source_attach().
4928 * You can do these steps manually if you need greater control.
4930 * Return value: the ID (greater than 0) of the event source.
4931 * Rename to: g_idle_add
4934 g_idle_add_full (gint priority,
4935 GSourceFunc function,
4937 GDestroyNotify notify)
4942 g_return_val_if_fail (function != NULL, 0);
4944 source = g_idle_source_new ();
4946 if (priority != G_PRIORITY_DEFAULT_IDLE)
4947 g_source_set_priority (source, priority);
4949 g_source_set_callback (source, function, data, notify);
4950 id = g_source_attach (source, NULL);
4951 g_source_unref (source);
4958 * @function: function to call
4959 * @data: data to pass to @function.
4961 * Adds a function to be called whenever there are no higher priority
4962 * events pending to the default main loop. The function is given the
4963 * default idle priority, #G_PRIORITY_DEFAULT_IDLE. If the function
4964 * returns %FALSE it is automatically removed from the list of event
4965 * sources and will not be called again.
4967 * This internally creates a main loop source using g_idle_source_new()
4968 * and attaches it to the main loop context using g_source_attach().
4969 * You can do these steps manually if you need greater control.
4971 * Return value: the ID (greater than 0) of the event source.
4974 g_idle_add (GSourceFunc function,
4977 return g_idle_add_full (G_PRIORITY_DEFAULT_IDLE, function, data, NULL);
4981 * g_idle_remove_by_data:
4982 * @data: the data for the idle source's callback.
4984 * Removes the idle function with the given data.
4986 * Return value: %TRUE if an idle source was found and removed.
4989 g_idle_remove_by_data (gpointer data)
4991 return g_source_remove_by_funcs_user_data (&g_idle_funcs, data);
4995 * g_main_context_invoke:
4996 * @context: (allow-none): a #GMainContext, or %NULL
4997 * @function: function to call
4998 * @data: data to pass to @function
5000 * Invokes a function in such a way that @context is owned during the
5001 * invocation of @function.
5003 * If @context is %NULL then the global default main context — as
5004 * returned by g_main_context_default() — is used.
5006 * If @context is owned by the current thread, @function is called
5007 * directly. Otherwise, if @context is the thread-default main context
5008 * of the current thread and g_main_context_acquire() succeeds, then
5009 * @function is called and g_main_context_release() is called
5012 * In any other case, an idle source is created to call @function and
5013 * that source is attached to @context (presumably to be run in another
5014 * thread). The idle source is attached with #G_PRIORITY_DEFAULT
5015 * priority. If you want a different priority, use
5016 * g_main_context_invoke_full().
5018 * Note that, as with normal idle functions, @function should probably
5019 * return %FALSE. If it returns %TRUE, it will be continuously run in a
5020 * loop (and may prevent this call from returning).
5025 g_main_context_invoke (GMainContext *context,
5026 GSourceFunc function,
5029 g_main_context_invoke_full (context,
5031 function, data, NULL);
5035 * g_main_context_invoke_full:
5036 * @context: (allow-none): a #GMainContext, or %NULL
5037 * @priority: the priority at which to run @function
5038 * @function: function to call
5039 * @data: data to pass to @function
5040 * @notify: (allow-none): a function to call when @data is no longer in use, or %NULL.
5042 * Invokes a function in such a way that @context is owned during the
5043 * invocation of @function.
5045 * This function is the same as g_main_context_invoke() except that it
5046 * lets you specify the priority incase @function ends up being
5047 * scheduled as an idle and also lets you give a #GDestroyNotify for @data.
5049 * @notify should not assume that it is called from any particular
5050 * thread or with any particular context acquired.
5055 g_main_context_invoke_full (GMainContext *context,
5057 GSourceFunc function,
5059 GDestroyNotify notify)
5061 g_return_if_fail (function != NULL);
5064 context = g_main_context_default ();
5066 if (g_main_context_is_owner (context))
5068 while (function (data));
5075 GMainContext *thread_default;
5077 thread_default = g_main_context_get_thread_default ();
5079 if (!thread_default)
5080 thread_default = g_main_context_default ();
5082 if (thread_default == context && g_main_context_acquire (context))
5084 while (function (data));
5086 g_main_context_release (context);
5095 source = g_idle_source_new ();
5096 g_source_set_priority (source, priority);
5097 g_source_set_callback (source, function, data, notify);
5098 g_source_attach (source, context);
5099 g_source_unref (source);
5105 glib_worker_main (gpointer data)
5109 g_main_context_iteration (glib_worker_context, TRUE);
5112 if (any_unix_signal_pending)
5113 dispatch_unix_signals ();
5117 return NULL; /* worst GCC warning message ever... */
5121 g_get_worker_context (void)
5123 static gsize initialised;
5125 if (g_once_init_enter (&initialised))
5127 /* mask all signals in the worker thread */
5133 pthread_sigmask (SIG_SETMASK, &all, &prev_mask);
5135 glib_worker_context = g_main_context_new ();
5136 g_thread_new ("gmain", glib_worker_main, NULL);
5138 pthread_sigmask (SIG_SETMASK, &prev_mask, NULL);
5140 g_once_init_leave (&initialised, TRUE);
5143 return glib_worker_context;