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 /* for pipe2; need to define it first to avoid
36 * other headers pulling in unistd.h
38 /* The meaning of_GNU_SOURCE that is intended here is present only on
39 * Linux; avoid the possibility that some misguided header in MinGW
40 * looks at it. Ideally we should define _GNU_SOURCE only on platforms
41 * where we know what it means and that is what we want here
42 * (i.e. Linux with glibc). After all, there might be some other POSIX
43 * platform even where _GNU_SOURCE is used for some unrelated change
44 * in semantics that isn't wanted. Sigh.
50 #include "glibconfig.h"
52 /* Uncomment the next line (and the corresponding line in gpoll.c) to
53 * enable debugging printouts if the environment variable
54 * G_MAIN_POLL_DEBUG is set to some value.
56 /* #define G_MAIN_POLL_DEBUG */
59 /* Always enable debugging printout on Windows, as it is more often
62 #define G_MAIN_POLL_DEBUG
66 #include "glib-unix.h"
70 #include <sys/types.h>
73 #ifdef HAVE_SYS_TIME_H
75 #endif /* HAVE_SYS_TIME_H */
78 #endif /* HAVE_UNISTD_H */
84 #endif /* G_OS_WIN32 */
87 #include <sys/socket.h>
89 #endif /* G_OS_BEOS */
94 #include "giochannel.h"
98 #include "gstrfuncs.h"
99 #include "gtestutils.h"
100 #include "gthreadprivate.h"
106 #ifdef G_MAIN_POLL_DEBUG
112 * @title: The Main Event Loop
113 * @short_description: manages all available sources of events
115 * The main event loop manages all the available sources of events for
116 * GLib and GTK+ applications. These events can come from any number of
117 * different types of sources such as file descriptors (plain files,
118 * pipes or sockets) and timeouts. New types of event sources can also
119 * be added using g_source_attach().
121 * To allow multiple independent sets of sources to be handled in
122 * different threads, each source is associated with a #GMainContext.
123 * A GMainContext can only be running in a single thread, but
124 * sources can be added to it and removed from it from other threads.
126 * Each event source is assigned a priority. The default priority,
127 * #G_PRIORITY_DEFAULT, is 0. Values less than 0 denote higher priorities.
128 * Values greater than 0 denote lower priorities. Events from high priority
129 * sources are always processed before events from lower priority sources.
131 * Idle functions can also be added, and assigned a priority. These will
132 * be run whenever no events with a higher priority are ready to be processed.
134 * The #GMainLoop data type represents a main event loop. A GMainLoop is
135 * created with g_main_loop_new(). After adding the initial event sources,
136 * g_main_loop_run() is called. This continuously checks for new events from
137 * each of the event sources and dispatches them. Finally, the processing of
138 * an event from one of the sources leads to a call to g_main_loop_quit() to
139 * exit the main loop, and g_main_loop_run() returns.
141 * It is possible to create new instances of #GMainLoop recursively.
142 * This is often used in GTK+ applications when showing modal dialog
143 * boxes. Note that event sources are associated with a particular
144 * #GMainContext, and will be checked and dispatched for all main
145 * loops associated with that GMainContext.
147 * GTK+ contains wrappers of some of these functions, e.g. gtk_main(),
148 * gtk_main_quit() and gtk_events_pending().
150 * <refsect2><title>Creating new source types</title>
151 * <para>One of the unusual features of the #GMainLoop functionality
152 * is that new types of event source can be created and used in
153 * addition to the builtin type of event source. A new event source
154 * type is used for handling GDK events. A new source type is created
155 * by <firstterm>deriving</firstterm> from the #GSource structure.
156 * The derived type of source is represented by a structure that has
157 * the #GSource structure as a first element, and other elements specific
158 * to the new source type. To create an instance of the new source type,
159 * call g_source_new() passing in the size of the derived structure and
160 * a table of functions. These #GSourceFuncs determine the behavior of
161 * the new source type.</para>
162 * <para>New source types basically interact with the main context
163 * in two ways. Their prepare function in #GSourceFuncs can set a timeout
164 * to determine the maximum amount of time that the main loop will sleep
165 * before checking the source again. In addition, or as well, the source
166 * can add file descriptors to the set that the main context checks using
167 * g_source_add_poll().</para>
169 * <refsect2><title>Customizing the main loop iteration</title>
170 * <para>Single iterations of a #GMainContext can be run with
171 * g_main_context_iteration(). In some cases, more detailed control
172 * of exactly how the details of the main loop work is desired, for
173 * instance, when integrating the #GMainLoop with an external main loop.
174 * In such cases, you can call the component functions of
175 * g_main_context_iteration() directly. These functions are
176 * g_main_context_prepare(), g_main_context_query(),
177 * g_main_context_check() and g_main_context_dispatch().</para>
178 * <para>The operation of these functions can best be seen in terms
179 * of a state diagram, as shown in <xref linkend="mainloop-states"/>.</para>
180 * <figure id="mainloop-states"><title>States of a Main Context</title>
181 * <graphic fileref="mainloop-states.gif" format="GIF"></graphic>
188 typedef struct _GTimeoutSource GTimeoutSource;
189 typedef struct _GChildWatchSource GChildWatchSource;
190 typedef struct _GPollRec GPollRec;
191 typedef struct _GSourceCallback GSourceCallback;
195 G_SOURCE_READY = 1 << G_HOOK_FLAG_USER_SHIFT,
196 G_SOURCE_CAN_RECURSE = 1 << (G_HOOK_FLAG_USER_SHIFT + 1)
199 #ifdef G_THREADS_ENABLED
200 typedef struct _GMainWaiter GMainWaiter;
209 typedef struct _GMainDispatch GMainDispatch;
211 struct _GMainDispatch
214 GSList *dispatching_sources; /* stack of current sources */
217 #ifdef G_MAIN_POLL_DEBUG
218 gboolean _g_main_poll_debug = FALSE;
223 #ifdef G_THREADS_ENABLED
224 /* The following lock is used for both the list of sources
225 * and the list of poll records
236 GPtrArray *pending_dispatches;
237 gint timeout; /* Timeout for current iteration */
240 GSource *source_list;
241 gint in_check_or_prepare;
243 GPollRec *poll_records;
244 guint n_poll_records;
245 GPollFD *cached_poll_array;
246 guint cached_poll_array_size;
248 #ifdef G_THREADS_ENABLED
250 /* this pipe is used to wake up the main loop when a source is added.
252 gint wake_up_pipe[2];
253 #else /* G_OS_WIN32 */
254 HANDLE wake_up_semaphore;
255 #endif /* G_OS_WIN32 */
258 gboolean poll_waiting;
260 /* Flag indicating whether the set of fd's changed during a poll */
261 gboolean poll_changed;
262 #endif /* G_THREADS_ENABLED */
267 gboolean time_is_fresh;
269 gboolean real_time_is_fresh;
272 struct _GSourceCallback
277 GDestroyNotify notify;
282 GMainContext *context;
287 struct _GTimeoutSource
295 struct _GChildWatchSource
302 #else /* G_OS_WIN32 */
304 gboolean child_exited;
305 #endif /* G_OS_WIN32 */
315 struct _GSourcePrivate
317 GSList *child_sources;
318 GSource *parent_source;
321 #ifdef G_THREADS_ENABLED
322 #define LOCK_CONTEXT(context) g_static_mutex_lock (&context->mutex)
323 #define UNLOCK_CONTEXT(context) g_static_mutex_unlock (&context->mutex)
324 #define G_THREAD_SELF g_thread_self ()
326 #define LOCK_CONTEXT(context) (void)0
327 #define UNLOCK_CONTEXT(context) (void)0
328 #define G_THREAD_SELF NULL
331 #define SOURCE_DESTROYED(source) (((source)->flags & G_HOOK_FLAG_ACTIVE) == 0)
332 #define SOURCE_BLOCKED(source) (((source)->flags & G_HOOK_FLAG_IN_CALL) != 0 && \
333 ((source)->flags & G_SOURCE_CAN_RECURSE) == 0)
335 #define SOURCE_UNREF(source, context) \
337 if ((source)->ref_count > 1) \
338 (source)->ref_count--; \
340 g_source_unref_internal ((source), (context), TRUE); \
344 /* Forward declarations */
346 static void g_source_unref_internal (GSource *source,
347 GMainContext *context,
349 static void g_source_destroy_internal (GSource *source,
350 GMainContext *context,
352 static void g_source_set_priority_unlocked (GSource *source,
353 GMainContext *context,
355 static void g_main_context_poll (GMainContext *context,
360 static void g_main_context_add_poll_unlocked (GMainContext *context,
363 static void g_main_context_remove_poll_unlocked (GMainContext *context,
365 static void g_main_context_wakeup_unlocked (GMainContext *context);
367 static gboolean g_timeout_prepare (GSource *source,
369 static gboolean g_timeout_check (GSource *source);
370 static gboolean g_timeout_dispatch (GSource *source,
371 GSourceFunc callback,
373 static gboolean g_child_watch_prepare (GSource *source,
375 static gboolean g_child_watch_check (GSource *source);
376 static gboolean g_child_watch_dispatch (GSource *source,
377 GSourceFunc callback,
379 static gboolean g_idle_prepare (GSource *source,
381 static gboolean g_idle_check (GSource *source);
382 static gboolean g_idle_dispatch (GSource *source,
383 GSourceFunc callback,
386 G_LOCK_DEFINE_STATIC (main_loop);
387 static GMainContext *default_main_context;
388 static GSList *main_contexts_without_pipe = NULL;
391 /* Child status monitoring code */
393 CHILD_WATCH_UNINITIALIZED,
394 CHILD_WATCH_INITIALIZED_SINGLE,
395 CHILD_WATCH_INITIALIZED_THREADED
397 static gint child_watch_init_state = CHILD_WATCH_UNINITIALIZED;
398 static gint child_watch_count = 1;
399 static gint child_watch_wake_up_pipe[2] = {0, 0};
400 #endif /* !G_OS_WIN32 */
401 G_LOCK_DEFINE_STATIC (main_context_list);
402 static GSList *main_context_list = NULL;
404 GSourceFuncs g_timeout_funcs =
412 GSourceFuncs g_child_watch_funcs =
414 g_child_watch_prepare,
416 g_child_watch_dispatch,
420 GSourceFuncs g_idle_funcs =
429 * g_main_context_ref:
430 * @context: a #GMainContext
432 * Increases the reference count on a #GMainContext object by one.
434 * Returns: the @context that was passed in (since 2.6)
437 g_main_context_ref (GMainContext *context)
439 g_return_val_if_fail (context != NULL, NULL);
440 g_return_val_if_fail (g_atomic_int_get (&context->ref_count) > 0, NULL);
442 g_atomic_int_inc (&context->ref_count);
448 poll_rec_list_free (GMainContext *context,
451 g_slice_free_chain (GPollRec, list, next);
455 * g_main_context_unref:
456 * @context: a #GMainContext
458 * Decreases the reference count on a #GMainContext object by one. If
459 * the result is zero, free the context and free all associated memory.
462 g_main_context_unref (GMainContext *context)
465 g_return_if_fail (context != NULL);
466 g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
468 if (!g_atomic_int_dec_and_test (&context->ref_count))
471 G_LOCK (main_context_list);
472 main_context_list = g_slist_remove (main_context_list, context);
473 G_UNLOCK (main_context_list);
475 source = context->source_list;
478 GSource *next = source->next;
479 g_source_destroy_internal (source, context, FALSE);
483 #ifdef G_THREADS_ENABLED
484 g_static_mutex_free (&context->mutex);
487 g_ptr_array_free (context->pending_dispatches, TRUE);
488 g_free (context->cached_poll_array);
490 poll_rec_list_free (context, context->poll_records);
492 #ifdef G_THREADS_ENABLED
493 if (g_thread_supported())
496 close (context->wake_up_pipe[0]);
497 close (context->wake_up_pipe[1]);
499 CloseHandle (context->wake_up_semaphore);
503 main_contexts_without_pipe = g_slist_remove (main_contexts_without_pipe,
506 if (context->cond != NULL)
507 g_cond_free (context->cond);
513 #ifdef G_THREADS_ENABLED
515 g_main_context_init_pipe (GMainContext *context)
517 GError *error = NULL;
520 if (context->wake_up_pipe[0] != -1)
523 if (!g_unix_pipe_flags (context->wake_up_pipe, FD_CLOEXEC, &error))
524 g_error ("Cannot create pipe main loop wake-up: %s", error->message);
526 context->wake_up_rec.fd = context->wake_up_pipe[0];
527 context->wake_up_rec.events = G_IO_IN;
529 if (context->wake_up_semaphore != NULL)
531 context->wake_up_semaphore = CreateSemaphore (NULL, 0, 100, NULL);
532 if (context->wake_up_semaphore == NULL)
533 g_error ("Cannot create wake-up semaphore: %s",
534 g_win32_error_message (GetLastError ()));
535 context->wake_up_rec.fd = (gintptr) context->wake_up_semaphore;
536 context->wake_up_rec.events = G_IO_IN;
538 if (_g_main_poll_debug)
539 g_print ("wake-up semaphore: %p\n", context->wake_up_semaphore);
541 g_main_context_add_poll_unlocked (context, 0, &context->wake_up_rec);
545 _g_main_thread_init (void)
547 GSList *curr = main_contexts_without_pipe;
550 g_main_context_init_pipe ((GMainContext *)curr->data);
553 g_slist_free (main_contexts_without_pipe);
554 main_contexts_without_pipe = NULL;
556 #endif /* G_THREADS_ENABLED */
559 * g_main_context_new:
561 * Creates a new #GMainContext structure.
563 * Return value: the new #GMainContext
566 g_main_context_new (void)
568 GMainContext *context = g_new0 (GMainContext, 1);
570 #ifdef G_MAIN_POLL_DEBUG
572 static gboolean beenhere = FALSE;
576 if (getenv ("G_MAIN_POLL_DEBUG") != NULL)
577 _g_main_poll_debug = TRUE;
583 #ifdef G_THREADS_ENABLED
584 g_static_mutex_init (&context->mutex);
586 context->owner = NULL;
587 context->waiters = NULL;
590 context->wake_up_pipe[0] = -1;
591 context->wake_up_pipe[1] = -1;
593 context->wake_up_semaphore = NULL;
597 context->ref_count = 1;
599 context->next_id = 1;
601 context->source_list = NULL;
603 context->poll_func = g_poll;
605 context->cached_poll_array = NULL;
606 context->cached_poll_array_size = 0;
608 context->pending_dispatches = g_ptr_array_new ();
610 context->time_is_fresh = FALSE;
611 context->real_time_is_fresh = FALSE;
613 #ifdef G_THREADS_ENABLED
614 if (g_thread_supported ())
615 g_main_context_init_pipe (context);
617 main_contexts_without_pipe = g_slist_prepend (main_contexts_without_pipe,
621 G_LOCK (main_context_list);
622 main_context_list = g_slist_append (main_context_list, context);
624 #ifdef G_MAIN_POLL_DEBUG
625 if (_g_main_poll_debug)
626 g_print ("created context=%p\n", context);
629 G_UNLOCK (main_context_list);
635 * g_main_context_default:
637 * Returns the global default main context. This is the main context
638 * used for main loop functions when a main loop is not explicitly
639 * specified, and corresponds to the "main" main loop. See also
640 * g_main_context_get_thread_default().
642 * Return value: the global default main context.
645 g_main_context_default (void)
651 if (!default_main_context)
653 default_main_context = g_main_context_new ();
654 #ifdef G_MAIN_POLL_DEBUG
655 if (_g_main_poll_debug)
656 g_print ("default context=%p\n", default_main_context);
660 G_UNLOCK (main_loop);
662 return default_main_context;
665 static GStaticPrivate thread_context_stack = G_STATIC_PRIVATE_INIT;
668 free_context_stack (gpointer data)
670 GQueue *stack = data;
671 GMainContext *context;
673 while (!g_queue_is_empty (stack))
675 context = g_queue_pop_head (stack);
676 g_main_context_release (context);
678 g_main_context_unref (context);
680 g_queue_free (stack);
684 * g_main_context_push_thread_default:
685 * @context: a #GMainContext, or %NULL for the global default context
687 * Acquires @context and sets it as the thread-default context for the
688 * current thread. This will cause certain asynchronous operations
689 * (such as most <link linkend="gio">gio</link>-based I/O) which are
690 * started in this thread to run under @context and deliver their
691 * results to its main loop, rather than running under the global
692 * default context in the main thread. Note that calling this function
693 * changes the context returned by
694 * g_main_context_get_thread_default(), <emphasis>not</emphasis> the
695 * one returned by g_main_context_default(), so it does not affect the
696 * context used by functions like g_idle_add().
698 * Normally you would call this function shortly after creating a new
699 * thread, passing it a #GMainContext which will be run by a
700 * #GMainLoop in that thread, to set a new default context for all
701 * async operations in that thread. (In this case, you don't need to
702 * ever call g_main_context_pop_thread_default().) In some cases
703 * however, you may want to schedule a single operation in a
704 * non-default context, or temporarily use a non-default context in
705 * the main thread. In that case, you can wrap the call to the
706 * asynchronous operation inside a
707 * g_main_context_push_thread_default() /
708 * g_main_context_pop_thread_default() pair, but it is up to you to
709 * ensure that no other asynchronous operations accidentally get
710 * started while the non-default context is active.
712 * Beware that libraries that predate this function may not correctly
713 * handle being used from a thread with a thread-default context. Eg,
714 * see g_file_supports_thread_contexts().
719 g_main_context_push_thread_default (GMainContext *context)
722 gboolean acquired_context;
724 acquired_context = g_main_context_acquire (context);
725 g_return_if_fail (acquired_context);
727 if (context == g_main_context_default ())
730 g_main_context_ref (context);
732 stack = g_static_private_get (&thread_context_stack);
735 stack = g_queue_new ();
736 g_static_private_set (&thread_context_stack, stack,
740 g_queue_push_head (stack, context);
744 * g_main_context_pop_thread_default:
745 * @context: a #GMainContext object, or %NULL
747 * Pops @context off the thread-default context stack (verifying that
748 * it was on the top of the stack).
753 g_main_context_pop_thread_default (GMainContext *context)
757 if (context == g_main_context_default ())
760 stack = g_static_private_get (&thread_context_stack);
762 g_return_if_fail (stack != NULL);
763 g_return_if_fail (g_queue_peek_head (stack) == context);
765 g_queue_pop_head (stack);
767 g_main_context_release (context);
769 g_main_context_unref (context);
773 * g_main_context_get_thread_default:
775 * Gets the thread-default #GMainContext for this thread. Asynchronous
776 * operations that want to be able to be run in contexts other than
777 * the default one should call this method to get a #GMainContext to
778 * add their #GSource<!-- -->s to. (Note that even in single-threaded
779 * programs applications may sometimes want to temporarily push a
780 * non-default context, so it is not safe to assume that this will
781 * always return %NULL if threads are not initialized.)
783 * Returns: the thread-default #GMainContext, or %NULL if the
784 * thread-default context is the global default context.
789 g_main_context_get_thread_default (void)
793 stack = g_static_private_get (&thread_context_stack);
795 return g_queue_peek_head (stack);
800 /* Hooks for adding to the main loop */
804 * @source_funcs: structure containing functions that implement
805 * the sources behavior.
806 * @struct_size: size of the #GSource structure to create.
808 * Creates a new #GSource structure. The size is specified to
809 * allow creating structures derived from #GSource that contain
810 * additional data. The size passed in must be at least
811 * <literal>sizeof (GSource)</literal>.
813 * The source will not initially be associated with any #GMainContext
814 * and must be added to one with g_source_attach() before it will be
817 * Return value: the newly-created #GSource.
820 g_source_new (GSourceFuncs *source_funcs,
825 g_return_val_if_fail (source_funcs != NULL, NULL);
826 g_return_val_if_fail (struct_size >= sizeof (GSource), NULL);
828 source = (GSource*) g_malloc0 (struct_size);
830 source->source_funcs = source_funcs;
831 source->ref_count = 1;
833 source->priority = G_PRIORITY_DEFAULT;
835 source->flags = G_HOOK_FLAG_ACTIVE;
837 /* NULL/0 initialization for all other fields */
842 /* Holds context's lock
845 g_source_list_add (GSource *source,
846 GMainContext *context)
848 GSource *tmp_source, *last_source;
850 if (source->priv && source->priv->parent_source)
852 /* Put the source immediately before its parent */
853 tmp_source = source->priv->parent_source;
854 last_source = source->priv->parent_source->prev;
859 tmp_source = context->source_list;
860 while (tmp_source && tmp_source->priority <= source->priority)
862 last_source = tmp_source;
863 tmp_source = tmp_source->next;
867 source->next = tmp_source;
869 tmp_source->prev = source;
871 source->prev = last_source;
873 last_source->next = source;
875 context->source_list = source;
878 /* Holds context's lock
881 g_source_list_remove (GSource *source,
882 GMainContext *context)
885 source->prev->next = source->next;
887 context->source_list = source->next;
890 source->next->prev = source->prev;
897 g_source_attach_unlocked (GSource *source,
898 GMainContext *context)
903 source->context = context;
904 result = source->source_id = context->next_id++;
907 g_source_list_add (source, context);
909 tmp_list = source->poll_fds;
912 g_main_context_add_poll_unlocked (context, source->priority, tmp_list->data);
913 tmp_list = tmp_list->next;
918 tmp_list = source->priv->child_sources;
921 g_source_attach_unlocked (tmp_list->data, context);
922 tmp_list = tmp_list->next;
931 * @source: a #GSource
932 * @context: a #GMainContext (if %NULL, the default context will be used)
934 * Adds a #GSource to a @context so that it will be executed within
935 * that context. Remove it by calling g_source_destroy().
937 * Return value: the ID (greater than 0) for the source within the
941 g_source_attach (GSource *source,
942 GMainContext *context)
946 g_return_val_if_fail (source->context == NULL, 0);
947 g_return_val_if_fail (!SOURCE_DESTROYED (source), 0);
950 context = g_main_context_default ();
952 LOCK_CONTEXT (context);
954 result = g_source_attach_unlocked (source, context);
956 #ifdef G_THREADS_ENABLED
957 /* Now wake up the main loop if it is waiting in the poll() */
958 g_main_context_wakeup_unlocked (context);
961 UNLOCK_CONTEXT (context);
967 g_source_destroy_internal (GSource *source,
968 GMainContext *context,
972 LOCK_CONTEXT (context);
974 if (!SOURCE_DESTROYED (source))
977 gpointer old_cb_data;
978 GSourceCallbackFuncs *old_cb_funcs;
980 source->flags &= ~G_HOOK_FLAG_ACTIVE;
982 old_cb_data = source->callback_data;
983 old_cb_funcs = source->callback_funcs;
985 source->callback_data = NULL;
986 source->callback_funcs = NULL;
990 UNLOCK_CONTEXT (context);
991 old_cb_funcs->unref (old_cb_data);
992 LOCK_CONTEXT (context);
995 if (!SOURCE_BLOCKED (source))
997 tmp_list = source->poll_fds;
1000 g_main_context_remove_poll_unlocked (context, tmp_list->data);
1001 tmp_list = tmp_list->next;
1005 if (source->priv && source->priv->child_sources)
1007 /* This is safe because even if a child_source finalizer or
1008 * closure notify tried to modify source->priv->child_sources
1009 * from outside the lock, it would fail since
1010 * SOURCE_DESTROYED(source) is now TRUE.
1012 tmp_list = source->priv->child_sources;
1015 g_source_destroy_internal (tmp_list->data, context, TRUE);
1016 g_source_unref_internal (tmp_list->data, context, TRUE);
1017 tmp_list = tmp_list->next;
1019 g_slist_free (source->priv->child_sources);
1020 source->priv->child_sources = NULL;
1023 g_source_unref_internal (source, context, TRUE);
1027 UNLOCK_CONTEXT (context);
1032 * @source: a #GSource
1034 * Removes a source from its #GMainContext, if any, and mark it as
1035 * destroyed. The source cannot be subsequently added to another
1039 g_source_destroy (GSource *source)
1041 GMainContext *context;
1043 g_return_if_fail (source != NULL);
1045 context = source->context;
1048 g_source_destroy_internal (source, context, FALSE);
1050 source->flags &= ~G_HOOK_FLAG_ACTIVE;
1055 * @source: a #GSource
1057 * Returns the numeric ID for a particular source. The ID of a source
1058 * is a positive integer which is unique within a particular main loop
1059 * context. The reverse
1060 * mapping from ID to source is done by g_main_context_find_source_by_id().
1062 * Return value: the ID (greater than 0) for the source
1065 g_source_get_id (GSource *source)
1069 g_return_val_if_fail (source != NULL, 0);
1070 g_return_val_if_fail (source->context != NULL, 0);
1072 LOCK_CONTEXT (source->context);
1073 result = source->source_id;
1074 UNLOCK_CONTEXT (source->context);
1080 * g_source_get_context:
1081 * @source: a #GSource
1083 * Gets the #GMainContext with which the source is associated.
1084 * Calling this function on a destroyed source is an error.
1086 * Return value: the #GMainContext with which the source is associated,
1087 * or %NULL if the context has not yet been added
1091 g_source_get_context (GSource *source)
1093 g_return_val_if_fail (!SOURCE_DESTROYED (source), NULL);
1095 return source->context;
1099 * g_source_add_poll:
1100 * @source:a #GSource
1101 * @fd: a #GPollFD structure holding information about a file
1102 * descriptor to watch.
1104 * Adds a file descriptor to the set of file descriptors polled for
1105 * this source. This is usually combined with g_source_new() to add an
1106 * event source. The event source's check function will typically test
1107 * the @revents field in the #GPollFD struct and return %TRUE if events need
1111 g_source_add_poll (GSource *source,
1114 GMainContext *context;
1116 g_return_if_fail (source != NULL);
1117 g_return_if_fail (fd != NULL);
1118 g_return_if_fail (!SOURCE_DESTROYED (source));
1120 context = source->context;
1123 LOCK_CONTEXT (context);
1125 source->poll_fds = g_slist_prepend (source->poll_fds, fd);
1129 if (!SOURCE_BLOCKED (source))
1130 g_main_context_add_poll_unlocked (context, source->priority, fd);
1131 UNLOCK_CONTEXT (context);
1136 * g_source_remove_poll:
1137 * @source:a #GSource
1138 * @fd: a #GPollFD structure previously passed to g_source_add_poll().
1140 * Removes a file descriptor from the set of file descriptors polled for
1144 g_source_remove_poll (GSource *source,
1147 GMainContext *context;
1149 g_return_if_fail (source != NULL);
1150 g_return_if_fail (fd != NULL);
1151 g_return_if_fail (!SOURCE_DESTROYED (source));
1153 context = source->context;
1156 LOCK_CONTEXT (context);
1158 source->poll_fds = g_slist_remove (source->poll_fds, fd);
1162 if (!SOURCE_BLOCKED (source))
1163 g_main_context_remove_poll_unlocked (context, fd);
1164 UNLOCK_CONTEXT (context);
1169 * g_source_add_child_source:
1170 * @source:a #GSource
1171 * @child_source: a second #GSource that @source should "poll"
1173 * Adds @child_source to @source as a "polled" source; when @source is
1174 * added to a #GMainContext, @child_source will be automatically added
1175 * with the same priority, when @child_source is triggered, it will
1176 * cause @source to dispatch (in addition to calling its own
1177 * callback), and when @source is destroyed, it will destroy
1178 * @child_source as well. (@source will also still be dispatched if
1179 * its own prepare/check functions indicate that it is ready.)
1181 * If you don't need @child_source to do anything on its own when it
1182 * triggers, you can call g_source_set_dummy_callback() on it to set a
1183 * callback that does nothing (except return %TRUE if appropriate).
1185 * @source will hold a reference on @child_source while @child_source
1186 * is attached to it.
1191 g_source_add_child_source (GSource *source,
1192 GSource *child_source)
1194 GMainContext *context;
1196 g_return_if_fail (source != NULL);
1197 g_return_if_fail (child_source != NULL);
1198 g_return_if_fail (!SOURCE_DESTROYED (source));
1199 g_return_if_fail (!SOURCE_DESTROYED (child_source));
1200 g_return_if_fail (child_source->context == NULL);
1201 g_return_if_fail (child_source->priv == NULL || child_source->priv->parent_source == NULL);
1203 context = source->context;
1206 LOCK_CONTEXT (context);
1209 source->priv = g_slice_new0 (GSourcePrivate);
1210 if (!child_source->priv)
1211 child_source->priv = g_slice_new0 (GSourcePrivate);
1213 source->priv->child_sources = g_slist_prepend (source->priv->child_sources,
1214 g_source_ref (child_source));
1215 child_source->priv->parent_source = source;
1216 g_source_set_priority_unlocked (child_source, context, source->priority);
1220 UNLOCK_CONTEXT (context);
1221 g_source_attach (child_source, context);
1226 * g_source_remove_child_source:
1227 * @source:a #GSource
1228 * @child_source: a #GSource previously passed to
1229 * g_source_add_child_source().
1231 * Detaches @child_source from @source and destroys it.
1236 g_source_remove_child_source (GSource *source,
1237 GSource *child_source)
1239 GMainContext *context;
1241 g_return_if_fail (source != NULL);
1242 g_return_if_fail (child_source != NULL);
1243 g_return_if_fail (child_source->priv != NULL && child_source->priv->parent_source == source);
1244 g_return_if_fail (!SOURCE_DESTROYED (source));
1245 g_return_if_fail (!SOURCE_DESTROYED (child_source));
1247 context = source->context;
1250 LOCK_CONTEXT (context);
1252 source->priv->child_sources = g_slist_remove (source->priv->child_sources, child_source);
1253 g_source_destroy_internal (child_source, context, TRUE);
1254 g_source_unref_internal (child_source, context, TRUE);
1257 UNLOCK_CONTEXT (context);
1261 * g_source_set_callback_indirect:
1262 * @source: the source
1263 * @callback_data: pointer to callback data "object"
1264 * @callback_funcs: functions for reference counting @callback_data
1265 * and getting the callback and data
1267 * Sets the callback function storing the data as a refcounted callback
1268 * "object". This is used internally. Note that calling
1269 * g_source_set_callback_indirect() assumes
1270 * an initial reference count on @callback_data, and thus
1271 * @callback_funcs->unref will eventually be called once more
1272 * than @callback_funcs->ref.
1275 g_source_set_callback_indirect (GSource *source,
1276 gpointer callback_data,
1277 GSourceCallbackFuncs *callback_funcs)
1279 GMainContext *context;
1280 gpointer old_cb_data;
1281 GSourceCallbackFuncs *old_cb_funcs;
1283 g_return_if_fail (source != NULL);
1284 g_return_if_fail (callback_funcs != NULL || callback_data == NULL);
1286 context = source->context;
1289 LOCK_CONTEXT (context);
1291 old_cb_data = source->callback_data;
1292 old_cb_funcs = source->callback_funcs;
1294 source->callback_data = callback_data;
1295 source->callback_funcs = callback_funcs;
1298 UNLOCK_CONTEXT (context);
1301 old_cb_funcs->unref (old_cb_data);
1305 g_source_callback_ref (gpointer cb_data)
1307 GSourceCallback *callback = cb_data;
1309 callback->ref_count++;
1314 g_source_callback_unref (gpointer cb_data)
1316 GSourceCallback *callback = cb_data;
1318 callback->ref_count--;
1319 if (callback->ref_count == 0)
1321 if (callback->notify)
1322 callback->notify (callback->data);
1328 g_source_callback_get (gpointer cb_data,
1333 GSourceCallback *callback = cb_data;
1335 *func = callback->func;
1336 *data = callback->data;
1339 static GSourceCallbackFuncs g_source_callback_funcs = {
1340 g_source_callback_ref,
1341 g_source_callback_unref,
1342 g_source_callback_get,
1346 * g_source_set_callback:
1347 * @source: the source
1348 * @func: a callback function
1349 * @data: the data to pass to callback function
1350 * @notify: a function to call when @data is no longer in use, or %NULL.
1352 * Sets the callback function for a source. The callback for a source is
1353 * called from the source's dispatch function.
1355 * The exact type of @func depends on the type of source; ie. you
1356 * should not count on @func being called with @data as its first
1359 * Typically, you won't use this function. Instead use functions specific
1360 * to the type of source you are using.
1363 g_source_set_callback (GSource *source,
1366 GDestroyNotify notify)
1368 GSourceCallback *new_callback;
1370 g_return_if_fail (source != NULL);
1372 new_callback = g_new (GSourceCallback, 1);
1374 new_callback->ref_count = 1;
1375 new_callback->func = func;
1376 new_callback->data = data;
1377 new_callback->notify = notify;
1379 g_source_set_callback_indirect (source, new_callback, &g_source_callback_funcs);
1384 * g_source_set_funcs:
1385 * @source: a #GSource
1386 * @funcs: the new #GSourceFuncs
1388 * Sets the source functions (can be used to override
1389 * default implementations) of an unattached source.
1394 g_source_set_funcs (GSource *source,
1395 GSourceFuncs *funcs)
1397 g_return_if_fail (source != NULL);
1398 g_return_if_fail (source->context == NULL);
1399 g_return_if_fail (source->ref_count > 0);
1400 g_return_if_fail (funcs != NULL);
1402 source->source_funcs = funcs;
1406 g_source_set_priority_unlocked (GSource *source,
1407 GMainContext *context,
1412 source->priority = priority;
1416 /* Remove the source from the context's source and then
1417 * add it back so it is sorted in the correct place
1419 g_source_list_remove (source, source->context);
1420 g_source_list_add (source, source->context);
1422 if (!SOURCE_BLOCKED (source))
1424 tmp_list = source->poll_fds;
1427 g_main_context_remove_poll_unlocked (context, tmp_list->data);
1428 g_main_context_add_poll_unlocked (context, priority, tmp_list->data);
1430 tmp_list = tmp_list->next;
1435 if (source->priv && source->priv->child_sources)
1437 tmp_list = source->priv->child_sources;
1440 g_source_set_priority_unlocked (tmp_list->data, context, priority);
1441 tmp_list = tmp_list->next;
1447 * g_source_set_priority:
1448 * @source: a #GSource
1449 * @priority: the new priority.
1451 * Sets the priority of a source. While the main loop is being run, a
1452 * source will be dispatched if it is ready to be dispatched and no
1453 * sources at a higher (numerically smaller) priority are ready to be
1457 g_source_set_priority (GSource *source,
1460 GMainContext *context;
1462 g_return_if_fail (source != NULL);
1464 context = source->context;
1467 LOCK_CONTEXT (context);
1468 g_source_set_priority_unlocked (source, context, priority);
1470 UNLOCK_CONTEXT (source->context);
1474 * g_source_get_priority:
1475 * @source: a #GSource
1477 * Gets the priority of a source.
1479 * Return value: the priority of the source
1482 g_source_get_priority (GSource *source)
1484 g_return_val_if_fail (source != NULL, 0);
1486 return source->priority;
1490 * g_source_set_can_recurse:
1491 * @source: a #GSource
1492 * @can_recurse: whether recursion is allowed for this source
1494 * Sets whether a source can be called recursively. If @can_recurse is
1495 * %TRUE, then while the source is being dispatched then this source
1496 * will be processed normally. Otherwise, all processing of this
1497 * source is blocked until the dispatch function returns.
1500 g_source_set_can_recurse (GSource *source,
1501 gboolean can_recurse)
1503 GMainContext *context;
1505 g_return_if_fail (source != NULL);
1507 context = source->context;
1510 LOCK_CONTEXT (context);
1513 source->flags |= G_SOURCE_CAN_RECURSE;
1515 source->flags &= ~G_SOURCE_CAN_RECURSE;
1518 UNLOCK_CONTEXT (context);
1522 * g_source_get_can_recurse:
1523 * @source: a #GSource
1525 * Checks whether a source is allowed to be called recursively.
1526 * see g_source_set_can_recurse().
1528 * Return value: whether recursion is allowed.
1531 g_source_get_can_recurse (GSource *source)
1533 g_return_val_if_fail (source != NULL, FALSE);
1535 return (source->flags & G_SOURCE_CAN_RECURSE) != 0;
1540 * g_source_set_name:
1541 * @source: a #GSource
1542 * @name: debug name for the source
1544 * Sets a name for the source, used in debugging and profiling.
1545 * The name defaults to #NULL.
1547 * The source name should describe in a human-readable way
1548 * what the source does. For example, "X11 event queue"
1549 * or "GTK+ repaint idle handler" or whatever it is.
1551 * It is permitted to call this function multiple times, but is not
1552 * recommended due to the potential performance impact. For example,
1553 * one could change the name in the "check" function of a #GSourceFuncs
1554 * to include details like the event type in the source name.
1559 g_source_set_name (GSource *source,
1562 g_return_if_fail (source != NULL);
1564 /* setting back to NULL is allowed, just because it's
1565 * weird if get_name can return NULL but you can't
1569 g_free (source->name);
1570 source->name = g_strdup (name);
1574 * g_source_get_name:
1575 * @source: a #GSource
1577 * Gets a name for the source, used in debugging and profiling.
1578 * The name may be #NULL if it has never been set with
1579 * g_source_set_name().
1581 * Return value: the name of the source
1584 G_CONST_RETURN char*
1585 g_source_get_name (GSource *source)
1587 g_return_val_if_fail (source != NULL, NULL);
1589 return source->name;
1593 * g_source_set_name_by_id:
1594 * @tag: a #GSource ID
1595 * @name: debug name for the source
1597 * Sets the name of a source using its ID.
1599 * This is a convenience utility to set source names from the return
1600 * value of g_idle_add(), g_timeout_add(), etc.
1605 g_source_set_name_by_id (guint tag,
1610 g_return_if_fail (tag > 0);
1612 source = g_main_context_find_source_by_id (NULL, tag);
1616 g_source_set_name (source, name);
1622 * @source: a #GSource
1624 * Increases the reference count on a source by one.
1626 * Return value: @source
1629 g_source_ref (GSource *source)
1631 GMainContext *context;
1633 g_return_val_if_fail (source != NULL, NULL);
1635 context = source->context;
1638 LOCK_CONTEXT (context);
1640 source->ref_count++;
1643 UNLOCK_CONTEXT (context);
1648 /* g_source_unref() but possible to call within context lock
1651 g_source_unref_internal (GSource *source,
1652 GMainContext *context,
1655 gpointer old_cb_data = NULL;
1656 GSourceCallbackFuncs *old_cb_funcs = NULL;
1658 g_return_if_fail (source != NULL);
1660 if (!have_lock && context)
1661 LOCK_CONTEXT (context);
1663 source->ref_count--;
1664 if (source->ref_count == 0)
1666 old_cb_data = source->callback_data;
1667 old_cb_funcs = source->callback_funcs;
1669 source->callback_data = NULL;
1670 source->callback_funcs = NULL;
1674 if (!SOURCE_DESTROYED (source))
1675 g_warning (G_STRLOC ": ref_count == 0, but source was still attached to a context!");
1676 g_source_list_remove (source, context);
1679 if (source->source_funcs->finalize)
1682 UNLOCK_CONTEXT (context);
1683 source->source_funcs->finalize (source);
1685 LOCK_CONTEXT (context);
1688 g_free (source->name);
1689 source->name = NULL;
1691 g_slist_free (source->poll_fds);
1692 source->poll_fds = NULL;
1696 g_slice_free (GSourcePrivate, source->priv);
1697 source->priv = NULL;
1703 if (!have_lock && context)
1704 UNLOCK_CONTEXT (context);
1709 UNLOCK_CONTEXT (context);
1711 old_cb_funcs->unref (old_cb_data);
1714 LOCK_CONTEXT (context);
1720 * @source: a #GSource
1722 * Decreases the reference count of a source by one. If the
1723 * resulting reference count is zero the source and associated
1724 * memory will be destroyed.
1727 g_source_unref (GSource *source)
1729 g_return_if_fail (source != NULL);
1731 g_source_unref_internal (source, source->context, FALSE);
1735 * g_main_context_find_source_by_id:
1736 * @context: a #GMainContext (if %NULL, the default context will be used)
1737 * @source_id: the source ID, as returned by g_source_get_id().
1739 * Finds a #GSource given a pair of context and ID.
1741 * Return value: the #GSource if found, otherwise, %NULL
1744 g_main_context_find_source_by_id (GMainContext *context,
1749 g_return_val_if_fail (source_id > 0, NULL);
1751 if (context == NULL)
1752 context = g_main_context_default ();
1754 LOCK_CONTEXT (context);
1756 source = context->source_list;
1759 if (!SOURCE_DESTROYED (source) &&
1760 source->source_id == source_id)
1762 source = source->next;
1765 UNLOCK_CONTEXT (context);
1771 * g_main_context_find_source_by_funcs_user_data:
1772 * @context: a #GMainContext (if %NULL, the default context will be used).
1773 * @funcs: the @source_funcs passed to g_source_new().
1774 * @user_data: the user data from the callback.
1776 * Finds a source with the given source functions and user data. If
1777 * multiple sources exist with the same source function and user data,
1778 * the first one found will be returned.
1780 * Return value: the source, if one was found, otherwise %NULL
1783 g_main_context_find_source_by_funcs_user_data (GMainContext *context,
1784 GSourceFuncs *funcs,
1789 g_return_val_if_fail (funcs != NULL, NULL);
1791 if (context == NULL)
1792 context = g_main_context_default ();
1794 LOCK_CONTEXT (context);
1796 source = context->source_list;
1799 if (!SOURCE_DESTROYED (source) &&
1800 source->source_funcs == funcs &&
1801 source->callback_funcs)
1803 GSourceFunc callback;
1804 gpointer callback_data;
1806 source->callback_funcs->get (source->callback_data, source, &callback, &callback_data);
1808 if (callback_data == user_data)
1811 source = source->next;
1814 UNLOCK_CONTEXT (context);
1820 * g_main_context_find_source_by_user_data:
1821 * @context: a #GMainContext
1822 * @user_data: the user_data for the callback.
1824 * Finds a source with the given user data for the callback. If
1825 * multiple sources exist with the same user data, the first
1826 * one found will be returned.
1828 * Return value: the source, if one was found, otherwise %NULL
1831 g_main_context_find_source_by_user_data (GMainContext *context,
1836 if (context == NULL)
1837 context = g_main_context_default ();
1839 LOCK_CONTEXT (context);
1841 source = context->source_list;
1844 if (!SOURCE_DESTROYED (source) &&
1845 source->callback_funcs)
1847 GSourceFunc callback;
1848 gpointer callback_data = NULL;
1850 source->callback_funcs->get (source->callback_data, source, &callback, &callback_data);
1852 if (callback_data == user_data)
1855 source = source->next;
1858 UNLOCK_CONTEXT (context);
1865 * @tag: the ID of the source to remove.
1867 * Removes the source with the given id from the default main context.
1869 * a #GSource is given by g_source_get_id(), or will be returned by the
1870 * functions g_source_attach(), g_idle_add(), g_idle_add_full(),
1871 * g_timeout_add(), g_timeout_add_full(), g_child_watch_add(),
1872 * g_child_watch_add_full(), g_io_add_watch(), and g_io_add_watch_full().
1874 * See also g_source_destroy(). You must use g_source_destroy() for sources
1875 * added to a non-default main context.
1877 * Return value: %TRUE if the source was found and removed.
1880 g_source_remove (guint tag)
1884 g_return_val_if_fail (tag > 0, FALSE);
1886 source = g_main_context_find_source_by_id (NULL, tag);
1888 g_source_destroy (source);
1890 return source != NULL;
1894 * g_source_remove_by_user_data:
1895 * @user_data: the user_data for the callback.
1897 * Removes a source from the default main loop context given the user
1898 * data for the callback. If multiple sources exist with the same user
1899 * data, only one will be destroyed.
1901 * Return value: %TRUE if a source was found and removed.
1904 g_source_remove_by_user_data (gpointer user_data)
1908 source = g_main_context_find_source_by_user_data (NULL, user_data);
1911 g_source_destroy (source);
1919 * g_source_remove_by_funcs_user_data:
1920 * @funcs: The @source_funcs passed to g_source_new()
1921 * @user_data: the user data for the callback
1923 * Removes a source from the default main loop context given the
1924 * source functions and user data. If multiple sources exist with the
1925 * same source functions and user data, only one will be destroyed.
1927 * Return value: %TRUE if a source was found and removed.
1930 g_source_remove_by_funcs_user_data (GSourceFuncs *funcs,
1935 g_return_val_if_fail (funcs != NULL, FALSE);
1937 source = g_main_context_find_source_by_funcs_user_data (NULL, funcs, user_data);
1940 g_source_destroy (source);
1948 * g_get_current_time:
1949 * @result: #GTimeVal structure in which to store current time.
1951 * Equivalent to the UNIX gettimeofday() function, but portable.
1953 * You may find g_get_real_time() to be more convenient.
1956 g_get_current_time (GTimeVal *result)
1961 g_return_if_fail (result != NULL);
1963 /*this is required on alpha, there the timeval structs are int's
1964 not longs and a cast only would fail horribly*/
1965 gettimeofday (&r, NULL);
1966 result->tv_sec = r.tv_sec;
1967 result->tv_usec = r.tv_usec;
1972 g_return_if_fail (result != NULL);
1974 GetSystemTimeAsFileTime (&ft);
1975 memmove (&time64, &ft, sizeof (FILETIME));
1977 /* Convert from 100s of nanoseconds since 1601-01-01
1978 * to Unix epoch. Yes, this is Y2038 unsafe.
1980 time64 -= G_GINT64_CONSTANT (116444736000000000);
1983 result->tv_sec = time64 / 1000000;
1984 result->tv_usec = time64 % 1000000;
1991 * Queries the system wall-clock time.
1993 * This call is functionally equivalent to g_get_current_time() except
1994 * that the return value is often more convenient than dealing with a
1997 * You should only use this call if you are actually interested in the real
1998 * wall-clock time. g_get_monotonic_time() is probably more useful for
1999 * measuring intervals.
2001 * Returns: the number of microseconds since January 1, 1970 UTC.
2006 g_get_real_time (void)
2010 g_get_current_time (&tv);
2012 return (((gint64) tv.tv_sec) * 1000000) + tv.tv_usec;
2016 * g_get_monotonic_time:
2018 * Queries the system monotonic time, if available.
2020 * On POSIX systems with clock_gettime() and %CLOCK_MONOTONIC this call
2021 * is a very shallow wrapper for that. Otherwise, we make a best effort
2022 * that probably involves returning the wall clock time (with at least
2023 * microsecond accuracy, subject to the limitations of the OS kernel).
2025 * Note that, on Windows, "limitations of the OS kernel" is a rather
2026 * substantial statement. Depending on the configuration of the system,
2027 * the wall clock time is updated as infrequently as 64 times a second
2028 * (which is approximately every 16ms).
2030 * Returns: the monotonic time, in microseconds
2035 g_get_monotonic_time (void)
2037 #ifdef HAVE_CLOCK_GETTIME
2038 /* librt clock_gettime() is our first choice */
2040 static int clockid = CLOCK_REALTIME;
2043 #ifdef HAVE_MONOTONIC_CLOCK
2044 /* We have to check if we actually have monotonic clock support.
2046 * There is no thread safety issue here since there is no harm if we
2050 static gboolean checked;
2052 if G_UNLIKELY (!checked)
2054 if (sysconf (_SC_MONOTONIC_CLOCK) >= 0)
2055 clockid = CLOCK_MONOTONIC;
2061 clock_gettime (clockid, &ts);
2063 /* In theory monotonic time can have any epoch.
2065 * glib presently assumes the following:
2067 * 1) The epoch comes some time after the birth of Jesus of Nazareth, but
2068 * not more than 10000 years later.
2070 * 2) The current time also falls sometime within this range.
2072 * These two reasonable assumptions leave us with a maximum deviation from
2073 * the epoch of 10000 years, or 315569520000000000 seconds.
2075 * If we restrict ourselves to this range then the number of microseconds
2076 * will always fit well inside the constraints of a int64 (by a factor of
2079 * If you actually hit the following assertion, probably you should file a
2080 * bug against your operating system for being excessively silly.
2082 g_assert (G_GINT64_CONSTANT (-315569520000000000) < ts.tv_sec &&
2083 ts.tv_sec < G_GINT64_CONSTANT (315569520000000000));
2085 return (((gint64) ts.tv_sec) * 1000000) + (ts.tv_nsec / 1000);
2088 /* It may look like we are discarding accuracy on Windows (since its
2089 * current time is expressed in 100s of nanoseconds) but according to
2090 * many sources, the time is only updated 64 times per second, so
2091 * microsecond accuracy is more than enough.
2096 g_get_current_time (&tv);
2098 return (((gint64) tv.tv_sec) * 1000000) + tv.tv_usec;
2104 g_main_dispatch_free (gpointer dispatch)
2106 g_slice_free (GMainDispatch, dispatch);
2109 /* Running the main loop */
2111 static GMainDispatch *
2114 static GStaticPrivate depth_private = G_STATIC_PRIVATE_INIT;
2115 GMainDispatch *dispatch = g_static_private_get (&depth_private);
2118 dispatch = g_slice_new0 (GMainDispatch);
2119 g_static_private_set (&depth_private, dispatch, g_main_dispatch_free);
2128 * Returns the depth of the stack of calls to
2129 * g_main_context_dispatch() on any #GMainContext in the current thread.
2130 * That is, when called from the toplevel, it gives 0. When
2131 * called from within a callback from g_main_context_iteration()
2132 * (or g_main_loop_run(), etc.) it returns 1. When called from within
2133 * a callback to a recursive call to g_main_context_iterate(),
2134 * it returns 2. And so forth.
2136 * This function is useful in a situation like the following:
2137 * Imagine an extremely simple "garbage collected" system.
2140 * static GList *free_list;
2143 * allocate_memory (gsize size)
2145 * gpointer result = g_malloc (size);
2146 * free_list = g_list_prepend (free_list, result);
2151 * free_allocated_memory (void)
2154 * for (l = free_list; l; l = l->next);
2156 * g_list_free (free_list);
2164 * g_main_context_iteration (NULL, TRUE);
2165 * free_allocated_memory();
2169 * This works from an application, however, if you want to do the same
2170 * thing from a library, it gets more difficult, since you no longer
2171 * control the main loop. You might think you can simply use an idle
2172 * function to make the call to free_allocated_memory(), but that
2173 * doesn't work, since the idle function could be called from a
2174 * recursive callback. This can be fixed by using g_main_depth()
2178 * allocate_memory (gsize size)
2180 * FreeListBlock *block = g_new (FreeListBlock, 1);
2181 * block->mem = g_malloc (size);
2182 * block->depth = g_main_depth ();
2183 * free_list = g_list_prepend (free_list, block);
2184 * return block->mem;
2188 * free_allocated_memory (void)
2192 * int depth = g_main_depth ();
2193 * for (l = free_list; l; );
2195 * GList *next = l->next;
2196 * FreeListBlock *block = l->data;
2197 * if (block->depth > depth)
2199 * g_free (block->mem);
2201 * free_list = g_list_delete_link (free_list, l);
2209 * There is a temptation to use g_main_depth() to solve
2210 * problems with reentrancy. For instance, while waiting for data
2211 * to be received from the network in response to a menu item,
2212 * the menu item might be selected again. It might seem that
2213 * one could make the menu item's callback return immediately
2214 * and do nothing if g_main_depth() returns a value greater than 1.
2215 * However, this should be avoided since the user then sees selecting
2216 * the menu item do nothing. Furthermore, you'll find yourself adding
2217 * these checks all over your code, since there are doubtless many,
2218 * many things that the user could do. Instead, you can use the
2219 * following techniques:
2224 * Use gtk_widget_set_sensitive() or modal dialogs to prevent
2225 * the user from interacting with elements while the main
2226 * loop is recursing.
2231 * Avoid main loop recursion in situations where you can't handle
2232 * arbitrary callbacks. Instead, structure your code so that you
2233 * simply return to the main loop and then get called again when
2234 * there is more work to do.
2239 * Return value: The main loop recursion level in the current thread
2244 GMainDispatch *dispatch = get_dispatch ();
2245 return dispatch->depth;
2249 * g_main_current_source:
2251 * Returns the currently firing source for this thread.
2253 * Return value: The currently firing source or %NULL.
2258 g_main_current_source (void)
2260 GMainDispatch *dispatch = get_dispatch ();
2261 return dispatch->dispatching_sources ? dispatch->dispatching_sources->data : NULL;
2265 * g_source_is_destroyed:
2266 * @source: a #GSource
2268 * Returns whether @source has been destroyed.
2270 * This is important when you operate upon your objects
2271 * from within idle handlers, but may have freed the object
2272 * before the dispatch of your idle handler.
2276 * idle_callback (gpointer data)
2278 * SomeWidget *self = data;
2280 * GDK_THREADS_ENTER (<!-- -->);
2281 * /<!-- -->* do stuff with self *<!-- -->/
2282 * self->idle_id = 0;
2283 * GDK_THREADS_LEAVE (<!-- -->);
2289 * some_widget_do_stuff_later (SomeWidget *self)
2291 * self->idle_id = g_idle_add (idle_callback, self);
2295 * some_widget_finalize (GObject *object)
2297 * SomeWidget *self = SOME_WIDGET (object);
2299 * if (self->idle_id)
2300 * g_source_remove (self->idle_id);
2302 * G_OBJECT_CLASS (parent_class)->finalize (object);
2306 * This will fail in a multi-threaded application if the
2307 * widget is destroyed before the idle handler fires due
2308 * to the use after free in the callback. A solution, to
2309 * this particular problem, is to check to if the source
2310 * has already been destroy within the callback.
2314 * idle_callback (gpointer data)
2316 * SomeWidget *self = data;
2318 * GDK_THREADS_ENTER ();
2319 * if (!g_source_is_destroyed (g_main_current_source ()))
2321 * /<!-- -->* do stuff with self *<!-- -->/
2323 * GDK_THREADS_LEAVE ();
2329 * Return value: %TRUE if the source has been destroyed
2334 g_source_is_destroyed (GSource *source)
2336 return SOURCE_DESTROYED (source);
2339 /* Temporarily remove all this source's file descriptors from the
2340 * poll(), so that if data comes available for one of the file descriptors
2341 * we don't continually spin in the poll()
2343 /* HOLDS: source->context's lock */
2345 block_source (GSource *source)
2349 g_return_if_fail (!SOURCE_BLOCKED (source));
2351 tmp_list = source->poll_fds;
2354 g_main_context_remove_poll_unlocked (source->context, tmp_list->data);
2355 tmp_list = tmp_list->next;
2359 /* HOLDS: source->context's lock */
2361 unblock_source (GSource *source)
2365 g_return_if_fail (!SOURCE_BLOCKED (source)); /* Source already unblocked */
2366 g_return_if_fail (!SOURCE_DESTROYED (source));
2368 tmp_list = source->poll_fds;
2371 g_main_context_add_poll_unlocked (source->context, source->priority, tmp_list->data);
2372 tmp_list = tmp_list->next;
2376 /* HOLDS: context's lock */
2378 g_main_dispatch (GMainContext *context)
2380 GMainDispatch *current = get_dispatch ();
2383 for (i = 0; i < context->pending_dispatches->len; i++)
2385 GSource *source = context->pending_dispatches->pdata[i];
2387 context->pending_dispatches->pdata[i] = NULL;
2390 source->flags &= ~G_SOURCE_READY;
2392 if (!SOURCE_DESTROYED (source))
2394 gboolean was_in_call;
2395 gpointer user_data = NULL;
2396 GSourceFunc callback = NULL;
2397 GSourceCallbackFuncs *cb_funcs;
2399 gboolean need_destroy;
2401 gboolean (*dispatch) (GSource *,
2404 GSList current_source_link;
2406 dispatch = source->source_funcs->dispatch;
2407 cb_funcs = source->callback_funcs;
2408 cb_data = source->callback_data;
2411 cb_funcs->ref (cb_data);
2413 if ((source->flags & G_SOURCE_CAN_RECURSE) == 0)
2414 block_source (source);
2416 was_in_call = source->flags & G_HOOK_FLAG_IN_CALL;
2417 source->flags |= G_HOOK_FLAG_IN_CALL;
2420 cb_funcs->get (cb_data, source, &callback, &user_data);
2422 UNLOCK_CONTEXT (context);
2425 /* The on-stack allocation of the GSList is unconventional, but
2426 * we know that the lifetime of the link is bounded to this
2427 * function as the link is kept in a thread specific list and
2428 * not manipulated outside of this function and its descendants.
2429 * Avoiding the overhead of a g_slist_alloc() is useful as many
2430 * applications do little more than dispatch events.
2432 * This is a performance hack - do not revert to g_slist_prepend()!
2434 current_source_link.data = source;
2435 current_source_link.next = current->dispatching_sources;
2436 current->dispatching_sources = ¤t_source_link;
2437 need_destroy = ! dispatch (source,
2440 g_assert (current->dispatching_sources == ¤t_source_link);
2441 current->dispatching_sources = current_source_link.next;
2445 cb_funcs->unref (cb_data);
2447 LOCK_CONTEXT (context);
2450 source->flags &= ~G_HOOK_FLAG_IN_CALL;
2452 if ((source->flags & G_SOURCE_CAN_RECURSE) == 0 &&
2453 !SOURCE_DESTROYED (source))
2454 unblock_source (source);
2456 /* Note: this depends on the fact that we can't switch
2457 * sources from one main context to another
2459 if (need_destroy && !SOURCE_DESTROYED (source))
2461 g_assert (source->context == context);
2462 g_source_destroy_internal (source, context, TRUE);
2466 SOURCE_UNREF (source, context);
2469 g_ptr_array_set_size (context->pending_dispatches, 0);
2472 /* Holds context's lock */
2473 static inline GSource *
2474 next_valid_source (GMainContext *context,
2477 GSource *new_source = source ? source->next : context->source_list;
2481 if (!SOURCE_DESTROYED (new_source))
2483 new_source->ref_count++;
2487 new_source = new_source->next;
2491 SOURCE_UNREF (source, context);
2497 * g_main_context_acquire:
2498 * @context: a #GMainContext
2500 * Tries to become the owner of the specified context.
2501 * If some other thread is the owner of the context,
2502 * returns %FALSE immediately. Ownership is properly
2503 * recursive: the owner can require ownership again
2504 * and will release ownership when g_main_context_release()
2505 * is called as many times as g_main_context_acquire().
2507 * You must be the owner of a context before you
2508 * can call g_main_context_prepare(), g_main_context_query(),
2509 * g_main_context_check(), g_main_context_dispatch().
2511 * Return value: %TRUE if the operation succeeded, and
2512 * this thread is now the owner of @context.
2515 g_main_context_acquire (GMainContext *context)
2517 #ifdef G_THREADS_ENABLED
2518 gboolean result = FALSE;
2519 GThread *self = G_THREAD_SELF;
2521 if (context == NULL)
2522 context = g_main_context_default ();
2524 LOCK_CONTEXT (context);
2526 if (!context->owner)
2528 context->owner = self;
2529 g_assert (context->owner_count == 0);
2532 if (context->owner == self)
2534 context->owner_count++;
2538 UNLOCK_CONTEXT (context);
2541 #else /* !G_THREADS_ENABLED */
2543 #endif /* G_THREADS_ENABLED */
2547 * g_main_context_release:
2548 * @context: a #GMainContext
2550 * Releases ownership of a context previously acquired by this thread
2551 * with g_main_context_acquire(). If the context was acquired multiple
2552 * times, the ownership will be released only when g_main_context_release()
2553 * is called as many times as it was acquired.
2556 g_main_context_release (GMainContext *context)
2558 #ifdef G_THREADS_ENABLED
2559 if (context == NULL)
2560 context = g_main_context_default ();
2562 LOCK_CONTEXT (context);
2564 context->owner_count--;
2565 if (context->owner_count == 0)
2567 context->owner = NULL;
2569 if (context->waiters)
2571 GMainWaiter *waiter = context->waiters->data;
2572 gboolean loop_internal_waiter =
2573 (waiter->mutex == g_static_mutex_get_mutex (&context->mutex));
2574 context->waiters = g_slist_delete_link (context->waiters,
2576 if (!loop_internal_waiter)
2577 g_mutex_lock (waiter->mutex);
2579 g_cond_signal (waiter->cond);
2581 if (!loop_internal_waiter)
2582 g_mutex_unlock (waiter->mutex);
2586 UNLOCK_CONTEXT (context);
2587 #endif /* G_THREADS_ENABLED */
2591 * g_main_context_wait:
2592 * @context: a #GMainContext
2593 * @cond: a condition variable
2594 * @mutex: a mutex, currently held
2596 * Tries to become the owner of the specified context,
2597 * as with g_main_context_acquire(). But if another thread
2598 * is the owner, atomically drop @mutex and wait on @cond until
2599 * that owner releases ownership or until @cond is signaled, then
2600 * try again (once) to become the owner.
2602 * Return value: %TRUE if the operation succeeded, and
2603 * this thread is now the owner of @context.
2606 g_main_context_wait (GMainContext *context,
2610 #ifdef G_THREADS_ENABLED
2611 gboolean result = FALSE;
2612 GThread *self = G_THREAD_SELF;
2613 gboolean loop_internal_waiter;
2615 if (context == NULL)
2616 context = g_main_context_default ();
2618 loop_internal_waiter = (mutex == g_static_mutex_get_mutex (&context->mutex));
2620 if (!loop_internal_waiter)
2621 LOCK_CONTEXT (context);
2623 if (context->owner && context->owner != self)
2628 waiter.mutex = mutex;
2630 context->waiters = g_slist_append (context->waiters, &waiter);
2632 if (!loop_internal_waiter)
2633 UNLOCK_CONTEXT (context);
2634 g_cond_wait (cond, mutex);
2635 if (!loop_internal_waiter)
2636 LOCK_CONTEXT (context);
2638 context->waiters = g_slist_remove (context->waiters, &waiter);
2641 if (!context->owner)
2643 context->owner = self;
2644 g_assert (context->owner_count == 0);
2647 if (context->owner == self)
2649 context->owner_count++;
2653 if (!loop_internal_waiter)
2654 UNLOCK_CONTEXT (context);
2657 #else /* !G_THREADS_ENABLED */
2659 #endif /* G_THREADS_ENABLED */
2663 * g_main_context_prepare:
2664 * @context: a #GMainContext
2665 * @priority: location to store priority of highest priority
2666 * source already ready.
2668 * Prepares to poll sources within a main loop. The resulting information
2669 * for polling is determined by calling g_main_context_query ().
2671 * Return value: %TRUE if some source is ready to be dispatched
2675 g_main_context_prepare (GMainContext *context,
2680 gint current_priority = G_MAXINT;
2683 if (context == NULL)
2684 context = g_main_context_default ();
2686 LOCK_CONTEXT (context);
2688 context->time_is_fresh = FALSE;
2689 context->real_time_is_fresh = FALSE;
2691 if (context->in_check_or_prepare)
2693 g_warning ("g_main_context_prepare() called recursively from within a source's check() or "
2694 "prepare() member.");
2695 UNLOCK_CONTEXT (context);
2699 #ifdef G_THREADS_ENABLED
2700 if (context->poll_waiting)
2702 g_warning("g_main_context_prepare(): main loop already active in another thread");
2703 UNLOCK_CONTEXT (context);
2707 context->poll_waiting = TRUE;
2708 #endif /* G_THREADS_ENABLED */
2711 /* If recursing, finish up current dispatch, before starting over */
2712 if (context->pending_dispatches)
2715 g_main_dispatch (context, ¤t_time);
2717 UNLOCK_CONTEXT (context);
2722 /* If recursing, clear list of pending dispatches */
2724 for (i = 0; i < context->pending_dispatches->len; i++)
2726 if (context->pending_dispatches->pdata[i])
2727 SOURCE_UNREF ((GSource *)context->pending_dispatches->pdata[i], context);
2729 g_ptr_array_set_size (context->pending_dispatches, 0);
2731 /* Prepare all sources */
2733 context->timeout = -1;
2735 source = next_valid_source (context, NULL);
2738 gint source_timeout = -1;
2740 if ((n_ready > 0) && (source->priority > current_priority))
2742 SOURCE_UNREF (source, context);
2745 if (SOURCE_BLOCKED (source))
2748 if (!(source->flags & G_SOURCE_READY))
2751 gboolean (*prepare) (GSource *source,
2754 prepare = source->source_funcs->prepare;
2755 context->in_check_or_prepare++;
2756 UNLOCK_CONTEXT (context);
2758 result = (*prepare) (source, &source_timeout);
2760 LOCK_CONTEXT (context);
2761 context->in_check_or_prepare--;
2765 GSource *ready_source = source;
2767 while (ready_source)
2769 ready_source->flags |= G_SOURCE_READY;
2770 ready_source = ready_source->priv ? ready_source->priv->parent_source : NULL;
2775 if (source->flags & G_SOURCE_READY)
2778 current_priority = source->priority;
2779 context->timeout = 0;
2782 if (source_timeout >= 0)
2784 if (context->timeout < 0)
2785 context->timeout = source_timeout;
2787 context->timeout = MIN (context->timeout, source_timeout);
2791 source = next_valid_source (context, source);
2794 UNLOCK_CONTEXT (context);
2797 *priority = current_priority;
2799 return (n_ready > 0);
2803 * g_main_context_query:
2804 * @context: a #GMainContext
2805 * @max_priority: maximum priority source to check
2806 * @timeout_: location to store timeout to be used in polling
2807 * @fds: location to store #GPollFD records that need to be polled.
2808 * @n_fds: length of @fds.
2810 * Determines information necessary to poll this main loop.
2812 * Return value: the number of records actually stored in @fds,
2813 * or, if more than @n_fds records need to be stored, the number
2814 * of records that need to be stored.
2817 g_main_context_query (GMainContext *context,
2826 LOCK_CONTEXT (context);
2828 pollrec = context->poll_records;
2830 while (pollrec && max_priority >= pollrec->priority)
2832 /* We need to include entries with fd->events == 0 in the array because
2833 * otherwise if the application changes fd->events behind our back and
2834 * makes it non-zero, we'll be out of sync when we check the fds[] array.
2835 * (Changing fd->events after adding an FD wasn't an anticipated use of
2836 * this API, but it occurs in practice.) */
2839 fds[n_poll].fd = pollrec->fd->fd;
2840 /* In direct contradiction to the Unix98 spec, IRIX runs into
2841 * difficulty if you pass in POLLERR, POLLHUP or POLLNVAL
2842 * flags in the events field of the pollfd while it should
2843 * just ignoring them. So we mask them out here.
2845 fds[n_poll].events = pollrec->fd->events & ~(G_IO_ERR|G_IO_HUP|G_IO_NVAL);
2846 fds[n_poll].revents = 0;
2849 pollrec = pollrec->next;
2853 #ifdef G_THREADS_ENABLED
2854 context->poll_changed = FALSE;
2859 *timeout = context->timeout;
2862 context->time_is_fresh = FALSE;
2863 context->real_time_is_fresh = FALSE;
2867 UNLOCK_CONTEXT (context);
2873 * g_main_context_check:
2874 * @context: a #GMainContext
2875 * @max_priority: the maximum numerical priority of sources to check
2876 * @fds: array of #GPollFD's that was passed to the last call to
2877 * g_main_context_query()
2878 * @n_fds: return value of g_main_context_query()
2880 * Passes the results of polling back to the main loop.
2882 * Return value: %TRUE if some sources are ready to be dispatched.
2885 g_main_context_check (GMainContext *context,
2895 LOCK_CONTEXT (context);
2897 if (context->in_check_or_prepare)
2899 g_warning ("g_main_context_check() called recursively from within a source's check() or "
2900 "prepare() member.");
2901 UNLOCK_CONTEXT (context);
2905 #ifdef G_THREADS_ENABLED
2906 if (!context->poll_waiting)
2910 read (context->wake_up_pipe[0], &a, 1);
2914 context->poll_waiting = FALSE;
2916 /* If the set of poll file descriptors changed, bail out
2917 * and let the main loop rerun
2919 if (context->poll_changed)
2921 UNLOCK_CONTEXT (context);
2924 #endif /* G_THREADS_ENABLED */
2926 pollrec = context->poll_records;
2930 if (pollrec->fd->events)
2931 pollrec->fd->revents = fds[i].revents;
2933 pollrec = pollrec->next;
2937 source = next_valid_source (context, NULL);
2940 if ((n_ready > 0) && (source->priority > max_priority))
2942 SOURCE_UNREF (source, context);
2945 if (SOURCE_BLOCKED (source))
2948 if (!(source->flags & G_SOURCE_READY))
2951 gboolean (*check) (GSource *source);
2953 check = source->source_funcs->check;
2955 context->in_check_or_prepare++;
2956 UNLOCK_CONTEXT (context);
2958 result = (*check) (source);
2960 LOCK_CONTEXT (context);
2961 context->in_check_or_prepare--;
2965 GSource *ready_source = source;
2967 while (ready_source)
2969 ready_source->flags |= G_SOURCE_READY;
2970 ready_source = ready_source->priv ? ready_source->priv->parent_source : NULL;
2975 if (source->flags & G_SOURCE_READY)
2977 source->ref_count++;
2978 g_ptr_array_add (context->pending_dispatches, source);
2982 /* never dispatch sources with less priority than the first
2983 * one we choose to dispatch
2985 max_priority = source->priority;
2989 source = next_valid_source (context, source);
2992 UNLOCK_CONTEXT (context);
2998 * g_main_context_dispatch:
2999 * @context: a #GMainContext
3001 * Dispatches all pending sources.
3004 g_main_context_dispatch (GMainContext *context)
3006 LOCK_CONTEXT (context);
3008 if (context->pending_dispatches->len > 0)
3010 g_main_dispatch (context);
3013 UNLOCK_CONTEXT (context);
3016 /* HOLDS context lock */
3018 g_main_context_iterate (GMainContext *context,
3025 gboolean some_ready;
3026 gint nfds, allocated_nfds;
3027 GPollFD *fds = NULL;
3029 UNLOCK_CONTEXT (context);
3031 #ifdef G_THREADS_ENABLED
3032 if (!g_main_context_acquire (context))
3034 gboolean got_ownership;
3036 LOCK_CONTEXT (context);
3038 g_return_val_if_fail (g_thread_supported (), FALSE);
3044 context->cond = g_cond_new ();
3046 got_ownership = g_main_context_wait (context,
3048 g_static_mutex_get_mutex (&context->mutex));
3054 LOCK_CONTEXT (context);
3055 #endif /* G_THREADS_ENABLED */
3057 if (!context->cached_poll_array)
3059 context->cached_poll_array_size = context->n_poll_records;
3060 context->cached_poll_array = g_new (GPollFD, context->n_poll_records);
3063 allocated_nfds = context->cached_poll_array_size;
3064 fds = context->cached_poll_array;
3066 UNLOCK_CONTEXT (context);
3068 g_main_context_prepare (context, &max_priority);
3070 while ((nfds = g_main_context_query (context, max_priority, &timeout, fds,
3071 allocated_nfds)) > allocated_nfds)
3073 LOCK_CONTEXT (context);
3075 context->cached_poll_array_size = allocated_nfds = nfds;
3076 context->cached_poll_array = fds = g_new (GPollFD, nfds);
3077 UNLOCK_CONTEXT (context);
3083 g_main_context_poll (context, timeout, max_priority, fds, nfds);
3085 some_ready = g_main_context_check (context, max_priority, fds, nfds);
3088 g_main_context_dispatch (context);
3090 #ifdef G_THREADS_ENABLED
3091 g_main_context_release (context);
3092 #endif /* G_THREADS_ENABLED */
3094 LOCK_CONTEXT (context);
3100 * g_main_context_pending:
3101 * @context: a #GMainContext (if %NULL, the default context will be used)
3103 * Checks if any sources have pending events for the given context.
3105 * Return value: %TRUE if events are pending.
3108 g_main_context_pending (GMainContext *context)
3113 context = g_main_context_default();
3115 LOCK_CONTEXT (context);
3116 retval = g_main_context_iterate (context, FALSE, FALSE, G_THREAD_SELF);
3117 UNLOCK_CONTEXT (context);
3123 * g_main_context_iteration:
3124 * @context: a #GMainContext (if %NULL, the default context will be used)
3125 * @may_block: whether the call may block.
3127 * Runs a single iteration for the given main loop. This involves
3128 * checking to see if any event sources are ready to be processed,
3129 * then if no events sources are ready and @may_block is %TRUE, waiting
3130 * for a source to become ready, then dispatching the highest priority
3131 * events sources that are ready. Otherwise, if @may_block is %FALSE
3132 * sources are not waited to become ready, only those highest priority
3133 * events sources will be dispatched (if any), that are ready at this
3134 * given moment without further waiting.
3136 * Note that even when @may_block is %TRUE, it is still possible for
3137 * g_main_context_iteration() to return %FALSE, since the the wait may
3138 * be interrupted for other reasons than an event source becoming ready.
3140 * Return value: %TRUE if events were dispatched.
3143 g_main_context_iteration (GMainContext *context, gboolean may_block)
3148 context = g_main_context_default();
3150 LOCK_CONTEXT (context);
3151 retval = g_main_context_iterate (context, may_block, TRUE, G_THREAD_SELF);
3152 UNLOCK_CONTEXT (context);
3159 * @context: a #GMainContext (if %NULL, the default context will be used).
3160 * @is_running: set to %TRUE to indicate that the loop is running. This
3161 * is not very important since calling g_main_loop_run() will set this to
3164 * Creates a new #GMainLoop structure.
3166 * Return value: a new #GMainLoop.
3169 g_main_loop_new (GMainContext *context,
3170 gboolean is_running)
3175 context = g_main_context_default();
3177 g_main_context_ref (context);
3179 loop = g_new0 (GMainLoop, 1);
3180 loop->context = context;
3181 loop->is_running = is_running != FALSE;
3182 loop->ref_count = 1;
3189 * @loop: a #GMainLoop
3191 * Increases the reference count on a #GMainLoop object by one.
3193 * Return value: @loop
3196 g_main_loop_ref (GMainLoop *loop)
3198 g_return_val_if_fail (loop != NULL, NULL);
3199 g_return_val_if_fail (g_atomic_int_get (&loop->ref_count) > 0, NULL);
3201 g_atomic_int_inc (&loop->ref_count);
3207 * g_main_loop_unref:
3208 * @loop: a #GMainLoop
3210 * Decreases the reference count on a #GMainLoop object by one. If
3211 * the result is zero, free the loop and free all associated memory.
3214 g_main_loop_unref (GMainLoop *loop)
3216 g_return_if_fail (loop != NULL);
3217 g_return_if_fail (g_atomic_int_get (&loop->ref_count) > 0);
3219 if (!g_atomic_int_dec_and_test (&loop->ref_count))
3222 g_main_context_unref (loop->context);
3228 * @loop: a #GMainLoop
3230 * Runs a main loop until g_main_loop_quit() is called on the loop.
3231 * If this is called for the thread of the loop's #GMainContext,
3232 * it will process events from the loop, otherwise it will
3236 g_main_loop_run (GMainLoop *loop)
3238 GThread *self = G_THREAD_SELF;
3240 g_return_if_fail (loop != NULL);
3241 g_return_if_fail (g_atomic_int_get (&loop->ref_count) > 0);
3243 #ifdef G_THREADS_ENABLED
3244 if (!g_main_context_acquire (loop->context))
3246 gboolean got_ownership = FALSE;
3248 /* Another thread owns this context */
3249 if (!g_thread_supported ())
3251 g_warning ("g_main_loop_run() was called from second thread but "
3252 "g_thread_init() was never called.");
3256 LOCK_CONTEXT (loop->context);
3258 g_atomic_int_inc (&loop->ref_count);
3260 if (!loop->is_running)
3261 loop->is_running = TRUE;
3263 if (!loop->context->cond)
3264 loop->context->cond = g_cond_new ();
3266 while (loop->is_running && !got_ownership)
3267 got_ownership = g_main_context_wait (loop->context,
3268 loop->context->cond,
3269 g_static_mutex_get_mutex (&loop->context->mutex));
3271 if (!loop->is_running)
3273 UNLOCK_CONTEXT (loop->context);
3275 g_main_context_release (loop->context);
3276 g_main_loop_unref (loop);
3280 g_assert (got_ownership);
3283 LOCK_CONTEXT (loop->context);
3284 #endif /* G_THREADS_ENABLED */
3286 if (loop->context->in_check_or_prepare)
3288 g_warning ("g_main_loop_run(): called recursively from within a source's "
3289 "check() or prepare() member, iteration not possible.");
3293 g_atomic_int_inc (&loop->ref_count);
3294 loop->is_running = TRUE;
3295 while (loop->is_running)
3296 g_main_context_iterate (loop->context, TRUE, TRUE, self);
3298 UNLOCK_CONTEXT (loop->context);
3300 #ifdef G_THREADS_ENABLED
3301 g_main_context_release (loop->context);
3302 #endif /* G_THREADS_ENABLED */
3304 g_main_loop_unref (loop);
3309 * @loop: a #GMainLoop
3311 * Stops a #GMainLoop from running. Any calls to g_main_loop_run()
3312 * for the loop will return.
3314 * Note that sources that have already been dispatched when
3315 * g_main_loop_quit() is called will still be executed.
3318 g_main_loop_quit (GMainLoop *loop)
3320 g_return_if_fail (loop != NULL);
3321 g_return_if_fail (g_atomic_int_get (&loop->ref_count) > 0);
3323 LOCK_CONTEXT (loop->context);
3324 loop->is_running = FALSE;
3325 g_main_context_wakeup_unlocked (loop->context);
3327 #ifdef G_THREADS_ENABLED
3328 if (loop->context->cond)
3329 g_cond_broadcast (loop->context->cond);
3330 #endif /* G_THREADS_ENABLED */
3332 UNLOCK_CONTEXT (loop->context);
3336 * g_main_loop_is_running:
3337 * @loop: a #GMainLoop.
3339 * Checks to see if the main loop is currently being run via g_main_loop_run().
3341 * Return value: %TRUE if the mainloop is currently being run.
3344 g_main_loop_is_running (GMainLoop *loop)
3346 g_return_val_if_fail (loop != NULL, FALSE);
3347 g_return_val_if_fail (g_atomic_int_get (&loop->ref_count) > 0, FALSE);
3349 return loop->is_running;
3353 * g_main_loop_get_context:
3354 * @loop: a #GMainLoop.
3356 * Returns the #GMainContext of @loop.
3358 * Return value: the #GMainContext of @loop
3361 g_main_loop_get_context (GMainLoop *loop)
3363 g_return_val_if_fail (loop != NULL, NULL);
3364 g_return_val_if_fail (g_atomic_int_get (&loop->ref_count) > 0, NULL);
3366 return loop->context;
3369 /* HOLDS: context's lock */
3371 g_main_context_poll (GMainContext *context,
3377 #ifdef G_MAIN_POLL_DEBUG
3383 GPollFunc poll_func;
3385 if (n_fds || timeout != 0)
3387 #ifdef G_MAIN_POLL_DEBUG
3388 if (_g_main_poll_debug)
3390 g_print ("polling context=%p n=%d timeout=%d\n",
3391 context, n_fds, timeout);
3392 poll_timer = g_timer_new ();
3396 LOCK_CONTEXT (context);
3398 poll_func = context->poll_func;
3400 UNLOCK_CONTEXT (context);
3401 if ((*poll_func) (fds, n_fds, timeout) < 0 && errno != EINTR)
3404 g_warning ("poll(2) failed due to: %s.",
3405 g_strerror (errno));
3407 /* If g_poll () returns -1, it has already called g_warning() */
3411 #ifdef G_MAIN_POLL_DEBUG
3412 if (_g_main_poll_debug)
3414 LOCK_CONTEXT (context);
3416 g_print ("g_main_poll(%d) timeout: %d - elapsed %12.10f seconds",
3419 g_timer_elapsed (poll_timer, NULL));
3420 g_timer_destroy (poll_timer);
3421 pollrec = context->poll_records;
3423 while (pollrec != NULL)
3428 if (fds[i].fd == pollrec->fd->fd &&
3429 pollrec->fd->events &&
3432 g_print (" [" G_POLLFD_FORMAT " :", fds[i].fd);
3433 if (fds[i].revents & G_IO_IN)
3435 if (fds[i].revents & G_IO_OUT)
3437 if (fds[i].revents & G_IO_PRI)
3439 if (fds[i].revents & G_IO_ERR)
3441 if (fds[i].revents & G_IO_HUP)
3443 if (fds[i].revents & G_IO_NVAL)
3449 pollrec = pollrec->next;
3453 UNLOCK_CONTEXT (context);
3456 } /* if (n_fds || timeout != 0) */
3460 * g_main_context_add_poll:
3461 * @context: a #GMainContext (or %NULL for the default context)
3462 * @fd: a #GPollFD structure holding information about a file
3463 * descriptor to watch.
3464 * @priority: the priority for this file descriptor which should be
3465 * the same as the priority used for g_source_attach() to ensure that the
3466 * file descriptor is polled whenever the results may be needed.
3468 * Adds a file descriptor to the set of file descriptors polled for
3469 * this context. This will very seldomly be used directly. Instead
3470 * a typical event source will use g_source_add_poll() instead.
3473 g_main_context_add_poll (GMainContext *context,
3478 context = g_main_context_default ();
3480 g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
3481 g_return_if_fail (fd);
3483 LOCK_CONTEXT (context);
3484 g_main_context_add_poll_unlocked (context, priority, fd);
3485 UNLOCK_CONTEXT (context);
3488 /* HOLDS: main_loop_lock */
3490 g_main_context_add_poll_unlocked (GMainContext *context,
3494 GPollRec *lastrec, *pollrec;
3495 GPollRec *newrec = g_slice_new (GPollRec);
3497 /* This file descriptor may be checked before we ever poll */
3500 newrec->priority = priority;
3503 pollrec = context->poll_records;
3504 while (pollrec && priority >= pollrec->priority)
3507 pollrec = pollrec->next;
3511 lastrec->next = newrec;
3513 context->poll_records = newrec;
3515 newrec->next = pollrec;
3517 context->n_poll_records++;
3519 #ifdef G_THREADS_ENABLED
3520 context->poll_changed = TRUE;
3522 /* Now wake up the main loop if it is waiting in the poll() */
3523 g_main_context_wakeup_unlocked (context);
3528 * g_main_context_remove_poll:
3529 * @context:a #GMainContext
3530 * @fd: a #GPollFD descriptor previously added with g_main_context_add_poll()
3532 * Removes file descriptor from the set of file descriptors to be
3533 * polled for a particular context.
3536 g_main_context_remove_poll (GMainContext *context,
3540 context = g_main_context_default ();
3542 g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
3543 g_return_if_fail (fd);
3545 LOCK_CONTEXT (context);
3546 g_main_context_remove_poll_unlocked (context, fd);
3547 UNLOCK_CONTEXT (context);
3551 g_main_context_remove_poll_unlocked (GMainContext *context,
3554 GPollRec *pollrec, *lastrec;
3557 pollrec = context->poll_records;
3561 if (pollrec->fd == fd)
3563 if (lastrec != NULL)
3564 lastrec->next = pollrec->next;
3566 context->poll_records = pollrec->next;
3568 g_slice_free (GPollRec, pollrec);
3570 context->n_poll_records--;
3574 pollrec = pollrec->next;
3577 #ifdef G_THREADS_ENABLED
3578 context->poll_changed = TRUE;
3580 /* Now wake up the main loop if it is waiting in the poll() */
3581 g_main_context_wakeup_unlocked (context);
3586 * g_source_get_current_time:
3587 * @source: a #GSource
3588 * @timeval: #GTimeVal structure in which to store current time.
3590 * Gets the "current time" to be used when checking
3591 * this source. The advantage of calling this function over
3592 * calling g_get_current_time() directly is that when
3593 * checking multiple sources, GLib can cache a single value
3594 * instead of having to repeatedly get the system time.
3596 * Deprecated: 2.28: use g_source_get_time() instead
3599 g_source_get_current_time (GSource *source,
3602 GMainContext *context;
3604 g_return_if_fail (source->context != NULL);
3606 context = source->context;
3608 LOCK_CONTEXT (context);
3610 if (!context->real_time_is_fresh)
3612 context->real_time = g_get_real_time ();
3613 context->real_time_is_fresh = TRUE;
3616 timeval->tv_sec = context->real_time / 1000000;
3617 timeval->tv_usec = context->real_time % 1000000;
3619 UNLOCK_CONTEXT (context);
3623 * g_source_get_time:
3624 * @source: a #GSource
3626 * Gets the time to be used when checking this source. The advantage of
3627 * calling this function over calling g_get_monotonic_time() directly is
3628 * that when checking multiple sources, GLib can cache a single value
3629 * instead of having to repeatedly get the system monotonic time.
3631 * The time here is the system monotonic time, if available, or some
3632 * other reasonable alternative otherwise. See g_get_monotonic_time().
3634 * Returns: the monotonic time in microseconds
3639 g_source_get_time (GSource *source)
3641 GMainContext *context;
3644 g_return_val_if_fail (source->context != NULL, 0);
3646 context = source->context;
3648 LOCK_CONTEXT (context);
3650 if (!context->time_is_fresh)
3652 context->time = g_get_monotonic_time ();
3653 context->time_is_fresh = TRUE;
3656 result = context->time;
3658 UNLOCK_CONTEXT (context);
3664 * g_main_context_set_poll_func:
3665 * @context: a #GMainContext
3666 * @func: the function to call to poll all file descriptors
3668 * Sets the function to use to handle polling of file descriptors. It
3669 * will be used instead of the poll() system call
3670 * (or GLib's replacement function, which is used where
3671 * poll() isn't available).
3673 * This function could possibly be used to integrate the GLib event
3674 * loop with an external event loop.
3677 g_main_context_set_poll_func (GMainContext *context,
3681 context = g_main_context_default ();
3683 g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
3685 LOCK_CONTEXT (context);
3688 context->poll_func = func;
3690 context->poll_func = g_poll;
3692 UNLOCK_CONTEXT (context);
3696 * g_main_context_get_poll_func:
3697 * @context: a #GMainContext
3699 * Gets the poll function set by g_main_context_set_poll_func().
3701 * Return value: the poll function
3704 g_main_context_get_poll_func (GMainContext *context)
3709 context = g_main_context_default ();
3711 g_return_val_if_fail (g_atomic_int_get (&context->ref_count) > 0, NULL);
3713 LOCK_CONTEXT (context);
3714 result = context->poll_func;
3715 UNLOCK_CONTEXT (context);
3720 /* HOLDS: context's lock */
3721 /* Wake the main loop up from a poll() */
3723 g_main_context_wakeup_unlocked (GMainContext *context)
3725 #ifdef G_THREADS_ENABLED
3726 if (g_thread_supported() && context->poll_waiting)
3728 context->poll_waiting = FALSE;
3730 write (context->wake_up_pipe[1], "A", 1);
3732 ReleaseSemaphore (context->wake_up_semaphore, 1, NULL);
3739 * g_main_context_wakeup:
3740 * @context: a #GMainContext
3742 * If @context is currently waiting in a poll(), interrupt
3743 * the poll(), and continue the iteration process.
3746 g_main_context_wakeup (GMainContext *context)
3749 context = g_main_context_default ();
3751 g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
3753 LOCK_CONTEXT (context);
3754 g_main_context_wakeup_unlocked (context);
3755 UNLOCK_CONTEXT (context);
3759 * g_main_context_is_owner:
3760 * @context: a #GMainContext
3762 * Determines whether this thread holds the (recursive)
3763 * ownership of this #GMaincontext. This is useful to
3764 * know before waiting on another thread that may be
3765 * blocking to get ownership of @context.
3767 * Returns: %TRUE if current thread is owner of @context.
3772 g_main_context_is_owner (GMainContext *context)
3777 context = g_main_context_default ();
3779 #ifdef G_THREADS_ENABLED
3780 LOCK_CONTEXT (context);
3781 is_owner = context->owner == G_THREAD_SELF;
3782 UNLOCK_CONTEXT (context);
3793 g_timeout_set_expiration (GTimeoutSource *timeout_source,
3794 gint64 current_time)
3796 timeout_source->expiration = current_time +
3797 (guint64) timeout_source->interval * 1000;
3799 if (timeout_source->seconds)
3802 static gint timer_perturb = -1;
3804 if (timer_perturb == -1)
3807 * we want a per machine/session unique 'random' value; try the dbus
3808 * address first, that has a UUID in it. If there is no dbus, use the
3809 * hostname for hashing.
3811 const char *session_bus_address = g_getenv ("DBUS_SESSION_BUS_ADDRESS");
3812 if (!session_bus_address)
3813 session_bus_address = g_getenv ("HOSTNAME");
3814 if (session_bus_address)
3815 timer_perturb = ABS ((gint) g_str_hash (session_bus_address)) % 1000000;
3820 /* We want the microseconds part of the timeout to land on the
3821 * 'timer_perturb' mark, but we need to make sure we don't try to
3822 * set the timeout in the past. We do this by ensuring that we
3823 * always only *increase* the expiration time by adding a full
3824 * second in the case that the microsecond portion decreases.
3826 timeout_source->expiration -= timer_perturb;
3828 remainder = timeout_source->expiration % 1000000;
3829 if (remainder >= 1000000/4)
3830 timeout_source->expiration += 1000000;
3832 timeout_source->expiration -= remainder;
3833 timeout_source->expiration += timer_perturb;
3838 g_timeout_prepare (GSource *source,
3841 GTimeoutSource *timeout_source = (GTimeoutSource *) source;
3842 gint64 now = g_source_get_time (source);
3844 if (now < timeout_source->expiration)
3846 /* Round up to ensure that we don't try again too early */
3847 *timeout = (timeout_source->expiration - now + 999) / 1000;
3856 g_timeout_check (GSource *source)
3858 GTimeoutSource *timeout_source = (GTimeoutSource *) source;
3859 gint64 now = g_source_get_time (source);
3861 return timeout_source->expiration <= now;
3865 g_timeout_dispatch (GSource *source,
3866 GSourceFunc callback,
3869 GTimeoutSource *timeout_source = (GTimeoutSource *)source;
3874 g_warning ("Timeout source dispatched without callback\n"
3875 "You must call g_source_set_callback().");
3879 again = callback (user_data);
3882 g_timeout_set_expiration (timeout_source, g_source_get_time (source));
3888 * g_timeout_source_new:
3889 * @interval: the timeout interval in milliseconds.
3891 * Creates a new timeout source.
3893 * The source will not initially be associated with any #GMainContext
3894 * and must be added to one with g_source_attach() before it will be
3897 * Return value: the newly-created timeout source
3900 g_timeout_source_new (guint interval)
3902 GSource *source = g_source_new (&g_timeout_funcs, sizeof (GTimeoutSource));
3903 GTimeoutSource *timeout_source = (GTimeoutSource *)source;
3905 timeout_source->interval = interval;
3906 g_timeout_set_expiration (timeout_source, g_get_monotonic_time ());
3912 * g_timeout_source_new_seconds:
3913 * @interval: the timeout interval in seconds
3915 * Creates a new timeout source.
3917 * The source will not initially be associated with any #GMainContext
3918 * and must be added to one with g_source_attach() before it will be
3921 * The scheduling granularity/accuracy of this timeout source will be
3924 * Return value: the newly-created timeout source
3929 g_timeout_source_new_seconds (guint interval)
3931 GSource *source = g_source_new (&g_timeout_funcs, sizeof (GTimeoutSource));
3932 GTimeoutSource *timeout_source = (GTimeoutSource *)source;
3934 timeout_source->interval = 1000 * interval;
3935 timeout_source->seconds = TRUE;
3937 g_timeout_set_expiration (timeout_source, g_get_monotonic_time ());
3944 * g_timeout_add_full:
3945 * @priority: the priority of the timeout source. Typically this will be in
3946 * the range between #G_PRIORITY_DEFAULT and #G_PRIORITY_HIGH.
3947 * @interval: the time between calls to the function, in milliseconds
3948 * (1/1000ths of a second)
3949 * @function: function to call
3950 * @data: data to pass to @function
3951 * @notify: function to call when the timeout is removed, or %NULL
3953 * Sets a function to be called at regular intervals, with the given
3954 * priority. The function is called repeatedly until it returns
3955 * %FALSE, at which point the timeout is automatically destroyed and
3956 * the function will not be called again. The @notify function is
3957 * called when the timeout is destroyed. The first call to the
3958 * function will be at the end of the first @interval.
3960 * Note that timeout functions may be delayed, due to the processing of other
3961 * event sources. Thus they should not be relied on for precise timing.
3962 * After each call to the timeout function, the time of the next
3963 * timeout is recalculated based on the current time and the given interval
3964 * (it does not try to 'catch up' time lost in delays).
3966 * This internally creates a main loop source using g_timeout_source_new()
3967 * and attaches it to the main loop context using g_source_attach(). You can
3968 * do these steps manually if you need greater control.
3970 * Return value: the ID (greater than 0) of the event source.
3973 g_timeout_add_full (gint priority,
3975 GSourceFunc function,
3977 GDestroyNotify notify)
3982 g_return_val_if_fail (function != NULL, 0);
3984 source = g_timeout_source_new (interval);
3986 if (priority != G_PRIORITY_DEFAULT)
3987 g_source_set_priority (source, priority);
3989 g_source_set_callback (source, function, data, notify);
3990 id = g_source_attach (source, NULL);
3991 g_source_unref (source);
3998 * @interval: the time between calls to the function, in milliseconds
3999 * (1/1000ths of a second)
4000 * @function: function to call
4001 * @data: data to pass to @function
4003 * Sets a function to be called at regular intervals, with the default
4004 * priority, #G_PRIORITY_DEFAULT. The function is called repeatedly
4005 * until it returns %FALSE, at which point the timeout is automatically
4006 * destroyed and the function will not be called again. The first call
4007 * to the function will be at the end of the first @interval.
4009 * Note that timeout functions may be delayed, due to the processing of other
4010 * event sources. Thus they should not be relied on for precise timing.
4011 * After each call to the timeout function, the time of the next
4012 * timeout is recalculated based on the current time and the given interval
4013 * (it does not try to 'catch up' time lost in delays).
4015 * If you want to have a timer in the "seconds" range and do not care
4016 * about the exact time of the first call of the timer, use the
4017 * g_timeout_add_seconds() function; this function allows for more
4018 * optimizations and more efficient system power usage.
4020 * This internally creates a main loop source using g_timeout_source_new()
4021 * and attaches it to the main loop context using g_source_attach(). You can
4022 * do these steps manually if you need greater control.
4024 * Return value: the ID (greater than 0) of the event source.
4027 g_timeout_add (guint32 interval,
4028 GSourceFunc function,
4031 return g_timeout_add_full (G_PRIORITY_DEFAULT,
4032 interval, function, data, NULL);
4036 * g_timeout_add_seconds_full:
4037 * @priority: the priority of the timeout source. Typically this will be in
4038 * the range between #G_PRIORITY_DEFAULT and #G_PRIORITY_HIGH.
4039 * @interval: the time between calls to the function, in seconds
4040 * @function: function to call
4041 * @data: data to pass to @function
4042 * @notify: function to call when the timeout is removed, or %NULL
4044 * Sets a function to be called at regular intervals, with @priority.
4045 * The function is called repeatedly until it returns %FALSE, at which
4046 * point the timeout is automatically destroyed and the function will
4047 * not be called again.
4049 * Unlike g_timeout_add(), this function operates at whole second granularity.
4050 * The initial starting point of the timer is determined by the implementation
4051 * and the implementation is expected to group multiple timers together so that
4052 * they fire all at the same time.
4053 * To allow this grouping, the @interval to the first timer is rounded
4054 * and can deviate up to one second from the specified interval.
4055 * Subsequent timer iterations will generally run at the specified interval.
4057 * Note that timeout functions may be delayed, due to the processing of other
4058 * event sources. Thus they should not be relied on for precise timing.
4059 * After each call to the timeout function, the time of the next
4060 * timeout is recalculated based on the current time and the given @interval
4062 * If you want timing more precise than whole seconds, use g_timeout_add()
4065 * The grouping of timers to fire at the same time results in a more power
4066 * and CPU efficient behavior so if your timer is in multiples of seconds
4067 * and you don't require the first timer exactly one second from now, the
4068 * use of g_timeout_add_seconds() is preferred over g_timeout_add().
4070 * This internally creates a main loop source using
4071 * g_timeout_source_new_seconds() and attaches it to the main loop context
4072 * using g_source_attach(). You can do these steps manually if you need
4075 * Return value: the ID (greater than 0) of the event source.
4080 g_timeout_add_seconds_full (gint priority,
4082 GSourceFunc function,
4084 GDestroyNotify notify)
4089 g_return_val_if_fail (function != NULL, 0);
4091 source = g_timeout_source_new_seconds (interval);
4093 if (priority != G_PRIORITY_DEFAULT)
4094 g_source_set_priority (source, priority);
4096 g_source_set_callback (source, function, data, notify);
4097 id = g_source_attach (source, NULL);
4098 g_source_unref (source);
4104 * g_timeout_add_seconds:
4105 * @interval: the time between calls to the function, in seconds
4106 * @function: function to call
4107 * @data: data to pass to @function
4109 * Sets a function to be called at regular intervals with the default
4110 * priority, #G_PRIORITY_DEFAULT. The function is called repeatedly until
4111 * it returns %FALSE, at which point the timeout is automatically destroyed
4112 * and the function will not be called again.
4114 * This internally creates a main loop source using
4115 * g_timeout_source_new_seconds() and attaches it to the main loop context
4116 * using g_source_attach(). You can do these steps manually if you need
4117 * greater control. Also see g_timout_add_seconds_full().
4119 * Note that the first call of the timer may not be precise for timeouts
4120 * of one second. If you need finer precision and have such a timeout,
4121 * you may want to use g_timeout_add() instead.
4123 * Return value: the ID (greater than 0) of the event source.
4128 g_timeout_add_seconds (guint interval,
4129 GSourceFunc function,
4132 g_return_val_if_fail (function != NULL, 0);
4134 return g_timeout_add_seconds_full (G_PRIORITY_DEFAULT, interval, function, data, NULL);
4137 /* Child watch functions */
4142 g_child_watch_prepare (GSource *source,
4151 g_child_watch_check (GSource *source)
4153 GChildWatchSource *child_watch_source;
4154 gboolean child_exited;
4156 child_watch_source = (GChildWatchSource *) source;
4158 child_exited = child_watch_source->poll.revents & G_IO_IN;
4165 * Note: We do _not_ check for the special value of STILL_ACTIVE
4166 * since we know that the process has exited and doing so runs into
4167 * problems if the child process "happens to return STILL_ACTIVE(259)"
4168 * as Microsoft's Platform SDK puts it.
4170 if (!GetExitCodeProcess (child_watch_source->pid, &child_status))
4172 gchar *emsg = g_win32_error_message (GetLastError ());
4173 g_warning (G_STRLOC ": GetExitCodeProcess() failed: %s", emsg);
4176 child_watch_source->child_status = -1;
4179 child_watch_source->child_status = child_status;
4182 return child_exited;
4185 #else /* G_OS_WIN32 */
4188 check_for_child_exited (GSource *source)
4190 GChildWatchSource *child_watch_source;
4193 /* protect against another SIGCHLD in the middle of this call */
4194 count = child_watch_count;
4196 child_watch_source = (GChildWatchSource *) source;
4198 if (child_watch_source->child_exited)
4201 if (child_watch_source->count < count)
4205 if (waitpid (child_watch_source->pid, &child_status, WNOHANG) > 0)
4207 child_watch_source->child_status = child_status;
4208 child_watch_source->child_exited = TRUE;
4210 child_watch_source->count = count;
4213 return child_watch_source->child_exited;
4217 g_child_watch_prepare (GSource *source,
4222 return check_for_child_exited (source);
4227 g_child_watch_check (GSource *source)
4229 return check_for_child_exited (source);
4232 #endif /* G_OS_WIN32 */
4235 g_child_watch_dispatch (GSource *source,
4236 GSourceFunc callback,
4239 GChildWatchSource *child_watch_source;
4240 GChildWatchFunc child_watch_callback = (GChildWatchFunc) callback;
4242 child_watch_source = (GChildWatchSource *) source;
4246 g_warning ("Child watch source dispatched without callback\n"
4247 "You must call g_source_set_callback().");
4251 (child_watch_callback) (child_watch_source->pid, child_watch_source->child_status, user_data);
4253 /* We never keep a child watch source around as the child is gone */
4260 g_child_watch_signal_handler (int signum)
4262 child_watch_count ++;
4264 if (child_watch_init_state == CHILD_WATCH_INITIALIZED_THREADED)
4266 write (child_watch_wake_up_pipe[1], "B", 1);
4270 /* We count on the signal interrupting the poll in the same thread.
4276 g_child_watch_source_init_single (void)
4278 struct sigaction action;
4280 g_assert (! g_thread_supported());
4281 g_assert (child_watch_init_state == CHILD_WATCH_UNINITIALIZED);
4283 child_watch_init_state = CHILD_WATCH_INITIALIZED_SINGLE;
4285 action.sa_handler = g_child_watch_signal_handler;
4286 sigemptyset (&action.sa_mask);
4287 action.sa_flags = SA_NOCLDSTOP;
4288 sigaction (SIGCHLD, &action, NULL);
4291 G_GNUC_NORETURN static gpointer
4292 child_watch_helper_thread (gpointer data)
4299 read (child_watch_wake_up_pipe[0], b, 20);
4301 /* We were woken up. Wake up all other contexts in all other threads */
4302 G_LOCK (main_context_list);
4303 for (list = main_context_list; list; list = list->next)
4305 GMainContext *context;
4307 context = list->data;
4308 if (g_atomic_int_get (&context->ref_count) > 0)
4309 /* Due to racing conditions we can find ref_count == 0, in
4310 * that case, however, the context is still not destroyed
4311 * and no poll can be active, otherwise the ref_count
4313 g_main_context_wakeup (context);
4315 G_UNLOCK (main_context_list);
4320 g_child_watch_source_init_multi_threaded (void)
4322 GError *error = NULL;
4323 struct sigaction action;
4325 g_assert (g_thread_supported());
4327 if (!g_unix_pipe_flags (child_watch_wake_up_pipe, FD_CLOEXEC, &error))
4328 g_error ("Cannot create wake up pipe: %s\n", error->message);
4329 fcntl (child_watch_wake_up_pipe[1], F_SETFL, O_NONBLOCK | fcntl (child_watch_wake_up_pipe[1], F_GETFL));
4331 /* We create a helper thread that polls on the wakeup pipe indefinitely */
4332 /* FIXME: Think this through for races */
4333 if (g_thread_create (child_watch_helper_thread, NULL, FALSE, &error) == NULL)
4334 g_error ("Cannot create a thread to monitor child exit status: %s\n", error->message);
4335 child_watch_init_state = CHILD_WATCH_INITIALIZED_THREADED;
4337 action.sa_handler = g_child_watch_signal_handler;
4338 sigemptyset (&action.sa_mask);
4339 action.sa_flags = SA_RESTART | SA_NOCLDSTOP;
4340 sigaction (SIGCHLD, &action, NULL);
4344 g_child_watch_source_init_promote_single_to_threaded (void)
4346 g_child_watch_source_init_multi_threaded ();
4350 g_child_watch_source_init (void)
4352 if (g_thread_supported())
4354 if (child_watch_init_state == CHILD_WATCH_UNINITIALIZED)
4355 g_child_watch_source_init_multi_threaded ();
4356 else if (child_watch_init_state == CHILD_WATCH_INITIALIZED_SINGLE)
4357 g_child_watch_source_init_promote_single_to_threaded ();
4361 if (child_watch_init_state == CHILD_WATCH_UNINITIALIZED)
4362 g_child_watch_source_init_single ();
4366 #endif /* !G_OS_WIN32 */
4369 * g_child_watch_source_new:
4370 * @pid: process to watch. On POSIX the pid of a child process. On
4371 * Windows a handle for a process (which doesn't have to be a child).
4373 * Creates a new child_watch source.
4375 * The source will not initially be associated with any #GMainContext
4376 * and must be added to one with g_source_attach() before it will be
4379 * Note that child watch sources can only be used in conjunction with
4380 * <literal>g_spawn...</literal> when the %G_SPAWN_DO_NOT_REAP_CHILD
4383 * Note that on platforms where #GPid must be explicitly closed
4384 * (see g_spawn_close_pid()) @pid must not be closed while the
4385 * source is still active. Typically, you will want to call
4386 * g_spawn_close_pid() in the callback function for the source.
4388 * Note further that using g_child_watch_source_new() is not
4389 * compatible with calling <literal>waitpid(-1)</literal> in
4390 * the application. Calling waitpid() for individual pids will
4393 * Return value: the newly-created child watch source
4398 g_child_watch_source_new (GPid pid)
4400 GSource *source = g_source_new (&g_child_watch_funcs, sizeof (GChildWatchSource));
4401 GChildWatchSource *child_watch_source = (GChildWatchSource *)source;
4404 child_watch_source->poll.fd = (gintptr) pid;
4405 child_watch_source->poll.events = G_IO_IN;
4407 g_source_add_poll (source, &child_watch_source->poll);
4408 #else /* G_OS_WIN32 */
4409 g_child_watch_source_init ();
4410 #endif /* G_OS_WIN32 */
4412 child_watch_source->pid = pid;
4418 * g_child_watch_add_full:
4419 * @priority: the priority of the idle source. Typically this will be in the
4420 * range between #G_PRIORITY_DEFAULT_IDLE and #G_PRIORITY_HIGH_IDLE.
4421 * @pid: process to watch. On POSIX the pid of a child process. On
4422 * Windows a handle for a process (which doesn't have to be a child).
4423 * @function: function to call
4424 * @data: data to pass to @function
4425 * @notify: function to call when the idle is removed, or %NULL
4427 * Sets a function to be called when the child indicated by @pid
4428 * exits, at the priority @priority.
4430 * If you obtain @pid from g_spawn_async() or g_spawn_async_with_pipes()
4431 * you will need to pass #G_SPAWN_DO_NOT_REAP_CHILD as flag to
4432 * the spawn function for the child watching to work.
4434 * Note that on platforms where #GPid must be explicitly closed
4435 * (see g_spawn_close_pid()) @pid must not be closed while the
4436 * source is still active. Typically, you will want to call
4437 * g_spawn_close_pid() in the callback function for the source.
4439 * GLib supports only a single callback per process id.
4441 * This internally creates a main loop source using
4442 * g_child_watch_source_new() and attaches it to the main loop context
4443 * using g_source_attach(). You can do these steps manually if you
4444 * need greater control.
4446 * Return value: the ID (greater than 0) of the event source.
4451 g_child_watch_add_full (gint priority,
4453 GChildWatchFunc function,
4455 GDestroyNotify notify)
4460 g_return_val_if_fail (function != NULL, 0);
4462 source = g_child_watch_source_new (pid);
4464 if (priority != G_PRIORITY_DEFAULT)
4465 g_source_set_priority (source, priority);
4467 g_source_set_callback (source, (GSourceFunc) function, data, notify);
4468 id = g_source_attach (source, NULL);
4469 g_source_unref (source);
4475 * g_child_watch_add:
4476 * @pid: process id to watch. On POSIX the pid of a child process. On
4477 * Windows a handle for a process (which doesn't have to be a child).
4478 * @function: function to call
4479 * @data: data to pass to @function
4481 * Sets a function to be called when the child indicated by @pid
4482 * exits, at a default priority, #G_PRIORITY_DEFAULT.
4484 * If you obtain @pid from g_spawn_async() or g_spawn_async_with_pipes()
4485 * you will need to pass #G_SPAWN_DO_NOT_REAP_CHILD as flag to
4486 * the spawn function for the child watching to work.
4488 * Note that on platforms where #GPid must be explicitly closed
4489 * (see g_spawn_close_pid()) @pid must not be closed while the
4490 * source is still active. Typically, you will want to call
4491 * g_spawn_close_pid() in the callback function for the source.
4493 * GLib supports only a single callback per process id.
4495 * This internally creates a main loop source using
4496 * g_child_watch_source_new() and attaches it to the main loop context
4497 * using g_source_attach(). You can do these steps manually if you
4498 * need greater control.
4500 * Return value: the ID (greater than 0) of the event source.
4505 g_child_watch_add (GPid pid,
4506 GChildWatchFunc function,
4509 return g_child_watch_add_full (G_PRIORITY_DEFAULT, pid, function, data, NULL);
4513 /* Idle functions */
4516 g_idle_prepare (GSource *source,
4525 g_idle_check (GSource *source)
4531 g_idle_dispatch (GSource *source,
4532 GSourceFunc callback,
4537 g_warning ("Idle source dispatched without callback\n"
4538 "You must call g_source_set_callback().");
4542 return callback (user_data);
4546 * g_idle_source_new:
4548 * Creates a new idle source.
4550 * The source will not initially be associated with any #GMainContext
4551 * and must be added to one with g_source_attach() before it will be
4552 * executed. Note that the default priority for idle sources is
4553 * %G_PRIORITY_DEFAULT_IDLE, as compared to other sources which
4554 * have a default priority of %G_PRIORITY_DEFAULT.
4556 * Return value: the newly-created idle source
4559 g_idle_source_new (void)
4563 source = g_source_new (&g_idle_funcs, sizeof (GSource));
4564 g_source_set_priority (source, G_PRIORITY_DEFAULT_IDLE);
4571 * @priority: the priority of the idle source. Typically this will be in the
4572 * range between #G_PRIORITY_DEFAULT_IDLE and #G_PRIORITY_HIGH_IDLE.
4573 * @function: function to call
4574 * @data: data to pass to @function
4575 * @notify: function to call when the idle is removed, or %NULL
4577 * Adds a function to be called whenever there are no higher priority
4578 * events pending. If the function returns %FALSE it is automatically
4579 * removed from the list of event sources and will not be called again.
4581 * This internally creates a main loop source using g_idle_source_new()
4582 * and attaches it to the main loop context using g_source_attach().
4583 * You can do these steps manually if you need greater control.
4585 * Return value: the ID (greater than 0) of the event source.
4588 g_idle_add_full (gint priority,
4589 GSourceFunc function,
4591 GDestroyNotify notify)
4596 g_return_val_if_fail (function != NULL, 0);
4598 source = g_idle_source_new ();
4600 if (priority != G_PRIORITY_DEFAULT_IDLE)
4601 g_source_set_priority (source, priority);
4603 g_source_set_callback (source, function, data, notify);
4604 id = g_source_attach (source, NULL);
4605 g_source_unref (source);
4612 * @function: function to call
4613 * @data: data to pass to @function.
4615 * Adds a function to be called whenever there are no higher priority
4616 * events pending to the default main loop. The function is given the
4617 * default idle priority, #G_PRIORITY_DEFAULT_IDLE. If the function
4618 * returns %FALSE it is automatically removed from the list of event
4619 * sources and will not be called again.
4621 * This internally creates a main loop source using g_idle_source_new()
4622 * and attaches it to the main loop context using g_source_attach().
4623 * You can do these steps manually if you need greater control.
4625 * Return value: the ID (greater than 0) of the event source.
4628 g_idle_add (GSourceFunc function,
4631 return g_idle_add_full (G_PRIORITY_DEFAULT_IDLE, function, data, NULL);
4635 * g_idle_remove_by_data:
4636 * @data: the data for the idle source's callback.
4638 * Removes the idle function with the given data.
4640 * Return value: %TRUE if an idle source was found and removed.
4643 g_idle_remove_by_data (gpointer data)
4645 return g_source_remove_by_funcs_user_data (&g_idle_funcs, data);
4649 * g_main_context_invoke:
4650 * @context: a #GMainContext, or %NULL
4651 * @function: function to call
4652 * @data: data to pass to @function
4654 * Invokes a function in such a way that @context is owned during the
4655 * invocation of @function.
4657 * If @context is %NULL then the global default main context — as
4658 * returned by g_main_context_default() — is used.
4660 * If @context is owned by the current thread, @function is called
4661 * directly. Otherwise, if @context is the thread-default main context
4662 * of the current thread and g_main_context_acquire() succeeds, then
4663 * @function is called and g_main_context_release() is called
4666 * In any other case, an idle source is created to call @function and
4667 * that source is attached to @context (presumably to be run in another
4668 * thread). The idle source is attached with #G_PRIORITY_DEFAULT
4669 * priority. If you want a different priority, use
4670 * g_main_context_invoke_full().
4672 * Note that, as with normal idle functions, @function should probably
4673 * return %FALSE. If it returns %TRUE, it will be continuously run in a
4674 * loop (and may prevent this call from returning).
4679 g_main_context_invoke (GMainContext *context,
4680 GSourceFunc function,
4683 g_main_context_invoke_full (context,
4685 function, data, NULL);
4689 * g_main_context_invoke_full:
4690 * @context: a #GMainContext, or %NULL
4691 * @priority: the priority at which to run @function
4692 * @function: function to call
4693 * @data: data to pass to @function
4694 * @notify: a function to call when @data is no longer in use, or %NULL.
4696 * Invokes a function in such a way that @context is owned during the
4697 * invocation of @function.
4699 * This function is the same as g_main_context_invoke() except that it
4700 * lets you specify the priority incase @function ends up being
4701 * scheduled as an idle and also lets you give a #GDestroyNotify for @data.
4703 * @notify should not assume that it is called from any particular
4704 * thread or with any particular context acquired.
4709 g_main_context_invoke_full (GMainContext *context,
4711 GSourceFunc function,
4713 GDestroyNotify notify)
4715 g_return_if_fail (function != NULL);
4718 context = g_main_context_default ();
4720 if (g_main_context_is_owner (context))
4722 while (function (data));
4729 GMainContext *thread_default;
4731 thread_default = g_main_context_get_thread_default ();
4733 if (!thread_default)
4734 thread_default = g_main_context_default ();
4736 if (thread_default == context && g_main_context_acquire (context))
4738 while (function (data));
4740 g_main_context_release (context);
4749 source = g_idle_source_new ();
4750 g_source_set_priority (source, priority);
4751 g_source_set_callback (source, function, data, notify);
4752 g_source_attach (source, context);
4753 g_source_unref (source);