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 */
85 #endif /* G_OS_WIN32 */
88 #include <sys/socket.h>
90 #endif /* G_OS_BEOS */
95 #include "giochannel.h"
99 #include "gstrfuncs.h"
100 #include "gtestutils.h"
101 #include "gthreadprivate.h"
107 #ifdef G_MAIN_POLL_DEBUG
113 * @title: The Main Event Loop
114 * @short_description: manages all available sources of events
116 * The main event loop manages all the available sources of events for
117 * GLib and GTK+ applications. These events can come from any number of
118 * different types of sources such as file descriptors (plain files,
119 * pipes or sockets) and timeouts. New types of event sources can also
120 * be added using g_source_attach().
122 * To allow multiple independent sets of sources to be handled in
123 * different threads, each source is associated with a #GMainContext.
124 * A GMainContext can only be running in a single thread, but
125 * sources can be added to it and removed from it from other threads.
127 * Each event source is assigned a priority. The default priority,
128 * #G_PRIORITY_DEFAULT, is 0. Values less than 0 denote higher priorities.
129 * Values greater than 0 denote lower priorities. Events from high priority
130 * sources are always processed before events from lower priority sources.
132 * Idle functions can also be added, and assigned a priority. These will
133 * be run whenever no events with a higher priority are ready to be processed.
135 * The #GMainLoop data type represents a main event loop. A GMainLoop is
136 * created with g_main_loop_new(). After adding the initial event sources,
137 * g_main_loop_run() is called. This continuously checks for new events from
138 * each of the event sources and dispatches them. Finally, the processing of
139 * an event from one of the sources leads to a call to g_main_loop_quit() to
140 * exit the main loop, and g_main_loop_run() returns.
142 * It is possible to create new instances of #GMainLoop recursively.
143 * This is often used in GTK+ applications when showing modal dialog
144 * boxes. Note that event sources are associated with a particular
145 * #GMainContext, and will be checked and dispatched for all main
146 * loops associated with that GMainContext.
148 * GTK+ contains wrappers of some of these functions, e.g. gtk_main(),
149 * gtk_main_quit() and gtk_events_pending().
151 * <refsect2><title>Creating new source types</title>
152 * <para>One of the unusual features of the #GMainLoop functionality
153 * is that new types of event source can be created and used in
154 * addition to the builtin type of event source. A new event source
155 * type is used for handling GDK events. A new source type is created
156 * by <firstterm>deriving</firstterm> from the #GSource structure.
157 * The derived type of source is represented by a structure that has
158 * the #GSource structure as a first element, and other elements specific
159 * to the new source type. To create an instance of the new source type,
160 * call g_source_new() passing in the size of the derived structure and
161 * a table of functions. These #GSourceFuncs determine the behavior of
162 * the new source type.</para>
163 * <para>New source types basically interact with the main context
164 * in two ways. Their prepare function in #GSourceFuncs can set a timeout
165 * to determine the maximum amount of time that the main loop will sleep
166 * before checking the source again. In addition, or as well, the source
167 * can add file descriptors to the set that the main context checks using
168 * g_source_add_poll().</para>
170 * <refsect2><title>Customizing the main loop iteration</title>
171 * <para>Single iterations of a #GMainContext can be run with
172 * g_main_context_iteration(). In some cases, more detailed control
173 * of exactly how the details of the main loop work is desired, for
174 * instance, when integrating the #GMainLoop with an external main loop.
175 * In such cases, you can call the component functions of
176 * g_main_context_iteration() directly. These functions are
177 * g_main_context_prepare(), g_main_context_query(),
178 * g_main_context_check() and g_main_context_dispatch().</para>
179 * <para>The operation of these functions can best be seen in terms
180 * of a state diagram, as shown in <xref linkend="mainloop-states"/>.</para>
181 * <figure id="mainloop-states"><title>States of a Main Context</title>
182 * <graphic fileref="mainloop-states.gif" format="GIF"></graphic>
189 typedef struct _GTimeoutSource GTimeoutSource;
190 typedef struct _GChildWatchSource GChildWatchSource;
191 typedef struct _GPollRec GPollRec;
192 typedef struct _GSourceCallback GSourceCallback;
196 G_SOURCE_READY = 1 << G_HOOK_FLAG_USER_SHIFT,
197 G_SOURCE_CAN_RECURSE = 1 << (G_HOOK_FLAG_USER_SHIFT + 1)
200 #ifdef G_THREADS_ENABLED
201 typedef struct _GMainWaiter GMainWaiter;
210 typedef struct _GMainDispatch GMainDispatch;
212 struct _GMainDispatch
215 GSList *dispatching_sources; /* stack of current sources */
218 #ifdef G_MAIN_POLL_DEBUG
219 gboolean _g_main_poll_debug = FALSE;
224 #ifdef G_THREADS_ENABLED
225 /* The following lock is used for both the list of sources
226 * and the list of poll records
237 GPtrArray *pending_dispatches;
238 gint timeout; /* Timeout for current iteration */
241 GSource *source_list;
242 gint in_check_or_prepare;
244 GPollRec *poll_records;
245 guint n_poll_records;
246 GPollFD *cached_poll_array;
247 guint cached_poll_array_size;
249 #ifdef G_THREADS_ENABLED
251 /* this pipe is used to wake up the main loop when a source is added.
253 gint wake_up_pipe[2];
254 #else /* G_OS_WIN32 */
255 HANDLE wake_up_semaphore;
256 #endif /* G_OS_WIN32 */
259 gboolean poll_waiting;
261 /* Flag indicating whether the set of fd's changed during a poll */
262 gboolean poll_changed;
263 #endif /* G_THREADS_ENABLED */
268 gboolean time_is_fresh;
270 gboolean real_time_is_fresh;
273 struct _GSourceCallback
278 GDestroyNotify notify;
283 GMainContext *context;
288 struct _GTimeoutSource
296 struct _GChildWatchSource
303 #else /* G_OS_WIN32 */
305 gboolean child_exited;
306 #endif /* G_OS_WIN32 */
316 struct _GSourcePrivate
318 GSList *child_sources;
319 GSource *parent_source;
322 #ifdef G_THREADS_ENABLED
323 #define LOCK_CONTEXT(context) g_static_mutex_lock (&context->mutex)
324 #define UNLOCK_CONTEXT(context) g_static_mutex_unlock (&context->mutex)
325 #define G_THREAD_SELF g_thread_self ()
327 #define LOCK_CONTEXT(context) (void)0
328 #define UNLOCK_CONTEXT(context) (void)0
329 #define G_THREAD_SELF NULL
332 #define SOURCE_DESTROYED(source) (((source)->flags & G_HOOK_FLAG_ACTIVE) == 0)
333 #define SOURCE_BLOCKED(source) (((source)->flags & G_HOOK_FLAG_IN_CALL) != 0 && \
334 ((source)->flags & G_SOURCE_CAN_RECURSE) == 0)
336 #define SOURCE_UNREF(source, context) \
338 if ((source)->ref_count > 1) \
339 (source)->ref_count--; \
341 g_source_unref_internal ((source), (context), TRUE); \
345 /* Forward declarations */
347 static void g_source_unref_internal (GSource *source,
348 GMainContext *context,
350 static void g_source_destroy_internal (GSource *source,
351 GMainContext *context,
353 static void g_source_set_priority_unlocked (GSource *source,
354 GMainContext *context,
356 static void g_main_context_poll (GMainContext *context,
361 static void g_main_context_add_poll_unlocked (GMainContext *context,
364 static void g_main_context_remove_poll_unlocked (GMainContext *context,
366 static void g_main_context_wakeup_unlocked (GMainContext *context);
368 static void _g_main_wake_up_all_contexts (void);
370 static gboolean g_timeout_prepare (GSource *source,
372 static gboolean g_timeout_check (GSource *source);
373 static gboolean g_timeout_dispatch (GSource *source,
374 GSourceFunc callback,
376 static gboolean g_child_watch_prepare (GSource *source,
378 static gboolean g_child_watch_check (GSource *source);
379 static gboolean g_child_watch_dispatch (GSource *source,
380 GSourceFunc callback,
382 static gboolean g_idle_prepare (GSource *source,
384 static gboolean g_idle_check (GSource *source);
385 static gboolean g_idle_dispatch (GSource *source,
386 GSourceFunc callback,
389 G_LOCK_DEFINE_STATIC (main_loop);
390 static GMainContext *default_main_context;
391 static GSList *main_contexts_without_pipe = NULL;
395 /* The UNIX signal pipe contains a single byte specifying which
396 * signal was received.
398 #define _UNIX_SIGNAL_PIPE_SIGCHLD_CHAR 'C'
399 /* Guards unix_signal_wake_up_pipe */
400 G_LOCK_DEFINE_STATIC (unix_signal_lock);
401 static gint unix_signal_wake_up_pipe[2] = {-1, -1};
403 /* Child status monitoring code */
405 CHILD_WATCH_UNINITIALIZED,
406 CHILD_WATCH_INITIALIZED_SINGLE,
407 CHILD_WATCH_INITIALIZED_THREADED
409 static gint child_watch_init_state = CHILD_WATCH_UNINITIALIZED;
410 static gint child_watch_count = 1;
411 #endif /* !G_OS_WIN32 */
412 G_LOCK_DEFINE_STATIC (main_context_list);
413 static GSList *main_context_list = NULL;
415 GSourceFuncs g_timeout_funcs =
423 GSourceFuncs g_child_watch_funcs =
425 g_child_watch_prepare,
427 g_child_watch_dispatch,
431 GSourceFuncs g_idle_funcs =
440 * g_main_context_ref:
441 * @context: a #GMainContext
443 * Increases the reference count on a #GMainContext object by one.
445 * Returns: the @context that was passed in (since 2.6)
448 g_main_context_ref (GMainContext *context)
450 g_return_val_if_fail (context != NULL, NULL);
451 g_return_val_if_fail (g_atomic_int_get (&context->ref_count) > 0, NULL);
453 g_atomic_int_inc (&context->ref_count);
459 poll_rec_list_free (GMainContext *context,
462 g_slice_free_chain (GPollRec, list, next);
466 * g_main_context_unref:
467 * @context: a #GMainContext
469 * Decreases the reference count on a #GMainContext object by one. If
470 * the result is zero, free the context and free all associated memory.
473 g_main_context_unref (GMainContext *context)
476 g_return_if_fail (context != NULL);
477 g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
479 if (!g_atomic_int_dec_and_test (&context->ref_count))
482 G_LOCK (main_context_list);
483 main_context_list = g_slist_remove (main_context_list, context);
484 G_UNLOCK (main_context_list);
486 source = context->source_list;
489 GSource *next = source->next;
490 g_source_destroy_internal (source, context, FALSE);
494 #ifdef G_THREADS_ENABLED
495 g_static_mutex_free (&context->mutex);
498 g_ptr_array_free (context->pending_dispatches, TRUE);
499 g_free (context->cached_poll_array);
501 poll_rec_list_free (context, context->poll_records);
503 #ifdef G_THREADS_ENABLED
504 if (g_thread_supported())
507 close (context->wake_up_pipe[0]);
508 close (context->wake_up_pipe[1]);
510 CloseHandle (context->wake_up_semaphore);
514 main_contexts_without_pipe = g_slist_remove (main_contexts_without_pipe,
517 if (context->cond != NULL)
518 g_cond_free (context->cond);
524 #ifdef G_THREADS_ENABLED
526 g_main_context_init_pipe (GMainContext *context)
528 GError *error = NULL;
531 if (context->wake_up_pipe[0] != -1)
534 if (!g_unix_pipe_flags (context->wake_up_pipe, FD_CLOEXEC, &error))
535 g_error ("Cannot create pipe main loop wake-up: %s", error->message);
537 context->wake_up_rec.fd = context->wake_up_pipe[0];
538 context->wake_up_rec.events = G_IO_IN;
540 if (context->wake_up_semaphore != NULL)
542 context->wake_up_semaphore = CreateSemaphore (NULL, 0, 100, NULL);
543 if (context->wake_up_semaphore == NULL)
544 g_error ("Cannot create wake-up semaphore: %s",
545 g_win32_error_message (GetLastError ()));
546 context->wake_up_rec.fd = (gintptr) context->wake_up_semaphore;
547 context->wake_up_rec.events = G_IO_IN;
549 if (_g_main_poll_debug)
550 g_print ("wake-up semaphore: %p\n", context->wake_up_semaphore);
552 g_main_context_add_poll_unlocked (context, 0, &context->wake_up_rec);
556 _g_main_thread_init (void)
558 GSList *curr = main_contexts_without_pipe;
561 g_main_context_init_pipe ((GMainContext *)curr->data);
564 g_slist_free (main_contexts_without_pipe);
565 main_contexts_without_pipe = NULL;
567 #endif /* G_THREADS_ENABLED */
570 * g_main_context_new:
572 * Creates a new #GMainContext structure.
574 * Return value: the new #GMainContext
577 g_main_context_new (void)
579 GMainContext *context = g_new0 (GMainContext, 1);
581 #ifdef G_MAIN_POLL_DEBUG
583 static gboolean beenhere = FALSE;
587 if (getenv ("G_MAIN_POLL_DEBUG") != NULL)
588 _g_main_poll_debug = TRUE;
594 #ifdef G_THREADS_ENABLED
595 g_static_mutex_init (&context->mutex);
597 context->owner = NULL;
598 context->waiters = NULL;
601 context->wake_up_pipe[0] = -1;
602 context->wake_up_pipe[1] = -1;
604 context->wake_up_semaphore = NULL;
608 context->ref_count = 1;
610 context->next_id = 1;
612 context->source_list = NULL;
614 context->poll_func = g_poll;
616 context->cached_poll_array = NULL;
617 context->cached_poll_array_size = 0;
619 context->pending_dispatches = g_ptr_array_new ();
621 context->time_is_fresh = FALSE;
622 context->real_time_is_fresh = FALSE;
624 #ifdef G_THREADS_ENABLED
625 if (g_thread_supported ())
626 g_main_context_init_pipe (context);
628 main_contexts_without_pipe = g_slist_prepend (main_contexts_without_pipe,
632 G_LOCK (main_context_list);
633 main_context_list = g_slist_append (main_context_list, context);
635 #ifdef G_MAIN_POLL_DEBUG
636 if (_g_main_poll_debug)
637 g_print ("created context=%p\n", context);
640 G_UNLOCK (main_context_list);
646 * g_main_context_default:
648 * Returns the global default main context. This is the main context
649 * used for main loop functions when a main loop is not explicitly
650 * specified, and corresponds to the "main" main loop. See also
651 * g_main_context_get_thread_default().
653 * Return value: the global default main context.
656 g_main_context_default (void)
662 if (!default_main_context)
664 default_main_context = g_main_context_new ();
665 #ifdef G_MAIN_POLL_DEBUG
666 if (_g_main_poll_debug)
667 g_print ("default context=%p\n", default_main_context);
671 G_UNLOCK (main_loop);
673 return default_main_context;
676 static GStaticPrivate thread_context_stack = G_STATIC_PRIVATE_INIT;
679 free_context_stack (gpointer data)
681 GQueue *stack = data;
682 GMainContext *context;
684 while (!g_queue_is_empty (stack))
686 context = g_queue_pop_head (stack);
687 g_main_context_release (context);
689 g_main_context_unref (context);
691 g_queue_free (stack);
695 * g_main_context_push_thread_default:
696 * @context: a #GMainContext, or %NULL for the global default context
698 * Acquires @context and sets it as the thread-default context for the
699 * current thread. This will cause certain asynchronous operations
700 * (such as most <link linkend="gio">gio</link>-based I/O) which are
701 * started in this thread to run under @context and deliver their
702 * results to its main loop, rather than running under the global
703 * default context in the main thread. Note that calling this function
704 * changes the context returned by
705 * g_main_context_get_thread_default(), <emphasis>not</emphasis> the
706 * one returned by g_main_context_default(), so it does not affect the
707 * context used by functions like g_idle_add().
709 * Normally you would call this function shortly after creating a new
710 * thread, passing it a #GMainContext which will be run by a
711 * #GMainLoop in that thread, to set a new default context for all
712 * async operations in that thread. (In this case, you don't need to
713 * ever call g_main_context_pop_thread_default().) In some cases
714 * however, you may want to schedule a single operation in a
715 * non-default context, or temporarily use a non-default context in
716 * the main thread. In that case, you can wrap the call to the
717 * asynchronous operation inside a
718 * g_main_context_push_thread_default() /
719 * g_main_context_pop_thread_default() pair, but it is up to you to
720 * ensure that no other asynchronous operations accidentally get
721 * started while the non-default context is active.
723 * Beware that libraries that predate this function may not correctly
724 * handle being used from a thread with a thread-default context. Eg,
725 * see g_file_supports_thread_contexts().
730 g_main_context_push_thread_default (GMainContext *context)
733 gboolean acquired_context;
735 acquired_context = g_main_context_acquire (context);
736 g_return_if_fail (acquired_context);
738 if (context == g_main_context_default ())
741 g_main_context_ref (context);
743 stack = g_static_private_get (&thread_context_stack);
746 stack = g_queue_new ();
747 g_static_private_set (&thread_context_stack, stack,
751 g_queue_push_head (stack, context);
755 * g_main_context_pop_thread_default:
756 * @context: a #GMainContext object, or %NULL
758 * Pops @context off the thread-default context stack (verifying that
759 * it was on the top of the stack).
764 g_main_context_pop_thread_default (GMainContext *context)
768 if (context == g_main_context_default ())
771 stack = g_static_private_get (&thread_context_stack);
773 g_return_if_fail (stack != NULL);
774 g_return_if_fail (g_queue_peek_head (stack) == context);
776 g_queue_pop_head (stack);
778 g_main_context_release (context);
780 g_main_context_unref (context);
784 * g_main_context_get_thread_default:
786 * Gets the thread-default #GMainContext for this thread. Asynchronous
787 * operations that want to be able to be run in contexts other than
788 * the default one should call this method to get a #GMainContext to
789 * add their #GSource<!-- -->s to. (Note that even in single-threaded
790 * programs applications may sometimes want to temporarily push a
791 * non-default context, so it is not safe to assume that this will
792 * always return %NULL if threads are not initialized.)
794 * Returns: the thread-default #GMainContext, or %NULL if the
795 * thread-default context is the global default context.
800 g_main_context_get_thread_default (void)
804 stack = g_static_private_get (&thread_context_stack);
806 return g_queue_peek_head (stack);
811 /* Hooks for adding to the main loop */
815 * @source_funcs: structure containing functions that implement
816 * the sources behavior.
817 * @struct_size: size of the #GSource structure to create.
819 * Creates a new #GSource structure. The size is specified to
820 * allow creating structures derived from #GSource that contain
821 * additional data. The size passed in must be at least
822 * <literal>sizeof (GSource)</literal>.
824 * The source will not initially be associated with any #GMainContext
825 * and must be added to one with g_source_attach() before it will be
828 * Return value: the newly-created #GSource.
831 g_source_new (GSourceFuncs *source_funcs,
836 g_return_val_if_fail (source_funcs != NULL, NULL);
837 g_return_val_if_fail (struct_size >= sizeof (GSource), NULL);
839 source = (GSource*) g_malloc0 (struct_size);
841 source->source_funcs = source_funcs;
842 source->ref_count = 1;
844 source->priority = G_PRIORITY_DEFAULT;
846 source->flags = G_HOOK_FLAG_ACTIVE;
848 /* NULL/0 initialization for all other fields */
853 /* Holds context's lock
856 g_source_list_add (GSource *source,
857 GMainContext *context)
859 GSource *tmp_source, *last_source;
861 if (source->priv && source->priv->parent_source)
863 /* Put the source immediately before its parent */
864 tmp_source = source->priv->parent_source;
865 last_source = source->priv->parent_source->prev;
870 tmp_source = context->source_list;
871 while (tmp_source && tmp_source->priority <= source->priority)
873 last_source = tmp_source;
874 tmp_source = tmp_source->next;
878 source->next = tmp_source;
880 tmp_source->prev = source;
882 source->prev = last_source;
884 last_source->next = source;
886 context->source_list = source;
889 /* Holds context's lock
892 g_source_list_remove (GSource *source,
893 GMainContext *context)
896 source->prev->next = source->next;
898 context->source_list = source->next;
901 source->next->prev = source->prev;
908 g_source_attach_unlocked (GSource *source,
909 GMainContext *context)
914 source->context = context;
915 result = source->source_id = context->next_id++;
918 g_source_list_add (source, context);
920 tmp_list = source->poll_fds;
923 g_main_context_add_poll_unlocked (context, source->priority, tmp_list->data);
924 tmp_list = tmp_list->next;
929 tmp_list = source->priv->child_sources;
932 g_source_attach_unlocked (tmp_list->data, context);
933 tmp_list = tmp_list->next;
942 * @source: a #GSource
943 * @context: a #GMainContext (if %NULL, the default context will be used)
945 * Adds a #GSource to a @context so that it will be executed within
946 * that context. Remove it by calling g_source_destroy().
948 * Return value: the ID (greater than 0) for the source within the
952 g_source_attach (GSource *source,
953 GMainContext *context)
957 g_return_val_if_fail (source->context == NULL, 0);
958 g_return_val_if_fail (!SOURCE_DESTROYED (source), 0);
961 context = g_main_context_default ();
963 LOCK_CONTEXT (context);
965 result = g_source_attach_unlocked (source, context);
967 #ifdef G_THREADS_ENABLED
968 /* Now wake up the main loop if it is waiting in the poll() */
969 g_main_context_wakeup_unlocked (context);
972 UNLOCK_CONTEXT (context);
978 g_source_destroy_internal (GSource *source,
979 GMainContext *context,
983 LOCK_CONTEXT (context);
985 if (!SOURCE_DESTROYED (source))
988 gpointer old_cb_data;
989 GSourceCallbackFuncs *old_cb_funcs;
991 source->flags &= ~G_HOOK_FLAG_ACTIVE;
993 old_cb_data = source->callback_data;
994 old_cb_funcs = source->callback_funcs;
996 source->callback_data = NULL;
997 source->callback_funcs = NULL;
1001 UNLOCK_CONTEXT (context);
1002 old_cb_funcs->unref (old_cb_data);
1003 LOCK_CONTEXT (context);
1006 if (!SOURCE_BLOCKED (source))
1008 tmp_list = source->poll_fds;
1011 g_main_context_remove_poll_unlocked (context, tmp_list->data);
1012 tmp_list = tmp_list->next;
1016 if (source->priv && source->priv->child_sources)
1018 /* This is safe because even if a child_source finalizer or
1019 * closure notify tried to modify source->priv->child_sources
1020 * from outside the lock, it would fail since
1021 * SOURCE_DESTROYED(source) is now TRUE.
1023 tmp_list = source->priv->child_sources;
1026 g_source_destroy_internal (tmp_list->data, context, TRUE);
1027 g_source_unref_internal (tmp_list->data, context, TRUE);
1028 tmp_list = tmp_list->next;
1030 g_slist_free (source->priv->child_sources);
1031 source->priv->child_sources = NULL;
1034 g_source_unref_internal (source, context, TRUE);
1038 UNLOCK_CONTEXT (context);
1043 * @source: a #GSource
1045 * Removes a source from its #GMainContext, if any, and mark it as
1046 * destroyed. The source cannot be subsequently added to another
1050 g_source_destroy (GSource *source)
1052 GMainContext *context;
1054 g_return_if_fail (source != NULL);
1056 context = source->context;
1059 g_source_destroy_internal (source, context, FALSE);
1061 source->flags &= ~G_HOOK_FLAG_ACTIVE;
1066 * @source: a #GSource
1068 * Returns the numeric ID for a particular source. The ID of a source
1069 * is a positive integer which is unique within a particular main loop
1070 * context. The reverse
1071 * mapping from ID to source is done by g_main_context_find_source_by_id().
1073 * Return value: the ID (greater than 0) for the source
1076 g_source_get_id (GSource *source)
1080 g_return_val_if_fail (source != NULL, 0);
1081 g_return_val_if_fail (source->context != NULL, 0);
1083 LOCK_CONTEXT (source->context);
1084 result = source->source_id;
1085 UNLOCK_CONTEXT (source->context);
1091 * g_source_get_context:
1092 * @source: a #GSource
1094 * Gets the #GMainContext with which the source is associated.
1095 * Calling this function on a destroyed source is an error.
1097 * Return value: the #GMainContext with which the source is associated,
1098 * or %NULL if the context has not yet been added
1102 g_source_get_context (GSource *source)
1104 g_return_val_if_fail (!SOURCE_DESTROYED (source), NULL);
1106 return source->context;
1110 * g_source_add_poll:
1111 * @source:a #GSource
1112 * @fd: a #GPollFD structure holding information about a file
1113 * descriptor to watch.
1115 * Adds a file descriptor to the set of file descriptors polled for
1116 * this source. This is usually combined with g_source_new() to add an
1117 * event source. The event source's check function will typically test
1118 * the @revents field in the #GPollFD struct and return %TRUE if events need
1122 g_source_add_poll (GSource *source,
1125 GMainContext *context;
1127 g_return_if_fail (source != NULL);
1128 g_return_if_fail (fd != NULL);
1129 g_return_if_fail (!SOURCE_DESTROYED (source));
1131 context = source->context;
1134 LOCK_CONTEXT (context);
1136 source->poll_fds = g_slist_prepend (source->poll_fds, fd);
1140 if (!SOURCE_BLOCKED (source))
1141 g_main_context_add_poll_unlocked (context, source->priority, fd);
1142 UNLOCK_CONTEXT (context);
1147 * g_source_remove_poll:
1148 * @source:a #GSource
1149 * @fd: a #GPollFD structure previously passed to g_source_add_poll().
1151 * Removes a file descriptor from the set of file descriptors polled for
1155 g_source_remove_poll (GSource *source,
1158 GMainContext *context;
1160 g_return_if_fail (source != NULL);
1161 g_return_if_fail (fd != NULL);
1162 g_return_if_fail (!SOURCE_DESTROYED (source));
1164 context = source->context;
1167 LOCK_CONTEXT (context);
1169 source->poll_fds = g_slist_remove (source->poll_fds, fd);
1173 if (!SOURCE_BLOCKED (source))
1174 g_main_context_remove_poll_unlocked (context, fd);
1175 UNLOCK_CONTEXT (context);
1180 * g_source_add_child_source:
1181 * @source:a #GSource
1182 * @child_source: a second #GSource that @source should "poll"
1184 * Adds @child_source to @source as a "polled" source; when @source is
1185 * added to a #GMainContext, @child_source will be automatically added
1186 * with the same priority, when @child_source is triggered, it will
1187 * cause @source to dispatch (in addition to calling its own
1188 * callback), and when @source is destroyed, it will destroy
1189 * @child_source as well. (@source will also still be dispatched if
1190 * its own prepare/check functions indicate that it is ready.)
1192 * If you don't need @child_source to do anything on its own when it
1193 * triggers, you can call g_source_set_dummy_callback() on it to set a
1194 * callback that does nothing (except return %TRUE if appropriate).
1196 * @source will hold a reference on @child_source while @child_source
1197 * is attached to it.
1202 g_source_add_child_source (GSource *source,
1203 GSource *child_source)
1205 GMainContext *context;
1207 g_return_if_fail (source != NULL);
1208 g_return_if_fail (child_source != NULL);
1209 g_return_if_fail (!SOURCE_DESTROYED (source));
1210 g_return_if_fail (!SOURCE_DESTROYED (child_source));
1211 g_return_if_fail (child_source->context == NULL);
1212 g_return_if_fail (child_source->priv == NULL || child_source->priv->parent_source == NULL);
1214 context = source->context;
1217 LOCK_CONTEXT (context);
1220 source->priv = g_slice_new0 (GSourcePrivate);
1221 if (!child_source->priv)
1222 child_source->priv = g_slice_new0 (GSourcePrivate);
1224 source->priv->child_sources = g_slist_prepend (source->priv->child_sources,
1225 g_source_ref (child_source));
1226 child_source->priv->parent_source = source;
1227 g_source_set_priority_unlocked (child_source, context, source->priority);
1231 UNLOCK_CONTEXT (context);
1232 g_source_attach (child_source, context);
1237 * g_source_remove_child_source:
1238 * @source:a #GSource
1239 * @child_source: a #GSource previously passed to
1240 * g_source_add_child_source().
1242 * Detaches @child_source from @source and destroys it.
1247 g_source_remove_child_source (GSource *source,
1248 GSource *child_source)
1250 GMainContext *context;
1252 g_return_if_fail (source != NULL);
1253 g_return_if_fail (child_source != NULL);
1254 g_return_if_fail (child_source->priv != NULL && child_source->priv->parent_source == source);
1255 g_return_if_fail (!SOURCE_DESTROYED (source));
1256 g_return_if_fail (!SOURCE_DESTROYED (child_source));
1258 context = source->context;
1261 LOCK_CONTEXT (context);
1263 source->priv->child_sources = g_slist_remove (source->priv->child_sources, child_source);
1264 g_source_destroy_internal (child_source, context, TRUE);
1265 g_source_unref_internal (child_source, context, TRUE);
1268 UNLOCK_CONTEXT (context);
1272 * g_source_set_callback_indirect:
1273 * @source: the source
1274 * @callback_data: pointer to callback data "object"
1275 * @callback_funcs: functions for reference counting @callback_data
1276 * and getting the callback and data
1278 * Sets the callback function storing the data as a refcounted callback
1279 * "object". This is used internally. Note that calling
1280 * g_source_set_callback_indirect() assumes
1281 * an initial reference count on @callback_data, and thus
1282 * @callback_funcs->unref will eventually be called once more
1283 * than @callback_funcs->ref.
1286 g_source_set_callback_indirect (GSource *source,
1287 gpointer callback_data,
1288 GSourceCallbackFuncs *callback_funcs)
1290 GMainContext *context;
1291 gpointer old_cb_data;
1292 GSourceCallbackFuncs *old_cb_funcs;
1294 g_return_if_fail (source != NULL);
1295 g_return_if_fail (callback_funcs != NULL || callback_data == NULL);
1297 context = source->context;
1300 LOCK_CONTEXT (context);
1302 old_cb_data = source->callback_data;
1303 old_cb_funcs = source->callback_funcs;
1305 source->callback_data = callback_data;
1306 source->callback_funcs = callback_funcs;
1309 UNLOCK_CONTEXT (context);
1312 old_cb_funcs->unref (old_cb_data);
1316 g_source_callback_ref (gpointer cb_data)
1318 GSourceCallback *callback = cb_data;
1320 callback->ref_count++;
1325 g_source_callback_unref (gpointer cb_data)
1327 GSourceCallback *callback = cb_data;
1329 callback->ref_count--;
1330 if (callback->ref_count == 0)
1332 if (callback->notify)
1333 callback->notify (callback->data);
1339 g_source_callback_get (gpointer cb_data,
1344 GSourceCallback *callback = cb_data;
1346 *func = callback->func;
1347 *data = callback->data;
1350 static GSourceCallbackFuncs g_source_callback_funcs = {
1351 g_source_callback_ref,
1352 g_source_callback_unref,
1353 g_source_callback_get,
1357 * g_source_set_callback:
1358 * @source: the source
1359 * @func: a callback function
1360 * @data: the data to pass to callback function
1361 * @notify: a function to call when @data is no longer in use, or %NULL.
1363 * Sets the callback function for a source. The callback for a source is
1364 * called from the source's dispatch function.
1366 * The exact type of @func depends on the type of source; ie. you
1367 * should not count on @func being called with @data as its first
1370 * Typically, you won't use this function. Instead use functions specific
1371 * to the type of source you are using.
1374 g_source_set_callback (GSource *source,
1377 GDestroyNotify notify)
1379 GSourceCallback *new_callback;
1381 g_return_if_fail (source != NULL);
1383 new_callback = g_new (GSourceCallback, 1);
1385 new_callback->ref_count = 1;
1386 new_callback->func = func;
1387 new_callback->data = data;
1388 new_callback->notify = notify;
1390 g_source_set_callback_indirect (source, new_callback, &g_source_callback_funcs);
1395 * g_source_set_funcs:
1396 * @source: a #GSource
1397 * @funcs: the new #GSourceFuncs
1399 * Sets the source functions (can be used to override
1400 * default implementations) of an unattached source.
1405 g_source_set_funcs (GSource *source,
1406 GSourceFuncs *funcs)
1408 g_return_if_fail (source != NULL);
1409 g_return_if_fail (source->context == NULL);
1410 g_return_if_fail (source->ref_count > 0);
1411 g_return_if_fail (funcs != NULL);
1413 source->source_funcs = funcs;
1417 g_source_set_priority_unlocked (GSource *source,
1418 GMainContext *context,
1423 source->priority = priority;
1427 /* Remove the source from the context's source and then
1428 * add it back so it is sorted in the correct place
1430 g_source_list_remove (source, source->context);
1431 g_source_list_add (source, source->context);
1433 if (!SOURCE_BLOCKED (source))
1435 tmp_list = source->poll_fds;
1438 g_main_context_remove_poll_unlocked (context, tmp_list->data);
1439 g_main_context_add_poll_unlocked (context, priority, tmp_list->data);
1441 tmp_list = tmp_list->next;
1446 if (source->priv && source->priv->child_sources)
1448 tmp_list = source->priv->child_sources;
1451 g_source_set_priority_unlocked (tmp_list->data, context, priority);
1452 tmp_list = tmp_list->next;
1458 * g_source_set_priority:
1459 * @source: a #GSource
1460 * @priority: the new priority.
1462 * Sets the priority of a source. While the main loop is being run, a
1463 * source will be dispatched if it is ready to be dispatched and no
1464 * sources at a higher (numerically smaller) priority are ready to be
1468 g_source_set_priority (GSource *source,
1471 GMainContext *context;
1473 g_return_if_fail (source != NULL);
1475 context = source->context;
1478 LOCK_CONTEXT (context);
1479 g_source_set_priority_unlocked (source, context, priority);
1481 UNLOCK_CONTEXT (source->context);
1485 * g_source_get_priority:
1486 * @source: a #GSource
1488 * Gets the priority of a source.
1490 * Return value: the priority of the source
1493 g_source_get_priority (GSource *source)
1495 g_return_val_if_fail (source != NULL, 0);
1497 return source->priority;
1501 * g_source_set_can_recurse:
1502 * @source: a #GSource
1503 * @can_recurse: whether recursion is allowed for this source
1505 * Sets whether a source can be called recursively. If @can_recurse is
1506 * %TRUE, then while the source is being dispatched then this source
1507 * will be processed normally. Otherwise, all processing of this
1508 * source is blocked until the dispatch function returns.
1511 g_source_set_can_recurse (GSource *source,
1512 gboolean can_recurse)
1514 GMainContext *context;
1516 g_return_if_fail (source != NULL);
1518 context = source->context;
1521 LOCK_CONTEXT (context);
1524 source->flags |= G_SOURCE_CAN_RECURSE;
1526 source->flags &= ~G_SOURCE_CAN_RECURSE;
1529 UNLOCK_CONTEXT (context);
1533 * g_source_get_can_recurse:
1534 * @source: a #GSource
1536 * Checks whether a source is allowed to be called recursively.
1537 * see g_source_set_can_recurse().
1539 * Return value: whether recursion is allowed.
1542 g_source_get_can_recurse (GSource *source)
1544 g_return_val_if_fail (source != NULL, FALSE);
1546 return (source->flags & G_SOURCE_CAN_RECURSE) != 0;
1551 * g_source_set_name:
1552 * @source: a #GSource
1553 * @name: debug name for the source
1555 * Sets a name for the source, used in debugging and profiling.
1556 * The name defaults to #NULL.
1558 * The source name should describe in a human-readable way
1559 * what the source does. For example, "X11 event queue"
1560 * or "GTK+ repaint idle handler" or whatever it is.
1562 * It is permitted to call this function multiple times, but is not
1563 * recommended due to the potential performance impact. For example,
1564 * one could change the name in the "check" function of a #GSourceFuncs
1565 * to include details like the event type in the source name.
1570 g_source_set_name (GSource *source,
1573 g_return_if_fail (source != NULL);
1575 /* setting back to NULL is allowed, just because it's
1576 * weird if get_name can return NULL but you can't
1580 g_free (source->name);
1581 source->name = g_strdup (name);
1585 * g_source_get_name:
1586 * @source: a #GSource
1588 * Gets a name for the source, used in debugging and profiling.
1589 * The name may be #NULL if it has never been set with
1590 * g_source_set_name().
1592 * Return value: the name of the source
1595 G_CONST_RETURN char*
1596 g_source_get_name (GSource *source)
1598 g_return_val_if_fail (source != NULL, NULL);
1600 return source->name;
1604 * g_source_set_name_by_id:
1605 * @tag: a #GSource ID
1606 * @name: debug name for the source
1608 * Sets the name of a source using its ID.
1610 * This is a convenience utility to set source names from the return
1611 * value of g_idle_add(), g_timeout_add(), etc.
1616 g_source_set_name_by_id (guint tag,
1621 g_return_if_fail (tag > 0);
1623 source = g_main_context_find_source_by_id (NULL, tag);
1627 g_source_set_name (source, name);
1633 * @source: a #GSource
1635 * Increases the reference count on a source by one.
1637 * Return value: @source
1640 g_source_ref (GSource *source)
1642 GMainContext *context;
1644 g_return_val_if_fail (source != NULL, NULL);
1646 context = source->context;
1649 LOCK_CONTEXT (context);
1651 source->ref_count++;
1654 UNLOCK_CONTEXT (context);
1659 /* g_source_unref() but possible to call within context lock
1662 g_source_unref_internal (GSource *source,
1663 GMainContext *context,
1666 gpointer old_cb_data = NULL;
1667 GSourceCallbackFuncs *old_cb_funcs = NULL;
1669 g_return_if_fail (source != NULL);
1671 if (!have_lock && context)
1672 LOCK_CONTEXT (context);
1674 source->ref_count--;
1675 if (source->ref_count == 0)
1677 old_cb_data = source->callback_data;
1678 old_cb_funcs = source->callback_funcs;
1680 source->callback_data = NULL;
1681 source->callback_funcs = NULL;
1685 if (!SOURCE_DESTROYED (source))
1686 g_warning (G_STRLOC ": ref_count == 0, but source was still attached to a context!");
1687 g_source_list_remove (source, context);
1690 if (source->source_funcs->finalize)
1693 UNLOCK_CONTEXT (context);
1694 source->source_funcs->finalize (source);
1696 LOCK_CONTEXT (context);
1699 g_free (source->name);
1700 source->name = NULL;
1702 g_slist_free (source->poll_fds);
1703 source->poll_fds = NULL;
1707 g_slice_free (GSourcePrivate, source->priv);
1708 source->priv = NULL;
1714 if (!have_lock && context)
1715 UNLOCK_CONTEXT (context);
1720 UNLOCK_CONTEXT (context);
1722 old_cb_funcs->unref (old_cb_data);
1725 LOCK_CONTEXT (context);
1731 * @source: a #GSource
1733 * Decreases the reference count of a source by one. If the
1734 * resulting reference count is zero the source and associated
1735 * memory will be destroyed.
1738 g_source_unref (GSource *source)
1740 g_return_if_fail (source != NULL);
1742 g_source_unref_internal (source, source->context, FALSE);
1746 * g_main_context_find_source_by_id:
1747 * @context: a #GMainContext (if %NULL, the default context will be used)
1748 * @source_id: the source ID, as returned by g_source_get_id().
1750 * Finds a #GSource given a pair of context and ID.
1752 * Return value: the #GSource if found, otherwise, %NULL
1755 g_main_context_find_source_by_id (GMainContext *context,
1760 g_return_val_if_fail (source_id > 0, NULL);
1762 if (context == NULL)
1763 context = g_main_context_default ();
1765 LOCK_CONTEXT (context);
1767 source = context->source_list;
1770 if (!SOURCE_DESTROYED (source) &&
1771 source->source_id == source_id)
1773 source = source->next;
1776 UNLOCK_CONTEXT (context);
1782 * g_main_context_find_source_by_funcs_user_data:
1783 * @context: a #GMainContext (if %NULL, the default context will be used).
1784 * @funcs: the @source_funcs passed to g_source_new().
1785 * @user_data: the user data from the callback.
1787 * Finds a source with the given source functions and user data. If
1788 * multiple sources exist with the same source function and user data,
1789 * the first one found will be returned.
1791 * Return value: the source, if one was found, otherwise %NULL
1794 g_main_context_find_source_by_funcs_user_data (GMainContext *context,
1795 GSourceFuncs *funcs,
1800 g_return_val_if_fail (funcs != NULL, NULL);
1802 if (context == NULL)
1803 context = g_main_context_default ();
1805 LOCK_CONTEXT (context);
1807 source = context->source_list;
1810 if (!SOURCE_DESTROYED (source) &&
1811 source->source_funcs == funcs &&
1812 source->callback_funcs)
1814 GSourceFunc callback;
1815 gpointer callback_data;
1817 source->callback_funcs->get (source->callback_data, source, &callback, &callback_data);
1819 if (callback_data == user_data)
1822 source = source->next;
1825 UNLOCK_CONTEXT (context);
1831 * g_main_context_find_source_by_user_data:
1832 * @context: a #GMainContext
1833 * @user_data: the user_data for the callback.
1835 * Finds a source with the given user data for the callback. If
1836 * multiple sources exist with the same user data, the first
1837 * one found will be returned.
1839 * Return value: the source, if one was found, otherwise %NULL
1842 g_main_context_find_source_by_user_data (GMainContext *context,
1847 if (context == NULL)
1848 context = g_main_context_default ();
1850 LOCK_CONTEXT (context);
1852 source = context->source_list;
1855 if (!SOURCE_DESTROYED (source) &&
1856 source->callback_funcs)
1858 GSourceFunc callback;
1859 gpointer callback_data = NULL;
1861 source->callback_funcs->get (source->callback_data, source, &callback, &callback_data);
1863 if (callback_data == user_data)
1866 source = source->next;
1869 UNLOCK_CONTEXT (context);
1876 * @tag: the ID of the source to remove.
1878 * Removes the source with the given id from the default main context.
1880 * a #GSource is given by g_source_get_id(), or will be returned by the
1881 * functions g_source_attach(), g_idle_add(), g_idle_add_full(),
1882 * g_timeout_add(), g_timeout_add_full(), g_child_watch_add(),
1883 * g_child_watch_add_full(), g_io_add_watch(), and g_io_add_watch_full().
1885 * See also g_source_destroy(). You must use g_source_destroy() for sources
1886 * added to a non-default main context.
1888 * Return value: %TRUE if the source was found and removed.
1891 g_source_remove (guint tag)
1895 g_return_val_if_fail (tag > 0, FALSE);
1897 source = g_main_context_find_source_by_id (NULL, tag);
1899 g_source_destroy (source);
1901 return source != NULL;
1905 * g_source_remove_by_user_data:
1906 * @user_data: the user_data for the callback.
1908 * Removes a source from the default main loop context given the user
1909 * data for the callback. If multiple sources exist with the same user
1910 * data, only one will be destroyed.
1912 * Return value: %TRUE if a source was found and removed.
1915 g_source_remove_by_user_data (gpointer user_data)
1919 source = g_main_context_find_source_by_user_data (NULL, user_data);
1922 g_source_destroy (source);
1930 * g_source_remove_by_funcs_user_data:
1931 * @funcs: The @source_funcs passed to g_source_new()
1932 * @user_data: the user data for the callback
1934 * Removes a source from the default main loop context given the
1935 * source functions and user data. If multiple sources exist with the
1936 * same source functions and user data, only one will be destroyed.
1938 * Return value: %TRUE if a source was found and removed.
1941 g_source_remove_by_funcs_user_data (GSourceFuncs *funcs,
1946 g_return_val_if_fail (funcs != NULL, FALSE);
1948 source = g_main_context_find_source_by_funcs_user_data (NULL, funcs, user_data);
1951 g_source_destroy (source);
1959 * g_get_current_time:
1960 * @result: #GTimeVal structure in which to store current time.
1962 * Equivalent to the UNIX gettimeofday() function, but portable.
1964 * You may find g_get_real_time() to be more convenient.
1967 g_get_current_time (GTimeVal *result)
1972 g_return_if_fail (result != NULL);
1974 /*this is required on alpha, there the timeval structs are int's
1975 not longs and a cast only would fail horribly*/
1976 gettimeofday (&r, NULL);
1977 result->tv_sec = r.tv_sec;
1978 result->tv_usec = r.tv_usec;
1983 g_return_if_fail (result != NULL);
1985 GetSystemTimeAsFileTime (&ft);
1986 memmove (&time64, &ft, sizeof (FILETIME));
1988 /* Convert from 100s of nanoseconds since 1601-01-01
1989 * to Unix epoch. Yes, this is Y2038 unsafe.
1991 time64 -= G_GINT64_CONSTANT (116444736000000000);
1994 result->tv_sec = time64 / 1000000;
1995 result->tv_usec = time64 % 1000000;
2002 * Queries the system wall-clock time.
2004 * This call is functionally equivalent to g_get_current_time() except
2005 * that the return value is often more convenient than dealing with a
2008 * You should only use this call if you are actually interested in the real
2009 * wall-clock time. g_get_monotonic_time() is probably more useful for
2010 * measuring intervals.
2012 * Returns: the number of microseconds since January 1, 1970 UTC.
2017 g_get_real_time (void)
2021 g_get_current_time (&tv);
2023 return (((gint64) tv.tv_sec) * 1000000) + tv.tv_usec;
2027 * g_get_monotonic_time:
2029 * Queries the system monotonic time, if available.
2031 * On POSIX systems with clock_gettime() and %CLOCK_MONOTONIC this call
2032 * is a very shallow wrapper for that. Otherwise, we make a best effort
2033 * that probably involves returning the wall clock time (with at least
2034 * microsecond accuracy, subject to the limitations of the OS kernel).
2036 * Note that, on Windows, "limitations of the OS kernel" is a rather
2037 * substantial statement. Depending on the configuration of the system,
2038 * the wall clock time is updated as infrequently as 64 times a second
2039 * (which is approximately every 16ms).
2041 * Returns: the monotonic time, in microseconds
2046 g_get_monotonic_time (void)
2048 #ifdef HAVE_CLOCK_GETTIME
2049 /* librt clock_gettime() is our first choice */
2051 static int clockid = CLOCK_REALTIME;
2054 #ifdef HAVE_MONOTONIC_CLOCK
2055 /* We have to check if we actually have monotonic clock support.
2057 * There is no thread safety issue here since there is no harm if we
2061 static gboolean checked;
2063 if G_UNLIKELY (!checked)
2065 if (sysconf (_SC_MONOTONIC_CLOCK) >= 0)
2066 clockid = CLOCK_MONOTONIC;
2072 clock_gettime (clockid, &ts);
2074 /* In theory monotonic time can have any epoch.
2076 * glib presently assumes the following:
2078 * 1) The epoch comes some time after the birth of Jesus of Nazareth, but
2079 * not more than 10000 years later.
2081 * 2) The current time also falls sometime within this range.
2083 * These two reasonable assumptions leave us with a maximum deviation from
2084 * the epoch of 10000 years, or 315569520000000000 seconds.
2086 * If we restrict ourselves to this range then the number of microseconds
2087 * will always fit well inside the constraints of a int64 (by a factor of
2090 * If you actually hit the following assertion, probably you should file a
2091 * bug against your operating system for being excessively silly.
2093 g_assert (G_GINT64_CONSTANT (-315569520000000000) < ts.tv_sec &&
2094 ts.tv_sec < G_GINT64_CONSTANT (315569520000000000));
2096 return (((gint64) ts.tv_sec) * 1000000) + (ts.tv_nsec / 1000);
2099 /* It may look like we are discarding accuracy on Windows (since its
2100 * current time is expressed in 100s of nanoseconds) but according to
2101 * many sources, the time is only updated 64 times per second, so
2102 * microsecond accuracy is more than enough.
2107 g_get_current_time (&tv);
2109 return (((gint64) tv.tv_sec) * 1000000) + tv.tv_usec;
2115 g_main_dispatch_free (gpointer dispatch)
2117 g_slice_free (GMainDispatch, dispatch);
2120 /* Running the main loop */
2122 static GMainDispatch *
2125 static GStaticPrivate depth_private = G_STATIC_PRIVATE_INIT;
2126 GMainDispatch *dispatch = g_static_private_get (&depth_private);
2129 dispatch = g_slice_new0 (GMainDispatch);
2130 g_static_private_set (&depth_private, dispatch, g_main_dispatch_free);
2139 * Returns the depth of the stack of calls to
2140 * g_main_context_dispatch() on any #GMainContext in the current thread.
2141 * That is, when called from the toplevel, it gives 0. When
2142 * called from within a callback from g_main_context_iteration()
2143 * (or g_main_loop_run(), etc.) it returns 1. When called from within
2144 * a callback to a recursive call to g_main_context_iterate(),
2145 * it returns 2. And so forth.
2147 * This function is useful in a situation like the following:
2148 * Imagine an extremely simple "garbage collected" system.
2151 * static GList *free_list;
2154 * allocate_memory (gsize size)
2156 * gpointer result = g_malloc (size);
2157 * free_list = g_list_prepend (free_list, result);
2162 * free_allocated_memory (void)
2165 * for (l = free_list; l; l = l->next);
2167 * g_list_free (free_list);
2175 * g_main_context_iteration (NULL, TRUE);
2176 * free_allocated_memory();
2180 * This works from an application, however, if you want to do the same
2181 * thing from a library, it gets more difficult, since you no longer
2182 * control the main loop. You might think you can simply use an idle
2183 * function to make the call to free_allocated_memory(), but that
2184 * doesn't work, since the idle function could be called from a
2185 * recursive callback. This can be fixed by using g_main_depth()
2189 * allocate_memory (gsize size)
2191 * FreeListBlock *block = g_new (FreeListBlock, 1);
2192 * block->mem = g_malloc (size);
2193 * block->depth = g_main_depth ();
2194 * free_list = g_list_prepend (free_list, block);
2195 * return block->mem;
2199 * free_allocated_memory (void)
2203 * int depth = g_main_depth ();
2204 * for (l = free_list; l; );
2206 * GList *next = l->next;
2207 * FreeListBlock *block = l->data;
2208 * if (block->depth > depth)
2210 * g_free (block->mem);
2212 * free_list = g_list_delete_link (free_list, l);
2220 * There is a temptation to use g_main_depth() to solve
2221 * problems with reentrancy. For instance, while waiting for data
2222 * to be received from the network in response to a menu item,
2223 * the menu item might be selected again. It might seem that
2224 * one could make the menu item's callback return immediately
2225 * and do nothing if g_main_depth() returns a value greater than 1.
2226 * However, this should be avoided since the user then sees selecting
2227 * the menu item do nothing. Furthermore, you'll find yourself adding
2228 * these checks all over your code, since there are doubtless many,
2229 * many things that the user could do. Instead, you can use the
2230 * following techniques:
2235 * Use gtk_widget_set_sensitive() or modal dialogs to prevent
2236 * the user from interacting with elements while the main
2237 * loop is recursing.
2242 * Avoid main loop recursion in situations where you can't handle
2243 * arbitrary callbacks. Instead, structure your code so that you
2244 * simply return to the main loop and then get called again when
2245 * there is more work to do.
2250 * Return value: The main loop recursion level in the current thread
2255 GMainDispatch *dispatch = get_dispatch ();
2256 return dispatch->depth;
2260 * g_main_current_source:
2262 * Returns the currently firing source for this thread.
2264 * Return value: The currently firing source or %NULL.
2269 g_main_current_source (void)
2271 GMainDispatch *dispatch = get_dispatch ();
2272 return dispatch->dispatching_sources ? dispatch->dispatching_sources->data : NULL;
2276 * g_source_is_destroyed:
2277 * @source: a #GSource
2279 * Returns whether @source has been destroyed.
2281 * This is important when you operate upon your objects
2282 * from within idle handlers, but may have freed the object
2283 * before the dispatch of your idle handler.
2287 * idle_callback (gpointer data)
2289 * SomeWidget *self = data;
2291 * GDK_THREADS_ENTER (<!-- -->);
2292 * /<!-- -->* do stuff with self *<!-- -->/
2293 * self->idle_id = 0;
2294 * GDK_THREADS_LEAVE (<!-- -->);
2300 * some_widget_do_stuff_later (SomeWidget *self)
2302 * self->idle_id = g_idle_add (idle_callback, self);
2306 * some_widget_finalize (GObject *object)
2308 * SomeWidget *self = SOME_WIDGET (object);
2310 * if (self->idle_id)
2311 * g_source_remove (self->idle_id);
2313 * G_OBJECT_CLASS (parent_class)->finalize (object);
2317 * This will fail in a multi-threaded application if the
2318 * widget is destroyed before the idle handler fires due
2319 * to the use after free in the callback. A solution, to
2320 * this particular problem, is to check to if the source
2321 * has already been destroy within the callback.
2325 * idle_callback (gpointer data)
2327 * SomeWidget *self = data;
2329 * GDK_THREADS_ENTER ();
2330 * if (!g_source_is_destroyed (g_main_current_source ()))
2332 * /<!-- -->* do stuff with self *<!-- -->/
2334 * GDK_THREADS_LEAVE ();
2340 * Return value: %TRUE if the source has been destroyed
2345 g_source_is_destroyed (GSource *source)
2347 return SOURCE_DESTROYED (source);
2350 /* Temporarily remove all this source's file descriptors from the
2351 * poll(), so that if data comes available for one of the file descriptors
2352 * we don't continually spin in the poll()
2354 /* HOLDS: source->context's lock */
2356 block_source (GSource *source)
2360 g_return_if_fail (!SOURCE_BLOCKED (source));
2362 tmp_list = source->poll_fds;
2365 g_main_context_remove_poll_unlocked (source->context, tmp_list->data);
2366 tmp_list = tmp_list->next;
2370 /* HOLDS: source->context's lock */
2372 unblock_source (GSource *source)
2376 g_return_if_fail (!SOURCE_BLOCKED (source)); /* Source already unblocked */
2377 g_return_if_fail (!SOURCE_DESTROYED (source));
2379 tmp_list = source->poll_fds;
2382 g_main_context_add_poll_unlocked (source->context, source->priority, tmp_list->data);
2383 tmp_list = tmp_list->next;
2387 /* HOLDS: context's lock */
2389 g_main_dispatch (GMainContext *context)
2391 GMainDispatch *current = get_dispatch ();
2394 for (i = 0; i < context->pending_dispatches->len; i++)
2396 GSource *source = context->pending_dispatches->pdata[i];
2398 context->pending_dispatches->pdata[i] = NULL;
2401 source->flags &= ~G_SOURCE_READY;
2403 if (!SOURCE_DESTROYED (source))
2405 gboolean was_in_call;
2406 gpointer user_data = NULL;
2407 GSourceFunc callback = NULL;
2408 GSourceCallbackFuncs *cb_funcs;
2410 gboolean need_destroy;
2412 gboolean (*dispatch) (GSource *,
2415 GSList current_source_link;
2417 dispatch = source->source_funcs->dispatch;
2418 cb_funcs = source->callback_funcs;
2419 cb_data = source->callback_data;
2422 cb_funcs->ref (cb_data);
2424 if ((source->flags & G_SOURCE_CAN_RECURSE) == 0)
2425 block_source (source);
2427 was_in_call = source->flags & G_HOOK_FLAG_IN_CALL;
2428 source->flags |= G_HOOK_FLAG_IN_CALL;
2431 cb_funcs->get (cb_data, source, &callback, &user_data);
2433 UNLOCK_CONTEXT (context);
2436 /* The on-stack allocation of the GSList is unconventional, but
2437 * we know that the lifetime of the link is bounded to this
2438 * function as the link is kept in a thread specific list and
2439 * not manipulated outside of this function and its descendants.
2440 * Avoiding the overhead of a g_slist_alloc() is useful as many
2441 * applications do little more than dispatch events.
2443 * This is a performance hack - do not revert to g_slist_prepend()!
2445 current_source_link.data = source;
2446 current_source_link.next = current->dispatching_sources;
2447 current->dispatching_sources = ¤t_source_link;
2448 need_destroy = ! dispatch (source,
2451 g_assert (current->dispatching_sources == ¤t_source_link);
2452 current->dispatching_sources = current_source_link.next;
2456 cb_funcs->unref (cb_data);
2458 LOCK_CONTEXT (context);
2461 source->flags &= ~G_HOOK_FLAG_IN_CALL;
2463 if ((source->flags & G_SOURCE_CAN_RECURSE) == 0 &&
2464 !SOURCE_DESTROYED (source))
2465 unblock_source (source);
2467 /* Note: this depends on the fact that we can't switch
2468 * sources from one main context to another
2470 if (need_destroy && !SOURCE_DESTROYED (source))
2472 g_assert (source->context == context);
2473 g_source_destroy_internal (source, context, TRUE);
2477 SOURCE_UNREF (source, context);
2480 g_ptr_array_set_size (context->pending_dispatches, 0);
2483 /* Holds context's lock */
2484 static inline GSource *
2485 next_valid_source (GMainContext *context,
2488 GSource *new_source = source ? source->next : context->source_list;
2492 if (!SOURCE_DESTROYED (new_source))
2494 new_source->ref_count++;
2498 new_source = new_source->next;
2502 SOURCE_UNREF (source, context);
2508 * g_main_context_acquire:
2509 * @context: a #GMainContext
2511 * Tries to become the owner of the specified context.
2512 * If some other thread is the owner of the context,
2513 * returns %FALSE immediately. Ownership is properly
2514 * recursive: the owner can require ownership again
2515 * and will release ownership when g_main_context_release()
2516 * is called as many times as g_main_context_acquire().
2518 * You must be the owner of a context before you
2519 * can call g_main_context_prepare(), g_main_context_query(),
2520 * g_main_context_check(), g_main_context_dispatch().
2522 * Return value: %TRUE if the operation succeeded, and
2523 * this thread is now the owner of @context.
2526 g_main_context_acquire (GMainContext *context)
2528 #ifdef G_THREADS_ENABLED
2529 gboolean result = FALSE;
2530 GThread *self = G_THREAD_SELF;
2532 if (context == NULL)
2533 context = g_main_context_default ();
2535 LOCK_CONTEXT (context);
2537 if (!context->owner)
2539 context->owner = self;
2540 g_assert (context->owner_count == 0);
2543 if (context->owner == self)
2545 context->owner_count++;
2549 UNLOCK_CONTEXT (context);
2552 #else /* !G_THREADS_ENABLED */
2554 #endif /* G_THREADS_ENABLED */
2558 * g_main_context_release:
2559 * @context: a #GMainContext
2561 * Releases ownership of a context previously acquired by this thread
2562 * with g_main_context_acquire(). If the context was acquired multiple
2563 * times, the ownership will be released only when g_main_context_release()
2564 * is called as many times as it was acquired.
2567 g_main_context_release (GMainContext *context)
2569 #ifdef G_THREADS_ENABLED
2570 if (context == NULL)
2571 context = g_main_context_default ();
2573 LOCK_CONTEXT (context);
2575 context->owner_count--;
2576 if (context->owner_count == 0)
2578 context->owner = NULL;
2580 if (context->waiters)
2582 GMainWaiter *waiter = context->waiters->data;
2583 gboolean loop_internal_waiter =
2584 (waiter->mutex == g_static_mutex_get_mutex (&context->mutex));
2585 context->waiters = g_slist_delete_link (context->waiters,
2587 if (!loop_internal_waiter)
2588 g_mutex_lock (waiter->mutex);
2590 g_cond_signal (waiter->cond);
2592 if (!loop_internal_waiter)
2593 g_mutex_unlock (waiter->mutex);
2597 UNLOCK_CONTEXT (context);
2598 #endif /* G_THREADS_ENABLED */
2602 * g_main_context_wait:
2603 * @context: a #GMainContext
2604 * @cond: a condition variable
2605 * @mutex: a mutex, currently held
2607 * Tries to become the owner of the specified context,
2608 * as with g_main_context_acquire(). But if another thread
2609 * is the owner, atomically drop @mutex and wait on @cond until
2610 * that owner releases ownership or until @cond is signaled, then
2611 * try again (once) to become the owner.
2613 * Return value: %TRUE if the operation succeeded, and
2614 * this thread is now the owner of @context.
2617 g_main_context_wait (GMainContext *context,
2621 #ifdef G_THREADS_ENABLED
2622 gboolean result = FALSE;
2623 GThread *self = G_THREAD_SELF;
2624 gboolean loop_internal_waiter;
2626 if (context == NULL)
2627 context = g_main_context_default ();
2629 loop_internal_waiter = (mutex == g_static_mutex_get_mutex (&context->mutex));
2631 if (!loop_internal_waiter)
2632 LOCK_CONTEXT (context);
2634 if (context->owner && context->owner != self)
2639 waiter.mutex = mutex;
2641 context->waiters = g_slist_append (context->waiters, &waiter);
2643 if (!loop_internal_waiter)
2644 UNLOCK_CONTEXT (context);
2645 g_cond_wait (cond, mutex);
2646 if (!loop_internal_waiter)
2647 LOCK_CONTEXT (context);
2649 context->waiters = g_slist_remove (context->waiters, &waiter);
2652 if (!context->owner)
2654 context->owner = self;
2655 g_assert (context->owner_count == 0);
2658 if (context->owner == self)
2660 context->owner_count++;
2664 if (!loop_internal_waiter)
2665 UNLOCK_CONTEXT (context);
2668 #else /* !G_THREADS_ENABLED */
2670 #endif /* G_THREADS_ENABLED */
2674 * g_main_context_prepare:
2675 * @context: a #GMainContext
2676 * @priority: location to store priority of highest priority
2677 * source already ready.
2679 * Prepares to poll sources within a main loop. The resulting information
2680 * for polling is determined by calling g_main_context_query ().
2682 * Return value: %TRUE if some source is ready to be dispatched
2686 g_main_context_prepare (GMainContext *context,
2691 gint current_priority = G_MAXINT;
2694 if (context == NULL)
2695 context = g_main_context_default ();
2697 LOCK_CONTEXT (context);
2699 context->time_is_fresh = FALSE;
2700 context->real_time_is_fresh = FALSE;
2702 if (context->in_check_or_prepare)
2704 g_warning ("g_main_context_prepare() called recursively from within a source's check() or "
2705 "prepare() member.");
2706 UNLOCK_CONTEXT (context);
2710 #ifdef G_THREADS_ENABLED
2711 if (context->poll_waiting)
2713 g_warning("g_main_context_prepare(): main loop already active in another thread");
2714 UNLOCK_CONTEXT (context);
2718 context->poll_waiting = TRUE;
2719 #endif /* G_THREADS_ENABLED */
2722 /* If recursing, finish up current dispatch, before starting over */
2723 if (context->pending_dispatches)
2726 g_main_dispatch (context, ¤t_time);
2728 UNLOCK_CONTEXT (context);
2733 /* If recursing, clear list of pending dispatches */
2735 for (i = 0; i < context->pending_dispatches->len; i++)
2737 if (context->pending_dispatches->pdata[i])
2738 SOURCE_UNREF ((GSource *)context->pending_dispatches->pdata[i], context);
2740 g_ptr_array_set_size (context->pending_dispatches, 0);
2742 /* Prepare all sources */
2744 context->timeout = -1;
2746 source = next_valid_source (context, NULL);
2749 gint source_timeout = -1;
2751 if ((n_ready > 0) && (source->priority > current_priority))
2753 SOURCE_UNREF (source, context);
2756 if (SOURCE_BLOCKED (source))
2759 if (!(source->flags & G_SOURCE_READY))
2762 gboolean (*prepare) (GSource *source,
2765 prepare = source->source_funcs->prepare;
2766 context->in_check_or_prepare++;
2767 UNLOCK_CONTEXT (context);
2769 result = (*prepare) (source, &source_timeout);
2771 LOCK_CONTEXT (context);
2772 context->in_check_or_prepare--;
2776 GSource *ready_source = source;
2778 while (ready_source)
2780 ready_source->flags |= G_SOURCE_READY;
2781 ready_source = ready_source->priv ? ready_source->priv->parent_source : NULL;
2786 if (source->flags & G_SOURCE_READY)
2789 current_priority = source->priority;
2790 context->timeout = 0;
2793 if (source_timeout >= 0)
2795 if (context->timeout < 0)
2796 context->timeout = source_timeout;
2798 context->timeout = MIN (context->timeout, source_timeout);
2802 source = next_valid_source (context, source);
2805 UNLOCK_CONTEXT (context);
2808 *priority = current_priority;
2810 return (n_ready > 0);
2814 * g_main_context_query:
2815 * @context: a #GMainContext
2816 * @max_priority: maximum priority source to check
2817 * @timeout_: location to store timeout to be used in polling
2818 * @fds: location to store #GPollFD records that need to be polled.
2819 * @n_fds: length of @fds.
2821 * Determines information necessary to poll this main loop.
2823 * Return value: the number of records actually stored in @fds,
2824 * or, if more than @n_fds records need to be stored, the number
2825 * of records that need to be stored.
2828 g_main_context_query (GMainContext *context,
2837 LOCK_CONTEXT (context);
2839 pollrec = context->poll_records;
2841 while (pollrec && max_priority >= pollrec->priority)
2843 /* We need to include entries with fd->events == 0 in the array because
2844 * otherwise if the application changes fd->events behind our back and
2845 * makes it non-zero, we'll be out of sync when we check the fds[] array.
2846 * (Changing fd->events after adding an FD wasn't an anticipated use of
2847 * this API, but it occurs in practice.) */
2850 fds[n_poll].fd = pollrec->fd->fd;
2851 /* In direct contradiction to the Unix98 spec, IRIX runs into
2852 * difficulty if you pass in POLLERR, POLLHUP or POLLNVAL
2853 * flags in the events field of the pollfd while it should
2854 * just ignoring them. So we mask them out here.
2856 fds[n_poll].events = pollrec->fd->events & ~(G_IO_ERR|G_IO_HUP|G_IO_NVAL);
2857 fds[n_poll].revents = 0;
2860 pollrec = pollrec->next;
2864 #ifdef G_THREADS_ENABLED
2865 context->poll_changed = FALSE;
2870 *timeout = context->timeout;
2873 context->time_is_fresh = FALSE;
2874 context->real_time_is_fresh = FALSE;
2878 UNLOCK_CONTEXT (context);
2884 * g_main_context_check:
2885 * @context: a #GMainContext
2886 * @max_priority: the maximum numerical priority of sources to check
2887 * @fds: array of #GPollFD's that was passed to the last call to
2888 * g_main_context_query()
2889 * @n_fds: return value of g_main_context_query()
2891 * Passes the results of polling back to the main loop.
2893 * Return value: %TRUE if some sources are ready to be dispatched.
2896 g_main_context_check (GMainContext *context,
2906 LOCK_CONTEXT (context);
2908 if (context->in_check_or_prepare)
2910 g_warning ("g_main_context_check() called recursively from within a source's check() or "
2911 "prepare() member.");
2912 UNLOCK_CONTEXT (context);
2916 #ifdef G_THREADS_ENABLED
2917 if (!context->poll_waiting)
2921 read (context->wake_up_pipe[0], &a, 1);
2925 context->poll_waiting = FALSE;
2927 /* If the set of poll file descriptors changed, bail out
2928 * and let the main loop rerun
2930 if (context->poll_changed)
2932 UNLOCK_CONTEXT (context);
2935 #endif /* G_THREADS_ENABLED */
2937 pollrec = context->poll_records;
2941 if (pollrec->fd->events)
2942 pollrec->fd->revents = fds[i].revents;
2944 pollrec = pollrec->next;
2948 source = next_valid_source (context, NULL);
2951 if ((n_ready > 0) && (source->priority > max_priority))
2953 SOURCE_UNREF (source, context);
2956 if (SOURCE_BLOCKED (source))
2959 if (!(source->flags & G_SOURCE_READY))
2962 gboolean (*check) (GSource *source);
2964 check = source->source_funcs->check;
2966 context->in_check_or_prepare++;
2967 UNLOCK_CONTEXT (context);
2969 result = (*check) (source);
2971 LOCK_CONTEXT (context);
2972 context->in_check_or_prepare--;
2976 GSource *ready_source = source;
2978 while (ready_source)
2980 ready_source->flags |= G_SOURCE_READY;
2981 ready_source = ready_source->priv ? ready_source->priv->parent_source : NULL;
2986 if (source->flags & G_SOURCE_READY)
2988 source->ref_count++;
2989 g_ptr_array_add (context->pending_dispatches, source);
2993 /* never dispatch sources with less priority than the first
2994 * one we choose to dispatch
2996 max_priority = source->priority;
3000 source = next_valid_source (context, source);
3003 UNLOCK_CONTEXT (context);
3009 * g_main_context_dispatch:
3010 * @context: a #GMainContext
3012 * Dispatches all pending sources.
3015 g_main_context_dispatch (GMainContext *context)
3017 LOCK_CONTEXT (context);
3019 if (context->pending_dispatches->len > 0)
3021 g_main_dispatch (context);
3024 UNLOCK_CONTEXT (context);
3027 /* HOLDS context lock */
3029 g_main_context_iterate (GMainContext *context,
3036 gboolean some_ready;
3037 gint nfds, allocated_nfds;
3038 GPollFD *fds = NULL;
3040 UNLOCK_CONTEXT (context);
3042 #ifdef G_THREADS_ENABLED
3043 if (!g_main_context_acquire (context))
3045 gboolean got_ownership;
3047 LOCK_CONTEXT (context);
3049 g_return_val_if_fail (g_thread_supported (), FALSE);
3055 context->cond = g_cond_new ();
3057 got_ownership = g_main_context_wait (context,
3059 g_static_mutex_get_mutex (&context->mutex));
3065 LOCK_CONTEXT (context);
3066 #endif /* G_THREADS_ENABLED */
3068 if (!context->cached_poll_array)
3070 context->cached_poll_array_size = context->n_poll_records;
3071 context->cached_poll_array = g_new (GPollFD, context->n_poll_records);
3074 allocated_nfds = context->cached_poll_array_size;
3075 fds = context->cached_poll_array;
3077 UNLOCK_CONTEXT (context);
3079 g_main_context_prepare (context, &max_priority);
3081 while ((nfds = g_main_context_query (context, max_priority, &timeout, fds,
3082 allocated_nfds)) > allocated_nfds)
3084 LOCK_CONTEXT (context);
3086 context->cached_poll_array_size = allocated_nfds = nfds;
3087 context->cached_poll_array = fds = g_new (GPollFD, nfds);
3088 UNLOCK_CONTEXT (context);
3094 g_main_context_poll (context, timeout, max_priority, fds, nfds);
3096 some_ready = g_main_context_check (context, max_priority, fds, nfds);
3099 g_main_context_dispatch (context);
3101 #ifdef G_THREADS_ENABLED
3102 g_main_context_release (context);
3103 #endif /* G_THREADS_ENABLED */
3105 LOCK_CONTEXT (context);
3111 * g_main_context_pending:
3112 * @context: a #GMainContext (if %NULL, the default context will be used)
3114 * Checks if any sources have pending events for the given context.
3116 * Return value: %TRUE if events are pending.
3119 g_main_context_pending (GMainContext *context)
3124 context = g_main_context_default();
3126 LOCK_CONTEXT (context);
3127 retval = g_main_context_iterate (context, FALSE, FALSE, G_THREAD_SELF);
3128 UNLOCK_CONTEXT (context);
3134 * g_main_context_iteration:
3135 * @context: a #GMainContext (if %NULL, the default context will be used)
3136 * @may_block: whether the call may block.
3138 * Runs a single iteration for the given main loop. This involves
3139 * checking to see if any event sources are ready to be processed,
3140 * then if no events sources are ready and @may_block is %TRUE, waiting
3141 * for a source to become ready, then dispatching the highest priority
3142 * events sources that are ready. Otherwise, if @may_block is %FALSE
3143 * sources are not waited to become ready, only those highest priority
3144 * events sources will be dispatched (if any), that are ready at this
3145 * given moment without further waiting.
3147 * Note that even when @may_block is %TRUE, it is still possible for
3148 * g_main_context_iteration() to return %FALSE, since the the wait may
3149 * be interrupted for other reasons than an event source becoming ready.
3151 * Return value: %TRUE if events were dispatched.
3154 g_main_context_iteration (GMainContext *context, gboolean may_block)
3159 context = g_main_context_default();
3161 LOCK_CONTEXT (context);
3162 retval = g_main_context_iterate (context, may_block, TRUE, G_THREAD_SELF);
3163 UNLOCK_CONTEXT (context);
3170 * @context: a #GMainContext (if %NULL, the default context will be used).
3171 * @is_running: set to %TRUE to indicate that the loop is running. This
3172 * is not very important since calling g_main_loop_run() will set this to
3175 * Creates a new #GMainLoop structure.
3177 * Return value: a new #GMainLoop.
3180 g_main_loop_new (GMainContext *context,
3181 gboolean is_running)
3186 context = g_main_context_default();
3188 g_main_context_ref (context);
3190 loop = g_new0 (GMainLoop, 1);
3191 loop->context = context;
3192 loop->is_running = is_running != FALSE;
3193 loop->ref_count = 1;
3200 * @loop: a #GMainLoop
3202 * Increases the reference count on a #GMainLoop object by one.
3204 * Return value: @loop
3207 g_main_loop_ref (GMainLoop *loop)
3209 g_return_val_if_fail (loop != NULL, NULL);
3210 g_return_val_if_fail (g_atomic_int_get (&loop->ref_count) > 0, NULL);
3212 g_atomic_int_inc (&loop->ref_count);
3218 * g_main_loop_unref:
3219 * @loop: a #GMainLoop
3221 * Decreases the reference count on a #GMainLoop object by one. If
3222 * the result is zero, free the loop and free all associated memory.
3225 g_main_loop_unref (GMainLoop *loop)
3227 g_return_if_fail (loop != NULL);
3228 g_return_if_fail (g_atomic_int_get (&loop->ref_count) > 0);
3230 if (!g_atomic_int_dec_and_test (&loop->ref_count))
3233 g_main_context_unref (loop->context);
3239 * @loop: a #GMainLoop
3241 * Runs a main loop until g_main_loop_quit() is called on the loop.
3242 * If this is called for the thread of the loop's #GMainContext,
3243 * it will process events from the loop, otherwise it will
3247 g_main_loop_run (GMainLoop *loop)
3249 GThread *self = G_THREAD_SELF;
3251 g_return_if_fail (loop != NULL);
3252 g_return_if_fail (g_atomic_int_get (&loop->ref_count) > 0);
3254 #ifdef G_THREADS_ENABLED
3255 if (!g_main_context_acquire (loop->context))
3257 gboolean got_ownership = FALSE;
3259 /* Another thread owns this context */
3260 if (!g_thread_supported ())
3262 g_warning ("g_main_loop_run() was called from second thread but "
3263 "g_thread_init() was never called.");
3267 LOCK_CONTEXT (loop->context);
3269 g_atomic_int_inc (&loop->ref_count);
3271 if (!loop->is_running)
3272 loop->is_running = TRUE;
3274 if (!loop->context->cond)
3275 loop->context->cond = g_cond_new ();
3277 while (loop->is_running && !got_ownership)
3278 got_ownership = g_main_context_wait (loop->context,
3279 loop->context->cond,
3280 g_static_mutex_get_mutex (&loop->context->mutex));
3282 if (!loop->is_running)
3284 UNLOCK_CONTEXT (loop->context);
3286 g_main_context_release (loop->context);
3287 g_main_loop_unref (loop);
3291 g_assert (got_ownership);
3294 LOCK_CONTEXT (loop->context);
3295 #endif /* G_THREADS_ENABLED */
3297 if (loop->context->in_check_or_prepare)
3299 g_warning ("g_main_loop_run(): called recursively from within a source's "
3300 "check() or prepare() member, iteration not possible.");
3304 g_atomic_int_inc (&loop->ref_count);
3305 loop->is_running = TRUE;
3306 while (loop->is_running)
3307 g_main_context_iterate (loop->context, TRUE, TRUE, self);
3309 UNLOCK_CONTEXT (loop->context);
3311 #ifdef G_THREADS_ENABLED
3312 g_main_context_release (loop->context);
3313 #endif /* G_THREADS_ENABLED */
3315 g_main_loop_unref (loop);
3320 * @loop: a #GMainLoop
3322 * Stops a #GMainLoop from running. Any calls to g_main_loop_run()
3323 * for the loop will return.
3325 * Note that sources that have already been dispatched when
3326 * g_main_loop_quit() is called will still be executed.
3329 g_main_loop_quit (GMainLoop *loop)
3331 g_return_if_fail (loop != NULL);
3332 g_return_if_fail (g_atomic_int_get (&loop->ref_count) > 0);
3334 LOCK_CONTEXT (loop->context);
3335 loop->is_running = FALSE;
3336 g_main_context_wakeup_unlocked (loop->context);
3338 #ifdef G_THREADS_ENABLED
3339 if (loop->context->cond)
3340 g_cond_broadcast (loop->context->cond);
3341 #endif /* G_THREADS_ENABLED */
3343 UNLOCK_CONTEXT (loop->context);
3347 * g_main_loop_is_running:
3348 * @loop: a #GMainLoop.
3350 * Checks to see if the main loop is currently being run via g_main_loop_run().
3352 * Return value: %TRUE if the mainloop is currently being run.
3355 g_main_loop_is_running (GMainLoop *loop)
3357 g_return_val_if_fail (loop != NULL, FALSE);
3358 g_return_val_if_fail (g_atomic_int_get (&loop->ref_count) > 0, FALSE);
3360 return loop->is_running;
3364 * g_main_loop_get_context:
3365 * @loop: a #GMainLoop.
3367 * Returns the #GMainContext of @loop.
3369 * Return value: the #GMainContext of @loop
3372 g_main_loop_get_context (GMainLoop *loop)
3374 g_return_val_if_fail (loop != NULL, NULL);
3375 g_return_val_if_fail (g_atomic_int_get (&loop->ref_count) > 0, NULL);
3377 return loop->context;
3380 /* HOLDS: context's lock */
3382 g_main_context_poll (GMainContext *context,
3388 #ifdef G_MAIN_POLL_DEBUG
3394 GPollFunc poll_func;
3396 if (n_fds || timeout != 0)
3398 #ifdef G_MAIN_POLL_DEBUG
3399 if (_g_main_poll_debug)
3401 g_print ("polling context=%p n=%d timeout=%d\n",
3402 context, n_fds, timeout);
3403 poll_timer = g_timer_new ();
3407 LOCK_CONTEXT (context);
3409 poll_func = context->poll_func;
3411 UNLOCK_CONTEXT (context);
3412 if ((*poll_func) (fds, n_fds, timeout) < 0 && errno != EINTR)
3415 g_warning ("poll(2) failed due to: %s.",
3416 g_strerror (errno));
3418 /* If g_poll () returns -1, it has already called g_warning() */
3422 #ifdef G_MAIN_POLL_DEBUG
3423 if (_g_main_poll_debug)
3425 LOCK_CONTEXT (context);
3427 g_print ("g_main_poll(%d) timeout: %d - elapsed %12.10f seconds",
3430 g_timer_elapsed (poll_timer, NULL));
3431 g_timer_destroy (poll_timer);
3432 pollrec = context->poll_records;
3434 while (pollrec != NULL)
3439 if (fds[i].fd == pollrec->fd->fd &&
3440 pollrec->fd->events &&
3443 g_print (" [" G_POLLFD_FORMAT " :", fds[i].fd);
3444 if (fds[i].revents & G_IO_IN)
3446 if (fds[i].revents & G_IO_OUT)
3448 if (fds[i].revents & G_IO_PRI)
3450 if (fds[i].revents & G_IO_ERR)
3452 if (fds[i].revents & G_IO_HUP)
3454 if (fds[i].revents & G_IO_NVAL)
3460 pollrec = pollrec->next;
3464 UNLOCK_CONTEXT (context);
3467 } /* if (n_fds || timeout != 0) */
3471 * g_main_context_add_poll:
3472 * @context: a #GMainContext (or %NULL for the default context)
3473 * @fd: a #GPollFD structure holding information about a file
3474 * descriptor to watch.
3475 * @priority: the priority for this file descriptor which should be
3476 * the same as the priority used for g_source_attach() to ensure that the
3477 * file descriptor is polled whenever the results may be needed.
3479 * Adds a file descriptor to the set of file descriptors polled for
3480 * this context. This will very seldomly be used directly. Instead
3481 * a typical event source will use g_source_add_poll() instead.
3484 g_main_context_add_poll (GMainContext *context,
3489 context = g_main_context_default ();
3491 g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
3492 g_return_if_fail (fd);
3494 LOCK_CONTEXT (context);
3495 g_main_context_add_poll_unlocked (context, priority, fd);
3496 UNLOCK_CONTEXT (context);
3499 /* HOLDS: main_loop_lock */
3501 g_main_context_add_poll_unlocked (GMainContext *context,
3505 GPollRec *lastrec, *pollrec;
3506 GPollRec *newrec = g_slice_new (GPollRec);
3508 /* This file descriptor may be checked before we ever poll */
3511 newrec->priority = priority;
3514 pollrec = context->poll_records;
3515 while (pollrec && priority >= pollrec->priority)
3518 pollrec = pollrec->next;
3522 lastrec->next = newrec;
3524 context->poll_records = newrec;
3526 newrec->next = pollrec;
3528 context->n_poll_records++;
3530 #ifdef G_THREADS_ENABLED
3531 context->poll_changed = TRUE;
3533 /* Now wake up the main loop if it is waiting in the poll() */
3534 g_main_context_wakeup_unlocked (context);
3539 * g_main_context_remove_poll:
3540 * @context:a #GMainContext
3541 * @fd: a #GPollFD descriptor previously added with g_main_context_add_poll()
3543 * Removes file descriptor from the set of file descriptors to be
3544 * polled for a particular context.
3547 g_main_context_remove_poll (GMainContext *context,
3551 context = g_main_context_default ();
3553 g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
3554 g_return_if_fail (fd);
3556 LOCK_CONTEXT (context);
3557 g_main_context_remove_poll_unlocked (context, fd);
3558 UNLOCK_CONTEXT (context);
3562 g_main_context_remove_poll_unlocked (GMainContext *context,
3565 GPollRec *pollrec, *lastrec;
3568 pollrec = context->poll_records;
3572 if (pollrec->fd == fd)
3574 if (lastrec != NULL)
3575 lastrec->next = pollrec->next;
3577 context->poll_records = pollrec->next;
3579 g_slice_free (GPollRec, pollrec);
3581 context->n_poll_records--;
3585 pollrec = pollrec->next;
3588 #ifdef G_THREADS_ENABLED
3589 context->poll_changed = TRUE;
3591 /* Now wake up the main loop if it is waiting in the poll() */
3592 g_main_context_wakeup_unlocked (context);
3597 * g_source_get_current_time:
3598 * @source: a #GSource
3599 * @timeval: #GTimeVal structure in which to store current time.
3601 * Gets the "current time" to be used when checking
3602 * this source. The advantage of calling this function over
3603 * calling g_get_current_time() directly is that when
3604 * checking multiple sources, GLib can cache a single value
3605 * instead of having to repeatedly get the system time.
3607 * Deprecated: 2.28: use g_source_get_time() instead
3610 g_source_get_current_time (GSource *source,
3613 GMainContext *context;
3615 g_return_if_fail (source->context != NULL);
3617 context = source->context;
3619 LOCK_CONTEXT (context);
3621 if (!context->real_time_is_fresh)
3623 context->real_time = g_get_real_time ();
3624 context->real_time_is_fresh = TRUE;
3627 timeval->tv_sec = context->real_time / 1000000;
3628 timeval->tv_usec = context->real_time % 1000000;
3630 UNLOCK_CONTEXT (context);
3634 * g_source_get_time:
3635 * @source: a #GSource
3637 * Gets the time to be used when checking this source. The advantage of
3638 * calling this function over calling g_get_monotonic_time() directly is
3639 * that when checking multiple sources, GLib can cache a single value
3640 * instead of having to repeatedly get the system monotonic time.
3642 * The time here is the system monotonic time, if available, or some
3643 * other reasonable alternative otherwise. See g_get_monotonic_time().
3645 * Returns: the monotonic time in microseconds
3650 g_source_get_time (GSource *source)
3652 GMainContext *context;
3655 g_return_val_if_fail (source->context != NULL, 0);
3657 context = source->context;
3659 LOCK_CONTEXT (context);
3661 if (!context->time_is_fresh)
3663 context->time = g_get_monotonic_time ();
3664 context->time_is_fresh = TRUE;
3667 result = context->time;
3669 UNLOCK_CONTEXT (context);
3675 * g_main_context_set_poll_func:
3676 * @context: a #GMainContext
3677 * @func: the function to call to poll all file descriptors
3679 * Sets the function to use to handle polling of file descriptors. It
3680 * will be used instead of the poll() system call
3681 * (or GLib's replacement function, which is used where
3682 * poll() isn't available).
3684 * This function could possibly be used to integrate the GLib event
3685 * loop with an external event loop.
3688 g_main_context_set_poll_func (GMainContext *context,
3692 context = g_main_context_default ();
3694 g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
3696 LOCK_CONTEXT (context);
3699 context->poll_func = func;
3701 context->poll_func = g_poll;
3703 UNLOCK_CONTEXT (context);
3707 * g_main_context_get_poll_func:
3708 * @context: a #GMainContext
3710 * Gets the poll function set by g_main_context_set_poll_func().
3712 * Return value: the poll function
3715 g_main_context_get_poll_func (GMainContext *context)
3720 context = g_main_context_default ();
3722 g_return_val_if_fail (g_atomic_int_get (&context->ref_count) > 0, NULL);
3724 LOCK_CONTEXT (context);
3725 result = context->poll_func;
3726 UNLOCK_CONTEXT (context);
3732 _g_main_wake_up_all_contexts (void)
3736 /* We were woken up. Wake up all other contexts in all other threads */
3737 G_LOCK (main_context_list);
3738 for (list = main_context_list; list; list = list->next)
3740 GMainContext *context;
3742 context = list->data;
3743 if (g_atomic_int_get (&context->ref_count) > 0)
3744 /* Due to racing conditions we can find ref_count == 0, in
3745 * that case, however, the context is still not destroyed
3746 * and no poll can be active, otherwise the ref_count
3749 g_main_context_wakeup (context);
3751 G_UNLOCK (main_context_list);
3755 /* HOLDS: context's lock */
3756 /* Wake the main loop up from a poll() */
3758 g_main_context_wakeup_unlocked (GMainContext *context)
3760 #ifdef G_THREADS_ENABLED
3761 if (g_thread_supported() && context->poll_waiting)
3763 context->poll_waiting = FALSE;
3765 write (context->wake_up_pipe[1], "A", 1);
3767 ReleaseSemaphore (context->wake_up_semaphore, 1, NULL);
3774 * g_main_context_wakeup:
3775 * @context: a #GMainContext
3777 * If @context is currently waiting in a poll(), interrupt
3778 * the poll(), and continue the iteration process.
3781 g_main_context_wakeup (GMainContext *context)
3784 context = g_main_context_default ();
3786 g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
3788 LOCK_CONTEXT (context);
3789 g_main_context_wakeup_unlocked (context);
3790 UNLOCK_CONTEXT (context);
3794 * g_main_context_is_owner:
3795 * @context: a #GMainContext
3797 * Determines whether this thread holds the (recursive)
3798 * ownership of this #GMaincontext. This is useful to
3799 * know before waiting on another thread that may be
3800 * blocking to get ownership of @context.
3802 * Returns: %TRUE if current thread is owner of @context.
3807 g_main_context_is_owner (GMainContext *context)
3812 context = g_main_context_default ();
3814 #ifdef G_THREADS_ENABLED
3815 LOCK_CONTEXT (context);
3816 is_owner = context->owner == G_THREAD_SELF;
3817 UNLOCK_CONTEXT (context);
3828 g_timeout_set_expiration (GTimeoutSource *timeout_source,
3829 gint64 current_time)
3831 timeout_source->expiration = current_time +
3832 (guint64) timeout_source->interval * 1000;
3834 if (timeout_source->seconds)
3837 static gint timer_perturb = -1;
3839 if (timer_perturb == -1)
3842 * we want a per machine/session unique 'random' value; try the dbus
3843 * address first, that has a UUID in it. If there is no dbus, use the
3844 * hostname for hashing.
3846 const char *session_bus_address = g_getenv ("DBUS_SESSION_BUS_ADDRESS");
3847 if (!session_bus_address)
3848 session_bus_address = g_getenv ("HOSTNAME");
3849 if (session_bus_address)
3850 timer_perturb = ABS ((gint) g_str_hash (session_bus_address)) % 1000000;
3855 /* We want the microseconds part of the timeout to land on the
3856 * 'timer_perturb' mark, but we need to make sure we don't try to
3857 * set the timeout in the past. We do this by ensuring that we
3858 * always only *increase* the expiration time by adding a full
3859 * second in the case that the microsecond portion decreases.
3861 timeout_source->expiration -= timer_perturb;
3863 remainder = timeout_source->expiration % 1000000;
3864 if (remainder >= 1000000/4)
3865 timeout_source->expiration += 1000000;
3867 timeout_source->expiration -= remainder;
3868 timeout_source->expiration += timer_perturb;
3873 g_timeout_prepare (GSource *source,
3876 GTimeoutSource *timeout_source = (GTimeoutSource *) source;
3877 gint64 now = g_source_get_time (source);
3879 if (now < timeout_source->expiration)
3881 /* Round up to ensure that we don't try again too early */
3882 *timeout = (timeout_source->expiration - now + 999) / 1000;
3891 g_timeout_check (GSource *source)
3893 GTimeoutSource *timeout_source = (GTimeoutSource *) source;
3894 gint64 now = g_source_get_time (source);
3896 return timeout_source->expiration <= now;
3900 g_timeout_dispatch (GSource *source,
3901 GSourceFunc callback,
3904 GTimeoutSource *timeout_source = (GTimeoutSource *)source;
3909 g_warning ("Timeout source dispatched without callback\n"
3910 "You must call g_source_set_callback().");
3914 again = callback (user_data);
3917 g_timeout_set_expiration (timeout_source, g_source_get_time (source));
3923 * g_timeout_source_new:
3924 * @interval: the timeout interval in milliseconds.
3926 * Creates a new timeout source.
3928 * The source will not initially be associated with any #GMainContext
3929 * and must be added to one with g_source_attach() before it will be
3932 * Return value: the newly-created timeout source
3935 g_timeout_source_new (guint interval)
3937 GSource *source = g_source_new (&g_timeout_funcs, sizeof (GTimeoutSource));
3938 GTimeoutSource *timeout_source = (GTimeoutSource *)source;
3940 timeout_source->interval = interval;
3941 g_timeout_set_expiration (timeout_source, g_get_monotonic_time ());
3947 * g_timeout_source_new_seconds:
3948 * @interval: the timeout interval in seconds
3950 * Creates a new timeout source.
3952 * The source will not initially be associated with any #GMainContext
3953 * and must be added to one with g_source_attach() before it will be
3956 * The scheduling granularity/accuracy of this timeout source will be
3959 * Return value: the newly-created timeout source
3964 g_timeout_source_new_seconds (guint interval)
3966 GSource *source = g_source_new (&g_timeout_funcs, sizeof (GTimeoutSource));
3967 GTimeoutSource *timeout_source = (GTimeoutSource *)source;
3969 timeout_source->interval = 1000 * interval;
3970 timeout_source->seconds = TRUE;
3972 g_timeout_set_expiration (timeout_source, g_get_monotonic_time ());
3979 * g_timeout_add_full:
3980 * @priority: the priority of the timeout source. Typically this will be in
3981 * the range between #G_PRIORITY_DEFAULT and #G_PRIORITY_HIGH.
3982 * @interval: the time between calls to the function, in milliseconds
3983 * (1/1000ths of a second)
3984 * @function: function to call
3985 * @data: data to pass to @function
3986 * @notify: function to call when the timeout is removed, or %NULL
3988 * Sets a function to be called at regular intervals, with the given
3989 * priority. The function is called repeatedly until it returns
3990 * %FALSE, at which point the timeout is automatically destroyed and
3991 * the function will not be called again. The @notify function is
3992 * called when the timeout is destroyed. The first call to the
3993 * function will be at the end of the first @interval.
3995 * Note that timeout functions may be delayed, due to the processing of other
3996 * event sources. Thus they should not be relied on for precise timing.
3997 * After each call to the timeout function, the time of the next
3998 * timeout is recalculated based on the current time and the given interval
3999 * (it does not try to 'catch up' time lost in delays).
4001 * This internally creates a main loop source using g_timeout_source_new()
4002 * and attaches it to the main loop context using g_source_attach(). You can
4003 * do these steps manually if you need greater control.
4005 * Return value: the ID (greater than 0) of the event source.
4008 g_timeout_add_full (gint priority,
4010 GSourceFunc function,
4012 GDestroyNotify notify)
4017 g_return_val_if_fail (function != NULL, 0);
4019 source = g_timeout_source_new (interval);
4021 if (priority != G_PRIORITY_DEFAULT)
4022 g_source_set_priority (source, priority);
4024 g_source_set_callback (source, function, data, notify);
4025 id = g_source_attach (source, NULL);
4026 g_source_unref (source);
4033 * @interval: the time between calls to the function, in milliseconds
4034 * (1/1000ths of a second)
4035 * @function: function to call
4036 * @data: data to pass to @function
4038 * Sets a function to be called at regular intervals, with the default
4039 * priority, #G_PRIORITY_DEFAULT. The function is called repeatedly
4040 * until it returns %FALSE, at which point the timeout is automatically
4041 * destroyed and the function will not be called again. The first call
4042 * to the function will be at the end of the first @interval.
4044 * Note that timeout functions may be delayed, due to the processing of other
4045 * event sources. Thus they should not be relied on for precise timing.
4046 * After each call to the timeout function, the time of the next
4047 * timeout is recalculated based on the current time and the given interval
4048 * (it does not try to 'catch up' time lost in delays).
4050 * If you want to have a timer in the "seconds" range and do not care
4051 * about the exact time of the first call of the timer, use the
4052 * g_timeout_add_seconds() function; this function allows for more
4053 * optimizations and more efficient system power usage.
4055 * This internally creates a main loop source using g_timeout_source_new()
4056 * and attaches it to the main loop context using g_source_attach(). You can
4057 * do these steps manually if you need greater control.
4059 * Return value: the ID (greater than 0) of the event source.
4062 g_timeout_add (guint32 interval,
4063 GSourceFunc function,
4066 return g_timeout_add_full (G_PRIORITY_DEFAULT,
4067 interval, function, data, NULL);
4071 * g_timeout_add_seconds_full:
4072 * @priority: the priority of the timeout source. Typically this will be in
4073 * the range between #G_PRIORITY_DEFAULT and #G_PRIORITY_HIGH.
4074 * @interval: the time between calls to the function, in seconds
4075 * @function: function to call
4076 * @data: data to pass to @function
4077 * @notify: function to call when the timeout is removed, or %NULL
4079 * Sets a function to be called at regular intervals, with @priority.
4080 * The function is called repeatedly until it returns %FALSE, at which
4081 * point the timeout is automatically destroyed and the function will
4082 * not be called again.
4084 * Unlike g_timeout_add(), this function operates at whole second granularity.
4085 * The initial starting point of the timer is determined by the implementation
4086 * and the implementation is expected to group multiple timers together so that
4087 * they fire all at the same time.
4088 * To allow this grouping, the @interval to the first timer is rounded
4089 * and can deviate up to one second from the specified interval.
4090 * Subsequent timer iterations will generally run at the specified interval.
4092 * Note that timeout functions may be delayed, due to the processing of other
4093 * event sources. Thus they should not be relied on for precise timing.
4094 * After each call to the timeout function, the time of the next
4095 * timeout is recalculated based on the current time and the given @interval
4097 * If you want timing more precise than whole seconds, use g_timeout_add()
4100 * The grouping of timers to fire at the same time results in a more power
4101 * and CPU efficient behavior so if your timer is in multiples of seconds
4102 * and you don't require the first timer exactly one second from now, the
4103 * use of g_timeout_add_seconds() is preferred over g_timeout_add().
4105 * This internally creates a main loop source using
4106 * g_timeout_source_new_seconds() and attaches it to the main loop context
4107 * using g_source_attach(). You can do these steps manually if you need
4110 * Return value: the ID (greater than 0) of the event source.
4115 g_timeout_add_seconds_full (gint priority,
4117 GSourceFunc function,
4119 GDestroyNotify notify)
4124 g_return_val_if_fail (function != NULL, 0);
4126 source = g_timeout_source_new_seconds (interval);
4128 if (priority != G_PRIORITY_DEFAULT)
4129 g_source_set_priority (source, priority);
4131 g_source_set_callback (source, function, data, notify);
4132 id = g_source_attach (source, NULL);
4133 g_source_unref (source);
4139 * g_timeout_add_seconds:
4140 * @interval: the time between calls to the function, in seconds
4141 * @function: function to call
4142 * @data: data to pass to @function
4144 * Sets a function to be called at regular intervals with the default
4145 * priority, #G_PRIORITY_DEFAULT. The function is called repeatedly until
4146 * it returns %FALSE, at which point the timeout is automatically destroyed
4147 * and the function will not be called again.
4149 * This internally creates a main loop source using
4150 * g_timeout_source_new_seconds() and attaches it to the main loop context
4151 * using g_source_attach(). You can do these steps manually if you need
4152 * greater control. Also see g_timout_add_seconds_full().
4154 * Note that the first call of the timer may not be precise for timeouts
4155 * of one second. If you need finer precision and have such a timeout,
4156 * you may want to use g_timeout_add() instead.
4158 * Return value: the ID (greater than 0) of the event source.
4163 g_timeout_add_seconds (guint interval,
4164 GSourceFunc function,
4167 g_return_val_if_fail (function != NULL, 0);
4169 return g_timeout_add_seconds_full (G_PRIORITY_DEFAULT, interval, function, data, NULL);
4172 /* Child watch functions */
4177 g_child_watch_prepare (GSource *source,
4186 g_child_watch_check (GSource *source)
4188 GChildWatchSource *child_watch_source;
4189 gboolean child_exited;
4191 child_watch_source = (GChildWatchSource *) source;
4193 child_exited = child_watch_source->poll.revents & G_IO_IN;
4200 * Note: We do _not_ check for the special value of STILL_ACTIVE
4201 * since we know that the process has exited and doing so runs into
4202 * problems if the child process "happens to return STILL_ACTIVE(259)"
4203 * as Microsoft's Platform SDK puts it.
4205 if (!GetExitCodeProcess (child_watch_source->pid, &child_status))
4207 gchar *emsg = g_win32_error_message (GetLastError ());
4208 g_warning (G_STRLOC ": GetExitCodeProcess() failed: %s", emsg);
4211 child_watch_source->child_status = -1;
4214 child_watch_source->child_status = child_status;
4217 return child_exited;
4220 #else /* G_OS_WIN32 */
4223 check_for_child_exited (GSource *source)
4225 GChildWatchSource *child_watch_source;
4228 /* protect against another SIGCHLD in the middle of this call */
4229 count = child_watch_count;
4231 child_watch_source = (GChildWatchSource *) source;
4233 if (child_watch_source->child_exited)
4236 if (child_watch_source->count < count)
4240 if (waitpid (child_watch_source->pid, &child_status, WNOHANG) > 0)
4242 child_watch_source->child_status = child_status;
4243 child_watch_source->child_exited = TRUE;
4245 child_watch_source->count = count;
4248 return child_watch_source->child_exited;
4252 g_child_watch_prepare (GSource *source,
4257 return check_for_child_exited (source);
4262 g_child_watch_check (GSource *source)
4264 return check_for_child_exited (source);
4267 #endif /* G_OS_WIN32 */
4270 g_child_watch_dispatch (GSource *source,
4271 GSourceFunc callback,
4274 GChildWatchSource *child_watch_source;
4275 GChildWatchFunc child_watch_callback = (GChildWatchFunc) callback;
4277 child_watch_source = (GChildWatchSource *) source;
4281 g_warning ("Child watch source dispatched without callback\n"
4282 "You must call g_source_set_callback().");
4286 (child_watch_callback) (child_watch_source->pid, child_watch_source->child_status, user_data);
4288 /* We never keep a child watch source around as the child is gone */
4295 g_child_watch_signal_handler (int signum)
4297 child_watch_count ++;
4299 if (child_watch_init_state == CHILD_WATCH_INITIALIZED_THREADED)
4301 char buf[1] = { _UNIX_SIGNAL_PIPE_SIGCHLD_CHAR };
4302 write (unix_signal_wake_up_pipe[1], buf, 1);
4306 /* We count on the signal interrupting the poll in the same thread.
4312 g_child_watch_source_init_single (void)
4314 struct sigaction action;
4316 g_assert (! g_thread_supported());
4317 g_assert (child_watch_init_state == CHILD_WATCH_UNINITIALIZED);
4319 child_watch_init_state = CHILD_WATCH_INITIALIZED_SINGLE;
4321 action.sa_handler = g_child_watch_signal_handler;
4322 sigemptyset (&action.sa_mask);
4323 action.sa_flags = SA_NOCLDSTOP;
4324 sigaction (SIGCHLD, &action, NULL);
4327 static gpointer unix_signal_helper_thread (gpointer data) G_GNUC_NORETURN;
4330 * This thread is created whenever anything in GLib needs
4331 * to deal with UNIX signals; at present, just SIGCHLD
4332 * from g_child_watch_source_new().
4334 * Note: We could eventually make this thread a more public interface
4335 * and allow e.g. GDBus to use it instead of its own worker thread.
4338 unix_signal_helper_thread (gpointer data)
4343 ssize_t i, bytes_read;
4345 bytes_read = read (unix_signal_wake_up_pipe[0], b, sizeof (b));
4348 g_warning ("Failed to read from child watch wake up pipe: %s",
4350 /* Not much we can do here sanely; just wait a second and hope
4353 g_usleep (G_USEC_PER_SEC);
4356 for (i = 0; i < bytes_read; i++)
4360 case _UNIX_SIGNAL_PIPE_SIGCHLD_CHAR:
4361 /* The child watch source will call waitpid() in its
4362 * prepare() and check() methods; however, we don't
4363 * know which pid exited, so we need to wake up
4364 * all contexts. Note: actually we could get the pid
4365 * from the "siginfo_t" via the handler, but to pass
4366 * that info down the pipe would require a more structured
4367 * data stream (as opposed to a single byte).
4369 _g_main_wake_up_all_contexts ();
4372 g_warning ("Invalid char '%c' read from child watch pipe", b[i]);
4380 _g_main_init_unix_signal_wakeup_pipe (void)
4382 GError *error = NULL;
4384 G_LOCK (unix_signal_lock);
4386 if (unix_signal_wake_up_pipe[0] >= 0)
4389 g_assert (g_thread_supported());
4391 if (!g_unix_pipe_flags (unix_signal_wake_up_pipe, FD_CLOEXEC, &error))
4392 g_error ("Cannot create UNIX signal wake up pipe: %s\n", error->message);
4393 fcntl (unix_signal_wake_up_pipe[1], F_SETFL, O_NONBLOCK | fcntl (unix_signal_wake_up_pipe[1], F_GETFL));
4395 /* We create a helper thread that polls on the wakeup pipe indefinitely */
4396 /* FIXME: Think this through for races */
4397 if (g_thread_create (unix_signal_helper_thread, NULL, FALSE, &error) == NULL)
4398 g_error ("Cannot create a thread to monitor UNIX signals: %s\n", error->message);
4401 G_UNLOCK (unix_signal_lock);
4405 g_child_watch_source_init_multi_threaded (void)
4407 struct sigaction action;
4409 _g_main_init_unix_signal_wakeup_pipe ();
4411 child_watch_init_state = CHILD_WATCH_INITIALIZED_THREADED;
4413 action.sa_handler = g_child_watch_signal_handler;
4414 sigemptyset (&action.sa_mask);
4415 action.sa_flags = SA_RESTART | SA_NOCLDSTOP;
4416 sigaction (SIGCHLD, &action, NULL);
4420 g_child_watch_source_init_promote_single_to_threaded (void)
4422 g_child_watch_source_init_multi_threaded ();
4426 g_child_watch_source_init (void)
4428 if (g_thread_supported())
4430 if (child_watch_init_state == CHILD_WATCH_UNINITIALIZED)
4431 g_child_watch_source_init_multi_threaded ();
4432 else if (child_watch_init_state == CHILD_WATCH_INITIALIZED_SINGLE)
4433 g_child_watch_source_init_promote_single_to_threaded ();
4437 if (child_watch_init_state == CHILD_WATCH_UNINITIALIZED)
4438 g_child_watch_source_init_single ();
4442 #endif /* !G_OS_WIN32 */
4445 * g_child_watch_source_new:
4446 * @pid: process to watch. On POSIX the pid of a child process. On
4447 * Windows a handle for a process (which doesn't have to be a child).
4449 * Creates a new child_watch source.
4451 * The source will not initially be associated with any #GMainContext
4452 * and must be added to one with g_source_attach() before it will be
4455 * Note that child watch sources can only be used in conjunction with
4456 * <literal>g_spawn...</literal> when the %G_SPAWN_DO_NOT_REAP_CHILD
4459 * Note that on platforms where #GPid must be explicitly closed
4460 * (see g_spawn_close_pid()) @pid must not be closed while the
4461 * source is still active. Typically, you will want to call
4462 * g_spawn_close_pid() in the callback function for the source.
4464 * Note further that using g_child_watch_source_new() is not
4465 * compatible with calling <literal>waitpid(-1)</literal> in
4466 * the application. Calling waitpid() for individual pids will
4469 * Return value: the newly-created child watch source
4474 g_child_watch_source_new (GPid pid)
4476 GSource *source = g_source_new (&g_child_watch_funcs, sizeof (GChildWatchSource));
4477 GChildWatchSource *child_watch_source = (GChildWatchSource *)source;
4480 child_watch_source->poll.fd = (gintptr) pid;
4481 child_watch_source->poll.events = G_IO_IN;
4483 g_source_add_poll (source, &child_watch_source->poll);
4484 #else /* G_OS_WIN32 */
4485 g_child_watch_source_init ();
4486 #endif /* G_OS_WIN32 */
4488 child_watch_source->pid = pid;
4494 * g_child_watch_add_full:
4495 * @priority: the priority of the idle source. Typically this will be in the
4496 * range between #G_PRIORITY_DEFAULT_IDLE and #G_PRIORITY_HIGH_IDLE.
4497 * @pid: process to watch. On POSIX the pid of a child process. On
4498 * Windows a handle for a process (which doesn't have to be a child).
4499 * @function: function to call
4500 * @data: data to pass to @function
4501 * @notify: function to call when the idle is removed, or %NULL
4503 * Sets a function to be called when the child indicated by @pid
4504 * exits, at the priority @priority.
4506 * If you obtain @pid from g_spawn_async() or g_spawn_async_with_pipes()
4507 * you will need to pass #G_SPAWN_DO_NOT_REAP_CHILD as flag to
4508 * the spawn function for the child watching to work.
4510 * Note that on platforms where #GPid must be explicitly closed
4511 * (see g_spawn_close_pid()) @pid must not be closed while the
4512 * source is still active. Typically, you will want to call
4513 * g_spawn_close_pid() in the callback function for the source.
4515 * GLib supports only a single callback per process id.
4517 * This internally creates a main loop source using
4518 * g_child_watch_source_new() and attaches it to the main loop context
4519 * using g_source_attach(). You can do these steps manually if you
4520 * need greater control.
4522 * Return value: the ID (greater than 0) of the event source.
4527 g_child_watch_add_full (gint priority,
4529 GChildWatchFunc function,
4531 GDestroyNotify notify)
4536 g_return_val_if_fail (function != NULL, 0);
4538 source = g_child_watch_source_new (pid);
4540 if (priority != G_PRIORITY_DEFAULT)
4541 g_source_set_priority (source, priority);
4543 g_source_set_callback (source, (GSourceFunc) function, data, notify);
4544 id = g_source_attach (source, NULL);
4545 g_source_unref (source);
4551 * g_child_watch_add:
4552 * @pid: process id to watch. On POSIX the pid of a child process. On
4553 * Windows a handle for a process (which doesn't have to be a child).
4554 * @function: function to call
4555 * @data: data to pass to @function
4557 * Sets a function to be called when the child indicated by @pid
4558 * exits, at a default priority, #G_PRIORITY_DEFAULT.
4560 * If you obtain @pid from g_spawn_async() or g_spawn_async_with_pipes()
4561 * you will need to pass #G_SPAWN_DO_NOT_REAP_CHILD as flag to
4562 * the spawn function for the child watching to work.
4564 * Note that on platforms where #GPid must be explicitly closed
4565 * (see g_spawn_close_pid()) @pid must not be closed while the
4566 * source is still active. Typically, you will want to call
4567 * g_spawn_close_pid() in the callback function for the source.
4569 * GLib supports only a single callback per process id.
4571 * This internally creates a main loop source using
4572 * g_child_watch_source_new() and attaches it to the main loop context
4573 * using g_source_attach(). You can do these steps manually if you
4574 * need greater control.
4576 * Return value: the ID (greater than 0) of the event source.
4581 g_child_watch_add (GPid pid,
4582 GChildWatchFunc function,
4585 return g_child_watch_add_full (G_PRIORITY_DEFAULT, pid, function, data, NULL);
4589 /* Idle functions */
4592 g_idle_prepare (GSource *source,
4601 g_idle_check (GSource *source)
4607 g_idle_dispatch (GSource *source,
4608 GSourceFunc callback,
4613 g_warning ("Idle source dispatched without callback\n"
4614 "You must call g_source_set_callback().");
4618 return callback (user_data);
4622 * g_idle_source_new:
4624 * Creates a new idle source.
4626 * The source will not initially be associated with any #GMainContext
4627 * and must be added to one with g_source_attach() before it will be
4628 * executed. Note that the default priority for idle sources is
4629 * %G_PRIORITY_DEFAULT_IDLE, as compared to other sources which
4630 * have a default priority of %G_PRIORITY_DEFAULT.
4632 * Return value: the newly-created idle source
4635 g_idle_source_new (void)
4639 source = g_source_new (&g_idle_funcs, sizeof (GSource));
4640 g_source_set_priority (source, G_PRIORITY_DEFAULT_IDLE);
4647 * @priority: the priority of the idle source. Typically this will be in the
4648 * range between #G_PRIORITY_DEFAULT_IDLE and #G_PRIORITY_HIGH_IDLE.
4649 * @function: function to call
4650 * @data: data to pass to @function
4651 * @notify: function to call when the idle is removed, or %NULL
4653 * Adds a function to be called whenever there are no higher priority
4654 * events pending. If the function returns %FALSE it is automatically
4655 * removed from the list of event sources and will not be called again.
4657 * This internally creates a main loop source using g_idle_source_new()
4658 * and attaches it to the main loop context using g_source_attach().
4659 * You can do these steps manually if you need greater control.
4661 * Return value: the ID (greater than 0) of the event source.
4664 g_idle_add_full (gint priority,
4665 GSourceFunc function,
4667 GDestroyNotify notify)
4672 g_return_val_if_fail (function != NULL, 0);
4674 source = g_idle_source_new ();
4676 if (priority != G_PRIORITY_DEFAULT_IDLE)
4677 g_source_set_priority (source, priority);
4679 g_source_set_callback (source, function, data, notify);
4680 id = g_source_attach (source, NULL);
4681 g_source_unref (source);
4688 * @function: function to call
4689 * @data: data to pass to @function.
4691 * Adds a function to be called whenever there are no higher priority
4692 * events pending to the default main loop. The function is given the
4693 * default idle priority, #G_PRIORITY_DEFAULT_IDLE. If the function
4694 * returns %FALSE it is automatically removed from the list of event
4695 * sources and will not be called again.
4697 * This internally creates a main loop source using g_idle_source_new()
4698 * and attaches it to the main loop context using g_source_attach().
4699 * You can do these steps manually if you need greater control.
4701 * Return value: the ID (greater than 0) of the event source.
4704 g_idle_add (GSourceFunc function,
4707 return g_idle_add_full (G_PRIORITY_DEFAULT_IDLE, function, data, NULL);
4711 * g_idle_remove_by_data:
4712 * @data: the data for the idle source's callback.
4714 * Removes the idle function with the given data.
4716 * Return value: %TRUE if an idle source was found and removed.
4719 g_idle_remove_by_data (gpointer data)
4721 return g_source_remove_by_funcs_user_data (&g_idle_funcs, data);
4725 * g_main_context_invoke:
4726 * @context: a #GMainContext, or %NULL
4727 * @function: function to call
4728 * @data: data to pass to @function
4730 * Invokes a function in such a way that @context is owned during the
4731 * invocation of @function.
4733 * If @context is %NULL then the global default main context — as
4734 * returned by g_main_context_default() — is used.
4736 * If @context is owned by the current thread, @function is called
4737 * directly. Otherwise, if @context is the thread-default main context
4738 * of the current thread and g_main_context_acquire() succeeds, then
4739 * @function is called and g_main_context_release() is called
4742 * In any other case, an idle source is created to call @function and
4743 * that source is attached to @context (presumably to be run in another
4744 * thread). The idle source is attached with #G_PRIORITY_DEFAULT
4745 * priority. If you want a different priority, use
4746 * g_main_context_invoke_full().
4748 * Note that, as with normal idle functions, @function should probably
4749 * return %FALSE. If it returns %TRUE, it will be continuously run in a
4750 * loop (and may prevent this call from returning).
4755 g_main_context_invoke (GMainContext *context,
4756 GSourceFunc function,
4759 g_main_context_invoke_full (context,
4761 function, data, NULL);
4765 * g_main_context_invoke_full:
4766 * @context: a #GMainContext, or %NULL
4767 * @priority: the priority at which to run @function
4768 * @function: function to call
4769 * @data: data to pass to @function
4770 * @notify: a function to call when @data is no longer in use, or %NULL.
4772 * Invokes a function in such a way that @context is owned during the
4773 * invocation of @function.
4775 * This function is the same as g_main_context_invoke() except that it
4776 * lets you specify the priority incase @function ends up being
4777 * scheduled as an idle and also lets you give a #GDestroyNotify for @data.
4779 * @notify should not assume that it is called from any particular
4780 * thread or with any particular context acquired.
4785 g_main_context_invoke_full (GMainContext *context,
4787 GSourceFunc function,
4789 GDestroyNotify notify)
4791 g_return_if_fail (function != NULL);
4794 context = g_main_context_default ();
4796 if (g_main_context_is_owner (context))
4798 while (function (data));
4805 GMainContext *thread_default;
4807 thread_default = g_main_context_get_thread_default ();
4809 if (!thread_default)
4810 thread_default = g_main_context_default ();
4812 if (thread_default == context && g_main_context_acquire (context))
4814 while (function (data));
4816 g_main_context_release (context);
4825 source = g_idle_source_new ();
4826 g_source_set_priority (source, priority);
4827 g_source_set_callback (source, function, data, notify);
4828 g_source_attach (source, context);
4829 g_source_unref (source);