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"
53 #include <sys/eventfd.h>
58 #include <sys/types.h>
61 #ifdef HAVE_SYS_TIME_H
63 #endif /* HAVE_SYS_TIME_H */
66 #endif /* HAVE_UNISTD_H */
73 #endif /* G_OS_WIN32 */
76 #include <sys/socket.h>
78 #endif /* G_OS_BEOS */
83 #include "giochannel.h"
87 #include "gstrfuncs.h"
88 #include "gtestutils.h"
89 #include "gthreadprivate.h"
95 #ifdef G_MAIN_POLL_DEBUG
101 #include "glibprivate.h"
105 * @title: The Main Event Loop
106 * @short_description: manages all available sources of events
108 * The main event loop manages all the available sources of events for
109 * GLib and GTK+ applications. These events can come from any number of
110 * different types of sources such as file descriptors (plain files,
111 * pipes or sockets) and timeouts. New types of event sources can also
112 * be added using g_source_attach().
114 * To allow multiple independent sets of sources to be handled in
115 * different threads, each source is associated with a #GMainContext.
116 * A GMainContext can only be running in a single thread, but
117 * sources can be added to it and removed from it from other threads.
119 * Each event source is assigned a priority. The default priority,
120 * #G_PRIORITY_DEFAULT, is 0. Values less than 0 denote higher priorities.
121 * Values greater than 0 denote lower priorities. Events from high priority
122 * sources are always processed before events from lower priority sources.
124 * Idle functions can also be added, and assigned a priority. These will
125 * be run whenever no events with a higher priority are ready to be processed.
127 * The #GMainLoop data type represents a main event loop. A GMainLoop is
128 * created with g_main_loop_new(). After adding the initial event sources,
129 * g_main_loop_run() is called. This continuously checks for new events from
130 * each of the event sources and dispatches them. Finally, the processing of
131 * an event from one of the sources leads to a call to g_main_loop_quit() to
132 * exit the main loop, and g_main_loop_run() returns.
134 * It is possible to create new instances of #GMainLoop recursively.
135 * This is often used in GTK+ applications when showing modal dialog
136 * boxes. Note that event sources are associated with a particular
137 * #GMainContext, and will be checked and dispatched for all main
138 * loops associated with that GMainContext.
140 * GTK+ contains wrappers of some of these functions, e.g. gtk_main(),
141 * gtk_main_quit() and gtk_events_pending().
143 * <refsect2><title>Creating new source types</title>
144 * <para>One of the unusual features of the #GMainLoop functionality
145 * is that new types of event source can be created and used in
146 * addition to the builtin type of event source. A new event source
147 * type is used for handling GDK events. A new source type is created
148 * by <firstterm>deriving</firstterm> from the #GSource structure.
149 * The derived type of source is represented by a structure that has
150 * the #GSource structure as a first element, and other elements specific
151 * to the new source type. To create an instance of the new source type,
152 * call g_source_new() passing in the size of the derived structure and
153 * a table of functions. These #GSourceFuncs determine the behavior of
154 * the new source type.</para>
155 * <para>New source types basically interact with the main context
156 * in two ways. Their prepare function in #GSourceFuncs can set a timeout
157 * to determine the maximum amount of time that the main loop will sleep
158 * before checking the source again. In addition, or as well, the source
159 * can add file descriptors to the set that the main context checks using
160 * g_source_add_poll().</para>
162 * <refsect2><title>Customizing the main loop iteration</title>
163 * <para>Single iterations of a #GMainContext can be run with
164 * g_main_context_iteration(). In some cases, more detailed control
165 * of exactly how the details of the main loop work is desired, for
166 * instance, when integrating the #GMainLoop with an external main loop.
167 * In such cases, you can call the component functions of
168 * g_main_context_iteration() directly. These functions are
169 * g_main_context_prepare(), g_main_context_query(),
170 * g_main_context_check() and g_main_context_dispatch().</para>
171 * <para>The operation of these functions can best be seen in terms
172 * of a state diagram, as shown in <xref linkend="mainloop-states"/>.</para>
173 * <figure id="mainloop-states"><title>States of a Main Context</title>
174 * <graphic fileref="mainloop-states.gif" format="GIF"></graphic>
181 typedef struct _GTimeoutSource GTimeoutSource;
182 typedef struct _GChildWatchSource GChildWatchSource;
183 typedef struct _GUnixSignalWatchSource GUnixSignalWatchSource;
184 typedef struct _GPollRec GPollRec;
185 typedef struct _GSourceCallback GSourceCallback;
189 G_SOURCE_READY = 1 << G_HOOK_FLAG_USER_SHIFT,
190 G_SOURCE_CAN_RECURSE = 1 << (G_HOOK_FLAG_USER_SHIFT + 1)
193 typedef struct _GMainWaiter GMainWaiter;
201 typedef struct _GMainDispatch GMainDispatch;
203 struct _GMainDispatch
206 GSList *dispatching_sources; /* stack of current sources */
209 #ifdef G_MAIN_POLL_DEBUG
210 gboolean _g_main_poll_debug = FALSE;
215 /* The following lock is used for both the list of sources
216 * and the list of poll records
226 GPtrArray *pending_dispatches;
227 gint timeout; /* Timeout for current iteration */
230 GSource *source_list;
231 gint in_check_or_prepare;
233 GPollRec *poll_records, *poll_records_tail;
234 guint n_poll_records;
235 GPollFD *cached_poll_array;
236 guint cached_poll_array_size;
241 gboolean poll_waiting;
243 /* Flag indicating whether the set of fd's changed during a poll */
244 gboolean poll_changed;
249 gboolean time_is_fresh;
251 gboolean real_time_is_fresh;
254 struct _GSourceCallback
259 GDestroyNotify notify;
264 GMainContext *context;
269 struct _GTimeoutSource
277 struct _GChildWatchSource
284 #else /* G_OS_WIN32 */
286 gboolean child_exited;
287 #endif /* G_OS_WIN32 */
290 struct _GUnixSignalWatchSource
305 struct _GSourcePrivate
307 GSList *child_sources;
308 GSource *parent_source;
311 #define LOCK_CONTEXT(context) g_static_mutex_lock (&context->mutex)
312 #define UNLOCK_CONTEXT(context) g_static_mutex_unlock (&context->mutex)
313 #define G_THREAD_SELF g_thread_self ()
315 #define SOURCE_DESTROYED(source) (((source)->flags & G_HOOK_FLAG_ACTIVE) == 0)
316 #define SOURCE_BLOCKED(source) (((source)->flags & G_HOOK_FLAG_IN_CALL) != 0 && \
317 ((source)->flags & G_SOURCE_CAN_RECURSE) == 0)
319 #define SOURCE_UNREF(source, context) \
321 if ((source)->ref_count > 1) \
322 (source)->ref_count--; \
324 g_source_unref_internal ((source), (context), TRUE); \
328 /* Forward declarations */
330 static void g_source_unref_internal (GSource *source,
331 GMainContext *context,
333 static void g_source_destroy_internal (GSource *source,
334 GMainContext *context,
336 static void g_source_set_priority_unlocked (GSource *source,
337 GMainContext *context,
339 static void g_main_context_poll (GMainContext *context,
344 static void g_main_context_add_poll_unlocked (GMainContext *context,
347 static void g_main_context_remove_poll_unlocked (GMainContext *context,
349 static void g_main_context_wakeup_unlocked (GMainContext *context);
351 static void _g_main_wake_up_all_contexts (void);
353 static gboolean g_timeout_prepare (GSource *source,
355 static gboolean g_timeout_check (GSource *source);
356 static gboolean g_timeout_dispatch (GSource *source,
357 GSourceFunc callback,
359 static gboolean g_child_watch_prepare (GSource *source,
361 static gboolean g_child_watch_check (GSource *source);
362 static gboolean g_child_watch_dispatch (GSource *source,
363 GSourceFunc callback,
366 static gpointer unix_signal_helper_thread (gpointer data) G_GNUC_NORETURN;
367 static void g_unix_signal_handler (int signum);
368 static gboolean g_unix_signal_watch_prepare (GSource *source,
370 static gboolean g_unix_signal_watch_check (GSource *source);
371 static gboolean g_unix_signal_watch_dispatch (GSource *source,
372 GSourceFunc callback,
374 static void g_unix_signal_watch_finalize (GSource *source);
376 static gboolean g_idle_prepare (GSource *source,
378 static gboolean g_idle_check (GSource *source);
379 static gboolean g_idle_dispatch (GSource *source,
380 GSourceFunc callback,
383 static GMainContext *glib_worker_context;
385 G_LOCK_DEFINE_STATIC (main_loop);
386 static GMainContext *default_main_context;
387 static GSList *main_contexts_without_pipe = NULL;
391 /* The UNIX signal pipe contains a single byte specifying which
392 * signal was received.
394 #define _UNIX_SIGNAL_PIPE_SIGCHLD_CHAR 'C'
395 #define _UNIX_SIGNAL_PIPE_SIGHUP_CHAR 'H'
396 #define _UNIX_SIGNAL_PIPE_SIGINT_CHAR 'I'
397 #define _UNIX_SIGNAL_PIPE_SIGTERM_CHAR 'T'
398 /* Guards all the data below */
399 G_LOCK_DEFINE_STATIC (unix_signal_lock);
401 UNIX_SIGNAL_UNINITIALIZED = 0,
402 UNIX_SIGNAL_INITIALIZED_SINGLE,
403 UNIX_SIGNAL_INITIALIZED_THREADED
405 static gint unix_signal_init_state = UNIX_SIGNAL_UNINITIALIZED;
407 /* These are only used in the UNIX_SIGNAL_INITIALIZED_SINGLE case */
408 gboolean sighup_delivered : 1;
409 gboolean sigint_delivered : 1;
410 gboolean sigterm_delivered : 1;
412 static sigset_t unix_signal_mask;
413 static UnixSignalState unix_signal_state;
414 static gint unix_signal_wake_up_pipe[2];
415 GSList *unix_signal_watches;
417 /* Not guarded ( FIXME should it be? ) */
418 static gint child_watch_count = 1;
420 static GSourceFuncs g_unix_signal_funcs =
422 g_unix_signal_watch_prepare,
423 g_unix_signal_watch_check,
424 g_unix_signal_watch_dispatch,
425 g_unix_signal_watch_finalize
427 #endif /* !G_OS_WIN32 */
428 G_LOCK_DEFINE_STATIC (main_context_list);
429 static GSList *main_context_list = NULL;
431 GSourceFuncs g_timeout_funcs =
439 GSourceFuncs g_child_watch_funcs =
441 g_child_watch_prepare,
443 g_child_watch_dispatch,
447 GSourceFuncs g_idle_funcs =
456 * g_main_context_ref:
457 * @context: a #GMainContext
459 * Increases the reference count on a #GMainContext object by one.
461 * Returns: the @context that was passed in (since 2.6)
464 g_main_context_ref (GMainContext *context)
466 g_return_val_if_fail (context != NULL, NULL);
467 g_return_val_if_fail (g_atomic_int_get (&context->ref_count) > 0, NULL);
469 g_atomic_int_inc (&context->ref_count);
475 poll_rec_list_free (GMainContext *context,
478 g_slice_free_chain (GPollRec, list, next);
482 * g_main_context_unref:
483 * @context: a #GMainContext
485 * Decreases the reference count on a #GMainContext object by one. If
486 * the result is zero, free the context and free all associated memory.
489 g_main_context_unref (GMainContext *context)
492 g_return_if_fail (context != NULL);
493 g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
495 if (!g_atomic_int_dec_and_test (&context->ref_count))
498 G_LOCK (main_context_list);
499 main_context_list = g_slist_remove (main_context_list, context);
500 G_UNLOCK (main_context_list);
502 source = context->source_list;
505 GSource *next = source->next;
506 g_source_destroy_internal (source, context, FALSE);
510 g_static_mutex_free (&context->mutex);
512 g_ptr_array_free (context->pending_dispatches, TRUE);
513 g_free (context->cached_poll_array);
515 poll_rec_list_free (context, context->poll_records);
517 if (g_thread_supported())
518 g_wakeup_free (context->wakeup);
521 main_contexts_without_pipe = g_slist_remove (main_contexts_without_pipe,
524 if (context->cond != NULL)
525 g_cond_free (context->cond);
531 g_main_context_init_pipe (GMainContext *context)
533 context->wakeup = g_wakeup_new ();
534 g_wakeup_get_pollfd (context->wakeup, &context->wake_up_rec);
535 g_main_context_add_poll_unlocked (context, 0, &context->wake_up_rec);
539 _g_main_thread_init (void)
543 curr = main_contexts_without_pipe;
546 g_main_context_init_pipe ((GMainContext *)curr->data);
549 g_slist_free (main_contexts_without_pipe);
550 main_contexts_without_pipe = NULL;
554 * g_main_context_new:
556 * Creates a new #GMainContext structure.
558 * Return value: the new #GMainContext
561 g_main_context_new (void)
563 GMainContext *context = g_new0 (GMainContext, 1);
565 #ifdef G_MAIN_POLL_DEBUG
567 static gboolean beenhere = FALSE;
571 if (getenv ("G_MAIN_POLL_DEBUG") != NULL)
572 _g_main_poll_debug = TRUE;
578 g_static_mutex_init (&context->mutex);
580 context->owner = NULL;
581 context->waiters = NULL;
583 context->ref_count = 1;
585 context->next_id = 1;
587 context->source_list = NULL;
589 context->poll_func = g_poll;
591 context->cached_poll_array = NULL;
592 context->cached_poll_array_size = 0;
594 context->pending_dispatches = g_ptr_array_new ();
596 context->time_is_fresh = FALSE;
597 context->real_time_is_fresh = FALSE;
599 if (g_thread_supported ())
600 g_main_context_init_pipe (context);
602 main_contexts_without_pipe = g_slist_prepend (main_contexts_without_pipe,
605 G_LOCK (main_context_list);
606 main_context_list = g_slist_append (main_context_list, context);
608 #ifdef G_MAIN_POLL_DEBUG
609 if (_g_main_poll_debug)
610 g_print ("created context=%p\n", context);
613 G_UNLOCK (main_context_list);
619 * g_main_context_default:
621 * Returns the global default main context. This is the main context
622 * used for main loop functions when a main loop is not explicitly
623 * specified, and corresponds to the "main" main loop. See also
624 * g_main_context_get_thread_default().
626 * Return value: (transfer none): the global default main context.
629 g_main_context_default (void)
635 if (!default_main_context)
637 default_main_context = g_main_context_new ();
638 #ifdef G_MAIN_POLL_DEBUG
639 if (_g_main_poll_debug)
640 g_print ("default context=%p\n", default_main_context);
644 G_UNLOCK (main_loop);
646 return default_main_context;
649 static GStaticPrivate thread_context_stack = G_STATIC_PRIVATE_INIT;
652 free_context_stack (gpointer data)
654 GQueue *stack = data;
655 GMainContext *context;
657 while (!g_queue_is_empty (stack))
659 context = g_queue_pop_head (stack);
660 g_main_context_release (context);
662 g_main_context_unref (context);
664 g_queue_free (stack);
668 * g_main_context_push_thread_default:
669 * @context: a #GMainContext, or %NULL for the global default context
671 * Acquires @context and sets it as the thread-default context for the
672 * current thread. This will cause certain asynchronous operations
673 * (such as most <link linkend="gio">gio</link>-based I/O) which are
674 * started in this thread to run under @context and deliver their
675 * results to its main loop, rather than running under the global
676 * default context in the main thread. Note that calling this function
677 * changes the context returned by
678 * g_main_context_get_thread_default(), <emphasis>not</emphasis> the
679 * one returned by g_main_context_default(), so it does not affect the
680 * context used by functions like g_idle_add().
682 * Normally you would call this function shortly after creating a new
683 * thread, passing it a #GMainContext which will be run by a
684 * #GMainLoop in that thread, to set a new default context for all
685 * async operations in that thread. (In this case, you don't need to
686 * ever call g_main_context_pop_thread_default().) In some cases
687 * however, you may want to schedule a single operation in a
688 * non-default context, or temporarily use a non-default context in
689 * the main thread. In that case, you can wrap the call to the
690 * asynchronous operation inside a
691 * g_main_context_push_thread_default() /
692 * g_main_context_pop_thread_default() pair, but it is up to you to
693 * ensure that no other asynchronous operations accidentally get
694 * started while the non-default context is active.
696 * Beware that libraries that predate this function may not correctly
697 * handle being used from a thread with a thread-default context. Eg,
698 * see g_file_supports_thread_contexts().
703 g_main_context_push_thread_default (GMainContext *context)
706 gboolean acquired_context;
708 acquired_context = g_main_context_acquire (context);
709 g_return_if_fail (acquired_context);
711 if (context == g_main_context_default ())
714 g_main_context_ref (context);
716 stack = g_static_private_get (&thread_context_stack);
719 stack = g_queue_new ();
720 g_static_private_set (&thread_context_stack, stack,
724 g_queue_push_head (stack, context);
728 * g_main_context_pop_thread_default:
729 * @context: a #GMainContext object, or %NULL
731 * Pops @context off the thread-default context stack (verifying that
732 * it was on the top of the stack).
737 g_main_context_pop_thread_default (GMainContext *context)
741 if (context == g_main_context_default ())
744 stack = g_static_private_get (&thread_context_stack);
746 g_return_if_fail (stack != NULL);
747 g_return_if_fail (g_queue_peek_head (stack) == context);
749 g_queue_pop_head (stack);
751 g_main_context_release (context);
753 g_main_context_unref (context);
757 * g_main_context_get_thread_default:
759 * Gets the thread-default #GMainContext for this thread. Asynchronous
760 * operations that want to be able to be run in contexts other than
761 * the default one should call this method to get a #GMainContext to
762 * add their #GSource<!-- -->s to. (Note that even in single-threaded
763 * programs applications may sometimes want to temporarily push a
764 * non-default context, so it is not safe to assume that this will
765 * always return %NULL if threads are not initialized.)
767 * Returns: (transfer none): the thread-default #GMainContext, or
768 * %NULL if the thread-default context is the global default context.
773 g_main_context_get_thread_default (void)
777 stack = g_static_private_get (&thread_context_stack);
779 return g_queue_peek_head (stack);
784 /* Hooks for adding to the main loop */
788 * @source_funcs: structure containing functions that implement
789 * the sources behavior.
790 * @struct_size: size of the #GSource structure to create.
792 * Creates a new #GSource structure. The size is specified to
793 * allow creating structures derived from #GSource that contain
794 * additional data. The size passed in must be at least
795 * <literal>sizeof (GSource)</literal>.
797 * The source will not initially be associated with any #GMainContext
798 * and must be added to one with g_source_attach() before it will be
801 * Return value: the newly-created #GSource.
804 g_source_new (GSourceFuncs *source_funcs,
809 g_return_val_if_fail (source_funcs != NULL, NULL);
810 g_return_val_if_fail (struct_size >= sizeof (GSource), NULL);
812 source = (GSource*) g_malloc0 (struct_size);
814 source->source_funcs = source_funcs;
815 source->ref_count = 1;
817 source->priority = G_PRIORITY_DEFAULT;
819 source->flags = G_HOOK_FLAG_ACTIVE;
821 /* NULL/0 initialization for all other fields */
826 /* Holds context's lock
829 g_source_list_add (GSource *source,
830 GMainContext *context)
832 GSource *tmp_source, *last_source;
834 if (source->priv && source->priv->parent_source)
836 /* Put the source immediately before its parent */
837 tmp_source = source->priv->parent_source;
838 last_source = source->priv->parent_source->prev;
843 tmp_source = context->source_list;
844 while (tmp_source && tmp_source->priority <= source->priority)
846 last_source = tmp_source;
847 tmp_source = tmp_source->next;
851 source->next = tmp_source;
853 tmp_source->prev = source;
855 source->prev = last_source;
857 last_source->next = source;
859 context->source_list = source;
862 /* Holds context's lock
865 g_source_list_remove (GSource *source,
866 GMainContext *context)
869 source->prev->next = source->next;
871 context->source_list = source->next;
874 source->next->prev = source->prev;
881 g_source_attach_unlocked (GSource *source,
882 GMainContext *context)
887 source->context = context;
888 result = source->source_id = context->next_id++;
891 g_source_list_add (source, context);
893 tmp_list = source->poll_fds;
896 g_main_context_add_poll_unlocked (context, source->priority, tmp_list->data);
897 tmp_list = tmp_list->next;
902 tmp_list = source->priv->child_sources;
905 g_source_attach_unlocked (tmp_list->data, context);
906 tmp_list = tmp_list->next;
915 * @source: a #GSource
916 * @context: a #GMainContext (if %NULL, the default context will be used)
918 * Adds a #GSource to a @context so that it will be executed within
919 * that context. Remove it by calling g_source_destroy().
921 * Return value: the ID (greater than 0) for the source within the
925 g_source_attach (GSource *source,
926 GMainContext *context)
930 g_return_val_if_fail (source->context == NULL, 0);
931 g_return_val_if_fail (!SOURCE_DESTROYED (source), 0);
934 context = g_main_context_default ();
936 LOCK_CONTEXT (context);
938 result = g_source_attach_unlocked (source, context);
940 /* Now wake up the main loop if it is waiting in the poll() */
941 g_main_context_wakeup_unlocked (context);
943 UNLOCK_CONTEXT (context);
949 g_source_destroy_internal (GSource *source,
950 GMainContext *context,
954 LOCK_CONTEXT (context);
956 if (!SOURCE_DESTROYED (source))
959 gpointer old_cb_data;
960 GSourceCallbackFuncs *old_cb_funcs;
962 source->flags &= ~G_HOOK_FLAG_ACTIVE;
964 old_cb_data = source->callback_data;
965 old_cb_funcs = source->callback_funcs;
967 source->callback_data = NULL;
968 source->callback_funcs = NULL;
972 UNLOCK_CONTEXT (context);
973 old_cb_funcs->unref (old_cb_data);
974 LOCK_CONTEXT (context);
977 if (!SOURCE_BLOCKED (source))
979 tmp_list = source->poll_fds;
982 g_main_context_remove_poll_unlocked (context, tmp_list->data);
983 tmp_list = tmp_list->next;
987 if (source->priv && source->priv->child_sources)
989 /* This is safe because even if a child_source finalizer or
990 * closure notify tried to modify source->priv->child_sources
991 * from outside the lock, it would fail since
992 * SOURCE_DESTROYED(source) is now TRUE.
994 tmp_list = source->priv->child_sources;
997 g_source_destroy_internal (tmp_list->data, context, TRUE);
998 g_source_unref_internal (tmp_list->data, context, TRUE);
999 tmp_list = tmp_list->next;
1001 g_slist_free (source->priv->child_sources);
1002 source->priv->child_sources = NULL;
1005 g_source_unref_internal (source, context, TRUE);
1009 UNLOCK_CONTEXT (context);
1014 * @source: a #GSource
1016 * Removes a source from its #GMainContext, if any, and mark it as
1017 * destroyed. The source cannot be subsequently added to another
1021 g_source_destroy (GSource *source)
1023 GMainContext *context;
1025 g_return_if_fail (source != NULL);
1027 context = source->context;
1030 g_source_destroy_internal (source, context, FALSE);
1032 source->flags &= ~G_HOOK_FLAG_ACTIVE;
1037 * @source: a #GSource
1039 * Returns the numeric ID for a particular source. The ID of a source
1040 * is a positive integer which is unique within a particular main loop
1041 * context. The reverse
1042 * mapping from ID to source is done by g_main_context_find_source_by_id().
1044 * Return value: the ID (greater than 0) for the source
1047 g_source_get_id (GSource *source)
1051 g_return_val_if_fail (source != NULL, 0);
1052 g_return_val_if_fail (source->context != NULL, 0);
1054 LOCK_CONTEXT (source->context);
1055 result = source->source_id;
1056 UNLOCK_CONTEXT (source->context);
1062 * g_source_get_context:
1063 * @source: a #GSource
1065 * Gets the #GMainContext with which the source is associated.
1066 * Calling this function on a destroyed source is an error.
1068 * Return value: (transfer none): the #GMainContext with which the
1069 * source is associated, or %NULL if the context has not
1070 * yet been added to a source.
1073 g_source_get_context (GSource *source)
1075 g_return_val_if_fail (!SOURCE_DESTROYED (source), NULL);
1077 return source->context;
1081 * g_source_add_poll:
1082 * @source:a #GSource
1083 * @fd: a #GPollFD structure holding information about a file
1084 * descriptor to watch.
1086 * Adds a file descriptor to the set of file descriptors polled for
1087 * this source. This is usually combined with g_source_new() to add an
1088 * event source. The event source's check function will typically test
1089 * the @revents field in the #GPollFD struct and return %TRUE if events need
1093 g_source_add_poll (GSource *source,
1096 GMainContext *context;
1098 g_return_if_fail (source != NULL);
1099 g_return_if_fail (fd != NULL);
1100 g_return_if_fail (!SOURCE_DESTROYED (source));
1102 context = source->context;
1105 LOCK_CONTEXT (context);
1107 source->poll_fds = g_slist_prepend (source->poll_fds, fd);
1111 if (!SOURCE_BLOCKED (source))
1112 g_main_context_add_poll_unlocked (context, source->priority, fd);
1113 UNLOCK_CONTEXT (context);
1118 * g_source_remove_poll:
1119 * @source:a #GSource
1120 * @fd: a #GPollFD structure previously passed to g_source_add_poll().
1122 * Removes a file descriptor from the set of file descriptors polled for
1126 g_source_remove_poll (GSource *source,
1129 GMainContext *context;
1131 g_return_if_fail (source != NULL);
1132 g_return_if_fail (fd != NULL);
1133 g_return_if_fail (!SOURCE_DESTROYED (source));
1135 context = source->context;
1138 LOCK_CONTEXT (context);
1140 source->poll_fds = g_slist_remove (source->poll_fds, fd);
1144 if (!SOURCE_BLOCKED (source))
1145 g_main_context_remove_poll_unlocked (context, fd);
1146 UNLOCK_CONTEXT (context);
1151 * g_source_add_child_source:
1152 * @source:a #GSource
1153 * @child_source: a second #GSource that @source should "poll"
1155 * Adds @child_source to @source as a "polled" source; when @source is
1156 * added to a #GMainContext, @child_source will be automatically added
1157 * with the same priority, when @child_source is triggered, it will
1158 * cause @source to dispatch (in addition to calling its own
1159 * callback), and when @source is destroyed, it will destroy
1160 * @child_source as well. (@source will also still be dispatched if
1161 * its own prepare/check functions indicate that it is ready.)
1163 * If you don't need @child_source to do anything on its own when it
1164 * triggers, you can call g_source_set_dummy_callback() on it to set a
1165 * callback that does nothing (except return %TRUE if appropriate).
1167 * @source will hold a reference on @child_source while @child_source
1168 * is attached to it.
1173 g_source_add_child_source (GSource *source,
1174 GSource *child_source)
1176 GMainContext *context;
1178 g_return_if_fail (source != NULL);
1179 g_return_if_fail (child_source != NULL);
1180 g_return_if_fail (!SOURCE_DESTROYED (source));
1181 g_return_if_fail (!SOURCE_DESTROYED (child_source));
1182 g_return_if_fail (child_source->context == NULL);
1183 g_return_if_fail (child_source->priv == NULL || child_source->priv->parent_source == NULL);
1185 context = source->context;
1188 LOCK_CONTEXT (context);
1191 source->priv = g_slice_new0 (GSourcePrivate);
1192 if (!child_source->priv)
1193 child_source->priv = g_slice_new0 (GSourcePrivate);
1195 source->priv->child_sources = g_slist_prepend (source->priv->child_sources,
1196 g_source_ref (child_source));
1197 child_source->priv->parent_source = source;
1198 g_source_set_priority_unlocked (child_source, context, source->priority);
1202 UNLOCK_CONTEXT (context);
1203 g_source_attach (child_source, context);
1208 * g_source_remove_child_source:
1209 * @source:a #GSource
1210 * @child_source: a #GSource previously passed to
1211 * g_source_add_child_source().
1213 * Detaches @child_source from @source and destroys it.
1218 g_source_remove_child_source (GSource *source,
1219 GSource *child_source)
1221 GMainContext *context;
1223 g_return_if_fail (source != NULL);
1224 g_return_if_fail (child_source != NULL);
1225 g_return_if_fail (child_source->priv != NULL && child_source->priv->parent_source == source);
1226 g_return_if_fail (!SOURCE_DESTROYED (source));
1227 g_return_if_fail (!SOURCE_DESTROYED (child_source));
1229 context = source->context;
1232 LOCK_CONTEXT (context);
1234 source->priv->child_sources = g_slist_remove (source->priv->child_sources, child_source);
1235 g_source_destroy_internal (child_source, context, TRUE);
1236 g_source_unref_internal (child_source, context, TRUE);
1239 UNLOCK_CONTEXT (context);
1243 * g_source_set_callback_indirect:
1244 * @source: the source
1245 * @callback_data: pointer to callback data "object"
1246 * @callback_funcs: functions for reference counting @callback_data
1247 * and getting the callback and data
1249 * Sets the callback function storing the data as a refcounted callback
1250 * "object". This is used internally. Note that calling
1251 * g_source_set_callback_indirect() assumes
1252 * an initial reference count on @callback_data, and thus
1253 * @callback_funcs->unref will eventually be called once more
1254 * than @callback_funcs->ref.
1257 g_source_set_callback_indirect (GSource *source,
1258 gpointer callback_data,
1259 GSourceCallbackFuncs *callback_funcs)
1261 GMainContext *context;
1262 gpointer old_cb_data;
1263 GSourceCallbackFuncs *old_cb_funcs;
1265 g_return_if_fail (source != NULL);
1266 g_return_if_fail (callback_funcs != NULL || callback_data == NULL);
1268 context = source->context;
1271 LOCK_CONTEXT (context);
1273 old_cb_data = source->callback_data;
1274 old_cb_funcs = source->callback_funcs;
1276 source->callback_data = callback_data;
1277 source->callback_funcs = callback_funcs;
1280 UNLOCK_CONTEXT (context);
1283 old_cb_funcs->unref (old_cb_data);
1287 g_source_callback_ref (gpointer cb_data)
1289 GSourceCallback *callback = cb_data;
1291 callback->ref_count++;
1296 g_source_callback_unref (gpointer cb_data)
1298 GSourceCallback *callback = cb_data;
1300 callback->ref_count--;
1301 if (callback->ref_count == 0)
1303 if (callback->notify)
1304 callback->notify (callback->data);
1310 g_source_callback_get (gpointer cb_data,
1315 GSourceCallback *callback = cb_data;
1317 *func = callback->func;
1318 *data = callback->data;
1321 static GSourceCallbackFuncs g_source_callback_funcs = {
1322 g_source_callback_ref,
1323 g_source_callback_unref,
1324 g_source_callback_get,
1328 * g_source_set_callback:
1329 * @source: the source
1330 * @func: a callback function
1331 * @data: the data to pass to callback function
1332 * @notify: a function to call when @data is no longer in use, or %NULL.
1334 * Sets the callback function for a source. The callback for a source is
1335 * called from the source's dispatch function.
1337 * The exact type of @func depends on the type of source; ie. you
1338 * should not count on @func being called with @data as its first
1341 * Typically, you won't use this function. Instead use functions specific
1342 * to the type of source you are using.
1345 g_source_set_callback (GSource *source,
1348 GDestroyNotify notify)
1350 GSourceCallback *new_callback;
1352 g_return_if_fail (source != NULL);
1354 new_callback = g_new (GSourceCallback, 1);
1356 new_callback->ref_count = 1;
1357 new_callback->func = func;
1358 new_callback->data = data;
1359 new_callback->notify = notify;
1361 g_source_set_callback_indirect (source, new_callback, &g_source_callback_funcs);
1366 * g_source_set_funcs:
1367 * @source: a #GSource
1368 * @funcs: the new #GSourceFuncs
1370 * Sets the source functions (can be used to override
1371 * default implementations) of an unattached source.
1376 g_source_set_funcs (GSource *source,
1377 GSourceFuncs *funcs)
1379 g_return_if_fail (source != NULL);
1380 g_return_if_fail (source->context == NULL);
1381 g_return_if_fail (source->ref_count > 0);
1382 g_return_if_fail (funcs != NULL);
1384 source->source_funcs = funcs;
1388 g_source_set_priority_unlocked (GSource *source,
1389 GMainContext *context,
1394 source->priority = priority;
1398 /* Remove the source from the context's source and then
1399 * add it back so it is sorted in the correct place
1401 g_source_list_remove (source, source->context);
1402 g_source_list_add (source, source->context);
1404 if (!SOURCE_BLOCKED (source))
1406 tmp_list = source->poll_fds;
1409 g_main_context_remove_poll_unlocked (context, tmp_list->data);
1410 g_main_context_add_poll_unlocked (context, priority, tmp_list->data);
1412 tmp_list = tmp_list->next;
1417 if (source->priv && source->priv->child_sources)
1419 tmp_list = source->priv->child_sources;
1422 g_source_set_priority_unlocked (tmp_list->data, context, priority);
1423 tmp_list = tmp_list->next;
1429 * g_source_set_priority:
1430 * @source: a #GSource
1431 * @priority: the new priority.
1433 * Sets the priority of a source. While the main loop is being run, a
1434 * source will be dispatched if it is ready to be dispatched and no
1435 * sources at a higher (numerically smaller) priority are ready to be
1439 g_source_set_priority (GSource *source,
1442 GMainContext *context;
1444 g_return_if_fail (source != NULL);
1446 context = source->context;
1449 LOCK_CONTEXT (context);
1450 g_source_set_priority_unlocked (source, context, priority);
1452 UNLOCK_CONTEXT (source->context);
1456 * g_source_get_priority:
1457 * @source: a #GSource
1459 * Gets the priority of a source.
1461 * Return value: the priority of the source
1464 g_source_get_priority (GSource *source)
1466 g_return_val_if_fail (source != NULL, 0);
1468 return source->priority;
1472 * g_source_set_can_recurse:
1473 * @source: a #GSource
1474 * @can_recurse: whether recursion is allowed for this source
1476 * Sets whether a source can be called recursively. If @can_recurse is
1477 * %TRUE, then while the source is being dispatched then this source
1478 * will be processed normally. Otherwise, all processing of this
1479 * source is blocked until the dispatch function returns.
1482 g_source_set_can_recurse (GSource *source,
1483 gboolean can_recurse)
1485 GMainContext *context;
1487 g_return_if_fail (source != NULL);
1489 context = source->context;
1492 LOCK_CONTEXT (context);
1495 source->flags |= G_SOURCE_CAN_RECURSE;
1497 source->flags &= ~G_SOURCE_CAN_RECURSE;
1500 UNLOCK_CONTEXT (context);
1504 * g_source_get_can_recurse:
1505 * @source: a #GSource
1507 * Checks whether a source is allowed to be called recursively.
1508 * see g_source_set_can_recurse().
1510 * Return value: whether recursion is allowed.
1513 g_source_get_can_recurse (GSource *source)
1515 g_return_val_if_fail (source != NULL, FALSE);
1517 return (source->flags & G_SOURCE_CAN_RECURSE) != 0;
1522 * g_source_set_name:
1523 * @source: a #GSource
1524 * @name: debug name for the source
1526 * Sets a name for the source, used in debugging and profiling.
1527 * The name defaults to #NULL.
1529 * The source name should describe in a human-readable way
1530 * what the source does. For example, "X11 event queue"
1531 * or "GTK+ repaint idle handler" or whatever it is.
1533 * It is permitted to call this function multiple times, but is not
1534 * recommended due to the potential performance impact. For example,
1535 * one could change the name in the "check" function of a #GSourceFuncs
1536 * to include details like the event type in the source name.
1541 g_source_set_name (GSource *source,
1544 g_return_if_fail (source != NULL);
1546 /* setting back to NULL is allowed, just because it's
1547 * weird if get_name can return NULL but you can't
1551 g_free (source->name);
1552 source->name = g_strdup (name);
1556 * g_source_get_name:
1557 * @source: a #GSource
1559 * Gets a name for the source, used in debugging and profiling.
1560 * The name may be #NULL if it has never been set with
1561 * g_source_set_name().
1563 * Return value: the name of the source
1567 g_source_get_name (GSource *source)
1569 g_return_val_if_fail (source != NULL, NULL);
1571 return source->name;
1575 * g_source_set_name_by_id:
1576 * @tag: a #GSource ID
1577 * @name: debug name for the source
1579 * Sets the name of a source using its ID.
1581 * This is a convenience utility to set source names from the return
1582 * value of g_idle_add(), g_timeout_add(), etc.
1587 g_source_set_name_by_id (guint tag,
1592 g_return_if_fail (tag > 0);
1594 source = g_main_context_find_source_by_id (NULL, tag);
1598 g_source_set_name (source, name);
1604 * @source: a #GSource
1606 * Increases the reference count on a source by one.
1608 * Return value: @source
1611 g_source_ref (GSource *source)
1613 GMainContext *context;
1615 g_return_val_if_fail (source != NULL, NULL);
1617 context = source->context;
1620 LOCK_CONTEXT (context);
1622 source->ref_count++;
1625 UNLOCK_CONTEXT (context);
1630 /* g_source_unref() but possible to call within context lock
1633 g_source_unref_internal (GSource *source,
1634 GMainContext *context,
1637 gpointer old_cb_data = NULL;
1638 GSourceCallbackFuncs *old_cb_funcs = NULL;
1640 g_return_if_fail (source != NULL);
1642 if (!have_lock && context)
1643 LOCK_CONTEXT (context);
1645 source->ref_count--;
1646 if (source->ref_count == 0)
1648 old_cb_data = source->callback_data;
1649 old_cb_funcs = source->callback_funcs;
1651 source->callback_data = NULL;
1652 source->callback_funcs = NULL;
1656 if (!SOURCE_DESTROYED (source))
1657 g_warning (G_STRLOC ": ref_count == 0, but source was still attached to a context!");
1658 g_source_list_remove (source, context);
1661 if (source->source_funcs->finalize)
1664 UNLOCK_CONTEXT (context);
1665 source->source_funcs->finalize (source);
1667 LOCK_CONTEXT (context);
1670 g_free (source->name);
1671 source->name = NULL;
1673 g_slist_free (source->poll_fds);
1674 source->poll_fds = NULL;
1678 g_slice_free (GSourcePrivate, source->priv);
1679 source->priv = NULL;
1685 if (!have_lock && context)
1686 UNLOCK_CONTEXT (context);
1691 UNLOCK_CONTEXT (context);
1693 old_cb_funcs->unref (old_cb_data);
1696 LOCK_CONTEXT (context);
1702 * @source: a #GSource
1704 * Decreases the reference count of a source by one. If the
1705 * resulting reference count is zero the source and associated
1706 * memory will be destroyed.
1709 g_source_unref (GSource *source)
1711 g_return_if_fail (source != NULL);
1713 g_source_unref_internal (source, source->context, FALSE);
1717 * g_main_context_find_source_by_id:
1718 * @context: a #GMainContext (if %NULL, the default context will be used)
1719 * @source_id: the source ID, as returned by g_source_get_id().
1721 * Finds a #GSource given a pair of context and ID.
1723 * Return value: (transfer none): the #GSource if found, otherwise, %NULL
1726 g_main_context_find_source_by_id (GMainContext *context,
1731 g_return_val_if_fail (source_id > 0, NULL);
1733 if (context == NULL)
1734 context = g_main_context_default ();
1736 LOCK_CONTEXT (context);
1738 source = context->source_list;
1741 if (!SOURCE_DESTROYED (source) &&
1742 source->source_id == source_id)
1744 source = source->next;
1747 UNLOCK_CONTEXT (context);
1753 * g_main_context_find_source_by_funcs_user_data:
1754 * @context: a #GMainContext (if %NULL, the default context will be used).
1755 * @funcs: the @source_funcs passed to g_source_new().
1756 * @user_data: the user data from the callback.
1758 * Finds a source with the given source functions and user data. If
1759 * multiple sources exist with the same source function and user data,
1760 * the first one found will be returned.
1762 * Return value: (transfer none): the source, if one was found, otherwise %NULL
1765 g_main_context_find_source_by_funcs_user_data (GMainContext *context,
1766 GSourceFuncs *funcs,
1771 g_return_val_if_fail (funcs != NULL, NULL);
1773 if (context == NULL)
1774 context = g_main_context_default ();
1776 LOCK_CONTEXT (context);
1778 source = context->source_list;
1781 if (!SOURCE_DESTROYED (source) &&
1782 source->source_funcs == funcs &&
1783 source->callback_funcs)
1785 GSourceFunc callback;
1786 gpointer callback_data;
1788 source->callback_funcs->get (source->callback_data, source, &callback, &callback_data);
1790 if (callback_data == user_data)
1793 source = source->next;
1796 UNLOCK_CONTEXT (context);
1802 * g_main_context_find_source_by_user_data:
1803 * @context: a #GMainContext
1804 * @user_data: the user_data for the callback.
1806 * Finds a source with the given user data for the callback. If
1807 * multiple sources exist with the same user data, the first
1808 * one found will be returned.
1810 * Return value: (transfer none): the source, if one was found, otherwise %NULL
1813 g_main_context_find_source_by_user_data (GMainContext *context,
1818 if (context == NULL)
1819 context = g_main_context_default ();
1821 LOCK_CONTEXT (context);
1823 source = context->source_list;
1826 if (!SOURCE_DESTROYED (source) &&
1827 source->callback_funcs)
1829 GSourceFunc callback;
1830 gpointer callback_data = NULL;
1832 source->callback_funcs->get (source->callback_data, source, &callback, &callback_data);
1834 if (callback_data == user_data)
1837 source = source->next;
1840 UNLOCK_CONTEXT (context);
1847 * @tag: the ID of the source to remove.
1849 * Removes the source with the given id from the default main context.
1851 * a #GSource is given by g_source_get_id(), or will be returned by the
1852 * functions g_source_attach(), g_idle_add(), g_idle_add_full(),
1853 * g_timeout_add(), g_timeout_add_full(), g_child_watch_add(),
1854 * g_child_watch_add_full(), g_io_add_watch(), and g_io_add_watch_full().
1856 * See also g_source_destroy(). You must use g_source_destroy() for sources
1857 * added to a non-default main context.
1859 * Return value: %TRUE if the source was found and removed.
1862 g_source_remove (guint tag)
1866 g_return_val_if_fail (tag > 0, FALSE);
1868 source = g_main_context_find_source_by_id (NULL, tag);
1870 g_source_destroy (source);
1872 return source != NULL;
1876 * g_source_remove_by_user_data:
1877 * @user_data: the user_data for the callback.
1879 * Removes a source from the default main loop context given the user
1880 * data for the callback. If multiple sources exist with the same user
1881 * data, only one will be destroyed.
1883 * Return value: %TRUE if a source was found and removed.
1886 g_source_remove_by_user_data (gpointer user_data)
1890 source = g_main_context_find_source_by_user_data (NULL, user_data);
1893 g_source_destroy (source);
1901 * g_source_remove_by_funcs_user_data:
1902 * @funcs: The @source_funcs passed to g_source_new()
1903 * @user_data: the user data for the callback
1905 * Removes a source from the default main loop context given the
1906 * source functions and user data. If multiple sources exist with the
1907 * same source functions and user data, only one will be destroyed.
1909 * Return value: %TRUE if a source was found and removed.
1912 g_source_remove_by_funcs_user_data (GSourceFuncs *funcs,
1917 g_return_val_if_fail (funcs != NULL, FALSE);
1919 source = g_main_context_find_source_by_funcs_user_data (NULL, funcs, user_data);
1922 g_source_destroy (source);
1930 * g_get_current_time:
1931 * @result: #GTimeVal structure in which to store current time.
1933 * Equivalent to the UNIX gettimeofday() function, but portable.
1935 * You may find g_get_real_time() to be more convenient.
1938 g_get_current_time (GTimeVal *result)
1943 g_return_if_fail (result != NULL);
1945 /*this is required on alpha, there the timeval structs are int's
1946 not longs and a cast only would fail horribly*/
1947 gettimeofday (&r, NULL);
1948 result->tv_sec = r.tv_sec;
1949 result->tv_usec = r.tv_usec;
1954 g_return_if_fail (result != NULL);
1956 GetSystemTimeAsFileTime (&ft);
1957 memmove (&time64, &ft, sizeof (FILETIME));
1959 /* Convert from 100s of nanoseconds since 1601-01-01
1960 * to Unix epoch. Yes, this is Y2038 unsafe.
1962 time64 -= G_GINT64_CONSTANT (116444736000000000);
1965 result->tv_sec = time64 / 1000000;
1966 result->tv_usec = time64 % 1000000;
1973 * Queries the system wall-clock time.
1975 * This call is functionally equivalent to g_get_current_time() except
1976 * that the return value is often more convenient than dealing with a
1979 * You should only use this call if you are actually interested in the real
1980 * wall-clock time. g_get_monotonic_time() is probably more useful for
1981 * measuring intervals.
1983 * Returns: the number of microseconds since January 1, 1970 UTC.
1988 g_get_real_time (void)
1992 g_get_current_time (&tv);
1994 return (((gint64) tv.tv_sec) * 1000000) + tv.tv_usec;
1998 * g_get_monotonic_time:
2000 * Queries the system monotonic time, if available.
2002 * On POSIX systems with clock_gettime() and %CLOCK_MONOTONIC this call
2003 * is a very shallow wrapper for that. Otherwise, we make a best effort
2004 * that probably involves returning the wall clock time (with at least
2005 * microsecond accuracy, subject to the limitations of the OS kernel).
2007 * It's important to note that POSIX %CLOCK_MONOTONIC does not count
2008 * time spent while the machine is suspended.
2010 * On Windows, "limitations of the OS kernel" is a rather substantial
2011 * statement. Depending on the configuration of the system, the wall
2012 * clock time is updated as infrequently as 64 times a second (which
2013 * is approximately every 16ms).
2015 * Returns: the monotonic time, in microseconds
2020 g_get_monotonic_time (void)
2022 #ifdef HAVE_CLOCK_GETTIME
2023 /* librt clock_gettime() is our first choice */
2025 #ifdef HAVE_MONOTONIC_CLOCK
2026 static volatile gsize clockid = 0;
2028 static clockid_t clockid = CLOCK_REALTIME;
2032 #ifdef HAVE_MONOTONIC_CLOCK
2033 if (g_once_init_enter (&clockid))
2035 clockid_t best_clockid;
2037 if (sysconf (_SC_MONOTONIC_CLOCK) >= 0)
2038 best_clockid = CLOCK_MONOTONIC;
2040 best_clockid = CLOCK_REALTIME;
2041 g_once_init_leave (&clockid, (gsize)best_clockid);
2045 clock_gettime (clockid, &ts);
2047 /* In theory monotonic time can have any epoch.
2049 * glib presently assumes the following:
2051 * 1) The epoch comes some time after the birth of Jesus of Nazareth, but
2052 * not more than 10000 years later.
2054 * 2) The current time also falls sometime within this range.
2056 * These two reasonable assumptions leave us with a maximum deviation from
2057 * the epoch of 10000 years, or 315569520000000000 seconds.
2059 * If we restrict ourselves to this range then the number of microseconds
2060 * will always fit well inside the constraints of a int64 (by a factor of
2063 * If you actually hit the following assertion, probably you should file a
2064 * bug against your operating system for being excessively silly.
2066 g_assert (G_GINT64_CONSTANT (-315569520000000000) < ts.tv_sec &&
2067 ts.tv_sec < G_GINT64_CONSTANT (315569520000000000));
2069 return (((gint64) ts.tv_sec) * 1000000) + (ts.tv_nsec / 1000);
2072 /* It may look like we are discarding accuracy on Windows (since its
2073 * current time is expressed in 100s of nanoseconds) but according to
2074 * many sources, the time is only updated 64 times per second, so
2075 * microsecond accuracy is more than enough.
2080 g_get_current_time (&tv);
2082 return (((gint64) tv.tv_sec) * 1000000) + tv.tv_usec;
2088 g_main_dispatch_free (gpointer dispatch)
2090 g_slice_free (GMainDispatch, dispatch);
2093 /* Running the main loop */
2095 static GMainDispatch *
2098 static GStaticPrivate depth_private = G_STATIC_PRIVATE_INIT;
2099 GMainDispatch *dispatch = g_static_private_get (&depth_private);
2102 dispatch = g_slice_new0 (GMainDispatch);
2103 g_static_private_set (&depth_private, dispatch, g_main_dispatch_free);
2112 * Returns the depth of the stack of calls to
2113 * g_main_context_dispatch() on any #GMainContext in the current thread.
2114 * That is, when called from the toplevel, it gives 0. When
2115 * called from within a callback from g_main_context_iteration()
2116 * (or g_main_loop_run(), etc.) it returns 1. When called from within
2117 * a callback to a recursive call to g_main_context_iteration(),
2118 * it returns 2. And so forth.
2120 * This function is useful in a situation like the following:
2121 * Imagine an extremely simple "garbage collected" system.
2124 * static GList *free_list;
2127 * allocate_memory (gsize size)
2129 * gpointer result = g_malloc (size);
2130 * free_list = g_list_prepend (free_list, result);
2135 * free_allocated_memory (void)
2138 * for (l = free_list; l; l = l->next);
2140 * g_list_free (free_list);
2148 * g_main_context_iteration (NULL, TRUE);
2149 * free_allocated_memory();
2153 * This works from an application, however, if you want to do the same
2154 * thing from a library, it gets more difficult, since you no longer
2155 * control the main loop. You might think you can simply use an idle
2156 * function to make the call to free_allocated_memory(), but that
2157 * doesn't work, since the idle function could be called from a
2158 * recursive callback. This can be fixed by using g_main_depth()
2162 * allocate_memory (gsize size)
2164 * FreeListBlock *block = g_new (FreeListBlock, 1);
2165 * block->mem = g_malloc (size);
2166 * block->depth = g_main_depth ();
2167 * free_list = g_list_prepend (free_list, block);
2168 * return block->mem;
2172 * free_allocated_memory (void)
2176 * int depth = g_main_depth ();
2177 * for (l = free_list; l; );
2179 * GList *next = l->next;
2180 * FreeListBlock *block = l->data;
2181 * if (block->depth > depth)
2183 * g_free (block->mem);
2185 * free_list = g_list_delete_link (free_list, l);
2193 * There is a temptation to use g_main_depth() to solve
2194 * problems with reentrancy. For instance, while waiting for data
2195 * to be received from the network in response to a menu item,
2196 * the menu item might be selected again. It might seem that
2197 * one could make the menu item's callback return immediately
2198 * and do nothing if g_main_depth() returns a value greater than 1.
2199 * However, this should be avoided since the user then sees selecting
2200 * the menu item do nothing. Furthermore, you'll find yourself adding
2201 * these checks all over your code, since there are doubtless many,
2202 * many things that the user could do. Instead, you can use the
2203 * following techniques:
2208 * Use gtk_widget_set_sensitive() or modal dialogs to prevent
2209 * the user from interacting with elements while the main
2210 * loop is recursing.
2215 * Avoid main loop recursion in situations where you can't handle
2216 * arbitrary callbacks. Instead, structure your code so that you
2217 * simply return to the main loop and then get called again when
2218 * there is more work to do.
2223 * Return value: The main loop recursion level in the current thread
2228 GMainDispatch *dispatch = get_dispatch ();
2229 return dispatch->depth;
2233 * g_main_current_source:
2235 * Returns the currently firing source for this thread.
2237 * Return value: (transfer none): The currently firing source or %NULL.
2242 g_main_current_source (void)
2244 GMainDispatch *dispatch = get_dispatch ();
2245 return dispatch->dispatching_sources ? dispatch->dispatching_sources->data : NULL;
2249 * g_source_is_destroyed:
2250 * @source: a #GSource
2252 * Returns whether @source has been destroyed.
2254 * This is important when you operate upon your objects
2255 * from within idle handlers, but may have freed the object
2256 * before the dispatch of your idle handler.
2260 * idle_callback (gpointer data)
2262 * SomeWidget *self = data;
2264 * GDK_THREADS_ENTER (<!-- -->);
2265 * /<!-- -->* do stuff with self *<!-- -->/
2266 * self->idle_id = 0;
2267 * GDK_THREADS_LEAVE (<!-- -->);
2273 * some_widget_do_stuff_later (SomeWidget *self)
2275 * self->idle_id = g_idle_add (idle_callback, self);
2279 * some_widget_finalize (GObject *object)
2281 * SomeWidget *self = SOME_WIDGET (object);
2283 * if (self->idle_id)
2284 * g_source_remove (self->idle_id);
2286 * G_OBJECT_CLASS (parent_class)->finalize (object);
2290 * This will fail in a multi-threaded application if the
2291 * widget is destroyed before the idle handler fires due
2292 * to the use after free in the callback. A solution, to
2293 * this particular problem, is to check to if the source
2294 * has already been destroy within the callback.
2298 * idle_callback (gpointer data)
2300 * SomeWidget *self = data;
2302 * GDK_THREADS_ENTER ();
2303 * if (!g_source_is_destroyed (g_main_current_source ()))
2305 * /<!-- -->* do stuff with self *<!-- -->/
2307 * GDK_THREADS_LEAVE ();
2313 * Return value: %TRUE if the source has been destroyed
2318 g_source_is_destroyed (GSource *source)
2320 return SOURCE_DESTROYED (source);
2323 /* Temporarily remove all this source's file descriptors from the
2324 * poll(), so that if data comes available for one of the file descriptors
2325 * we don't continually spin in the poll()
2327 /* HOLDS: source->context's lock */
2329 block_source (GSource *source)
2333 g_return_if_fail (!SOURCE_BLOCKED (source));
2335 tmp_list = source->poll_fds;
2338 g_main_context_remove_poll_unlocked (source->context, tmp_list->data);
2339 tmp_list = tmp_list->next;
2343 /* HOLDS: source->context's lock */
2345 unblock_source (GSource *source)
2349 g_return_if_fail (!SOURCE_BLOCKED (source)); /* Source already unblocked */
2350 g_return_if_fail (!SOURCE_DESTROYED (source));
2352 tmp_list = source->poll_fds;
2355 g_main_context_add_poll_unlocked (source->context, source->priority, tmp_list->data);
2356 tmp_list = tmp_list->next;
2360 /* HOLDS: context's lock */
2362 g_main_dispatch (GMainContext *context)
2364 GMainDispatch *current = get_dispatch ();
2367 for (i = 0; i < context->pending_dispatches->len; i++)
2369 GSource *source = context->pending_dispatches->pdata[i];
2371 context->pending_dispatches->pdata[i] = NULL;
2374 source->flags &= ~G_SOURCE_READY;
2376 if (!SOURCE_DESTROYED (source))
2378 gboolean was_in_call;
2379 gpointer user_data = NULL;
2380 GSourceFunc callback = NULL;
2381 GSourceCallbackFuncs *cb_funcs;
2383 gboolean need_destroy;
2385 gboolean (*dispatch) (GSource *,
2388 GSList current_source_link;
2390 dispatch = source->source_funcs->dispatch;
2391 cb_funcs = source->callback_funcs;
2392 cb_data = source->callback_data;
2395 cb_funcs->ref (cb_data);
2397 if ((source->flags & G_SOURCE_CAN_RECURSE) == 0)
2398 block_source (source);
2400 was_in_call = source->flags & G_HOOK_FLAG_IN_CALL;
2401 source->flags |= G_HOOK_FLAG_IN_CALL;
2404 cb_funcs->get (cb_data, source, &callback, &user_data);
2406 UNLOCK_CONTEXT (context);
2409 /* The on-stack allocation of the GSList is unconventional, but
2410 * we know that the lifetime of the link is bounded to this
2411 * function as the link is kept in a thread specific list and
2412 * not manipulated outside of this function and its descendants.
2413 * Avoiding the overhead of a g_slist_alloc() is useful as many
2414 * applications do little more than dispatch events.
2416 * This is a performance hack - do not revert to g_slist_prepend()!
2418 current_source_link.data = source;
2419 current_source_link.next = current->dispatching_sources;
2420 current->dispatching_sources = ¤t_source_link;
2421 need_destroy = ! dispatch (source,
2424 g_assert (current->dispatching_sources == ¤t_source_link);
2425 current->dispatching_sources = current_source_link.next;
2429 cb_funcs->unref (cb_data);
2431 LOCK_CONTEXT (context);
2434 source->flags &= ~G_HOOK_FLAG_IN_CALL;
2436 if ((source->flags & G_SOURCE_CAN_RECURSE) == 0 &&
2437 !SOURCE_DESTROYED (source))
2438 unblock_source (source);
2440 /* Note: this depends on the fact that we can't switch
2441 * sources from one main context to another
2443 if (need_destroy && !SOURCE_DESTROYED (source))
2445 g_assert (source->context == context);
2446 g_source_destroy_internal (source, context, TRUE);
2450 SOURCE_UNREF (source, context);
2453 g_ptr_array_set_size (context->pending_dispatches, 0);
2456 /* Holds context's lock */
2457 static inline GSource *
2458 next_valid_source (GMainContext *context,
2461 GSource *new_source = source ? source->next : context->source_list;
2465 if (!SOURCE_DESTROYED (new_source))
2467 new_source->ref_count++;
2471 new_source = new_source->next;
2475 SOURCE_UNREF (source, context);
2481 * g_main_context_acquire:
2482 * @context: a #GMainContext
2484 * Tries to become the owner of the specified context.
2485 * If some other thread is the owner of the context,
2486 * returns %FALSE immediately. Ownership is properly
2487 * recursive: the owner can require ownership again
2488 * and will release ownership when g_main_context_release()
2489 * is called as many times as g_main_context_acquire().
2491 * You must be the owner of a context before you
2492 * can call g_main_context_prepare(), g_main_context_query(),
2493 * g_main_context_check(), g_main_context_dispatch().
2495 * Return value: %TRUE if the operation succeeded, and
2496 * this thread is now the owner of @context.
2499 g_main_context_acquire (GMainContext *context)
2501 gboolean result = FALSE;
2502 GThread *self = G_THREAD_SELF;
2504 if (context == NULL)
2505 context = g_main_context_default ();
2507 LOCK_CONTEXT (context);
2509 if (!context->owner)
2511 context->owner = self;
2512 g_assert (context->owner_count == 0);
2515 if (context->owner == self)
2517 context->owner_count++;
2521 UNLOCK_CONTEXT (context);
2527 * g_main_context_release:
2528 * @context: a #GMainContext
2530 * Releases ownership of a context previously acquired by this thread
2531 * with g_main_context_acquire(). If the context was acquired multiple
2532 * times, the ownership will be released only when g_main_context_release()
2533 * is called as many times as it was acquired.
2536 g_main_context_release (GMainContext *context)
2538 if (context == NULL)
2539 context = g_main_context_default ();
2541 LOCK_CONTEXT (context);
2543 context->owner_count--;
2544 if (context->owner_count == 0)
2546 context->owner = NULL;
2548 if (context->waiters)
2550 GMainWaiter *waiter = context->waiters->data;
2551 gboolean loop_internal_waiter =
2552 (waiter->mutex == g_static_mutex_get_mutex (&context->mutex));
2553 context->waiters = g_slist_delete_link (context->waiters,
2555 if (!loop_internal_waiter)
2556 g_mutex_lock (waiter->mutex);
2558 g_cond_signal (waiter->cond);
2560 if (!loop_internal_waiter)
2561 g_mutex_unlock (waiter->mutex);
2565 UNLOCK_CONTEXT (context);
2569 * g_main_context_wait:
2570 * @context: a #GMainContext
2571 * @cond: a condition variable
2572 * @mutex: a mutex, currently held
2574 * Tries to become the owner of the specified context,
2575 * as with g_main_context_acquire(). But if another thread
2576 * is the owner, atomically drop @mutex and wait on @cond until
2577 * that owner releases ownership or until @cond is signaled, then
2578 * try again (once) to become the owner.
2580 * Return value: %TRUE if the operation succeeded, and
2581 * this thread is now the owner of @context.
2584 g_main_context_wait (GMainContext *context,
2588 gboolean result = FALSE;
2589 GThread *self = G_THREAD_SELF;
2590 gboolean loop_internal_waiter;
2592 if (context == NULL)
2593 context = g_main_context_default ();
2595 loop_internal_waiter = (mutex == g_static_mutex_get_mutex (&context->mutex));
2597 if (!loop_internal_waiter)
2598 LOCK_CONTEXT (context);
2600 if (context->owner && context->owner != self)
2605 waiter.mutex = mutex;
2607 context->waiters = g_slist_append (context->waiters, &waiter);
2609 if (!loop_internal_waiter)
2610 UNLOCK_CONTEXT (context);
2611 g_cond_wait (cond, mutex);
2612 if (!loop_internal_waiter)
2613 LOCK_CONTEXT (context);
2615 context->waiters = g_slist_remove (context->waiters, &waiter);
2618 if (!context->owner)
2620 context->owner = self;
2621 g_assert (context->owner_count == 0);
2624 if (context->owner == self)
2626 context->owner_count++;
2630 if (!loop_internal_waiter)
2631 UNLOCK_CONTEXT (context);
2637 * g_main_context_prepare:
2638 * @context: a #GMainContext
2639 * @priority: location to store priority of highest priority
2640 * source already ready.
2642 * Prepares to poll sources within a main loop. The resulting information
2643 * for polling is determined by calling g_main_context_query ().
2645 * Return value: %TRUE if some source is ready to be dispatched
2649 g_main_context_prepare (GMainContext *context,
2654 gint current_priority = G_MAXINT;
2657 if (context == NULL)
2658 context = g_main_context_default ();
2660 LOCK_CONTEXT (context);
2662 context->time_is_fresh = FALSE;
2663 context->real_time_is_fresh = FALSE;
2665 if (context->in_check_or_prepare)
2667 g_warning ("g_main_context_prepare() called recursively from within a source's check() or "
2668 "prepare() member.");
2669 UNLOCK_CONTEXT (context);
2673 if (context->poll_waiting)
2675 g_warning("g_main_context_prepare(): main loop already active in another thread");
2676 UNLOCK_CONTEXT (context);
2680 context->poll_waiting = TRUE;
2683 /* If recursing, finish up current dispatch, before starting over */
2684 if (context->pending_dispatches)
2687 g_main_dispatch (context, ¤t_time);
2689 UNLOCK_CONTEXT (context);
2694 /* If recursing, clear list of pending dispatches */
2696 for (i = 0; i < context->pending_dispatches->len; i++)
2698 if (context->pending_dispatches->pdata[i])
2699 SOURCE_UNREF ((GSource *)context->pending_dispatches->pdata[i], context);
2701 g_ptr_array_set_size (context->pending_dispatches, 0);
2703 /* Prepare all sources */
2705 context->timeout = -1;
2707 source = next_valid_source (context, NULL);
2710 gint source_timeout = -1;
2712 if ((n_ready > 0) && (source->priority > current_priority))
2714 SOURCE_UNREF (source, context);
2717 if (SOURCE_BLOCKED (source))
2720 if (!(source->flags & G_SOURCE_READY))
2723 gboolean (*prepare) (GSource *source,
2726 prepare = source->source_funcs->prepare;
2727 context->in_check_or_prepare++;
2728 UNLOCK_CONTEXT (context);
2730 result = (*prepare) (source, &source_timeout);
2732 LOCK_CONTEXT (context);
2733 context->in_check_or_prepare--;
2737 GSource *ready_source = source;
2739 while (ready_source)
2741 ready_source->flags |= G_SOURCE_READY;
2742 ready_source = ready_source->priv ? ready_source->priv->parent_source : NULL;
2747 if (source->flags & G_SOURCE_READY)
2750 current_priority = source->priority;
2751 context->timeout = 0;
2754 if (source_timeout >= 0)
2756 if (context->timeout < 0)
2757 context->timeout = source_timeout;
2759 context->timeout = MIN (context->timeout, source_timeout);
2763 source = next_valid_source (context, source);
2766 UNLOCK_CONTEXT (context);
2769 *priority = current_priority;
2771 return (n_ready > 0);
2775 * g_main_context_query:
2776 * @context: a #GMainContext
2777 * @max_priority: maximum priority source to check
2778 * @timeout_: (out): location to store timeout to be used in polling
2779 * @fds: (out caller-allocates) (array length=n_fds): location to
2780 * store #GPollFD records that need to be polled.
2781 * @n_fds: length of @fds.
2783 * Determines information necessary to poll this main loop.
2785 * Return value: the number of records actually stored in @fds,
2786 * or, if more than @n_fds records need to be stored, the number
2787 * of records that need to be stored.
2790 g_main_context_query (GMainContext *context,
2799 LOCK_CONTEXT (context);
2801 pollrec = context->poll_records;
2803 while (pollrec && max_priority >= pollrec->priority)
2805 /* We need to include entries with fd->events == 0 in the array because
2806 * otherwise if the application changes fd->events behind our back and
2807 * makes it non-zero, we'll be out of sync when we check the fds[] array.
2808 * (Changing fd->events after adding an FD wasn't an anticipated use of
2809 * this API, but it occurs in practice.) */
2812 fds[n_poll].fd = pollrec->fd->fd;
2813 /* In direct contradiction to the Unix98 spec, IRIX runs into
2814 * difficulty if you pass in POLLERR, POLLHUP or POLLNVAL
2815 * flags in the events field of the pollfd while it should
2816 * just ignoring them. So we mask them out here.
2818 fds[n_poll].events = pollrec->fd->events & ~(G_IO_ERR|G_IO_HUP|G_IO_NVAL);
2819 fds[n_poll].revents = 0;
2822 pollrec = pollrec->next;
2826 context->poll_changed = FALSE;
2830 *timeout = context->timeout;
2833 context->time_is_fresh = FALSE;
2834 context->real_time_is_fresh = FALSE;
2838 UNLOCK_CONTEXT (context);
2844 * g_main_context_check:
2845 * @context: a #GMainContext
2846 * @max_priority: the maximum numerical priority of sources to check
2847 * @fds: (array length=n_fds): array of #GPollFD's that was passed to
2848 * the last call to g_main_context_query()
2849 * @n_fds: return value of g_main_context_query()
2851 * Passes the results of polling back to the main loop.
2853 * Return value: %TRUE if some sources are ready to be dispatched.
2856 g_main_context_check (GMainContext *context,
2866 LOCK_CONTEXT (context);
2868 if (context->in_check_or_prepare)
2870 g_warning ("g_main_context_check() called recursively from within a source's check() or "
2871 "prepare() member.");
2872 UNLOCK_CONTEXT (context);
2876 if (!context->poll_waiting)
2877 g_wakeup_acknowledge (context->wakeup);
2880 context->poll_waiting = FALSE;
2882 /* If the set of poll file descriptors changed, bail out
2883 * and let the main loop rerun
2885 if (context->poll_changed)
2887 UNLOCK_CONTEXT (context);
2891 pollrec = context->poll_records;
2895 if (pollrec->fd->events)
2896 pollrec->fd->revents = fds[i].revents;
2898 pollrec = pollrec->next;
2902 source = next_valid_source (context, NULL);
2905 if ((n_ready > 0) && (source->priority > max_priority))
2907 SOURCE_UNREF (source, context);
2910 if (SOURCE_BLOCKED (source))
2913 if (!(source->flags & G_SOURCE_READY))
2916 gboolean (*check) (GSource *source);
2918 check = source->source_funcs->check;
2920 context->in_check_or_prepare++;
2921 UNLOCK_CONTEXT (context);
2923 result = (*check) (source);
2925 LOCK_CONTEXT (context);
2926 context->in_check_or_prepare--;
2930 GSource *ready_source = source;
2932 while (ready_source)
2934 ready_source->flags |= G_SOURCE_READY;
2935 ready_source = ready_source->priv ? ready_source->priv->parent_source : NULL;
2940 if (source->flags & G_SOURCE_READY)
2942 source->ref_count++;
2943 g_ptr_array_add (context->pending_dispatches, source);
2947 /* never dispatch sources with less priority than the first
2948 * one we choose to dispatch
2950 max_priority = source->priority;
2954 source = next_valid_source (context, source);
2957 UNLOCK_CONTEXT (context);
2963 * g_main_context_dispatch:
2964 * @context: a #GMainContext
2966 * Dispatches all pending sources.
2969 g_main_context_dispatch (GMainContext *context)
2971 LOCK_CONTEXT (context);
2973 if (context->pending_dispatches->len > 0)
2975 g_main_dispatch (context);
2978 UNLOCK_CONTEXT (context);
2981 /* HOLDS context lock */
2983 g_main_context_iterate (GMainContext *context,
2990 gboolean some_ready;
2991 gint nfds, allocated_nfds;
2992 GPollFD *fds = NULL;
2994 UNLOCK_CONTEXT (context);
2996 if (!g_main_context_acquire (context))
2998 gboolean got_ownership;
3000 LOCK_CONTEXT (context);
3002 g_return_val_if_fail (g_thread_supported (), FALSE);
3008 context->cond = g_cond_new ();
3010 got_ownership = g_main_context_wait (context,
3012 g_static_mutex_get_mutex (&context->mutex));
3018 LOCK_CONTEXT (context);
3020 if (!context->cached_poll_array)
3022 context->cached_poll_array_size = context->n_poll_records;
3023 context->cached_poll_array = g_new (GPollFD, context->n_poll_records);
3026 allocated_nfds = context->cached_poll_array_size;
3027 fds = context->cached_poll_array;
3029 UNLOCK_CONTEXT (context);
3031 g_main_context_prepare (context, &max_priority);
3033 while ((nfds = g_main_context_query (context, max_priority, &timeout, fds,
3034 allocated_nfds)) > allocated_nfds)
3036 LOCK_CONTEXT (context);
3038 context->cached_poll_array_size = allocated_nfds = nfds;
3039 context->cached_poll_array = fds = g_new (GPollFD, nfds);
3040 UNLOCK_CONTEXT (context);
3046 g_main_context_poll (context, timeout, max_priority, fds, nfds);
3048 some_ready = g_main_context_check (context, max_priority, fds, nfds);
3051 g_main_context_dispatch (context);
3053 g_main_context_release (context);
3055 LOCK_CONTEXT (context);
3061 * g_main_context_pending:
3062 * @context: a #GMainContext (if %NULL, the default context will be used)
3064 * Checks if any sources have pending events for the given context.
3066 * Return value: %TRUE if events are pending.
3069 g_main_context_pending (GMainContext *context)
3074 context = g_main_context_default();
3076 LOCK_CONTEXT (context);
3077 retval = g_main_context_iterate (context, FALSE, FALSE, G_THREAD_SELF);
3078 UNLOCK_CONTEXT (context);
3084 * g_main_context_iteration:
3085 * @context: a #GMainContext (if %NULL, the default context will be used)
3086 * @may_block: whether the call may block.
3088 * Runs a single iteration for the given main loop. This involves
3089 * checking to see if any event sources are ready to be processed,
3090 * then if no events sources are ready and @may_block is %TRUE, waiting
3091 * for a source to become ready, then dispatching the highest priority
3092 * events sources that are ready. Otherwise, if @may_block is %FALSE
3093 * sources are not waited to become ready, only those highest priority
3094 * events sources will be dispatched (if any), that are ready at this
3095 * given moment without further waiting.
3097 * Note that even when @may_block is %TRUE, it is still possible for
3098 * g_main_context_iteration() to return %FALSE, since the the wait may
3099 * be interrupted for other reasons than an event source becoming ready.
3101 * Return value: %TRUE if events were dispatched.
3104 g_main_context_iteration (GMainContext *context, gboolean may_block)
3109 context = g_main_context_default();
3111 LOCK_CONTEXT (context);
3112 retval = g_main_context_iterate (context, may_block, TRUE, G_THREAD_SELF);
3113 UNLOCK_CONTEXT (context);
3120 * @context: (allow-none): a #GMainContext (if %NULL, the default context will be used).
3121 * @is_running: set to %TRUE to indicate that the loop is running. This
3122 * is not very important since calling g_main_loop_run() will set this to
3125 * Creates a new #GMainLoop structure.
3127 * Return value: a new #GMainLoop.
3130 g_main_loop_new (GMainContext *context,
3131 gboolean is_running)
3136 context = g_main_context_default();
3138 g_main_context_ref (context);
3140 loop = g_new0 (GMainLoop, 1);
3141 loop->context = context;
3142 loop->is_running = is_running != FALSE;
3143 loop->ref_count = 1;
3150 * @loop: a #GMainLoop
3152 * Increases the reference count on a #GMainLoop object by one.
3154 * Return value: @loop
3157 g_main_loop_ref (GMainLoop *loop)
3159 g_return_val_if_fail (loop != NULL, NULL);
3160 g_return_val_if_fail (g_atomic_int_get (&loop->ref_count) > 0, NULL);
3162 g_atomic_int_inc (&loop->ref_count);
3168 * g_main_loop_unref:
3169 * @loop: a #GMainLoop
3171 * Decreases the reference count on a #GMainLoop object by one. If
3172 * the result is zero, free the loop and free all associated memory.
3175 g_main_loop_unref (GMainLoop *loop)
3177 g_return_if_fail (loop != NULL);
3178 g_return_if_fail (g_atomic_int_get (&loop->ref_count) > 0);
3180 if (!g_atomic_int_dec_and_test (&loop->ref_count))
3183 g_main_context_unref (loop->context);
3189 * @loop: a #GMainLoop
3191 * Runs a main loop until g_main_loop_quit() is called on the loop.
3192 * If this is called for the thread of the loop's #GMainContext,
3193 * it will process events from the loop, otherwise it will
3197 g_main_loop_run (GMainLoop *loop)
3199 GThread *self = G_THREAD_SELF;
3201 g_return_if_fail (loop != NULL);
3202 g_return_if_fail (g_atomic_int_get (&loop->ref_count) > 0);
3204 if (!g_main_context_acquire (loop->context))
3206 gboolean got_ownership = FALSE;
3208 /* Another thread owns this context */
3209 if (!g_thread_supported ())
3211 g_warning ("g_main_loop_run() was called from second thread but "
3212 "g_thread_init() was never called.");
3216 LOCK_CONTEXT (loop->context);
3218 g_atomic_int_inc (&loop->ref_count);
3220 if (!loop->is_running)
3221 loop->is_running = TRUE;
3223 if (!loop->context->cond)
3224 loop->context->cond = g_cond_new ();
3226 while (loop->is_running && !got_ownership)
3227 got_ownership = g_main_context_wait (loop->context,
3228 loop->context->cond,
3229 g_static_mutex_get_mutex (&loop->context->mutex));
3231 if (!loop->is_running)
3233 UNLOCK_CONTEXT (loop->context);
3235 g_main_context_release (loop->context);
3236 g_main_loop_unref (loop);
3240 g_assert (got_ownership);
3243 LOCK_CONTEXT (loop->context);
3245 if (loop->context->in_check_or_prepare)
3247 g_warning ("g_main_loop_run(): called recursively from within a source's "
3248 "check() or prepare() member, iteration not possible.");
3252 g_atomic_int_inc (&loop->ref_count);
3253 loop->is_running = TRUE;
3254 while (loop->is_running)
3255 g_main_context_iterate (loop->context, TRUE, TRUE, self);
3257 UNLOCK_CONTEXT (loop->context);
3259 g_main_context_release (loop->context);
3261 g_main_loop_unref (loop);
3266 * @loop: a #GMainLoop
3268 * Stops a #GMainLoop from running. Any calls to g_main_loop_run()
3269 * for the loop will return.
3271 * Note that sources that have already been dispatched when
3272 * g_main_loop_quit() is called will still be executed.
3275 g_main_loop_quit (GMainLoop *loop)
3277 g_return_if_fail (loop != NULL);
3278 g_return_if_fail (g_atomic_int_get (&loop->ref_count) > 0);
3280 LOCK_CONTEXT (loop->context);
3281 loop->is_running = FALSE;
3282 g_main_context_wakeup_unlocked (loop->context);
3284 if (loop->context->cond)
3285 g_cond_broadcast (loop->context->cond);
3287 UNLOCK_CONTEXT (loop->context);
3291 * g_main_loop_is_running:
3292 * @loop: a #GMainLoop.
3294 * Checks to see if the main loop is currently being run via g_main_loop_run().
3296 * Return value: %TRUE if the mainloop is currently being run.
3299 g_main_loop_is_running (GMainLoop *loop)
3301 g_return_val_if_fail (loop != NULL, FALSE);
3302 g_return_val_if_fail (g_atomic_int_get (&loop->ref_count) > 0, FALSE);
3304 return loop->is_running;
3308 * g_main_loop_get_context:
3309 * @loop: a #GMainLoop.
3311 * Returns the #GMainContext of @loop.
3313 * Return value: (transfer none): the #GMainContext of @loop
3316 g_main_loop_get_context (GMainLoop *loop)
3318 g_return_val_if_fail (loop != NULL, NULL);
3319 g_return_val_if_fail (g_atomic_int_get (&loop->ref_count) > 0, NULL);
3321 return loop->context;
3324 /* HOLDS: context's lock */
3326 g_main_context_poll (GMainContext *context,
3332 #ifdef G_MAIN_POLL_DEBUG
3338 GPollFunc poll_func;
3340 if (n_fds || timeout != 0)
3342 #ifdef G_MAIN_POLL_DEBUG
3343 if (_g_main_poll_debug)
3345 g_print ("polling context=%p n=%d timeout=%d\n",
3346 context, n_fds, timeout);
3347 poll_timer = g_timer_new ();
3351 LOCK_CONTEXT (context);
3353 poll_func = context->poll_func;
3355 UNLOCK_CONTEXT (context);
3356 if ((*poll_func) (fds, n_fds, timeout) < 0 && errno != EINTR)
3359 g_warning ("poll(2) failed due to: %s.",
3360 g_strerror (errno));
3362 /* If g_poll () returns -1, it has already called g_warning() */
3366 #ifdef G_MAIN_POLL_DEBUG
3367 if (_g_main_poll_debug)
3369 LOCK_CONTEXT (context);
3371 g_print ("g_main_poll(%d) timeout: %d - elapsed %12.10f seconds",
3374 g_timer_elapsed (poll_timer, NULL));
3375 g_timer_destroy (poll_timer);
3376 pollrec = context->poll_records;
3378 while (pollrec != NULL)
3383 if (fds[i].fd == pollrec->fd->fd &&
3384 pollrec->fd->events &&
3387 g_print (" [" G_POLLFD_FORMAT " :", fds[i].fd);
3388 if (fds[i].revents & G_IO_IN)
3390 if (fds[i].revents & G_IO_OUT)
3392 if (fds[i].revents & G_IO_PRI)
3394 if (fds[i].revents & G_IO_ERR)
3396 if (fds[i].revents & G_IO_HUP)
3398 if (fds[i].revents & G_IO_NVAL)
3404 pollrec = pollrec->next;
3408 UNLOCK_CONTEXT (context);
3411 } /* if (n_fds || timeout != 0) */
3415 * g_main_context_add_poll:
3416 * @context: a #GMainContext (or %NULL for the default context)
3417 * @fd: a #GPollFD structure holding information about a file
3418 * descriptor to watch.
3419 * @priority: the priority for this file descriptor which should be
3420 * the same as the priority used for g_source_attach() to ensure that the
3421 * file descriptor is polled whenever the results may be needed.
3423 * Adds a file descriptor to the set of file descriptors polled for
3424 * this context. This will very seldom be used directly. Instead
3425 * a typical event source will use g_source_add_poll() instead.
3428 g_main_context_add_poll (GMainContext *context,
3433 context = g_main_context_default ();
3435 g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
3436 g_return_if_fail (fd);
3438 LOCK_CONTEXT (context);
3439 g_main_context_add_poll_unlocked (context, priority, fd);
3440 UNLOCK_CONTEXT (context);
3443 /* HOLDS: main_loop_lock */
3445 g_main_context_add_poll_unlocked (GMainContext *context,
3449 GPollRec *prevrec, *nextrec;
3450 GPollRec *newrec = g_slice_new (GPollRec);
3452 /* This file descriptor may be checked before we ever poll */
3455 newrec->priority = priority;
3457 prevrec = context->poll_records_tail;
3459 while (prevrec && priority < prevrec->priority)
3462 prevrec = prevrec->prev;
3466 prevrec->next = newrec;
3468 context->poll_records = newrec;
3470 newrec->prev = prevrec;
3471 newrec->next = nextrec;
3474 nextrec->prev = newrec;
3476 context->poll_records_tail = newrec;
3478 context->n_poll_records++;
3480 context->poll_changed = TRUE;
3482 /* Now wake up the main loop if it is waiting in the poll() */
3483 g_main_context_wakeup_unlocked (context);
3487 * g_main_context_remove_poll:
3488 * @context:a #GMainContext
3489 * @fd: a #GPollFD descriptor previously added with g_main_context_add_poll()
3491 * Removes file descriptor from the set of file descriptors to be
3492 * polled for a particular context.
3495 g_main_context_remove_poll (GMainContext *context,
3499 context = g_main_context_default ();
3501 g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
3502 g_return_if_fail (fd);
3504 LOCK_CONTEXT (context);
3505 g_main_context_remove_poll_unlocked (context, fd);
3506 UNLOCK_CONTEXT (context);
3510 g_main_context_remove_poll_unlocked (GMainContext *context,
3513 GPollRec *pollrec, *prevrec, *nextrec;
3516 pollrec = context->poll_records;
3520 nextrec = pollrec->next;
3521 if (pollrec->fd == fd)
3523 if (prevrec != NULL)
3524 prevrec->next = nextrec;
3526 context->poll_records = nextrec;
3528 if (nextrec != NULL)
3529 nextrec->prev = prevrec;
3531 context->poll_records_tail = prevrec;
3533 g_slice_free (GPollRec, pollrec);
3535 context->n_poll_records--;
3542 context->poll_changed = TRUE;
3544 /* Now wake up the main loop if it is waiting in the poll() */
3545 g_main_context_wakeup_unlocked (context);
3549 * g_source_get_current_time:
3550 * @source: a #GSource
3551 * @timeval: #GTimeVal structure in which to store current time.
3553 * Gets the "current time" to be used when checking
3554 * this source. The advantage of calling this function over
3555 * calling g_get_current_time() directly is that when
3556 * checking multiple sources, GLib can cache a single value
3557 * instead of having to repeatedly get the system time.
3559 * Deprecated: 2.28: use g_source_get_time() instead
3562 g_source_get_current_time (GSource *source,
3565 GMainContext *context;
3567 g_return_if_fail (source->context != NULL);
3569 context = source->context;
3571 LOCK_CONTEXT (context);
3573 if (!context->real_time_is_fresh)
3575 context->real_time = g_get_real_time ();
3576 context->real_time_is_fresh = TRUE;
3579 timeval->tv_sec = context->real_time / 1000000;
3580 timeval->tv_usec = context->real_time % 1000000;
3582 UNLOCK_CONTEXT (context);
3586 * g_source_get_time:
3587 * @source: a #GSource
3589 * Gets the time to be used when checking this source. The advantage of
3590 * calling this function over calling g_get_monotonic_time() directly is
3591 * that when checking multiple sources, GLib can cache a single value
3592 * instead of having to repeatedly get the system monotonic time.
3594 * The time here is the system monotonic time, if available, or some
3595 * other reasonable alternative otherwise. See g_get_monotonic_time().
3597 * Returns: the monotonic time in microseconds
3602 g_source_get_time (GSource *source)
3604 GMainContext *context;
3607 g_return_val_if_fail (source->context != NULL, 0);
3609 context = source->context;
3611 LOCK_CONTEXT (context);
3613 if (!context->time_is_fresh)
3615 context->time = g_get_monotonic_time ();
3616 context->time_is_fresh = TRUE;
3619 result = context->time;
3621 UNLOCK_CONTEXT (context);
3627 * g_main_context_set_poll_func:
3628 * @context: a #GMainContext
3629 * @func: the function to call to poll all file descriptors
3631 * Sets the function to use to handle polling of file descriptors. It
3632 * will be used instead of the poll() system call
3633 * (or GLib's replacement function, which is used where
3634 * poll() isn't available).
3636 * This function could possibly be used to integrate the GLib event
3637 * loop with an external event loop.
3640 g_main_context_set_poll_func (GMainContext *context,
3644 context = g_main_context_default ();
3646 g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
3648 LOCK_CONTEXT (context);
3651 context->poll_func = func;
3653 context->poll_func = g_poll;
3655 UNLOCK_CONTEXT (context);
3659 * g_main_context_get_poll_func:
3660 * @context: a #GMainContext
3662 * Gets the poll function set by g_main_context_set_poll_func().
3664 * Return value: the poll function
3667 g_main_context_get_poll_func (GMainContext *context)
3672 context = g_main_context_default ();
3674 g_return_val_if_fail (g_atomic_int_get (&context->ref_count) > 0, NULL);
3676 LOCK_CONTEXT (context);
3677 result = context->poll_func;
3678 UNLOCK_CONTEXT (context);
3684 _g_main_wake_up_all_contexts (void)
3688 /* We were woken up. Wake up all other contexts in all other threads */
3689 G_LOCK (main_context_list);
3690 for (list = main_context_list; list; list = list->next)
3692 GMainContext *context = list->data;
3694 LOCK_CONTEXT (context);
3695 g_main_context_wakeup_unlocked (context);
3696 UNLOCK_CONTEXT (context);
3698 G_UNLOCK (main_context_list);
3702 /* HOLDS: context's lock */
3703 /* Wake the main loop up from a poll() */
3705 g_main_context_wakeup_unlocked (GMainContext *context)
3707 if (g_thread_supported() && context->poll_waiting)
3709 context->poll_waiting = FALSE;
3710 g_wakeup_signal (context->wakeup);
3715 * g_main_context_wakeup:
3716 * @context: a #GMainContext
3718 * If @context is currently waiting in a poll(), interrupt
3719 * the poll(), and continue the iteration process.
3722 g_main_context_wakeup (GMainContext *context)
3725 context = g_main_context_default ();
3727 g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
3729 LOCK_CONTEXT (context);
3730 g_main_context_wakeup_unlocked (context);
3731 UNLOCK_CONTEXT (context);
3735 * g_main_context_is_owner:
3736 * @context: a #GMainContext
3738 * Determines whether this thread holds the (recursive)
3739 * ownership of this #GMainContext. This is useful to
3740 * know before waiting on another thread that may be
3741 * blocking to get ownership of @context.
3743 * Returns: %TRUE if current thread is owner of @context.
3748 g_main_context_is_owner (GMainContext *context)
3753 context = g_main_context_default ();
3755 LOCK_CONTEXT (context);
3756 is_owner = context->owner == G_THREAD_SELF;
3757 UNLOCK_CONTEXT (context);
3765 g_timeout_set_expiration (GTimeoutSource *timeout_source,
3766 gint64 current_time)
3768 timeout_source->expiration = current_time +
3769 (guint64) timeout_source->interval * 1000;
3771 if (timeout_source->seconds)
3774 static gint timer_perturb = -1;
3776 if (timer_perturb == -1)
3779 * we want a per machine/session unique 'random' value; try the dbus
3780 * address first, that has a UUID in it. If there is no dbus, use the
3781 * hostname for hashing.
3783 const char *session_bus_address = g_getenv ("DBUS_SESSION_BUS_ADDRESS");
3784 if (!session_bus_address)
3785 session_bus_address = g_getenv ("HOSTNAME");
3786 if (session_bus_address)
3787 timer_perturb = ABS ((gint) g_str_hash (session_bus_address)) % 1000000;
3792 /* We want the microseconds part of the timeout to land on the
3793 * 'timer_perturb' mark, but we need to make sure we don't try to
3794 * set the timeout in the past. We do this by ensuring that we
3795 * always only *increase* the expiration time by adding a full
3796 * second in the case that the microsecond portion decreases.
3798 timeout_source->expiration -= timer_perturb;
3800 remainder = timeout_source->expiration % 1000000;
3801 if (remainder >= 1000000/4)
3802 timeout_source->expiration += 1000000;
3804 timeout_source->expiration -= remainder;
3805 timeout_source->expiration += timer_perturb;
3810 g_timeout_prepare (GSource *source,
3813 GTimeoutSource *timeout_source = (GTimeoutSource *) source;
3814 gint64 now = g_source_get_time (source);
3816 if (now < timeout_source->expiration)
3818 /* Round up to ensure that we don't try again too early */
3819 *timeout = (timeout_source->expiration - now + 999) / 1000;
3828 g_timeout_check (GSource *source)
3830 GTimeoutSource *timeout_source = (GTimeoutSource *) source;
3831 gint64 now = g_source_get_time (source);
3833 return timeout_source->expiration <= now;
3837 g_timeout_dispatch (GSource *source,
3838 GSourceFunc callback,
3841 GTimeoutSource *timeout_source = (GTimeoutSource *)source;
3846 g_warning ("Timeout source dispatched without callback\n"
3847 "You must call g_source_set_callback().");
3851 again = callback (user_data);
3854 g_timeout_set_expiration (timeout_source, g_source_get_time (source));
3860 * g_timeout_source_new:
3861 * @interval: the timeout interval in milliseconds.
3863 * Creates a new timeout source.
3865 * The source will not initially be associated with any #GMainContext
3866 * and must be added to one with g_source_attach() before it will be
3869 * The interval given is in terms of monotonic time, not wall clock
3870 * time. See g_get_monotonic_time().
3872 * Return value: the newly-created timeout source
3875 g_timeout_source_new (guint interval)
3877 GSource *source = g_source_new (&g_timeout_funcs, sizeof (GTimeoutSource));
3878 GTimeoutSource *timeout_source = (GTimeoutSource *)source;
3880 timeout_source->interval = interval;
3881 g_timeout_set_expiration (timeout_source, g_get_monotonic_time ());
3887 * g_timeout_source_new_seconds:
3888 * @interval: the timeout interval in seconds
3890 * Creates a new timeout source.
3892 * The source will not initially be associated with any #GMainContext
3893 * and must be added to one with g_source_attach() before it will be
3896 * The scheduling granularity/accuracy of this timeout source will be
3899 * The interval given in terms of monotonic time, not wall clock time.
3900 * See g_get_monotonic_time().
3902 * Return value: the newly-created timeout source
3907 g_timeout_source_new_seconds (guint interval)
3909 GSource *source = g_source_new (&g_timeout_funcs, sizeof (GTimeoutSource));
3910 GTimeoutSource *timeout_source = (GTimeoutSource *)source;
3912 timeout_source->interval = 1000 * interval;
3913 timeout_source->seconds = TRUE;
3915 g_timeout_set_expiration (timeout_source, g_get_monotonic_time ());
3922 * g_timeout_add_full:
3923 * @priority: the priority of the timeout source. Typically this will be in
3924 * the range between #G_PRIORITY_DEFAULT and #G_PRIORITY_HIGH.
3925 * @interval: the time between calls to the function, in milliseconds
3926 * (1/1000ths of a second)
3927 * @function: function to call
3928 * @data: data to pass to @function
3929 * @notify: function to call when the timeout is removed, or %NULL
3931 * Sets a function to be called at regular intervals, with the given
3932 * priority. The function is called repeatedly until it returns
3933 * %FALSE, at which point the timeout is automatically destroyed and
3934 * the function will not be called again. The @notify function is
3935 * called when the timeout is destroyed. The first call to the
3936 * function will be at the end of the first @interval.
3938 * Note that timeout functions may be delayed, due to the processing of other
3939 * event sources. Thus they should not be relied on for precise timing.
3940 * After each call to the timeout function, the time of the next
3941 * timeout is recalculated based on the current time and the given interval
3942 * (it does not try to 'catch up' time lost in delays).
3944 * This internally creates a main loop source using g_timeout_source_new()
3945 * and attaches it to the main loop context using g_source_attach(). You can
3946 * do these steps manually if you need greater control.
3948 * The interval given in terms of monotonic time, not wall clock time.
3949 * See g_get_monotonic_time().
3951 * Return value: the ID (greater than 0) of the event source.
3952 * Rename to: g_timeout_add
3955 g_timeout_add_full (gint priority,
3957 GSourceFunc function,
3959 GDestroyNotify notify)
3964 g_return_val_if_fail (function != NULL, 0);
3966 source = g_timeout_source_new (interval);
3968 if (priority != G_PRIORITY_DEFAULT)
3969 g_source_set_priority (source, priority);
3971 g_source_set_callback (source, function, data, notify);
3972 id = g_source_attach (source, NULL);
3973 g_source_unref (source);
3980 * @interval: the time between calls to the function, in milliseconds
3981 * (1/1000ths of a second)
3982 * @function: function to call
3983 * @data: data to pass to @function
3985 * Sets a function to be called at regular intervals, with the default
3986 * priority, #G_PRIORITY_DEFAULT. The function is called repeatedly
3987 * until it returns %FALSE, at which point the timeout is automatically
3988 * destroyed and the function will not be called again. The first call
3989 * to the function will be at the end of the first @interval.
3991 * Note that timeout functions may be delayed, due to the processing of other
3992 * event sources. Thus they should not be relied on for precise timing.
3993 * After each call to the timeout function, the time of the next
3994 * timeout is recalculated based on the current time and the given interval
3995 * (it does not try to 'catch up' time lost in delays).
3997 * If you want to have a timer in the "seconds" range and do not care
3998 * about the exact time of the first call of the timer, use the
3999 * g_timeout_add_seconds() function; this function allows for more
4000 * optimizations and more efficient system power usage.
4002 * This internally creates a main loop source using g_timeout_source_new()
4003 * and attaches it to the main loop context using g_source_attach(). You can
4004 * do these steps manually if you need greater control.
4006 * The interval given is in terms of monotonic time, not wall clock
4007 * time. See g_get_monotonic_time().
4009 * Return value: the ID (greater than 0) of the event source.
4012 g_timeout_add (guint32 interval,
4013 GSourceFunc function,
4016 return g_timeout_add_full (G_PRIORITY_DEFAULT,
4017 interval, function, data, NULL);
4021 * g_timeout_add_seconds_full:
4022 * @priority: the priority of the timeout source. Typically this will be in
4023 * the range between #G_PRIORITY_DEFAULT and #G_PRIORITY_HIGH.
4024 * @interval: the time between calls to the function, in seconds
4025 * @function: function to call
4026 * @data: data to pass to @function
4027 * @notify: function to call when the timeout is removed, or %NULL
4029 * Sets a function to be called at regular intervals, with @priority.
4030 * The function is called repeatedly until it returns %FALSE, at which
4031 * point the timeout is automatically destroyed and the function will
4032 * not be called again.
4034 * Unlike g_timeout_add(), this function operates at whole second granularity.
4035 * The initial starting point of the timer is determined by the implementation
4036 * and the implementation is expected to group multiple timers together so that
4037 * they fire all at the same time.
4038 * To allow this grouping, the @interval to the first timer is rounded
4039 * and can deviate up to one second from the specified interval.
4040 * Subsequent timer iterations will generally run at the specified interval.
4042 * Note that timeout functions may be delayed, due to the processing of other
4043 * event sources. Thus they should not be relied on for precise timing.
4044 * After each call to the timeout function, the time of the next
4045 * timeout is recalculated based on the current time and the given @interval
4047 * If you want timing more precise than whole seconds, use g_timeout_add()
4050 * The grouping of timers to fire at the same time results in a more power
4051 * and CPU efficient behavior so if your timer is in multiples of seconds
4052 * and you don't require the first timer exactly one second from now, the
4053 * use of g_timeout_add_seconds() is preferred over g_timeout_add().
4055 * This internally creates a main loop source using
4056 * g_timeout_source_new_seconds() and attaches it to the main loop context
4057 * using g_source_attach(). You can do these steps manually if you need
4060 * The interval given is in terms of monotonic time, not wall clock
4061 * time. See g_get_monotonic_time().
4063 * Return value: the ID (greater than 0) of the event source.
4065 * Rename to: g_timeout_add_seconds
4069 g_timeout_add_seconds_full (gint priority,
4071 GSourceFunc function,
4073 GDestroyNotify notify)
4078 g_return_val_if_fail (function != NULL, 0);
4080 source = g_timeout_source_new_seconds (interval);
4082 if (priority != G_PRIORITY_DEFAULT)
4083 g_source_set_priority (source, priority);
4085 g_source_set_callback (source, function, data, notify);
4086 id = g_source_attach (source, NULL);
4087 g_source_unref (source);
4093 * g_timeout_add_seconds:
4094 * @interval: the time between calls to the function, in seconds
4095 * @function: function to call
4096 * @data: data to pass to @function
4098 * Sets a function to be called at regular intervals with the default
4099 * priority, #G_PRIORITY_DEFAULT. The function is called repeatedly until
4100 * it returns %FALSE, at which point the timeout is automatically destroyed
4101 * and the function will not be called again.
4103 * This internally creates a main loop source using
4104 * g_timeout_source_new_seconds() and attaches it to the main loop context
4105 * using g_source_attach(). You can do these steps manually if you need
4106 * greater control. Also see g_timeout_add_seconds_full().
4108 * Note that the first call of the timer may not be precise for timeouts
4109 * of one second. If you need finer precision and have such a timeout,
4110 * you may want to use g_timeout_add() instead.
4112 * The interval given is in terms of monotonic time, not wall clock
4113 * time. See g_get_monotonic_time().
4115 * Return value: the ID (greater than 0) of the event source.
4120 g_timeout_add_seconds (guint interval,
4121 GSourceFunc function,
4124 g_return_val_if_fail (function != NULL, 0);
4126 return g_timeout_add_seconds_full (G_PRIORITY_DEFAULT, interval, function, data, NULL);
4129 /* Child watch functions */
4134 g_child_watch_prepare (GSource *source,
4143 g_child_watch_check (GSource *source)
4145 GChildWatchSource *child_watch_source;
4146 gboolean child_exited;
4148 child_watch_source = (GChildWatchSource *) source;
4150 child_exited = child_watch_source->poll.revents & G_IO_IN;
4157 * Note: We do _not_ check for the special value of STILL_ACTIVE
4158 * since we know that the process has exited and doing so runs into
4159 * problems if the child process "happens to return STILL_ACTIVE(259)"
4160 * as Microsoft's Platform SDK puts it.
4162 if (!GetExitCodeProcess (child_watch_source->pid, &child_status))
4164 gchar *emsg = g_win32_error_message (GetLastError ());
4165 g_warning (G_STRLOC ": GetExitCodeProcess() failed: %s", emsg);
4168 child_watch_source->child_status = -1;
4171 child_watch_source->child_status = child_status;
4174 return child_exited;
4177 #else /* G_OS_WIN32 */
4180 check_for_child_exited (GSource *source)
4182 GChildWatchSource *child_watch_source;
4185 /* protect against another SIGCHLD in the middle of this call */
4186 count = child_watch_count;
4188 child_watch_source = (GChildWatchSource *) source;
4190 if (child_watch_source->child_exited)
4193 if (child_watch_source->count < count)
4197 if (waitpid (child_watch_source->pid, &child_status, WNOHANG) > 0)
4199 child_watch_source->child_status = child_status;
4200 child_watch_source->child_exited = TRUE;
4202 child_watch_source->count = count;
4205 return child_watch_source->child_exited;
4209 g_child_watch_prepare (GSource *source,
4214 return check_for_child_exited (source);
4218 g_child_watch_check (GSource *source)
4220 return check_for_child_exited (source);
4224 check_for_signal_delivery (GSource *source)
4226 GUnixSignalWatchSource *unix_signal_source = (GUnixSignalWatchSource*) source;
4229 G_LOCK (unix_signal_lock);
4230 if (unix_signal_init_state == UNIX_SIGNAL_INITIALIZED_SINGLE)
4232 switch (unix_signal_source->signum)
4235 delivered = unix_signal_state.sighup_delivered;
4238 delivered = unix_signal_state.sigint_delivered;
4241 delivered = unix_signal_state.sigterm_delivered;
4244 g_assert_not_reached ();
4251 g_assert (unix_signal_init_state == UNIX_SIGNAL_INITIALIZED_THREADED);
4252 delivered = unix_signal_source->pending;
4254 G_UNLOCK (unix_signal_lock);
4260 g_unix_signal_watch_prepare (GSource *source,
4265 return check_for_signal_delivery (source);
4269 g_unix_signal_watch_check (GSource *source)
4271 return check_for_signal_delivery (source);
4275 g_unix_signal_watch_dispatch (GSource *source,
4276 GSourceFunc callback,
4279 GUnixSignalWatchSource *unix_signal_source;
4281 unix_signal_source = (GUnixSignalWatchSource *) source;
4285 g_warning ("Unix signal source dispatched without callback\n"
4286 "You must call g_source_set_callback().");
4290 (callback) (user_data);
4292 G_LOCK (unix_signal_lock);
4293 if (unix_signal_init_state == UNIX_SIGNAL_INITIALIZED_SINGLE)
4295 switch (unix_signal_source->signum)
4298 unix_signal_state.sighup_delivered = FALSE;
4301 unix_signal_state.sigint_delivered = FALSE;
4304 unix_signal_state.sigterm_delivered = FALSE;
4310 g_assert (unix_signal_init_state == UNIX_SIGNAL_INITIALIZED_THREADED);
4311 unix_signal_source->pending = FALSE;
4313 G_UNLOCK (unix_signal_lock);
4319 ensure_unix_signal_handler_installed_unlocked (int signum)
4321 struct sigaction action;
4322 GError *error = NULL;
4324 if (unix_signal_init_state == UNIX_SIGNAL_UNINITIALIZED)
4326 sigemptyset (&unix_signal_mask);
4329 if (unix_signal_init_state == UNIX_SIGNAL_UNINITIALIZED
4330 || unix_signal_init_state == UNIX_SIGNAL_INITIALIZED_SINGLE)
4332 if (!g_thread_supported ())
4334 /* There is nothing to do for initializing in the non-threaded
4337 if (unix_signal_init_state == UNIX_SIGNAL_UNINITIALIZED)
4338 unix_signal_init_state = UNIX_SIGNAL_INITIALIZED_SINGLE;
4342 if (!g_unix_open_pipe (unix_signal_wake_up_pipe, FD_CLOEXEC, &error))
4343 g_error ("Cannot create UNIX signal wake up pipe: %s\n", error->message);
4344 g_unix_set_fd_nonblocking (unix_signal_wake_up_pipe[1], TRUE, NULL);
4346 /* We create a helper thread that polls on the wakeup pipe indefinitely */
4347 if (g_thread_create (unix_signal_helper_thread, NULL, FALSE, &error) == NULL)
4348 g_error ("Cannot create a thread to monitor UNIX signals: %s\n", error->message);
4350 unix_signal_init_state = UNIX_SIGNAL_INITIALIZED_THREADED;
4354 if (sigismember (&unix_signal_mask, signum))
4357 sigaddset (&unix_signal_mask, signum);
4359 action.sa_handler = g_unix_signal_handler;
4360 sigemptyset (&action.sa_mask);
4361 action.sa_flags = SA_RESTART | SA_NOCLDSTOP;
4362 sigaction (signum, &action, NULL);
4366 _g_main_create_unix_signal_watch (int signum)
4369 GUnixSignalWatchSource *unix_signal_source;
4371 source = g_source_new (&g_unix_signal_funcs, sizeof (GUnixSignalWatchSource));
4372 unix_signal_source = (GUnixSignalWatchSource *) source;
4374 unix_signal_source->signum = signum;
4375 unix_signal_source->pending = FALSE;
4377 G_LOCK (unix_signal_lock);
4378 ensure_unix_signal_handler_installed_unlocked (signum);
4379 unix_signal_watches = g_slist_prepend (unix_signal_watches, unix_signal_source);
4380 G_UNLOCK (unix_signal_lock);
4386 g_unix_signal_watch_finalize (GSource *source)
4388 G_LOCK (unix_signal_lock);
4389 unix_signal_watches = g_slist_remove (unix_signal_watches, source);
4390 G_UNLOCK (unix_signal_lock);
4393 #endif /* G_OS_WIN32 */
4396 g_child_watch_dispatch (GSource *source,
4397 GSourceFunc callback,
4400 GChildWatchSource *child_watch_source;
4401 GChildWatchFunc child_watch_callback = (GChildWatchFunc) callback;
4403 child_watch_source = (GChildWatchSource *) source;
4407 g_warning ("Child watch source dispatched without callback\n"
4408 "You must call g_source_set_callback().");
4412 (child_watch_callback) (child_watch_source->pid, child_watch_source->child_status, user_data);
4414 /* We never keep a child watch source around as the child is gone */
4421 g_unix_signal_handler (int signum)
4423 if (signum == SIGCHLD)
4424 child_watch_count ++;
4426 if (unix_signal_init_state == UNIX_SIGNAL_INITIALIZED_THREADED)
4432 buf[0] = _UNIX_SIGNAL_PIPE_SIGCHLD_CHAR;
4435 buf[0] = _UNIX_SIGNAL_PIPE_SIGHUP_CHAR;
4438 buf[0] = _UNIX_SIGNAL_PIPE_SIGINT_CHAR;
4441 buf[0] = _UNIX_SIGNAL_PIPE_SIGTERM_CHAR;
4444 /* Shouldn't happen */
4447 write (unix_signal_wake_up_pipe[1], buf, 1);
4451 /* We count on the signal interrupting the poll in the same thread. */
4455 /* Nothing to do - the handler will call waitpid() */
4458 unix_signal_state.sighup_delivered = TRUE;
4461 unix_signal_state.sigint_delivered = TRUE;
4464 unix_signal_state.sigterm_delivered = TRUE;
4467 g_assert_not_reached ();
4474 deliver_unix_signal (int signum)
4477 g_assert (signum == SIGHUP || signum == SIGINT || signum == SIGTERM);
4479 G_LOCK (unix_signal_lock);
4480 for (iter = unix_signal_watches; iter; iter = iter->next)
4482 GUnixSignalWatchSource *source = iter->data;
4484 if (source->signum != signum)
4487 source->pending = TRUE;
4489 G_UNLOCK (unix_signal_lock);
4493 * This thread is created whenever anything in GLib needs
4494 * to deal with UNIX signals; at present, just SIGCHLD
4495 * from g_child_watch_source_new().
4497 * Note: We could eventually make this thread a more public interface
4498 * and allow e.g. GDBus to use it instead of its own worker thread.
4501 unix_signal_helper_thread (gpointer data)
4506 ssize_t i, bytes_read;
4507 gboolean sigterm_received = FALSE;
4508 gboolean sigint_received = FALSE;
4509 gboolean sighup_received = FALSE;
4511 bytes_read = read (unix_signal_wake_up_pipe[0], b, sizeof (b));
4514 g_warning ("Failed to read from child watch wake up pipe: %s",
4516 /* Not much we can do here sanely; just wait a second and hope
4519 g_usleep (G_USEC_PER_SEC);
4522 for (i = 0; i < bytes_read; i++)
4526 case _UNIX_SIGNAL_PIPE_SIGCHLD_CHAR:
4527 /* The child watch source will call waitpid() in its
4528 * prepare() and check() methods; however, we don't
4529 * know which pid exited, so we need to wake up
4530 * all contexts. Note: actually we could get the pid
4531 * from the "siginfo_t" via the handler, but to pass
4532 * that info down the pipe would require a more structured
4533 * data stream (as opposed to a single byte).
4536 case _UNIX_SIGNAL_PIPE_SIGTERM_CHAR:
4537 sigterm_received = TRUE;
4539 case _UNIX_SIGNAL_PIPE_SIGHUP_CHAR:
4540 sighup_received = TRUE;
4542 case _UNIX_SIGNAL_PIPE_SIGINT_CHAR:
4543 sigint_received = TRUE;
4546 g_warning ("Invalid char '%c' read from child watch pipe", b[i]);
4550 if (sigterm_received)
4551 deliver_unix_signal (SIGTERM);
4552 if (sigint_received)
4553 deliver_unix_signal (SIGINT);
4554 if (sighup_received)
4555 deliver_unix_signal (SIGHUP);
4556 _g_main_wake_up_all_contexts ();
4561 g_child_watch_source_init (void)
4563 G_LOCK (unix_signal_lock);
4564 ensure_unix_signal_handler_installed_unlocked (SIGCHLD);
4565 G_UNLOCK (unix_signal_lock);
4568 #endif /* !G_OS_WIN32 */
4571 * g_child_watch_source_new:
4572 * @pid: process to watch. On POSIX the pid of a child process. On
4573 * Windows a handle for a process (which doesn't have to be a child).
4575 * Creates a new child_watch source.
4577 * The source will not initially be associated with any #GMainContext
4578 * and must be added to one with g_source_attach() before it will be
4581 * Note that child watch sources can only be used in conjunction with
4582 * <literal>g_spawn...</literal> when the %G_SPAWN_DO_NOT_REAP_CHILD
4585 * Note that on platforms where #GPid must be explicitly closed
4586 * (see g_spawn_close_pid()) @pid must not be closed while the
4587 * source is still active. Typically, you will want to call
4588 * g_spawn_close_pid() in the callback function for the source.
4590 * Note further that using g_child_watch_source_new() is not
4591 * compatible with calling <literal>waitpid(-1)</literal> in
4592 * the application. Calling waitpid() for individual pids will
4595 * Return value: the newly-created child watch source
4600 g_child_watch_source_new (GPid pid)
4602 GSource *source = g_source_new (&g_child_watch_funcs, sizeof (GChildWatchSource));
4603 GChildWatchSource *child_watch_source = (GChildWatchSource *)source;
4606 child_watch_source->poll.fd = (gintptr) pid;
4607 child_watch_source->poll.events = G_IO_IN;
4609 g_source_add_poll (source, &child_watch_source->poll);
4610 #else /* G_OS_WIN32 */
4611 g_child_watch_source_init ();
4612 #endif /* G_OS_WIN32 */
4614 child_watch_source->pid = pid;
4620 * g_child_watch_add_full:
4621 * @priority: the priority of the idle source. Typically this will be in the
4622 * range between #G_PRIORITY_DEFAULT_IDLE and #G_PRIORITY_HIGH_IDLE.
4623 * @pid: process to watch. On POSIX the pid of a child process. On
4624 * Windows a handle for a process (which doesn't have to be a child).
4625 * @function: function to call
4626 * @data: data to pass to @function
4627 * @notify: function to call when the idle is removed, or %NULL
4629 * Sets a function to be called when the child indicated by @pid
4630 * exits, at the priority @priority.
4632 * If you obtain @pid from g_spawn_async() or g_spawn_async_with_pipes()
4633 * you will need to pass #G_SPAWN_DO_NOT_REAP_CHILD as flag to
4634 * the spawn function for the child watching to work.
4636 * Note that on platforms where #GPid must be explicitly closed
4637 * (see g_spawn_close_pid()) @pid must not be closed while the
4638 * source is still active. Typically, you will want to call
4639 * g_spawn_close_pid() in the callback function for the source.
4641 * GLib supports only a single callback per process id.
4643 * This internally creates a main loop source using
4644 * g_child_watch_source_new() and attaches it to the main loop context
4645 * using g_source_attach(). You can do these steps manually if you
4646 * need greater control.
4648 * Return value: the ID (greater than 0) of the event source.
4650 * Rename to: g_child_watch_add
4654 g_child_watch_add_full (gint priority,
4656 GChildWatchFunc function,
4658 GDestroyNotify notify)
4663 g_return_val_if_fail (function != NULL, 0);
4665 source = g_child_watch_source_new (pid);
4667 if (priority != G_PRIORITY_DEFAULT)
4668 g_source_set_priority (source, priority);
4670 g_source_set_callback (source, (GSourceFunc) function, data, notify);
4671 id = g_source_attach (source, NULL);
4672 g_source_unref (source);
4678 * g_child_watch_add:
4679 * @pid: process id to watch. On POSIX the pid of a child process. On
4680 * Windows a handle for a process (which doesn't have to be a child).
4681 * @function: function to call
4682 * @data: data to pass to @function
4684 * Sets a function to be called when the child indicated by @pid
4685 * exits, at a default priority, #G_PRIORITY_DEFAULT.
4687 * If you obtain @pid from g_spawn_async() or g_spawn_async_with_pipes()
4688 * you will need to pass #G_SPAWN_DO_NOT_REAP_CHILD as flag to
4689 * the spawn function for the child watching to work.
4691 * Note that on platforms where #GPid must be explicitly closed
4692 * (see g_spawn_close_pid()) @pid must not be closed while the
4693 * source is still active. Typically, you will want to call
4694 * g_spawn_close_pid() in the callback function for the source.
4696 * GLib supports only a single callback per process id.
4698 * This internally creates a main loop source using
4699 * g_child_watch_source_new() and attaches it to the main loop context
4700 * using g_source_attach(). You can do these steps manually if you
4701 * need greater control.
4703 * Return value: the ID (greater than 0) of the event source.
4708 g_child_watch_add (GPid pid,
4709 GChildWatchFunc function,
4712 return g_child_watch_add_full (G_PRIORITY_DEFAULT, pid, function, data, NULL);
4716 /* Idle functions */
4719 g_idle_prepare (GSource *source,
4728 g_idle_check (GSource *source)
4734 g_idle_dispatch (GSource *source,
4735 GSourceFunc callback,
4740 g_warning ("Idle source dispatched without callback\n"
4741 "You must call g_source_set_callback().");
4745 return callback (user_data);
4749 * g_idle_source_new:
4751 * Creates a new idle source.
4753 * The source will not initially be associated with any #GMainContext
4754 * and must be added to one with g_source_attach() before it will be
4755 * executed. Note that the default priority for idle sources is
4756 * %G_PRIORITY_DEFAULT_IDLE, as compared to other sources which
4757 * have a default priority of %G_PRIORITY_DEFAULT.
4759 * Return value: the newly-created idle source
4762 g_idle_source_new (void)
4766 source = g_source_new (&g_idle_funcs, sizeof (GSource));
4767 g_source_set_priority (source, G_PRIORITY_DEFAULT_IDLE);
4774 * @priority: the priority of the idle source. Typically this will be in the
4775 * range between #G_PRIORITY_DEFAULT_IDLE and #G_PRIORITY_HIGH_IDLE.
4776 * @function: function to call
4777 * @data: data to pass to @function
4778 * @notify: function to call when the idle is removed, or %NULL
4780 * Adds a function to be called whenever there are no higher priority
4781 * events pending. If the function returns %FALSE it is automatically
4782 * removed from the list of event sources and will not be called again.
4784 * This internally creates a main loop source using g_idle_source_new()
4785 * and attaches it to the main loop context using g_source_attach().
4786 * You can do these steps manually if you need greater control.
4788 * Return value: the ID (greater than 0) of the event source.
4789 * Rename to: g_idle_add
4792 g_idle_add_full (gint priority,
4793 GSourceFunc function,
4795 GDestroyNotify notify)
4800 g_return_val_if_fail (function != NULL, 0);
4802 source = g_idle_source_new ();
4804 if (priority != G_PRIORITY_DEFAULT_IDLE)
4805 g_source_set_priority (source, priority);
4807 g_source_set_callback (source, function, data, notify);
4808 id = g_source_attach (source, NULL);
4809 g_source_unref (source);
4816 * @function: function to call
4817 * @data: data to pass to @function.
4819 * Adds a function to be called whenever there are no higher priority
4820 * events pending to the default main loop. The function is given the
4821 * default idle priority, #G_PRIORITY_DEFAULT_IDLE. If the function
4822 * returns %FALSE it is automatically removed from the list of event
4823 * sources and will not be called again.
4825 * This internally creates a main loop source using g_idle_source_new()
4826 * and attaches it to the main loop context using g_source_attach().
4827 * You can do these steps manually if you need greater control.
4829 * Return value: the ID (greater than 0) of the event source.
4832 g_idle_add (GSourceFunc function,
4835 return g_idle_add_full (G_PRIORITY_DEFAULT_IDLE, function, data, NULL);
4839 * g_idle_remove_by_data:
4840 * @data: the data for the idle source's callback.
4842 * Removes the idle function with the given data.
4844 * Return value: %TRUE if an idle source was found and removed.
4847 g_idle_remove_by_data (gpointer data)
4849 return g_source_remove_by_funcs_user_data (&g_idle_funcs, data);
4853 * g_main_context_invoke:
4854 * @context: (allow-none): a #GMainContext, or %NULL
4855 * @function: function to call
4856 * @data: data to pass to @function
4858 * Invokes a function in such a way that @context is owned during the
4859 * invocation of @function.
4861 * If @context is %NULL then the global default main context — as
4862 * returned by g_main_context_default() — is used.
4864 * If @context is owned by the current thread, @function is called
4865 * directly. Otherwise, if @context is the thread-default main context
4866 * of the current thread and g_main_context_acquire() succeeds, then
4867 * @function is called and g_main_context_release() is called
4870 * In any other case, an idle source is created to call @function and
4871 * that source is attached to @context (presumably to be run in another
4872 * thread). The idle source is attached with #G_PRIORITY_DEFAULT
4873 * priority. If you want a different priority, use
4874 * g_main_context_invoke_full().
4876 * Note that, as with normal idle functions, @function should probably
4877 * return %FALSE. If it returns %TRUE, it will be continuously run in a
4878 * loop (and may prevent this call from returning).
4883 g_main_context_invoke (GMainContext *context,
4884 GSourceFunc function,
4887 g_main_context_invoke_full (context,
4889 function, data, NULL);
4893 * g_main_context_invoke_full:
4894 * @context: (allow-none): a #GMainContext, or %NULL
4895 * @priority: the priority at which to run @function
4896 * @function: function to call
4897 * @data: data to pass to @function
4898 * @notify: a function to call when @data is no longer in use, or %NULL.
4900 * Invokes a function in such a way that @context is owned during the
4901 * invocation of @function.
4903 * This function is the same as g_main_context_invoke() except that it
4904 * lets you specify the priority incase @function ends up being
4905 * scheduled as an idle and also lets you give a #GDestroyNotify for @data.
4907 * @notify should not assume that it is called from any particular
4908 * thread or with any particular context acquired.
4913 g_main_context_invoke_full (GMainContext *context,
4915 GSourceFunc function,
4917 GDestroyNotify notify)
4919 g_return_if_fail (function != NULL);
4922 context = g_main_context_default ();
4924 if (g_main_context_is_owner (context))
4926 while (function (data));
4933 GMainContext *thread_default;
4935 thread_default = g_main_context_get_thread_default ();
4937 if (!thread_default)
4938 thread_default = g_main_context_default ();
4940 if (thread_default == context && g_main_context_acquire (context))
4942 while (function (data));
4944 g_main_context_release (context);
4953 source = g_idle_source_new ();
4954 g_source_set_priority (source, priority);
4955 g_source_set_callback (source, function, data, notify);
4956 g_source_attach (source, context);
4957 g_source_unref (source);
4963 glib_worker_main (gpointer data)
4965 LOCK_CONTEXT (glib_worker_context);
4968 g_main_context_iterate (glib_worker_context, TRUE, TRUE, G_THREAD_SELF);
4970 return NULL; /* worst GCC warning message ever... */
4974 glib_get_worker_context (void)
4978 g_thread_init_glib ();
4980 if (g_once_init_enter (&initialised))
4982 GError *error = NULL;
4984 glib_worker_context = g_main_context_new ();
4985 if (g_thread_create (glib_worker_main, NULL, FALSE, &error) == NULL)
4986 g_error ("Creating GLib worker thread failed: %s\n", error->message);
4988 g_once_init_leave (&initialised, TRUE);
4991 return glib_worker_context;