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 <sys/types.h>
69 #ifdef HAVE_SYS_TIME_H
71 #endif /* HAVE_SYS_TIME_H */
74 #endif /* HAVE_UNISTD_H */
80 #endif /* G_OS_WIN32 */
83 #include <sys/socket.h>
85 #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 gboolean g_timeout_prepare (GSource *source,
370 static gboolean g_timeout_check (GSource *source);
371 static gboolean g_timeout_dispatch (GSource *source,
372 GSourceFunc callback,
374 static gboolean g_child_watch_prepare (GSource *source,
376 static gboolean g_child_watch_check (GSource *source);
377 static gboolean g_child_watch_dispatch (GSource *source,
378 GSourceFunc callback,
380 static gboolean g_idle_prepare (GSource *source,
382 static gboolean g_idle_check (GSource *source);
383 static gboolean g_idle_dispatch (GSource *source,
384 GSourceFunc callback,
387 G_LOCK_DEFINE_STATIC (main_loop);
388 static GMainContext *default_main_context;
389 static GSList *main_contexts_without_pipe = NULL;
392 /* Child status monitoring code */
394 CHILD_WATCH_UNINITIALIZED,
395 CHILD_WATCH_INITIALIZED_SINGLE,
396 CHILD_WATCH_INITIALIZED_THREADED
398 static gint child_watch_init_state = CHILD_WATCH_UNINITIALIZED;
399 static gint child_watch_count = 1;
400 static gint child_watch_wake_up_pipe[2] = {0, 0};
401 #endif /* !G_OS_WIN32 */
402 G_LOCK_DEFINE_STATIC (main_context_list);
403 static GSList *main_context_list = NULL;
405 GSourceFuncs g_timeout_funcs =
413 GSourceFuncs g_child_watch_funcs =
415 g_child_watch_prepare,
417 g_child_watch_dispatch,
421 GSourceFuncs g_idle_funcs =
430 * g_main_context_ref:
431 * @context: a #GMainContext
433 * Increases the reference count on a #GMainContext object by one.
435 * Returns: the @context that was passed in (since 2.6)
438 g_main_context_ref (GMainContext *context)
440 g_return_val_if_fail (context != NULL, NULL);
441 g_return_val_if_fail (g_atomic_int_get (&context->ref_count) > 0, NULL);
443 g_atomic_int_inc (&context->ref_count);
449 poll_rec_list_free (GMainContext *context,
452 g_slice_free_chain (GPollRec, list, next);
456 * g_main_context_unref:
457 * @context: a #GMainContext
459 * Decreases the reference count on a #GMainContext object by one. If
460 * the result is zero, free the context and free all associated memory.
463 g_main_context_unref (GMainContext *context)
466 g_return_if_fail (context != NULL);
467 g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
469 if (!g_atomic_int_dec_and_test (&context->ref_count))
472 G_LOCK (main_context_list);
473 main_context_list = g_slist_remove (main_context_list, context);
474 G_UNLOCK (main_context_list);
476 source = context->source_list;
479 GSource *next = source->next;
480 g_source_destroy_internal (source, context, FALSE);
484 #ifdef G_THREADS_ENABLED
485 g_static_mutex_free (&context->mutex);
488 g_ptr_array_free (context->pending_dispatches, TRUE);
489 g_free (context->cached_poll_array);
491 poll_rec_list_free (context, context->poll_records);
493 #ifdef G_THREADS_ENABLED
494 if (g_thread_supported())
497 close (context->wake_up_pipe[0]);
498 close (context->wake_up_pipe[1]);
500 CloseHandle (context->wake_up_semaphore);
504 main_contexts_without_pipe = g_slist_remove (main_contexts_without_pipe,
507 if (context->cond != NULL)
508 g_cond_free (context->cond);
514 #ifdef G_THREADS_ENABLED
516 g_main_context_init_pipe (GMainContext *context)
519 if (context->wake_up_pipe[0] != -1)
523 /* if this fails, we fall through and try pipe */
524 pipe2 (context->wake_up_pipe, O_CLOEXEC);
526 if (context->wake_up_pipe[0] == -1)
528 if (pipe (context->wake_up_pipe) < 0)
529 g_error ("Cannot create pipe main loop wake-up: %s\n",
532 fcntl (context->wake_up_pipe[0], F_SETFD, FD_CLOEXEC);
533 fcntl (context->wake_up_pipe[1], F_SETFD, FD_CLOEXEC);
536 context->wake_up_rec.fd = context->wake_up_pipe[0];
537 context->wake_up_rec.events = G_IO_IN;
539 if (context->wake_up_semaphore != NULL)
541 context->wake_up_semaphore = CreateSemaphore (NULL, 0, 100, NULL);
542 if (context->wake_up_semaphore == NULL)
543 g_error ("Cannot create wake-up semaphore: %s",
544 g_win32_error_message (GetLastError ()));
545 context->wake_up_rec.fd = (gintptr) context->wake_up_semaphore;
546 context->wake_up_rec.events = G_IO_IN;
548 if (_g_main_poll_debug)
549 g_print ("wake-up semaphore: %p\n", context->wake_up_semaphore);
551 g_main_context_add_poll_unlocked (context, 0, &context->wake_up_rec);
555 _g_main_thread_init (void)
557 GSList *curr = main_contexts_without_pipe;
560 g_main_context_init_pipe ((GMainContext *)curr->data);
563 g_slist_free (main_contexts_without_pipe);
564 main_contexts_without_pipe = NULL;
566 #endif /* G_THREADS_ENABLED */
569 * g_main_context_new:
571 * Creates a new #GMainContext structure.
573 * Return value: the new #GMainContext
576 g_main_context_new (void)
578 GMainContext *context = g_new0 (GMainContext, 1);
580 #ifdef G_MAIN_POLL_DEBUG
582 static gboolean beenhere = FALSE;
586 if (getenv ("G_MAIN_POLL_DEBUG") != NULL)
587 _g_main_poll_debug = TRUE;
593 #ifdef G_THREADS_ENABLED
594 g_static_mutex_init (&context->mutex);
596 context->owner = NULL;
597 context->waiters = NULL;
600 context->wake_up_pipe[0] = -1;
601 context->wake_up_pipe[1] = -1;
603 context->wake_up_semaphore = NULL;
607 context->ref_count = 1;
609 context->next_id = 1;
611 context->source_list = NULL;
613 context->poll_func = g_poll;
615 context->cached_poll_array = NULL;
616 context->cached_poll_array_size = 0;
618 context->pending_dispatches = g_ptr_array_new ();
620 context->time_is_fresh = FALSE;
621 context->real_time_is_fresh = FALSE;
623 #ifdef G_THREADS_ENABLED
624 if (g_thread_supported ())
625 g_main_context_init_pipe (context);
627 main_contexts_without_pipe = g_slist_prepend (main_contexts_without_pipe,
631 G_LOCK (main_context_list);
632 main_context_list = g_slist_append (main_context_list, context);
634 #ifdef G_MAIN_POLL_DEBUG
635 if (_g_main_poll_debug)
636 g_print ("created context=%p\n", context);
639 G_UNLOCK (main_context_list);
645 * g_main_context_default:
647 * Returns the global default main context. This is the main context
648 * used for main loop functions when a main loop is not explicitly
649 * specified, and corresponds to the "main" main loop. See also
650 * g_main_context_get_thread_default().
652 * Return value: the global default main context.
655 g_main_context_default (void)
661 if (!default_main_context)
663 default_main_context = g_main_context_new ();
664 #ifdef G_MAIN_POLL_DEBUG
665 if (_g_main_poll_debug)
666 g_print ("default context=%p\n", default_main_context);
670 G_UNLOCK (main_loop);
672 return default_main_context;
675 static GStaticPrivate thread_context_stack = G_STATIC_PRIVATE_INIT;
678 free_context_stack (gpointer data)
680 GQueue *stack = data;
681 GMainContext *context;
683 while (!g_queue_is_empty (stack))
685 context = g_queue_pop_head (stack);
686 g_main_context_release (context);
688 g_main_context_unref (context);
690 g_queue_free (stack);
694 * g_main_context_push_thread_default:
695 * @context: a #GMainContext, or %NULL for the global default context
697 * Acquires @context and sets it as the thread-default context for the
698 * current thread. This will cause certain asynchronous operations
699 * (such as most <link linkend="gio">gio</link>-based I/O) which are
700 * started in this thread to run under @context and deliver their
701 * results to its main loop, rather than running under the global
702 * default context in the main thread. Note that calling this function
703 * changes the context returned by
704 * g_main_context_get_thread_default(), <emphasis>not</emphasis> the
705 * one returned by g_main_context_default(), so it does not affect the
706 * context used by functions like g_idle_add().
708 * Normally you would call this function shortly after creating a new
709 * thread, passing it a #GMainContext which will be run by a
710 * #GMainLoop in that thread, to set a new default context for all
711 * async operations in that thread. (In this case, you don't need to
712 * ever call g_main_context_pop_thread_default().) In some cases
713 * however, you may want to schedule a single operation in a
714 * non-default context, or temporarily use a non-default context in
715 * the main thread. In that case, you can wrap the call to the
716 * asynchronous operation inside a
717 * g_main_context_push_thread_default() /
718 * g_main_context_pop_thread_default() pair, but it is up to you to
719 * ensure that no other asynchronous operations accidentally get
720 * started while the non-default context is active.
722 * Beware that libraries that predate this function may not correctly
723 * handle being used from a thread with a thread-default context. Eg,
724 * see g_file_supports_thread_contexts().
729 g_main_context_push_thread_default (GMainContext *context)
732 gboolean acquired_context;
734 acquired_context = g_main_context_acquire (context);
735 g_return_if_fail (acquired_context);
737 if (context == g_main_context_default ())
740 g_main_context_ref (context);
742 stack = g_static_private_get (&thread_context_stack);
745 stack = g_queue_new ();
746 g_static_private_set (&thread_context_stack, stack,
750 g_queue_push_head (stack, context);
754 * g_main_context_pop_thread_default:
755 * @context: a #GMainContext object, or %NULL
757 * Pops @context off the thread-default context stack (verifying that
758 * it was on the top of the stack).
763 g_main_context_pop_thread_default (GMainContext *context)
767 if (context == g_main_context_default ())
770 stack = g_static_private_get (&thread_context_stack);
772 g_return_if_fail (stack != NULL);
773 g_return_if_fail (g_queue_peek_head (stack) == context);
775 g_queue_pop_head (stack);
777 g_main_context_release (context);
779 g_main_context_unref (context);
783 * g_main_context_get_thread_default:
785 * Gets the thread-default #GMainContext for this thread. Asynchronous
786 * operations that want to be able to be run in contexts other than
787 * the default one should call this method to get a #GMainContext to
788 * add their #GSource<!-- -->s to. (Note that even in single-threaded
789 * programs applications may sometimes want to temporarily push a
790 * non-default context, so it is not safe to assume that this will
791 * always return %NULL if threads are not initialized.)
793 * Returns: the thread-default #GMainContext, or %NULL if the
794 * thread-default context is the global default context.
799 g_main_context_get_thread_default (void)
803 stack = g_static_private_get (&thread_context_stack);
805 return g_queue_peek_head (stack);
810 /* Hooks for adding to the main loop */
814 * @source_funcs: structure containing functions that implement
815 * the sources behavior.
816 * @struct_size: size of the #GSource structure to create.
818 * Creates a new #GSource structure. The size is specified to
819 * allow creating structures derived from #GSource that contain
820 * additional data. The size passed in must be at least
821 * <literal>sizeof (GSource)</literal>.
823 * The source will not initially be associated with any #GMainContext
824 * and must be added to one with g_source_attach() before it will be
827 * Return value: the newly-created #GSource.
830 g_source_new (GSourceFuncs *source_funcs,
835 g_return_val_if_fail (source_funcs != NULL, NULL);
836 g_return_val_if_fail (struct_size >= sizeof (GSource), NULL);
838 source = (GSource*) g_malloc0 (struct_size);
840 source->source_funcs = source_funcs;
841 source->ref_count = 1;
843 source->priority = G_PRIORITY_DEFAULT;
845 source->flags = G_HOOK_FLAG_ACTIVE;
847 /* NULL/0 initialization for all other fields */
852 /* Holds context's lock
855 g_source_list_add (GSource *source,
856 GMainContext *context)
858 GSource *tmp_source, *last_source;
860 if (source->priv && source->priv->parent_source)
862 /* Put the source immediately before its parent */
863 tmp_source = source->priv->parent_source;
864 last_source = source->priv->parent_source->prev;
869 tmp_source = context->source_list;
870 while (tmp_source && tmp_source->priority <= source->priority)
872 last_source = tmp_source;
873 tmp_source = tmp_source->next;
877 source->next = tmp_source;
879 tmp_source->prev = source;
881 source->prev = last_source;
883 last_source->next = source;
885 context->source_list = source;
888 /* Holds context's lock
891 g_source_list_remove (GSource *source,
892 GMainContext *context)
895 source->prev->next = source->next;
897 context->source_list = source->next;
900 source->next->prev = source->prev;
907 g_source_attach_unlocked (GSource *source,
908 GMainContext *context)
913 source->context = context;
914 result = source->source_id = context->next_id++;
917 g_source_list_add (source, context);
919 tmp_list = source->poll_fds;
922 g_main_context_add_poll_unlocked (context, source->priority, tmp_list->data);
923 tmp_list = tmp_list->next;
928 tmp_list = source->priv->child_sources;
931 g_source_attach_unlocked (tmp_list->data, context);
932 tmp_list = tmp_list->next;
941 * @source: a #GSource
942 * @context: a #GMainContext (if %NULL, the default context will be used)
944 * Adds a #GSource to a @context so that it will be executed within
945 * that context. Remove it by calling g_source_destroy().
947 * Return value: the ID (greater than 0) for the source within the
951 g_source_attach (GSource *source,
952 GMainContext *context)
956 g_return_val_if_fail (source->context == NULL, 0);
957 g_return_val_if_fail (!SOURCE_DESTROYED (source), 0);
960 context = g_main_context_default ();
962 LOCK_CONTEXT (context);
964 result = g_source_attach_unlocked (source, context);
966 #ifdef G_THREADS_ENABLED
967 /* Now wake up the main loop if it is waiting in the poll() */
968 g_main_context_wakeup_unlocked (context);
971 UNLOCK_CONTEXT (context);
977 g_source_destroy_internal (GSource *source,
978 GMainContext *context,
982 LOCK_CONTEXT (context);
984 if (!SOURCE_DESTROYED (source))
987 gpointer old_cb_data;
988 GSourceCallbackFuncs *old_cb_funcs;
990 source->flags &= ~G_HOOK_FLAG_ACTIVE;
992 old_cb_data = source->callback_data;
993 old_cb_funcs = source->callback_funcs;
995 source->callback_data = NULL;
996 source->callback_funcs = NULL;
1000 UNLOCK_CONTEXT (context);
1001 old_cb_funcs->unref (old_cb_data);
1002 LOCK_CONTEXT (context);
1005 if (!SOURCE_BLOCKED (source))
1007 tmp_list = source->poll_fds;
1010 g_main_context_remove_poll_unlocked (context, tmp_list->data);
1011 tmp_list = tmp_list->next;
1015 if (source->priv && source->priv->child_sources)
1017 /* This is safe because even if a child_source finalizer or
1018 * closure notify tried to modify source->priv->child_sources
1019 * from outside the lock, it would fail since
1020 * SOURCE_DESTROYED(source) is now TRUE.
1022 tmp_list = source->priv->child_sources;
1025 g_source_destroy_internal (tmp_list->data, context, TRUE);
1026 g_source_unref_internal (tmp_list->data, context, TRUE);
1027 tmp_list = tmp_list->next;
1029 g_slist_free (source->priv->child_sources);
1030 source->priv->child_sources = NULL;
1033 g_source_unref_internal (source, context, TRUE);
1037 UNLOCK_CONTEXT (context);
1042 * @source: a #GSource
1044 * Removes a source from its #GMainContext, if any, and mark it as
1045 * destroyed. The source cannot be subsequently added to another
1049 g_source_destroy (GSource *source)
1051 GMainContext *context;
1053 g_return_if_fail (source != NULL);
1055 context = source->context;
1058 g_source_destroy_internal (source, context, FALSE);
1060 source->flags &= ~G_HOOK_FLAG_ACTIVE;
1065 * @source: a #GSource
1067 * Returns the numeric ID for a particular source. The ID of a source
1068 * is a positive integer which is unique within a particular main loop
1069 * context. The reverse
1070 * mapping from ID to source is done by g_main_context_find_source_by_id().
1072 * Return value: the ID (greater than 0) for the source
1075 g_source_get_id (GSource *source)
1079 g_return_val_if_fail (source != NULL, 0);
1080 g_return_val_if_fail (source->context != NULL, 0);
1082 LOCK_CONTEXT (source->context);
1083 result = source->source_id;
1084 UNLOCK_CONTEXT (source->context);
1090 * g_source_get_context:
1091 * @source: a #GSource
1093 * Gets the #GMainContext with which the source is associated.
1094 * Calling this function on a destroyed source is an error.
1096 * Return value: the #GMainContext with which the source is associated,
1097 * or %NULL if the context has not yet been added
1101 g_source_get_context (GSource *source)
1103 g_return_val_if_fail (!SOURCE_DESTROYED (source), NULL);
1105 return source->context;
1109 * g_source_add_poll:
1110 * @source:a #GSource
1111 * @fd: a #GPollFD structure holding information about a file
1112 * descriptor to watch.
1114 * Adds a file descriptor to the set of file descriptors polled for
1115 * this source. This is usually combined with g_source_new() to add an
1116 * event source. The event source's check function will typically test
1117 * the @revents field in the #GPollFD struct and return %TRUE if events need
1121 g_source_add_poll (GSource *source,
1124 GMainContext *context;
1126 g_return_if_fail (source != NULL);
1127 g_return_if_fail (fd != NULL);
1128 g_return_if_fail (!SOURCE_DESTROYED (source));
1130 context = source->context;
1133 LOCK_CONTEXT (context);
1135 source->poll_fds = g_slist_prepend (source->poll_fds, fd);
1139 if (!SOURCE_BLOCKED (source))
1140 g_main_context_add_poll_unlocked (context, source->priority, fd);
1141 UNLOCK_CONTEXT (context);
1146 * g_source_remove_poll:
1147 * @source:a #GSource
1148 * @fd: a #GPollFD structure previously passed to g_source_add_poll().
1150 * Removes a file descriptor from the set of file descriptors polled for
1154 g_source_remove_poll (GSource *source,
1157 GMainContext *context;
1159 g_return_if_fail (source != NULL);
1160 g_return_if_fail (fd != NULL);
1161 g_return_if_fail (!SOURCE_DESTROYED (source));
1163 context = source->context;
1166 LOCK_CONTEXT (context);
1168 source->poll_fds = g_slist_remove (source->poll_fds, fd);
1172 if (!SOURCE_BLOCKED (source))
1173 g_main_context_remove_poll_unlocked (context, fd);
1174 UNLOCK_CONTEXT (context);
1179 * g_source_add_child_source:
1180 * @source:a #GSource
1181 * @child_source: a second #GSource that @source should "poll"
1183 * Adds @child_source to @source as a "polled" source; when @source is
1184 * added to a #GMainContext, @child_source will be automatically added
1185 * with the same priority, when @child_source is triggered, it will
1186 * cause @source to dispatch (in addition to calling its own
1187 * callback), and when @source is destroyed, it will destroy
1188 * @child_source as well. (@source will also still be dispatched if
1189 * its own prepare/check functions indicate that it is ready.)
1191 * If you don't need @child_source to do anything on its own when it
1192 * triggers, you can call g_source_set_dummy_callback() on it to set a
1193 * callback that does nothing (except return %TRUE if appropriate).
1195 * @source will hold a reference on @child_source while @child_source
1196 * is attached to it.
1201 g_source_add_child_source (GSource *source,
1202 GSource *child_source)
1204 GMainContext *context;
1206 g_return_if_fail (source != NULL);
1207 g_return_if_fail (child_source != NULL);
1208 g_return_if_fail (!SOURCE_DESTROYED (source));
1209 g_return_if_fail (!SOURCE_DESTROYED (child_source));
1210 g_return_if_fail (child_source->context == NULL);
1211 g_return_if_fail (child_source->priv == NULL || child_source->priv->parent_source == NULL);
1213 context = source->context;
1216 LOCK_CONTEXT (context);
1219 source->priv = g_slice_new0 (GSourcePrivate);
1220 if (!child_source->priv)
1221 child_source->priv = g_slice_new0 (GSourcePrivate);
1223 source->priv->child_sources = g_slist_prepend (source->priv->child_sources,
1224 g_source_ref (child_source));
1225 child_source->priv->parent_source = source;
1226 g_source_set_priority_unlocked (child_source, context, source->priority);
1230 UNLOCK_CONTEXT (context);
1231 g_source_attach (child_source, context);
1236 * g_source_remove_child_source:
1237 * @source:a #GSource
1238 * @child_source: a #GSource previously passed to
1239 * g_source_add_child_source().
1241 * Detaches @child_source from @source and destroys it.
1246 g_source_remove_child_source (GSource *source,
1247 GSource *child_source)
1249 GMainContext *context;
1251 g_return_if_fail (source != NULL);
1252 g_return_if_fail (child_source != NULL);
1253 g_return_if_fail (child_source->priv != NULL && child_source->priv->parent_source == source);
1254 g_return_if_fail (!SOURCE_DESTROYED (source));
1255 g_return_if_fail (!SOURCE_DESTROYED (child_source));
1257 context = source->context;
1260 LOCK_CONTEXT (context);
1262 source->priv->child_sources = g_slist_remove (source->priv->child_sources, child_source);
1263 g_source_destroy_internal (child_source, context, TRUE);
1264 g_source_unref_internal (child_source, context, TRUE);
1267 UNLOCK_CONTEXT (context);
1271 * g_source_set_callback_indirect:
1272 * @source: the source
1273 * @callback_data: pointer to callback data "object"
1274 * @callback_funcs: functions for reference counting @callback_data
1275 * and getting the callback and data
1277 * Sets the callback function storing the data as a refcounted callback
1278 * "object". This is used internally. Note that calling
1279 * g_source_set_callback_indirect() assumes
1280 * an initial reference count on @callback_data, and thus
1281 * @callback_funcs->unref will eventually be called once more
1282 * than @callback_funcs->ref.
1285 g_source_set_callback_indirect (GSource *source,
1286 gpointer callback_data,
1287 GSourceCallbackFuncs *callback_funcs)
1289 GMainContext *context;
1290 gpointer old_cb_data;
1291 GSourceCallbackFuncs *old_cb_funcs;
1293 g_return_if_fail (source != NULL);
1294 g_return_if_fail (callback_funcs != NULL || callback_data == NULL);
1296 context = source->context;
1299 LOCK_CONTEXT (context);
1301 old_cb_data = source->callback_data;
1302 old_cb_funcs = source->callback_funcs;
1304 source->callback_data = callback_data;
1305 source->callback_funcs = callback_funcs;
1308 UNLOCK_CONTEXT (context);
1311 old_cb_funcs->unref (old_cb_data);
1315 g_source_callback_ref (gpointer cb_data)
1317 GSourceCallback *callback = cb_data;
1319 callback->ref_count++;
1324 g_source_callback_unref (gpointer cb_data)
1326 GSourceCallback *callback = cb_data;
1328 callback->ref_count--;
1329 if (callback->ref_count == 0)
1331 if (callback->notify)
1332 callback->notify (callback->data);
1338 g_source_callback_get (gpointer cb_data,
1343 GSourceCallback *callback = cb_data;
1345 *func = callback->func;
1346 *data = callback->data;
1349 static GSourceCallbackFuncs g_source_callback_funcs = {
1350 g_source_callback_ref,
1351 g_source_callback_unref,
1352 g_source_callback_get,
1356 * g_source_set_callback:
1357 * @source: the source
1358 * @func: a callback function
1359 * @data: the data to pass to callback function
1360 * @notify: a function to call when @data is no longer in use, or %NULL.
1362 * Sets the callback function for a source. The callback for a source is
1363 * called from the source's dispatch function.
1365 * The exact type of @func depends on the type of source; ie. you
1366 * should not count on @func being called with @data as its first
1369 * Typically, you won't use this function. Instead use functions specific
1370 * to the type of source you are using.
1373 g_source_set_callback (GSource *source,
1376 GDestroyNotify notify)
1378 GSourceCallback *new_callback;
1380 g_return_if_fail (source != NULL);
1382 new_callback = g_new (GSourceCallback, 1);
1384 new_callback->ref_count = 1;
1385 new_callback->func = func;
1386 new_callback->data = data;
1387 new_callback->notify = notify;
1389 g_source_set_callback_indirect (source, new_callback, &g_source_callback_funcs);
1394 * g_source_set_funcs:
1395 * @source: a #GSource
1396 * @funcs: the new #GSourceFuncs
1398 * Sets the source functions (can be used to override
1399 * default implementations) of an unattached source.
1404 g_source_set_funcs (GSource *source,
1405 GSourceFuncs *funcs)
1407 g_return_if_fail (source != NULL);
1408 g_return_if_fail (source->context == NULL);
1409 g_return_if_fail (source->ref_count > 0);
1410 g_return_if_fail (funcs != NULL);
1412 source->source_funcs = funcs;
1416 g_source_set_priority_unlocked (GSource *source,
1417 GMainContext *context,
1422 source->priority = priority;
1426 /* Remove the source from the context's source and then
1427 * add it back so it is sorted in the correct place
1429 g_source_list_remove (source, source->context);
1430 g_source_list_add (source, source->context);
1432 if (!SOURCE_BLOCKED (source))
1434 tmp_list = source->poll_fds;
1437 g_main_context_remove_poll_unlocked (context, tmp_list->data);
1438 g_main_context_add_poll_unlocked (context, priority, tmp_list->data);
1440 tmp_list = tmp_list->next;
1445 if (source->priv && source->priv->child_sources)
1447 tmp_list = source->priv->child_sources;
1450 g_source_set_priority_unlocked (tmp_list->data, context, priority);
1451 tmp_list = tmp_list->next;
1457 * g_source_set_priority:
1458 * @source: a #GSource
1459 * @priority: the new priority.
1461 * Sets the priority of a source. While the main loop is being run, a
1462 * source will be dispatched if it is ready to be dispatched and no
1463 * sources at a higher (numerically smaller) priority are ready to be
1467 g_source_set_priority (GSource *source,
1470 GMainContext *context;
1472 g_return_if_fail (source != NULL);
1474 context = source->context;
1477 LOCK_CONTEXT (context);
1478 g_source_set_priority_unlocked (source, context, priority);
1480 UNLOCK_CONTEXT (source->context);
1484 * g_source_get_priority:
1485 * @source: a #GSource
1487 * Gets the priority of a source.
1489 * Return value: the priority of the source
1492 g_source_get_priority (GSource *source)
1494 g_return_val_if_fail (source != NULL, 0);
1496 return source->priority;
1500 * g_source_set_can_recurse:
1501 * @source: a #GSource
1502 * @can_recurse: whether recursion is allowed for this source
1504 * Sets whether a source can be called recursively. If @can_recurse is
1505 * %TRUE, then while the source is being dispatched then this source
1506 * will be processed normally. Otherwise, all processing of this
1507 * source is blocked until the dispatch function returns.
1510 g_source_set_can_recurse (GSource *source,
1511 gboolean can_recurse)
1513 GMainContext *context;
1515 g_return_if_fail (source != NULL);
1517 context = source->context;
1520 LOCK_CONTEXT (context);
1523 source->flags |= G_SOURCE_CAN_RECURSE;
1525 source->flags &= ~G_SOURCE_CAN_RECURSE;
1528 UNLOCK_CONTEXT (context);
1532 * g_source_get_can_recurse:
1533 * @source: a #GSource
1535 * Checks whether a source is allowed to be called recursively.
1536 * see g_source_set_can_recurse().
1538 * Return value: whether recursion is allowed.
1541 g_source_get_can_recurse (GSource *source)
1543 g_return_val_if_fail (source != NULL, FALSE);
1545 return (source->flags & G_SOURCE_CAN_RECURSE) != 0;
1550 * g_source_set_name:
1551 * @source: a #GSource
1552 * @name: debug name for the source
1554 * Sets a name for the source, used in debugging and profiling.
1555 * The name defaults to #NULL.
1557 * The source name should describe in a human-readable way
1558 * what the source does. For example, "X11 event queue"
1559 * or "GTK+ repaint idle handler" or whatever it is.
1561 * It is permitted to call this function multiple times, but is not
1562 * recommended due to the potential performance impact. For example,
1563 * one could change the name in the "check" function of a #GSourceFuncs
1564 * to include details like the event type in the source name.
1569 g_source_set_name (GSource *source,
1572 g_return_if_fail (source != NULL);
1574 /* setting back to NULL is allowed, just because it's
1575 * weird if get_name can return NULL but you can't
1579 g_free (source->name);
1580 source->name = g_strdup (name);
1584 * g_source_get_name:
1585 * @source: a #GSource
1587 * Gets a name for the source, used in debugging and profiling.
1588 * The name may be #NULL if it has never been set with
1589 * g_source_set_name().
1591 * Return value: the name of the source
1595 g_source_get_name (GSource *source)
1597 g_return_val_if_fail (source != NULL, NULL);
1599 return source->name;
1603 * g_source_set_name_by_id:
1604 * @tag: a #GSource ID
1605 * @name: debug name for the source
1607 * Sets the name of a source using its ID.
1609 * This is a convenience utility to set source names from the return
1610 * value of g_idle_add(), g_timeout_add(), etc.
1615 g_source_set_name_by_id (guint tag,
1620 g_return_if_fail (tag > 0);
1622 source = g_main_context_find_source_by_id (NULL, tag);
1626 g_source_set_name (source, name);
1632 * @source: a #GSource
1634 * Increases the reference count on a source by one.
1636 * Return value: @source
1639 g_source_ref (GSource *source)
1641 GMainContext *context;
1643 g_return_val_if_fail (source != NULL, NULL);
1645 context = source->context;
1648 LOCK_CONTEXT (context);
1650 source->ref_count++;
1653 UNLOCK_CONTEXT (context);
1658 /* g_source_unref() but possible to call within context lock
1661 g_source_unref_internal (GSource *source,
1662 GMainContext *context,
1665 gpointer old_cb_data = NULL;
1666 GSourceCallbackFuncs *old_cb_funcs = NULL;
1668 g_return_if_fail (source != NULL);
1670 if (!have_lock && context)
1671 LOCK_CONTEXT (context);
1673 source->ref_count--;
1674 if (source->ref_count == 0)
1676 old_cb_data = source->callback_data;
1677 old_cb_funcs = source->callback_funcs;
1679 source->callback_data = NULL;
1680 source->callback_funcs = NULL;
1684 if (!SOURCE_DESTROYED (source))
1685 g_warning (G_STRLOC ": ref_count == 0, but source was still attached to a context!");
1686 g_source_list_remove (source, context);
1689 if (source->source_funcs->finalize)
1692 UNLOCK_CONTEXT (context);
1693 source->source_funcs->finalize (source);
1695 LOCK_CONTEXT (context);
1698 g_free (source->name);
1699 source->name = NULL;
1701 g_slist_free (source->poll_fds);
1702 source->poll_fds = NULL;
1706 if (!have_lock && context)
1707 UNLOCK_CONTEXT (context);
1712 UNLOCK_CONTEXT (context);
1714 old_cb_funcs->unref (old_cb_data);
1717 LOCK_CONTEXT (context);
1723 * @source: a #GSource
1725 * Decreases the reference count of a source by one. If the
1726 * resulting reference count is zero the source and associated
1727 * memory will be destroyed.
1730 g_source_unref (GSource *source)
1732 g_return_if_fail (source != NULL);
1734 g_source_unref_internal (source, source->context, FALSE);
1738 * g_main_context_find_source_by_id:
1739 * @context: a #GMainContext (if %NULL, the default context will be used)
1740 * @source_id: the source ID, as returned by g_source_get_id().
1742 * Finds a #GSource given a pair of context and ID.
1744 * Return value: the #GSource if found, otherwise, %NULL
1747 g_main_context_find_source_by_id (GMainContext *context,
1752 g_return_val_if_fail (source_id > 0, NULL);
1754 if (context == NULL)
1755 context = g_main_context_default ();
1757 LOCK_CONTEXT (context);
1759 source = context->source_list;
1762 if (!SOURCE_DESTROYED (source) &&
1763 source->source_id == source_id)
1765 source = source->next;
1768 UNLOCK_CONTEXT (context);
1774 * g_main_context_find_source_by_funcs_user_data:
1775 * @context: a #GMainContext (if %NULL, the default context will be used).
1776 * @funcs: the @source_funcs passed to g_source_new().
1777 * @user_data: the user data from the callback.
1779 * Finds a source with the given source functions and user data. If
1780 * multiple sources exist with the same source function and user data,
1781 * the first one found will be returned.
1783 * Return value: the source, if one was found, otherwise %NULL
1786 g_main_context_find_source_by_funcs_user_data (GMainContext *context,
1787 GSourceFuncs *funcs,
1792 g_return_val_if_fail (funcs != NULL, NULL);
1794 if (context == NULL)
1795 context = g_main_context_default ();
1797 LOCK_CONTEXT (context);
1799 source = context->source_list;
1802 if (!SOURCE_DESTROYED (source) &&
1803 source->source_funcs == funcs &&
1804 source->callback_funcs)
1806 GSourceFunc callback;
1807 gpointer callback_data;
1809 source->callback_funcs->get (source->callback_data, source, &callback, &callback_data);
1811 if (callback_data == user_data)
1814 source = source->next;
1817 UNLOCK_CONTEXT (context);
1823 * g_main_context_find_source_by_user_data:
1824 * @context: a #GMainContext
1825 * @user_data: the user_data for the callback.
1827 * Finds a source with the given user data for the callback. If
1828 * multiple sources exist with the same user data, the first
1829 * one found will be returned.
1831 * Return value: the source, if one was found, otherwise %NULL
1834 g_main_context_find_source_by_user_data (GMainContext *context,
1839 if (context == NULL)
1840 context = g_main_context_default ();
1842 LOCK_CONTEXT (context);
1844 source = context->source_list;
1847 if (!SOURCE_DESTROYED (source) &&
1848 source->callback_funcs)
1850 GSourceFunc callback;
1851 gpointer callback_data = NULL;
1853 source->callback_funcs->get (source->callback_data, source, &callback, &callback_data);
1855 if (callback_data == user_data)
1858 source = source->next;
1861 UNLOCK_CONTEXT (context);
1868 * @tag: the ID of the source to remove.
1870 * Removes the source with the given id from the default main context.
1872 * a #GSource is given by g_source_get_id(), or will be returned by the
1873 * functions g_source_attach(), g_idle_add(), g_idle_add_full(),
1874 * g_timeout_add(), g_timeout_add_full(), g_child_watch_add(),
1875 * g_child_watch_add_full(), g_io_add_watch(), and g_io_add_watch_full().
1877 * See also g_source_destroy(). You must use g_source_destroy() for sources
1878 * added to a non-default main context.
1880 * Return value: %TRUE if the source was found and removed.
1883 g_source_remove (guint tag)
1887 g_return_val_if_fail (tag > 0, FALSE);
1889 source = g_main_context_find_source_by_id (NULL, tag);
1891 g_source_destroy (source);
1893 return source != NULL;
1897 * g_source_remove_by_user_data:
1898 * @user_data: the user_data for the callback.
1900 * Removes a source from the default main loop context given the user
1901 * data for the callback. If multiple sources exist with the same user
1902 * data, only one will be destroyed.
1904 * Return value: %TRUE if a source was found and removed.
1907 g_source_remove_by_user_data (gpointer user_data)
1911 source = g_main_context_find_source_by_user_data (NULL, user_data);
1914 g_source_destroy (source);
1922 * g_source_remove_by_funcs_user_data:
1923 * @funcs: The @source_funcs passed to g_source_new()
1924 * @user_data: the user data for the callback
1926 * Removes a source from the default main loop context given the
1927 * source functions and user data. If multiple sources exist with the
1928 * same source functions and user data, only one will be destroyed.
1930 * Return value: %TRUE if a source was found and removed.
1933 g_source_remove_by_funcs_user_data (GSourceFuncs *funcs,
1938 g_return_val_if_fail (funcs != NULL, FALSE);
1940 source = g_main_context_find_source_by_funcs_user_data (NULL, funcs, user_data);
1943 g_source_destroy (source);
1951 * g_get_current_time:
1952 * @result: #GTimeVal structure in which to store current time.
1954 * Equivalent to the UNIX gettimeofday() function, but portable.
1956 * You may find g_get_real_time() to be more convenient.
1959 g_get_current_time (GTimeVal *result)
1964 g_return_if_fail (result != NULL);
1966 /*this is required on alpha, there the timeval structs are int's
1967 not longs and a cast only would fail horribly*/
1968 gettimeofday (&r, NULL);
1969 result->tv_sec = r.tv_sec;
1970 result->tv_usec = r.tv_usec;
1975 g_return_if_fail (result != NULL);
1977 GetSystemTimeAsFileTime (&ft);
1978 memmove (&time64, &ft, sizeof (FILETIME));
1980 /* Convert from 100s of nanoseconds since 1601-01-01
1981 * to Unix epoch. Yes, this is Y2038 unsafe.
1983 time64 -= G_GINT64_CONSTANT (116444736000000000);
1986 result->tv_sec = time64 / 1000000;
1987 result->tv_usec = time64 % 1000000;
1994 * Queries the system wall-clock time.
1996 * This call is functionally equivalent to g_get_current_time() except
1997 * that the return value is often more convenient than dealing with a
2000 * You should only use this call if you are actually interested in the real
2001 * wall-clock time. g_get_monotonic_time() is probably more useful for
2002 * measuring intervals.
2004 * Returns: the number of microseconds since January 1, 1970 UTC.
2009 g_get_real_time (void)
2013 g_get_current_time (&tv);
2015 return (((gint64) tv.tv_sec) * 1000000) + tv.tv_usec;
2019 * g_get_monotonic_time:
2021 * Queries the system monotonic time, if available.
2023 * On POSIX systems with clock_gettime() and %CLOCK_MONOTONIC this call
2024 * is a very shallow wrapper for that. Otherwise, we make a best effort
2025 * that probably involves returning the wall clock time (with at least
2026 * microsecond accuracy, subject to the limitations of the OS kernel).
2028 * Note that, on Windows, "limitations of the OS kernel" is a rather
2029 * substantial statement. Depending on the configuration of the system,
2030 * the wall clock time is updated as infrequently as 64 times a second
2031 * (which is approximately every 16ms).
2033 * Returns: the monotonic time, in microseconds
2038 g_get_monotonic_time (void)
2040 #ifdef HAVE_CLOCK_GETTIME
2041 /* librt clock_gettime() is our first choice */
2043 static int clockid = CLOCK_REALTIME;
2046 #ifdef HAVE_MONOTONIC_CLOCK
2047 /* We have to check if we actually have monotonic clock support.
2049 * There is no thread safety issue here since there is no harm if we
2053 static gboolean checked;
2055 if G_UNLIKELY (!checked)
2057 if (sysconf (_SC_MONOTONIC_CLOCK) >= 0)
2058 clockid = CLOCK_MONOTONIC;
2064 clock_gettime (clockid, &ts);
2066 /* In theory monotonic time can have any epoch.
2068 * glib presently assumes the following:
2070 * 1) The epoch comes some time after the birth of Jesus of Nazareth, but
2071 * not more than 10000 years later.
2073 * 2) The current time also falls sometime within this range.
2075 * These two reasonable assumptions leave us with a maximum deviation from
2076 * the epoch of 10000 years, or 315569520000000000 seconds.
2078 * If we restrict ourselves to this range then the number of microseconds
2079 * will always fit well inside the constraints of a int64 (by a factor of
2082 * If you actually hit the following assertion, probably you should file a
2083 * bug against your operating system for being excessively silly.
2085 g_assert (G_GINT64_CONSTANT (-315569520000000000) < ts.tv_sec &&
2086 ts.tv_sec < G_GINT64_CONSTANT (315569520000000000));
2088 return (((gint64) ts.tv_sec) * 1000000) + (ts.tv_nsec / 1000);
2091 /* It may look like we are discarding accuracy on Windows (since its
2092 * current time is expressed in 100s of nanoseconds) but according to
2093 * many sources, the time is only updated 64 times per second, so
2094 * microsecond accuracy is more than enough.
2099 g_get_current_time (&tv);
2101 return (((gint64) tv.tv_sec) * 1000000) + tv.tv_usec;
2107 g_main_dispatch_free (gpointer dispatch)
2109 g_slice_free (GMainDispatch, dispatch);
2112 /* Running the main loop */
2114 static GMainDispatch *
2117 static GStaticPrivate depth_private = G_STATIC_PRIVATE_INIT;
2118 GMainDispatch *dispatch = g_static_private_get (&depth_private);
2121 dispatch = g_slice_new0 (GMainDispatch);
2122 g_static_private_set (&depth_private, dispatch, g_main_dispatch_free);
2131 * Returns the depth of the stack of calls to
2132 * g_main_context_dispatch() on any #GMainContext in the current thread.
2133 * That is, when called from the toplevel, it gives 0. When
2134 * called from within a callback from g_main_context_iteration()
2135 * (or g_main_loop_run(), etc.) it returns 1. When called from within
2136 * a callback to a recursive call to g_main_context_iterate(),
2137 * it returns 2. And so forth.
2139 * This function is useful in a situation like the following:
2140 * Imagine an extremely simple "garbage collected" system.
2143 * static GList *free_list;
2146 * allocate_memory (gsize size)
2148 * gpointer result = g_malloc (size);
2149 * free_list = g_list_prepend (free_list, result);
2154 * free_allocated_memory (void)
2157 * for (l = free_list; l; l = l->next);
2159 * g_list_free (free_list);
2167 * g_main_context_iteration (NULL, TRUE);
2168 * free_allocated_memory();
2172 * This works from an application, however, if you want to do the same
2173 * thing from a library, it gets more difficult, since you no longer
2174 * control the main loop. You might think you can simply use an idle
2175 * function to make the call to free_allocated_memory(), but that
2176 * doesn't work, since the idle function could be called from a
2177 * recursive callback. This can be fixed by using g_main_depth()
2181 * allocate_memory (gsize size)
2183 * FreeListBlock *block = g_new (FreeListBlock, 1);
2184 * block->mem = g_malloc (size);
2185 * block->depth = g_main_depth ();
2186 * free_list = g_list_prepend (free_list, block);
2187 * return block->mem;
2191 * free_allocated_memory (void)
2195 * int depth = g_main_depth ();
2196 * for (l = free_list; l; );
2198 * GList *next = l->next;
2199 * FreeListBlock *block = l->data;
2200 * if (block->depth > depth)
2202 * g_free (block->mem);
2204 * free_list = g_list_delete_link (free_list, l);
2212 * There is a temptation to use g_main_depth() to solve
2213 * problems with reentrancy. For instance, while waiting for data
2214 * to be received from the network in response to a menu item,
2215 * the menu item might be selected again. It might seem that
2216 * one could make the menu item's callback return immediately
2217 * and do nothing if g_main_depth() returns a value greater than 1.
2218 * However, this should be avoided since the user then sees selecting
2219 * the menu item do nothing. Furthermore, you'll find yourself adding
2220 * these checks all over your code, since there are doubtless many,
2221 * many things that the user could do. Instead, you can use the
2222 * following techniques:
2227 * Use gtk_widget_set_sensitive() or modal dialogs to prevent
2228 * the user from interacting with elements while the main
2229 * loop is recursing.
2234 * Avoid main loop recursion in situations where you can't handle
2235 * arbitrary callbacks. Instead, structure your code so that you
2236 * simply return to the main loop and then get called again when
2237 * there is more work to do.
2242 * Return value: The main loop recursion level in the current thread
2247 GMainDispatch *dispatch = get_dispatch ();
2248 return dispatch->depth;
2252 * g_main_current_source:
2254 * Returns the currently firing source for this thread.
2256 * Return value: The currently firing source or %NULL.
2261 g_main_current_source (void)
2263 GMainDispatch *dispatch = get_dispatch ();
2264 return dispatch->dispatching_sources ? dispatch->dispatching_sources->data : NULL;
2268 * g_source_is_destroyed:
2269 * @source: a #GSource
2271 * Returns whether @source has been destroyed.
2273 * This is important when you operate upon your objects
2274 * from within idle handlers, but may have freed the object
2275 * before the dispatch of your idle handler.
2279 * idle_callback (gpointer data)
2281 * SomeWidget *self = data;
2283 * GDK_THREADS_ENTER (<!-- -->);
2284 * /<!-- -->* do stuff with self *<!-- -->/
2285 * self->idle_id = 0;
2286 * GDK_THREADS_LEAVE (<!-- -->);
2292 * some_widget_do_stuff_later (SomeWidget *self)
2294 * self->idle_id = g_idle_add (idle_callback, self);
2298 * some_widget_finalize (GObject *object)
2300 * SomeWidget *self = SOME_WIDGET (object);
2302 * if (self->idle_id)
2303 * g_source_remove (self->idle_id);
2305 * G_OBJECT_CLASS (parent_class)->finalize (object);
2309 * This will fail in a multi-threaded application if the
2310 * widget is destroyed before the idle handler fires due
2311 * to the use after free in the callback. A solution, to
2312 * this particular problem, is to check to if the source
2313 * has already been destroy within the callback.
2317 * idle_callback (gpointer data)
2319 * SomeWidget *self = data;
2321 * GDK_THREADS_ENTER ();
2322 * if (!g_source_is_destroyed (g_main_current_source ()))
2324 * /<!-- -->* do stuff with self *<!-- -->/
2326 * GDK_THREADS_LEAVE ();
2332 * Return value: %TRUE if the source has been destroyed
2337 g_source_is_destroyed (GSource *source)
2339 return SOURCE_DESTROYED (source);
2342 /* Temporarily remove all this source's file descriptors from the
2343 * poll(), so that if data comes available for one of the file descriptors
2344 * we don't continually spin in the poll()
2346 /* HOLDS: source->context's lock */
2348 block_source (GSource *source)
2352 g_return_if_fail (!SOURCE_BLOCKED (source));
2354 tmp_list = source->poll_fds;
2357 g_main_context_remove_poll_unlocked (source->context, tmp_list->data);
2358 tmp_list = tmp_list->next;
2362 /* HOLDS: source->context's lock */
2364 unblock_source (GSource *source)
2368 g_return_if_fail (!SOURCE_BLOCKED (source)); /* Source already unblocked */
2369 g_return_if_fail (!SOURCE_DESTROYED (source));
2371 tmp_list = source->poll_fds;
2374 g_main_context_add_poll_unlocked (source->context, source->priority, tmp_list->data);
2375 tmp_list = tmp_list->next;
2379 /* HOLDS: context's lock */
2381 g_main_dispatch (GMainContext *context)
2383 GMainDispatch *current = get_dispatch ();
2386 for (i = 0; i < context->pending_dispatches->len; i++)
2388 GSource *source = context->pending_dispatches->pdata[i];
2390 context->pending_dispatches->pdata[i] = NULL;
2393 source->flags &= ~G_SOURCE_READY;
2395 if (!SOURCE_DESTROYED (source))
2397 gboolean was_in_call;
2398 gpointer user_data = NULL;
2399 GSourceFunc callback = NULL;
2400 GSourceCallbackFuncs *cb_funcs;
2402 gboolean need_destroy;
2404 gboolean (*dispatch) (GSource *,
2407 GSList current_source_link;
2409 dispatch = source->source_funcs->dispatch;
2410 cb_funcs = source->callback_funcs;
2411 cb_data = source->callback_data;
2414 cb_funcs->ref (cb_data);
2416 if ((source->flags & G_SOURCE_CAN_RECURSE) == 0)
2417 block_source (source);
2419 was_in_call = source->flags & G_HOOK_FLAG_IN_CALL;
2420 source->flags |= G_HOOK_FLAG_IN_CALL;
2423 cb_funcs->get (cb_data, source, &callback, &user_data);
2425 UNLOCK_CONTEXT (context);
2428 /* The on-stack allocation of the GSList is unconventional, but
2429 * we know that the lifetime of the link is bounded to this
2430 * function as the link is kept in a thread specific list and
2431 * not manipulated outside of this function and its descendants.
2432 * Avoiding the overhead of a g_slist_alloc() is useful as many
2433 * applications do little more than dispatch events.
2435 * This is a performance hack - do not revert to g_slist_prepend()!
2437 current_source_link.data = source;
2438 current_source_link.next = current->dispatching_sources;
2439 current->dispatching_sources = ¤t_source_link;
2440 need_destroy = ! dispatch (source,
2443 g_assert (current->dispatching_sources == ¤t_source_link);
2444 current->dispatching_sources = current_source_link.next;
2448 cb_funcs->unref (cb_data);
2450 LOCK_CONTEXT (context);
2453 source->flags &= ~G_HOOK_FLAG_IN_CALL;
2455 if ((source->flags & G_SOURCE_CAN_RECURSE) == 0 &&
2456 !SOURCE_DESTROYED (source))
2457 unblock_source (source);
2459 /* Note: this depends on the fact that we can't switch
2460 * sources from one main context to another
2462 if (need_destroy && !SOURCE_DESTROYED (source))
2464 g_assert (source->context == context);
2465 g_source_destroy_internal (source, context, TRUE);
2469 SOURCE_UNREF (source, context);
2472 g_ptr_array_set_size (context->pending_dispatches, 0);
2475 /* Holds context's lock */
2476 static inline GSource *
2477 next_valid_source (GMainContext *context,
2480 GSource *new_source = source ? source->next : context->source_list;
2484 if (!SOURCE_DESTROYED (new_source))
2486 new_source->ref_count++;
2490 new_source = new_source->next;
2494 SOURCE_UNREF (source, context);
2500 * g_main_context_acquire:
2501 * @context: a #GMainContext
2503 * Tries to become the owner of the specified context.
2504 * If some other thread is the owner of the context,
2505 * returns %FALSE immediately. Ownership is properly
2506 * recursive: the owner can require ownership again
2507 * and will release ownership when g_main_context_release()
2508 * is called as many times as g_main_context_acquire().
2510 * You must be the owner of a context before you
2511 * can call g_main_context_prepare(), g_main_context_query(),
2512 * g_main_context_check(), g_main_context_dispatch().
2514 * Return value: %TRUE if the operation succeeded, and
2515 * this thread is now the owner of @context.
2518 g_main_context_acquire (GMainContext *context)
2520 #ifdef G_THREADS_ENABLED
2521 gboolean result = FALSE;
2522 GThread *self = G_THREAD_SELF;
2524 if (context == NULL)
2525 context = g_main_context_default ();
2527 LOCK_CONTEXT (context);
2529 if (!context->owner)
2531 context->owner = self;
2532 g_assert (context->owner_count == 0);
2535 if (context->owner == self)
2537 context->owner_count++;
2541 UNLOCK_CONTEXT (context);
2544 #else /* !G_THREADS_ENABLED */
2546 #endif /* G_THREADS_ENABLED */
2550 * g_main_context_release:
2551 * @context: a #GMainContext
2553 * Releases ownership of a context previously acquired by this thread
2554 * with g_main_context_acquire(). If the context was acquired multiple
2555 * times, the ownership will be released only when g_main_context_release()
2556 * is called as many times as it was acquired.
2559 g_main_context_release (GMainContext *context)
2561 #ifdef G_THREADS_ENABLED
2562 if (context == NULL)
2563 context = g_main_context_default ();
2565 LOCK_CONTEXT (context);
2567 context->owner_count--;
2568 if (context->owner_count == 0)
2570 context->owner = NULL;
2572 if (context->waiters)
2574 GMainWaiter *waiter = context->waiters->data;
2575 gboolean loop_internal_waiter =
2576 (waiter->mutex == g_static_mutex_get_mutex (&context->mutex));
2577 context->waiters = g_slist_delete_link (context->waiters,
2579 if (!loop_internal_waiter)
2580 g_mutex_lock (waiter->mutex);
2582 g_cond_signal (waiter->cond);
2584 if (!loop_internal_waiter)
2585 g_mutex_unlock (waiter->mutex);
2589 UNLOCK_CONTEXT (context);
2590 #endif /* G_THREADS_ENABLED */
2594 * g_main_context_wait:
2595 * @context: a #GMainContext
2596 * @cond: a condition variable
2597 * @mutex: a mutex, currently held
2599 * Tries to become the owner of the specified context,
2600 * as with g_main_context_acquire(). But if another thread
2601 * is the owner, atomically drop @mutex and wait on @cond until
2602 * that owner releases ownership or until @cond is signaled, then
2603 * try again (once) to become the owner.
2605 * Return value: %TRUE if the operation succeeded, and
2606 * this thread is now the owner of @context.
2609 g_main_context_wait (GMainContext *context,
2613 #ifdef G_THREADS_ENABLED
2614 gboolean result = FALSE;
2615 GThread *self = G_THREAD_SELF;
2616 gboolean loop_internal_waiter;
2618 if (context == NULL)
2619 context = g_main_context_default ();
2621 loop_internal_waiter = (mutex == g_static_mutex_get_mutex (&context->mutex));
2623 if (!loop_internal_waiter)
2624 LOCK_CONTEXT (context);
2626 if (context->owner && context->owner != self)
2631 waiter.mutex = mutex;
2633 context->waiters = g_slist_append (context->waiters, &waiter);
2635 if (!loop_internal_waiter)
2636 UNLOCK_CONTEXT (context);
2637 g_cond_wait (cond, mutex);
2638 if (!loop_internal_waiter)
2639 LOCK_CONTEXT (context);
2641 context->waiters = g_slist_remove (context->waiters, &waiter);
2644 if (!context->owner)
2646 context->owner = self;
2647 g_assert (context->owner_count == 0);
2650 if (context->owner == self)
2652 context->owner_count++;
2656 if (!loop_internal_waiter)
2657 UNLOCK_CONTEXT (context);
2660 #else /* !G_THREADS_ENABLED */
2662 #endif /* G_THREADS_ENABLED */
2666 * g_main_context_prepare:
2667 * @context: a #GMainContext
2668 * @priority: location to store priority of highest priority
2669 * source already ready.
2671 * Prepares to poll sources within a main loop. The resulting information
2672 * for polling is determined by calling g_main_context_query ().
2674 * Return value: %TRUE if some source is ready to be dispatched
2678 g_main_context_prepare (GMainContext *context,
2683 gint current_priority = G_MAXINT;
2686 if (context == NULL)
2687 context = g_main_context_default ();
2689 LOCK_CONTEXT (context);
2691 context->time_is_fresh = FALSE;
2692 context->real_time_is_fresh = FALSE;
2694 if (context->in_check_or_prepare)
2696 g_warning ("g_main_context_prepare() called recursively from within a source's check() or "
2697 "prepare() member.");
2698 UNLOCK_CONTEXT (context);
2702 #ifdef G_THREADS_ENABLED
2703 if (context->poll_waiting)
2705 g_warning("g_main_context_prepare(): main loop already active in another thread");
2706 UNLOCK_CONTEXT (context);
2710 context->poll_waiting = TRUE;
2711 #endif /* G_THREADS_ENABLED */
2714 /* If recursing, finish up current dispatch, before starting over */
2715 if (context->pending_dispatches)
2718 g_main_dispatch (context, ¤t_time);
2720 UNLOCK_CONTEXT (context);
2725 /* If recursing, clear list of pending dispatches */
2727 for (i = 0; i < context->pending_dispatches->len; i++)
2729 if (context->pending_dispatches->pdata[i])
2730 SOURCE_UNREF ((GSource *)context->pending_dispatches->pdata[i], context);
2732 g_ptr_array_set_size (context->pending_dispatches, 0);
2734 /* Prepare all sources */
2736 context->timeout = -1;
2738 source = next_valid_source (context, NULL);
2741 gint source_timeout = -1;
2743 if ((n_ready > 0) && (source->priority > current_priority))
2745 SOURCE_UNREF (source, context);
2748 if (SOURCE_BLOCKED (source))
2751 if (!(source->flags & G_SOURCE_READY))
2754 gboolean (*prepare) (GSource *source,
2757 prepare = source->source_funcs->prepare;
2758 context->in_check_or_prepare++;
2759 UNLOCK_CONTEXT (context);
2761 result = (*prepare) (source, &source_timeout);
2763 LOCK_CONTEXT (context);
2764 context->in_check_or_prepare--;
2768 GSource *ready_source = source;
2770 while (ready_source)
2772 ready_source->flags |= G_SOURCE_READY;
2773 ready_source = ready_source->priv ? ready_source->priv->parent_source : NULL;
2778 if (source->flags & G_SOURCE_READY)
2781 current_priority = source->priority;
2782 context->timeout = 0;
2785 if (source_timeout >= 0)
2787 if (context->timeout < 0)
2788 context->timeout = source_timeout;
2790 context->timeout = MIN (context->timeout, source_timeout);
2794 source = next_valid_source (context, source);
2797 UNLOCK_CONTEXT (context);
2800 *priority = current_priority;
2802 return (n_ready > 0);
2806 * g_main_context_query:
2807 * @context: a #GMainContext
2808 * @max_priority: maximum priority source to check
2809 * @timeout_: location to store timeout to be used in polling
2810 * @fds: location to store #GPollFD records that need to be polled.
2811 * @n_fds: length of @fds.
2813 * Determines information necessary to poll this main loop.
2815 * Return value: the number of records actually stored in @fds,
2816 * or, if more than @n_fds records need to be stored, the number
2817 * of records that need to be stored.
2820 g_main_context_query (GMainContext *context,
2829 LOCK_CONTEXT (context);
2831 pollrec = context->poll_records;
2833 while (pollrec && max_priority >= pollrec->priority)
2835 /* We need to include entries with fd->events == 0 in the array because
2836 * otherwise if the application changes fd->events behind our back and
2837 * makes it non-zero, we'll be out of sync when we check the fds[] array.
2838 * (Changing fd->events after adding an FD wasn't an anticipated use of
2839 * this API, but it occurs in practice.) */
2842 fds[n_poll].fd = pollrec->fd->fd;
2843 /* In direct contradiction to the Unix98 spec, IRIX runs into
2844 * difficulty if you pass in POLLERR, POLLHUP or POLLNVAL
2845 * flags in the events field of the pollfd while it should
2846 * just ignoring them. So we mask them out here.
2848 fds[n_poll].events = pollrec->fd->events & ~(G_IO_ERR|G_IO_HUP|G_IO_NVAL);
2849 fds[n_poll].revents = 0;
2852 pollrec = pollrec->next;
2856 #ifdef G_THREADS_ENABLED
2857 context->poll_changed = FALSE;
2862 *timeout = context->timeout;
2865 context->time_is_fresh = FALSE;
2866 context->real_time_is_fresh = FALSE;
2870 UNLOCK_CONTEXT (context);
2876 * g_main_context_check:
2877 * @context: a #GMainContext
2878 * @max_priority: the maximum numerical priority of sources to check
2879 * @fds: array of #GPollFD's that was passed to the last call to
2880 * g_main_context_query()
2881 * @n_fds: return value of g_main_context_query()
2883 * Passes the results of polling back to the main loop.
2885 * Return value: %TRUE if some sources are ready to be dispatched.
2888 g_main_context_check (GMainContext *context,
2898 LOCK_CONTEXT (context);
2900 if (context->in_check_or_prepare)
2902 g_warning ("g_main_context_check() called recursively from within a source's check() or "
2903 "prepare() member.");
2904 UNLOCK_CONTEXT (context);
2908 #ifdef G_THREADS_ENABLED
2909 if (!context->poll_waiting)
2913 read (context->wake_up_pipe[0], &a, 1);
2917 context->poll_waiting = FALSE;
2919 /* If the set of poll file descriptors changed, bail out
2920 * and let the main loop rerun
2922 if (context->poll_changed)
2924 UNLOCK_CONTEXT (context);
2927 #endif /* G_THREADS_ENABLED */
2929 pollrec = context->poll_records;
2933 if (pollrec->fd->events)
2934 pollrec->fd->revents = fds[i].revents;
2936 pollrec = pollrec->next;
2940 source = next_valid_source (context, NULL);
2943 if ((n_ready > 0) && (source->priority > max_priority))
2945 SOURCE_UNREF (source, context);
2948 if (SOURCE_BLOCKED (source))
2951 if (!(source->flags & G_SOURCE_READY))
2954 gboolean (*check) (GSource *source);
2956 check = source->source_funcs->check;
2958 context->in_check_or_prepare++;
2959 UNLOCK_CONTEXT (context);
2961 result = (*check) (source);
2963 LOCK_CONTEXT (context);
2964 context->in_check_or_prepare--;
2968 GSource *ready_source = source;
2970 while (ready_source)
2972 ready_source->flags |= G_SOURCE_READY;
2973 ready_source = ready_source->priv ? ready_source->priv->parent_source : NULL;
2978 if (source->flags & G_SOURCE_READY)
2980 source->ref_count++;
2981 g_ptr_array_add (context->pending_dispatches, source);
2985 /* never dispatch sources with less priority than the first
2986 * one we choose to dispatch
2988 max_priority = source->priority;
2992 source = next_valid_source (context, source);
2995 UNLOCK_CONTEXT (context);
3001 * g_main_context_dispatch:
3002 * @context: a #GMainContext
3004 * Dispatches all pending sources.
3007 g_main_context_dispatch (GMainContext *context)
3009 LOCK_CONTEXT (context);
3011 if (context->pending_dispatches->len > 0)
3013 g_main_dispatch (context);
3016 UNLOCK_CONTEXT (context);
3019 /* HOLDS context lock */
3021 g_main_context_iterate (GMainContext *context,
3028 gboolean some_ready;
3029 gint nfds, allocated_nfds;
3030 GPollFD *fds = NULL;
3032 UNLOCK_CONTEXT (context);
3034 #ifdef G_THREADS_ENABLED
3035 if (!g_main_context_acquire (context))
3037 gboolean got_ownership;
3039 LOCK_CONTEXT (context);
3041 g_return_val_if_fail (g_thread_supported (), FALSE);
3047 context->cond = g_cond_new ();
3049 got_ownership = g_main_context_wait (context,
3051 g_static_mutex_get_mutex (&context->mutex));
3057 LOCK_CONTEXT (context);
3058 #endif /* G_THREADS_ENABLED */
3060 if (!context->cached_poll_array)
3062 context->cached_poll_array_size = context->n_poll_records;
3063 context->cached_poll_array = g_new (GPollFD, context->n_poll_records);
3066 allocated_nfds = context->cached_poll_array_size;
3067 fds = context->cached_poll_array;
3069 UNLOCK_CONTEXT (context);
3071 g_main_context_prepare (context, &max_priority);
3073 while ((nfds = g_main_context_query (context, max_priority, &timeout, fds,
3074 allocated_nfds)) > allocated_nfds)
3076 LOCK_CONTEXT (context);
3078 context->cached_poll_array_size = allocated_nfds = nfds;
3079 context->cached_poll_array = fds = g_new (GPollFD, nfds);
3080 UNLOCK_CONTEXT (context);
3086 g_main_context_poll (context, timeout, max_priority, fds, nfds);
3088 some_ready = g_main_context_check (context, max_priority, fds, nfds);
3091 g_main_context_dispatch (context);
3093 #ifdef G_THREADS_ENABLED
3094 g_main_context_release (context);
3095 #endif /* G_THREADS_ENABLED */
3097 LOCK_CONTEXT (context);
3103 * g_main_context_pending:
3104 * @context: a #GMainContext (if %NULL, the default context will be used)
3106 * Checks if any sources have pending events for the given context.
3108 * Return value: %TRUE if events are pending.
3111 g_main_context_pending (GMainContext *context)
3116 context = g_main_context_default();
3118 LOCK_CONTEXT (context);
3119 retval = g_main_context_iterate (context, FALSE, FALSE, G_THREAD_SELF);
3120 UNLOCK_CONTEXT (context);
3126 * g_main_context_iteration:
3127 * @context: a #GMainContext (if %NULL, the default context will be used)
3128 * @may_block: whether the call may block.
3130 * Runs a single iteration for the given main loop. This involves
3131 * checking to see if any event sources are ready to be processed,
3132 * then if no events sources are ready and @may_block is %TRUE, waiting
3133 * for a source to become ready, then dispatching the highest priority
3134 * events sources that are ready. Otherwise, if @may_block is %FALSE
3135 * sources are not waited to become ready, only those highest priority
3136 * events sources will be dispatched (if any), that are ready at this
3137 * given moment without further waiting.
3139 * Note that even when @may_block is %TRUE, it is still possible for
3140 * g_main_context_iteration() to return %FALSE, since the the wait may
3141 * be interrupted for other reasons than an event source becoming ready.
3143 * Return value: %TRUE if events were dispatched.
3146 g_main_context_iteration (GMainContext *context, gboolean may_block)
3151 context = g_main_context_default();
3153 LOCK_CONTEXT (context);
3154 retval = g_main_context_iterate (context, may_block, TRUE, G_THREAD_SELF);
3155 UNLOCK_CONTEXT (context);
3162 * @context: a #GMainContext (if %NULL, the default context will be used).
3163 * @is_running: set to %TRUE to indicate that the loop is running. This
3164 * is not very important since calling g_main_loop_run() will set this to
3167 * Creates a new #GMainLoop structure.
3169 * Return value: a new #GMainLoop.
3172 g_main_loop_new (GMainContext *context,
3173 gboolean is_running)
3178 context = g_main_context_default();
3180 g_main_context_ref (context);
3182 loop = g_new0 (GMainLoop, 1);
3183 loop->context = context;
3184 loop->is_running = is_running != FALSE;
3185 loop->ref_count = 1;
3192 * @loop: a #GMainLoop
3194 * Increases the reference count on a #GMainLoop object by one.
3196 * Return value: @loop
3199 g_main_loop_ref (GMainLoop *loop)
3201 g_return_val_if_fail (loop != NULL, NULL);
3202 g_return_val_if_fail (g_atomic_int_get (&loop->ref_count) > 0, NULL);
3204 g_atomic_int_inc (&loop->ref_count);
3210 * g_main_loop_unref:
3211 * @loop: a #GMainLoop
3213 * Decreases the reference count on a #GMainLoop object by one. If
3214 * the result is zero, free the loop and free all associated memory.
3217 g_main_loop_unref (GMainLoop *loop)
3219 g_return_if_fail (loop != NULL);
3220 g_return_if_fail (g_atomic_int_get (&loop->ref_count) > 0);
3222 if (!g_atomic_int_dec_and_test (&loop->ref_count))
3225 g_main_context_unref (loop->context);
3231 * @loop: a #GMainLoop
3233 * Runs a main loop until g_main_loop_quit() is called on the loop.
3234 * If this is called for the thread of the loop's #GMainContext,
3235 * it will process events from the loop, otherwise it will
3239 g_main_loop_run (GMainLoop *loop)
3241 GThread *self = G_THREAD_SELF;
3243 g_return_if_fail (loop != NULL);
3244 g_return_if_fail (g_atomic_int_get (&loop->ref_count) > 0);
3246 #ifdef G_THREADS_ENABLED
3247 if (!g_main_context_acquire (loop->context))
3249 gboolean got_ownership = FALSE;
3251 /* Another thread owns this context */
3252 if (!g_thread_supported ())
3254 g_warning ("g_main_loop_run() was called from second thread but "
3255 "g_thread_init() was never called.");
3259 LOCK_CONTEXT (loop->context);
3261 g_atomic_int_inc (&loop->ref_count);
3263 if (!loop->is_running)
3264 loop->is_running = TRUE;
3266 if (!loop->context->cond)
3267 loop->context->cond = g_cond_new ();
3269 while (loop->is_running && !got_ownership)
3270 got_ownership = g_main_context_wait (loop->context,
3271 loop->context->cond,
3272 g_static_mutex_get_mutex (&loop->context->mutex));
3274 if (!loop->is_running)
3276 UNLOCK_CONTEXT (loop->context);
3278 g_main_context_release (loop->context);
3279 g_main_loop_unref (loop);
3283 g_assert (got_ownership);
3286 LOCK_CONTEXT (loop->context);
3287 #endif /* G_THREADS_ENABLED */
3289 if (loop->context->in_check_or_prepare)
3291 g_warning ("g_main_loop_run(): called recursively from within a source's "
3292 "check() or prepare() member, iteration not possible.");
3296 g_atomic_int_inc (&loop->ref_count);
3297 loop->is_running = TRUE;
3298 while (loop->is_running)
3299 g_main_context_iterate (loop->context, TRUE, TRUE, self);
3301 UNLOCK_CONTEXT (loop->context);
3303 #ifdef G_THREADS_ENABLED
3304 g_main_context_release (loop->context);
3305 #endif /* G_THREADS_ENABLED */
3307 g_main_loop_unref (loop);
3312 * @loop: a #GMainLoop
3314 * Stops a #GMainLoop from running. Any calls to g_main_loop_run()
3315 * for the loop will return.
3317 * Note that sources that have already been dispatched when
3318 * g_main_loop_quit() is called will still be executed.
3321 g_main_loop_quit (GMainLoop *loop)
3323 g_return_if_fail (loop != NULL);
3324 g_return_if_fail (g_atomic_int_get (&loop->ref_count) > 0);
3326 LOCK_CONTEXT (loop->context);
3327 loop->is_running = FALSE;
3328 g_main_context_wakeup_unlocked (loop->context);
3330 #ifdef G_THREADS_ENABLED
3331 if (loop->context->cond)
3332 g_cond_broadcast (loop->context->cond);
3333 #endif /* G_THREADS_ENABLED */
3335 UNLOCK_CONTEXT (loop->context);
3339 * g_main_loop_is_running:
3340 * @loop: a #GMainLoop.
3342 * Checks to see if the main loop is currently being run via g_main_loop_run().
3344 * Return value: %TRUE if the mainloop is currently being run.
3347 g_main_loop_is_running (GMainLoop *loop)
3349 g_return_val_if_fail (loop != NULL, FALSE);
3350 g_return_val_if_fail (g_atomic_int_get (&loop->ref_count) > 0, FALSE);
3352 return loop->is_running;
3356 * g_main_loop_get_context:
3357 * @loop: a #GMainLoop.
3359 * Returns the #GMainContext of @loop.
3361 * Return value: the #GMainContext of @loop
3364 g_main_loop_get_context (GMainLoop *loop)
3366 g_return_val_if_fail (loop != NULL, NULL);
3367 g_return_val_if_fail (g_atomic_int_get (&loop->ref_count) > 0, NULL);
3369 return loop->context;
3372 /* HOLDS: context's lock */
3374 g_main_context_poll (GMainContext *context,
3380 #ifdef G_MAIN_POLL_DEBUG
3386 GPollFunc poll_func;
3388 if (n_fds || timeout != 0)
3390 #ifdef G_MAIN_POLL_DEBUG
3391 if (_g_main_poll_debug)
3393 g_print ("polling context=%p n=%d timeout=%d\n",
3394 context, n_fds, timeout);
3395 poll_timer = g_timer_new ();
3399 LOCK_CONTEXT (context);
3401 poll_func = context->poll_func;
3403 UNLOCK_CONTEXT (context);
3404 if ((*poll_func) (fds, n_fds, timeout) < 0 && errno != EINTR)
3407 g_warning ("poll(2) failed due to: %s.",
3408 g_strerror (errno));
3410 /* If g_poll () returns -1, it has already called g_warning() */
3414 #ifdef G_MAIN_POLL_DEBUG
3415 if (_g_main_poll_debug)
3417 LOCK_CONTEXT (context);
3419 g_print ("g_main_poll(%d) timeout: %d - elapsed %12.10f seconds",
3422 g_timer_elapsed (poll_timer, NULL));
3423 g_timer_destroy (poll_timer);
3424 pollrec = context->poll_records;
3426 while (pollrec != NULL)
3431 if (fds[i].fd == pollrec->fd->fd &&
3432 pollrec->fd->events &&
3435 g_print (" [" G_POLLFD_FORMAT " :", fds[i].fd);
3436 if (fds[i].revents & G_IO_IN)
3438 if (fds[i].revents & G_IO_OUT)
3440 if (fds[i].revents & G_IO_PRI)
3442 if (fds[i].revents & G_IO_ERR)
3444 if (fds[i].revents & G_IO_HUP)
3446 if (fds[i].revents & G_IO_NVAL)
3452 pollrec = pollrec->next;
3456 UNLOCK_CONTEXT (context);
3459 } /* if (n_fds || timeout != 0) */
3463 * g_main_context_add_poll:
3464 * @context: a #GMainContext (or %NULL for the default context)
3465 * @fd: a #GPollFD structure holding information about a file
3466 * descriptor to watch.
3467 * @priority: the priority for this file descriptor which should be
3468 * the same as the priority used for g_source_attach() to ensure that the
3469 * file descriptor is polled whenever the results may be needed.
3471 * Adds a file descriptor to the set of file descriptors polled for
3472 * this context. This will very seldomly be used directly. Instead
3473 * a typical event source will use g_source_add_poll() instead.
3476 g_main_context_add_poll (GMainContext *context,
3481 context = g_main_context_default ();
3483 g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
3484 g_return_if_fail (fd);
3486 LOCK_CONTEXT (context);
3487 g_main_context_add_poll_unlocked (context, priority, fd);
3488 UNLOCK_CONTEXT (context);
3491 /* HOLDS: main_loop_lock */
3493 g_main_context_add_poll_unlocked (GMainContext *context,
3497 GPollRec *lastrec, *pollrec;
3498 GPollRec *newrec = g_slice_new (GPollRec);
3500 /* This file descriptor may be checked before we ever poll */
3503 newrec->priority = priority;
3506 pollrec = context->poll_records;
3507 while (pollrec && priority >= pollrec->priority)
3510 pollrec = pollrec->next;
3514 lastrec->next = newrec;
3516 context->poll_records = newrec;
3518 newrec->next = pollrec;
3520 context->n_poll_records++;
3522 #ifdef G_THREADS_ENABLED
3523 context->poll_changed = TRUE;
3525 /* Now wake up the main loop if it is waiting in the poll() */
3526 g_main_context_wakeup_unlocked (context);
3531 * g_main_context_remove_poll:
3532 * @context:a #GMainContext
3533 * @fd: a #GPollFD descriptor previously added with g_main_context_add_poll()
3535 * Removes file descriptor from the set of file descriptors to be
3536 * polled for a particular context.
3539 g_main_context_remove_poll (GMainContext *context,
3543 context = g_main_context_default ();
3545 g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
3546 g_return_if_fail (fd);
3548 LOCK_CONTEXT (context);
3549 g_main_context_remove_poll_unlocked (context, fd);
3550 UNLOCK_CONTEXT (context);
3554 g_main_context_remove_poll_unlocked (GMainContext *context,
3557 GPollRec *pollrec, *lastrec;
3560 pollrec = context->poll_records;
3564 if (pollrec->fd == fd)
3566 if (lastrec != NULL)
3567 lastrec->next = pollrec->next;
3569 context->poll_records = pollrec->next;
3571 g_slice_free (GPollRec, pollrec);
3573 context->n_poll_records--;
3577 pollrec = pollrec->next;
3580 #ifdef G_THREADS_ENABLED
3581 context->poll_changed = TRUE;
3583 /* Now wake up the main loop if it is waiting in the poll() */
3584 g_main_context_wakeup_unlocked (context);
3589 * g_source_get_current_time:
3590 * @source: a #GSource
3591 * @timeval: #GTimeVal structure in which to store current time.
3593 * Gets the "current time" to be used when checking
3594 * this source. The advantage of calling this function over
3595 * calling g_get_current_time() directly is that when
3596 * checking multiple sources, GLib can cache a single value
3597 * instead of having to repeatedly get the system time.
3599 * Deprecated: 2.28: use g_source_get_time() instead
3602 g_source_get_current_time (GSource *source,
3605 GMainContext *context;
3607 g_return_if_fail (source->context != NULL);
3609 context = source->context;
3611 LOCK_CONTEXT (context);
3613 if (!context->real_time_is_fresh)
3615 context->real_time = g_get_real_time ();
3616 context->real_time_is_fresh = TRUE;
3619 timeval->tv_sec = context->real_time / 1000000;
3620 timeval->tv_usec = context->real_time % 1000000;
3622 UNLOCK_CONTEXT (context);
3626 * g_source_get_time:
3627 * @source: a #GSource
3629 * Gets the time to be used when checking this source. The advantage of
3630 * calling this function over calling g_get_monotonic_time() directly is
3631 * that when checking multiple sources, GLib can cache a single value
3632 * instead of having to repeatedly get the system monotonic time.
3634 * The time here is the system monotonic time, if available, or some
3635 * other reasonable alternative otherwise. See g_get_monotonic_time().
3637 * Returns: the monotonic time in microseconds
3642 g_source_get_time (GSource *source)
3644 GMainContext *context;
3647 g_return_val_if_fail (source->context != NULL, 0);
3649 context = source->context;
3651 LOCK_CONTEXT (context);
3653 if (!context->time_is_fresh)
3655 context->time = g_get_monotonic_time ();
3656 context->time_is_fresh = TRUE;
3659 result = context->time;
3661 UNLOCK_CONTEXT (context);
3667 * g_main_context_set_poll_func:
3668 * @context: a #GMainContext
3669 * @func: the function to call to poll all file descriptors
3671 * Sets the function to use to handle polling of file descriptors. It
3672 * will be used instead of the poll() system call
3673 * (or GLib's replacement function, which is used where
3674 * poll() isn't available).
3676 * This function could possibly be used to integrate the GLib event
3677 * loop with an external event loop.
3680 g_main_context_set_poll_func (GMainContext *context,
3684 context = g_main_context_default ();
3686 g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
3688 LOCK_CONTEXT (context);
3691 context->poll_func = func;
3693 context->poll_func = g_poll;
3695 UNLOCK_CONTEXT (context);
3699 * g_main_context_get_poll_func:
3700 * @context: a #GMainContext
3702 * Gets the poll function set by g_main_context_set_poll_func().
3704 * Return value: the poll function
3707 g_main_context_get_poll_func (GMainContext *context)
3712 context = g_main_context_default ();
3714 g_return_val_if_fail (g_atomic_int_get (&context->ref_count) > 0, NULL);
3716 LOCK_CONTEXT (context);
3717 result = context->poll_func;
3718 UNLOCK_CONTEXT (context);
3723 /* HOLDS: context's lock */
3724 /* Wake the main loop up from a poll() */
3726 g_main_context_wakeup_unlocked (GMainContext *context)
3728 #ifdef G_THREADS_ENABLED
3729 if (g_thread_supported() && context->poll_waiting)
3731 context->poll_waiting = FALSE;
3733 write (context->wake_up_pipe[1], "A", 1);
3735 ReleaseSemaphore (context->wake_up_semaphore, 1, NULL);
3742 * g_main_context_wakeup:
3743 * @context: a #GMainContext
3745 * If @context is currently waiting in a poll(), interrupt
3746 * the poll(), and continue the iteration process.
3749 g_main_context_wakeup (GMainContext *context)
3752 context = g_main_context_default ();
3754 g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
3756 LOCK_CONTEXT (context);
3757 g_main_context_wakeup_unlocked (context);
3758 UNLOCK_CONTEXT (context);
3762 * g_main_context_is_owner:
3763 * @context: a #GMainContext
3765 * Determines whether this thread holds the (recursive)
3766 * ownership of this #GMaincontext. This is useful to
3767 * know before waiting on another thread that may be
3768 * blocking to get ownership of @context.
3770 * Returns: %TRUE if current thread is owner of @context.
3775 g_main_context_is_owner (GMainContext *context)
3780 context = g_main_context_default ();
3782 #ifdef G_THREADS_ENABLED
3783 LOCK_CONTEXT (context);
3784 is_owner = context->owner == G_THREAD_SELF;
3785 UNLOCK_CONTEXT (context);
3796 g_timeout_set_expiration (GTimeoutSource *timeout_source,
3797 gint64 current_time)
3799 timeout_source->expiration = current_time +
3800 (guint64) timeout_source->interval * 1000;
3802 if (timeout_source->seconds)
3805 static gint timer_perturb = -1;
3807 if (timer_perturb == -1)
3810 * we want a per machine/session unique 'random' value; try the dbus
3811 * address first, that has a UUID in it. If there is no dbus, use the
3812 * hostname for hashing.
3814 const char *session_bus_address = g_getenv ("DBUS_SESSION_BUS_ADDRESS");
3815 if (!session_bus_address)
3816 session_bus_address = g_getenv ("HOSTNAME");
3817 if (session_bus_address)
3818 timer_perturb = ABS ((gint) g_str_hash (session_bus_address)) % 1000000;
3823 /* We want the microseconds part of the timeout to land on the
3824 * 'timer_perturb' mark, but we need to make sure we don't try to
3825 * set the timeout in the past. We do this by ensuring that we
3826 * always only *increase* the expiration time by adding a full
3827 * second in the case that the microsecond portion decreases.
3829 timeout_source->expiration -= timer_perturb;
3831 remainder = timeout_source->expiration % 1000000;
3832 if (remainder >= 1000000/4)
3833 timeout_source->expiration += 1000000;
3835 timeout_source->expiration -= remainder;
3836 timeout_source->expiration += timer_perturb;
3841 g_timeout_prepare (GSource *source,
3844 GTimeoutSource *timeout_source = (GTimeoutSource *) source;
3845 gint64 now = g_source_get_time (source);
3847 if (now < timeout_source->expiration)
3849 /* Round up to ensure that we don't try again too early */
3850 *timeout = (timeout_source->expiration - now + 999) / 1000;
3859 g_timeout_check (GSource *source)
3861 GTimeoutSource *timeout_source = (GTimeoutSource *) source;
3862 gint64 now = g_source_get_time (source);
3864 return timeout_source->expiration <= now;
3868 g_timeout_dispatch (GSource *source,
3869 GSourceFunc callback,
3872 GTimeoutSource *timeout_source = (GTimeoutSource *)source;
3877 g_warning ("Timeout source dispatched without callback\n"
3878 "You must call g_source_set_callback().");
3882 again = callback (user_data);
3885 g_timeout_set_expiration (timeout_source, g_source_get_time (source));
3891 * g_timeout_source_new:
3892 * @interval: the timeout interval in milliseconds.
3894 * Creates a new timeout source.
3896 * The source will not initially be associated with any #GMainContext
3897 * and must be added to one with g_source_attach() before it will be
3900 * Return value: the newly-created timeout source
3903 g_timeout_source_new (guint interval)
3905 GSource *source = g_source_new (&g_timeout_funcs, sizeof (GTimeoutSource));
3906 GTimeoutSource *timeout_source = (GTimeoutSource *)source;
3908 timeout_source->interval = interval;
3909 g_timeout_set_expiration (timeout_source, g_get_monotonic_time ());
3915 * g_timeout_source_new_seconds:
3916 * @interval: the timeout interval in seconds
3918 * Creates a new timeout source.
3920 * The source will not initially be associated with any #GMainContext
3921 * and must be added to one with g_source_attach() before it will be
3924 * The scheduling granularity/accuracy of this timeout source will be
3927 * Return value: the newly-created timeout source
3932 g_timeout_source_new_seconds (guint interval)
3934 GSource *source = g_source_new (&g_timeout_funcs, sizeof (GTimeoutSource));
3935 GTimeoutSource *timeout_source = (GTimeoutSource *)source;
3937 timeout_source->interval = 1000 * interval;
3938 timeout_source->seconds = TRUE;
3940 g_timeout_set_expiration (timeout_source, g_get_monotonic_time ());
3947 * g_timeout_add_full:
3948 * @priority: the priority of the timeout source. Typically this will be in
3949 * the range between #G_PRIORITY_DEFAULT and #G_PRIORITY_HIGH.
3950 * @interval: the time between calls to the function, in milliseconds
3951 * (1/1000ths of a second)
3952 * @function: function to call
3953 * @data: data to pass to @function
3954 * @notify: function to call when the timeout is removed, or %NULL
3956 * Sets a function to be called at regular intervals, with the given
3957 * priority. The function is called repeatedly until it returns
3958 * %FALSE, at which point the timeout is automatically destroyed and
3959 * the function will not be called again. The @notify function is
3960 * called when the timeout is destroyed. The first call to the
3961 * function will be at the end of the first @interval.
3963 * Note that timeout functions may be delayed, due to the processing of other
3964 * event sources. Thus they should not be relied on for precise timing.
3965 * After each call to the timeout function, the time of the next
3966 * timeout is recalculated based on the current time and the given interval
3967 * (it does not try to 'catch up' time lost in delays).
3969 * This internally creates a main loop source using g_timeout_source_new()
3970 * and attaches it to the main loop context using g_source_attach(). You can
3971 * do these steps manually if you need greater control.
3973 * Return value: the ID (greater than 0) of the event source.
3976 g_timeout_add_full (gint priority,
3978 GSourceFunc function,
3980 GDestroyNotify notify)
3985 g_return_val_if_fail (function != NULL, 0);
3987 source = g_timeout_source_new (interval);
3989 if (priority != G_PRIORITY_DEFAULT)
3990 g_source_set_priority (source, priority);
3992 g_source_set_callback (source, function, data, notify);
3993 id = g_source_attach (source, NULL);
3994 g_source_unref (source);
4001 * @interval: the time between calls to the function, in milliseconds
4002 * (1/1000ths of a second)
4003 * @function: function to call
4004 * @data: data to pass to @function
4006 * Sets a function to be called at regular intervals, with the default
4007 * priority, #G_PRIORITY_DEFAULT. The function is called repeatedly
4008 * until it returns %FALSE, at which point the timeout is automatically
4009 * destroyed and the function will not be called again. The first call
4010 * to the function will be at the end of the first @interval.
4012 * Note that timeout functions may be delayed, due to the processing of other
4013 * event sources. Thus they should not be relied on for precise timing.
4014 * After each call to the timeout function, the time of the next
4015 * timeout is recalculated based on the current time and the given interval
4016 * (it does not try to 'catch up' time lost in delays).
4018 * If you want to have a timer in the "seconds" range and do not care
4019 * about the exact time of the first call of the timer, use the
4020 * g_timeout_add_seconds() function; this function allows for more
4021 * optimizations and more efficient system power usage.
4023 * This internally creates a main loop source using g_timeout_source_new()
4024 * and attaches it to the main loop context using g_source_attach(). You can
4025 * do these steps manually if you need greater control.
4027 * Return value: the ID (greater than 0) of the event source.
4030 g_timeout_add (guint32 interval,
4031 GSourceFunc function,
4034 return g_timeout_add_full (G_PRIORITY_DEFAULT,
4035 interval, function, data, NULL);
4039 * g_timeout_add_seconds_full:
4040 * @priority: the priority of the timeout source. Typically this will be in
4041 * the range between #G_PRIORITY_DEFAULT and #G_PRIORITY_HIGH.
4042 * @interval: the time between calls to the function, in seconds
4043 * @function: function to call
4044 * @data: data to pass to @function
4045 * @notify: function to call when the timeout is removed, or %NULL
4047 * Sets a function to be called at regular intervals, with @priority.
4048 * The function is called repeatedly until it returns %FALSE, at which
4049 * point the timeout is automatically destroyed and the function will
4050 * not be called again.
4052 * Unlike g_timeout_add(), this function operates at whole second granularity.
4053 * The initial starting point of the timer is determined by the implementation
4054 * and the implementation is expected to group multiple timers together so that
4055 * they fire all at the same time.
4056 * To allow this grouping, the @interval to the first timer is rounded
4057 * and can deviate up to one second from the specified interval.
4058 * Subsequent timer iterations will generally run at the specified interval.
4060 * Note that timeout functions may be delayed, due to the processing of other
4061 * event sources. Thus they should not be relied on for precise timing.
4062 * After each call to the timeout function, the time of the next
4063 * timeout is recalculated based on the current time and the given @interval
4065 * If you want timing more precise than whole seconds, use g_timeout_add()
4068 * The grouping of timers to fire at the same time results in a more power
4069 * and CPU efficient behavior so if your timer is in multiples of seconds
4070 * and you don't require the first timer exactly one second from now, the
4071 * use of g_timeout_add_seconds() is preferred over g_timeout_add().
4073 * This internally creates a main loop source using
4074 * g_timeout_source_new_seconds() and attaches it to the main loop context
4075 * using g_source_attach(). You can do these steps manually if you need
4078 * Return value: the ID (greater than 0) of the event source.
4083 g_timeout_add_seconds_full (gint priority,
4085 GSourceFunc function,
4087 GDestroyNotify notify)
4092 g_return_val_if_fail (function != NULL, 0);
4094 source = g_timeout_source_new_seconds (interval);
4096 if (priority != G_PRIORITY_DEFAULT)
4097 g_source_set_priority (source, priority);
4099 g_source_set_callback (source, function, data, notify);
4100 id = g_source_attach (source, NULL);
4101 g_source_unref (source);
4107 * g_timeout_add_seconds:
4108 * @interval: the time between calls to the function, in seconds
4109 * @function: function to call
4110 * @data: data to pass to @function
4112 * Sets a function to be called at regular intervals with the default
4113 * priority, #G_PRIORITY_DEFAULT. The function is called repeatedly until
4114 * it returns %FALSE, at which point the timeout is automatically destroyed
4115 * and the function will not be called again.
4117 * This internally creates a main loop source using
4118 * g_timeout_source_new_seconds() and attaches it to the main loop context
4119 * using g_source_attach(). You can do these steps manually if you need
4120 * greater control. Also see g_timout_add_seconds_full().
4122 * Note that the first call of the timer may not be precise for timeouts
4123 * of one second. If you need finer precision and have such a timeout,
4124 * you may want to use g_timeout_add() instead.
4126 * Return value: the ID (greater than 0) of the event source.
4131 g_timeout_add_seconds (guint interval,
4132 GSourceFunc function,
4135 g_return_val_if_fail (function != NULL, 0);
4137 return g_timeout_add_seconds_full (G_PRIORITY_DEFAULT, interval, function, data, NULL);
4140 /* Child watch functions */
4145 g_child_watch_prepare (GSource *source,
4154 g_child_watch_check (GSource *source)
4156 GChildWatchSource *child_watch_source;
4157 gboolean child_exited;
4159 child_watch_source = (GChildWatchSource *) source;
4161 child_exited = child_watch_source->poll.revents & G_IO_IN;
4168 * Note: We do _not_ check for the special value of STILL_ACTIVE
4169 * since we know that the process has exited and doing so runs into
4170 * problems if the child process "happens to return STILL_ACTIVE(259)"
4171 * as Microsoft's Platform SDK puts it.
4173 if (!GetExitCodeProcess (child_watch_source->pid, &child_status))
4175 gchar *emsg = g_win32_error_message (GetLastError ());
4176 g_warning (G_STRLOC ": GetExitCodeProcess() failed: %s", emsg);
4179 child_watch_source->child_status = -1;
4182 child_watch_source->child_status = child_status;
4185 return child_exited;
4188 #else /* G_OS_WIN32 */
4191 check_for_child_exited (GSource *source)
4193 GChildWatchSource *child_watch_source;
4196 /* protect against another SIGCHLD in the middle of this call */
4197 count = child_watch_count;
4199 child_watch_source = (GChildWatchSource *) source;
4201 if (child_watch_source->child_exited)
4204 if (child_watch_source->count < count)
4208 if (waitpid (child_watch_source->pid, &child_status, WNOHANG) > 0)
4210 child_watch_source->child_status = child_status;
4211 child_watch_source->child_exited = TRUE;
4213 child_watch_source->count = count;
4216 return child_watch_source->child_exited;
4220 g_child_watch_prepare (GSource *source,
4225 return check_for_child_exited (source);
4230 g_child_watch_check (GSource *source)
4232 return check_for_child_exited (source);
4235 #endif /* G_OS_WIN32 */
4238 g_child_watch_dispatch (GSource *source,
4239 GSourceFunc callback,
4242 GChildWatchSource *child_watch_source;
4243 GChildWatchFunc child_watch_callback = (GChildWatchFunc) callback;
4245 child_watch_source = (GChildWatchSource *) source;
4249 g_warning ("Child watch source dispatched without callback\n"
4250 "You must call g_source_set_callback().");
4254 (child_watch_callback) (child_watch_source->pid, child_watch_source->child_status, user_data);
4256 /* We never keep a child watch source around as the child is gone */
4263 g_child_watch_signal_handler (int signum)
4265 child_watch_count ++;
4267 if (child_watch_init_state == CHILD_WATCH_INITIALIZED_THREADED)
4269 write (child_watch_wake_up_pipe[1], "B", 1);
4273 /* We count on the signal interrupting the poll in the same thread.
4279 g_child_watch_source_init_single (void)
4281 struct sigaction action;
4283 g_assert (! g_thread_supported());
4284 g_assert (child_watch_init_state == CHILD_WATCH_UNINITIALIZED);
4286 child_watch_init_state = CHILD_WATCH_INITIALIZED_SINGLE;
4288 action.sa_handler = g_child_watch_signal_handler;
4289 sigemptyset (&action.sa_mask);
4290 action.sa_flags = SA_NOCLDSTOP;
4291 sigaction (SIGCHLD, &action, NULL);
4294 G_GNUC_NORETURN static gpointer
4295 child_watch_helper_thread (gpointer data)
4302 read (child_watch_wake_up_pipe[0], b, 20);
4304 /* We were woken up. Wake up all other contexts in all other threads */
4305 G_LOCK (main_context_list);
4306 for (list = main_context_list; list; list = list->next)
4308 GMainContext *context;
4310 context = list->data;
4311 if (g_atomic_int_get (&context->ref_count) > 0)
4312 /* Due to racing conditions we can find ref_count == 0, in
4313 * that case, however, the context is still not destroyed
4314 * and no poll can be active, otherwise the ref_count
4316 g_main_context_wakeup (context);
4318 G_UNLOCK (main_context_list);
4323 g_child_watch_source_init_multi_threaded (void)
4325 GError *error = NULL;
4326 struct sigaction action;
4328 g_assert (g_thread_supported());
4330 if (pipe (child_watch_wake_up_pipe) < 0)
4331 g_error ("Cannot create wake up pipe: %s\n", g_strerror (errno));
4332 fcntl (child_watch_wake_up_pipe[1], F_SETFL, O_NONBLOCK | fcntl (child_watch_wake_up_pipe[1], F_GETFL));
4334 /* We create a helper thread that polls on the wakeup pipe indefinitely */
4335 /* FIXME: Think this through for races */
4336 if (g_thread_create (child_watch_helper_thread, NULL, FALSE, &error) == NULL)
4337 g_error ("Cannot create a thread to monitor child exit status: %s\n", error->message);
4338 child_watch_init_state = CHILD_WATCH_INITIALIZED_THREADED;
4340 action.sa_handler = g_child_watch_signal_handler;
4341 sigemptyset (&action.sa_mask);
4342 action.sa_flags = SA_RESTART | SA_NOCLDSTOP;
4343 sigaction (SIGCHLD, &action, NULL);
4347 g_child_watch_source_init_promote_single_to_threaded (void)
4349 g_child_watch_source_init_multi_threaded ();
4353 g_child_watch_source_init (void)
4355 if (g_thread_supported())
4357 if (child_watch_init_state == CHILD_WATCH_UNINITIALIZED)
4358 g_child_watch_source_init_multi_threaded ();
4359 else if (child_watch_init_state == CHILD_WATCH_INITIALIZED_SINGLE)
4360 g_child_watch_source_init_promote_single_to_threaded ();
4364 if (child_watch_init_state == CHILD_WATCH_UNINITIALIZED)
4365 g_child_watch_source_init_single ();
4369 #endif /* !G_OS_WIN32 */
4372 * g_child_watch_source_new:
4373 * @pid: process to watch. On POSIX the pid of a child process. On
4374 * Windows a handle for a process (which doesn't have to be a child).
4376 * Creates a new child_watch source.
4378 * The source will not initially be associated with any #GMainContext
4379 * and must be added to one with g_source_attach() before it will be
4382 * Note that child watch sources can only be used in conjunction with
4383 * <literal>g_spawn...</literal> when the %G_SPAWN_DO_NOT_REAP_CHILD
4386 * Note that on platforms where #GPid must be explicitly closed
4387 * (see g_spawn_close_pid()) @pid must not be closed while the
4388 * source is still active. Typically, you will want to call
4389 * g_spawn_close_pid() in the callback function for the source.
4391 * Note further that using g_child_watch_source_new() is not
4392 * compatible with calling <literal>waitpid(-1)</literal> in
4393 * the application. Calling waitpid() for individual pids will
4396 * Return value: the newly-created child watch source
4401 g_child_watch_source_new (GPid pid)
4403 GSource *source = g_source_new (&g_child_watch_funcs, sizeof (GChildWatchSource));
4404 GChildWatchSource *child_watch_source = (GChildWatchSource *)source;
4407 child_watch_source->poll.fd = (gintptr) pid;
4408 child_watch_source->poll.events = G_IO_IN;
4410 g_source_add_poll (source, &child_watch_source->poll);
4411 #else /* G_OS_WIN32 */
4412 g_child_watch_source_init ();
4413 #endif /* G_OS_WIN32 */
4415 child_watch_source->pid = pid;
4421 * g_child_watch_add_full:
4422 * @priority: the priority of the idle source. Typically this will be in the
4423 * range between #G_PRIORITY_DEFAULT_IDLE and #G_PRIORITY_HIGH_IDLE.
4424 * @pid: process to watch. On POSIX the pid of a child process. On
4425 * Windows a handle for a process (which doesn't have to be a child).
4426 * @function: function to call
4427 * @data: data to pass to @function
4428 * @notify: function to call when the idle is removed, or %NULL
4430 * Sets a function to be called when the child indicated by @pid
4431 * exits, at the priority @priority.
4433 * If you obtain @pid from g_spawn_async() or g_spawn_async_with_pipes()
4434 * you will need to pass #G_SPAWN_DO_NOT_REAP_CHILD as flag to
4435 * the spawn function for the child watching to work.
4437 * Note that on platforms where #GPid must be explicitly closed
4438 * (see g_spawn_close_pid()) @pid must not be closed while the
4439 * source is still active. Typically, you will want to call
4440 * g_spawn_close_pid() in the callback function for the source.
4442 * GLib supports only a single callback per process id.
4444 * This internally creates a main loop source using
4445 * g_child_watch_source_new() and attaches it to the main loop context
4446 * using g_source_attach(). You can do these steps manually if you
4447 * need greater control.
4449 * Return value: the ID (greater than 0) of the event source.
4454 g_child_watch_add_full (gint priority,
4456 GChildWatchFunc function,
4458 GDestroyNotify notify)
4463 g_return_val_if_fail (function != NULL, 0);
4465 source = g_child_watch_source_new (pid);
4467 if (priority != G_PRIORITY_DEFAULT)
4468 g_source_set_priority (source, priority);
4470 g_source_set_callback (source, (GSourceFunc) function, data, notify);
4471 id = g_source_attach (source, NULL);
4472 g_source_unref (source);
4478 * g_child_watch_add:
4479 * @pid: process id to watch. On POSIX the pid of a child process. On
4480 * Windows a handle for a process (which doesn't have to be a child).
4481 * @function: function to call
4482 * @data: data to pass to @function
4484 * Sets a function to be called when the child indicated by @pid
4485 * exits, at a default priority, #G_PRIORITY_DEFAULT.
4487 * If you obtain @pid from g_spawn_async() or g_spawn_async_with_pipes()
4488 * you will need to pass #G_SPAWN_DO_NOT_REAP_CHILD as flag to
4489 * the spawn function for the child watching to work.
4491 * Note that on platforms where #GPid must be explicitly closed
4492 * (see g_spawn_close_pid()) @pid must not be closed while the
4493 * source is still active. Typically, you will want to call
4494 * g_spawn_close_pid() in the callback function for the source.
4496 * GLib supports only a single callback per process id.
4498 * This internally creates a main loop source using
4499 * g_child_watch_source_new() and attaches it to the main loop context
4500 * using g_source_attach(). You can do these steps manually if you
4501 * need greater control.
4503 * Return value: the ID (greater than 0) of the event source.
4508 g_child_watch_add (GPid pid,
4509 GChildWatchFunc function,
4512 return g_child_watch_add_full (G_PRIORITY_DEFAULT, pid, function, data, NULL);
4516 /* Idle functions */
4519 g_idle_prepare (GSource *source,
4528 g_idle_check (GSource *source)
4534 g_idle_dispatch (GSource *source,
4535 GSourceFunc callback,
4540 g_warning ("Idle source dispatched without callback\n"
4541 "You must call g_source_set_callback().");
4545 return callback (user_data);
4549 * g_idle_source_new:
4551 * Creates a new idle source.
4553 * The source will not initially be associated with any #GMainContext
4554 * and must be added to one with g_source_attach() before it will be
4555 * executed. Note that the default priority for idle sources is
4556 * %G_PRIORITY_DEFAULT_IDLE, as compared to other sources which
4557 * have a default priority of %G_PRIORITY_DEFAULT.
4559 * Return value: the newly-created idle source
4562 g_idle_source_new (void)
4566 source = g_source_new (&g_idle_funcs, sizeof (GSource));
4567 g_source_set_priority (source, G_PRIORITY_DEFAULT_IDLE);
4574 * @priority: the priority of the idle source. Typically this will be in the
4575 * range between #G_PRIORITY_DEFAULT_IDLE and #G_PRIORITY_HIGH_IDLE.
4576 * @function: function to call
4577 * @data: data to pass to @function
4578 * @notify: function to call when the idle is removed, or %NULL
4580 * Adds a function to be called whenever there are no higher priority
4581 * events pending. If the function returns %FALSE it is automatically
4582 * removed from the list of event sources and will not be called again.
4584 * This internally creates a main loop source using g_idle_source_new()
4585 * and attaches it to the main loop context using g_source_attach().
4586 * You can do these steps manually if you need greater control.
4588 * Return value: the ID (greater than 0) of the event source.
4591 g_idle_add_full (gint priority,
4592 GSourceFunc function,
4594 GDestroyNotify notify)
4599 g_return_val_if_fail (function != NULL, 0);
4601 source = g_idle_source_new ();
4603 if (priority != G_PRIORITY_DEFAULT_IDLE)
4604 g_source_set_priority (source, priority);
4606 g_source_set_callback (source, function, data, notify);
4607 id = g_source_attach (source, NULL);
4608 g_source_unref (source);
4615 * @function: function to call
4616 * @data: data to pass to @function.
4618 * Adds a function to be called whenever there are no higher priority
4619 * events pending to the default main loop. The function is given the
4620 * default idle priority, #G_PRIORITY_DEFAULT_IDLE. If the function
4621 * returns %FALSE it is automatically removed from the list of event
4622 * sources and will not be called again.
4624 * This internally creates a main loop source using g_idle_source_new()
4625 * and attaches it to the main loop context using g_source_attach().
4626 * You can do these steps manually if you need greater control.
4628 * Return value: the ID (greater than 0) of the event source.
4631 g_idle_add (GSourceFunc function,
4634 return g_idle_add_full (G_PRIORITY_DEFAULT_IDLE, function, data, NULL);
4638 * g_idle_remove_by_data:
4639 * @data: the data for the idle source's callback.
4641 * Removes the idle function with the given data.
4643 * Return value: %TRUE if an idle source was found and removed.
4646 g_idle_remove_by_data (gpointer data)
4648 return g_source_remove_by_funcs_user_data (&g_idle_funcs, data);
4652 * g_main_context_invoke:
4653 * @context: a #GMainContext, or %NULL
4654 * @function: function to call
4655 * @data: data to pass to @function
4657 * Invokes a function in such a way that @context is owned during the
4658 * invocation of @function.
4660 * If @context is %NULL then the global default main context — as
4661 * returned by g_main_context_default() — is used.
4663 * If @context is owned by the current thread, @function is called
4664 * directly. Otherwise, if @context is the thread-default main context
4665 * of the current thread and g_main_context_acquire() succeeds, then
4666 * @function is called and g_main_context_release() is called
4669 * In any other case, an idle source is created to call @function and
4670 * that source is attached to @context (presumably to be run in another
4671 * thread). The idle source is attached with #G_PRIORITY_DEFAULT
4672 * priority. If you want a different priority, use
4673 * g_main_context_invoke_full().
4675 * Note that, as with normal idle functions, @function should probably
4676 * return %FALSE. If it returns %TRUE, it will be continuously run in a
4677 * loop (and may prevent this call from returning).
4682 g_main_context_invoke (GMainContext *context,
4683 GSourceFunc function,
4686 g_main_context_invoke_full (context,
4688 function, data, NULL);
4692 * g_main_context_invoke_full:
4693 * @context: a #GMainContext, or %NULL
4694 * @priority: the priority at which to run @function
4695 * @function: function to call
4696 * @data: data to pass to @function
4697 * @notify: a function to call when @data is no longer in use, or %NULL.
4699 * Invokes a function in such a way that @context is owned during the
4700 * invocation of @function.
4702 * This function is the same as g_main_context_invoke() except that it
4703 * lets you specify the priority incase @function ends up being
4704 * scheduled as an idle and also lets you give a #GDestroyNotify for @data.
4706 * @notify should not assume that it is called from any particular
4707 * thread or with any particular context acquired.
4712 g_main_context_invoke_full (GMainContext *context,
4714 GSourceFunc function,
4716 GDestroyNotify notify)
4718 g_return_if_fail (function != NULL);
4721 context = g_main_context_default ();
4723 if (g_main_context_is_owner (context))
4725 while (function (data));
4732 GMainContext *thread_default;
4734 thread_default = g_main_context_get_thread_default ();
4736 if (!thread_default)
4737 thread_default = g_main_context_default ();
4739 if (thread_default == context && g_main_context_acquire (context))
4741 while (function (data));
4743 g_main_context_release (context);
4752 source = g_idle_source_new ();
4753 g_source_set_priority (source, priority);
4754 g_source_set_callback (source, function, data, notify);
4755 g_source_attach (source, context);
4756 g_source_unref (source);