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 (and won't call @child_source's 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 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.
1199 g_source_add_child_source (GSource *source,
1200 GSource *child_source)
1202 GMainContext *context;
1204 g_return_if_fail (source != NULL);
1205 g_return_if_fail (child_source != NULL);
1206 g_return_if_fail (!SOURCE_DESTROYED (source));
1207 g_return_if_fail (!SOURCE_DESTROYED (child_source));
1208 g_return_if_fail (child_source->context == NULL);
1209 g_return_if_fail (child_source->priv == NULL || child_source->priv->parent_source == NULL);
1211 context = source->context;
1214 LOCK_CONTEXT (context);
1217 source->priv = g_slice_new0 (GSourcePrivate);
1218 if (!child_source->priv)
1219 child_source->priv = g_slice_new0 (GSourcePrivate);
1221 source->priv->child_sources = g_slist_prepend (source->priv->child_sources,
1222 g_source_ref (child_source));
1223 child_source->priv->parent_source = source;
1224 g_source_set_priority_unlocked (child_source, context, source->priority);
1228 UNLOCK_CONTEXT (context);
1229 g_source_attach (child_source, context);
1234 * g_source_remove_child_source:
1235 * @source:a #GSource
1236 * @child_source: a #GSource previously passed to
1237 * g_source_add_child_source().
1239 * Detaches @child_source from @source and destroys it.
1242 g_source_remove_child_source (GSource *source,
1243 GSource *child_source)
1245 GMainContext *context;
1247 g_return_if_fail (source != NULL);
1248 g_return_if_fail (child_source != NULL);
1249 g_return_if_fail (child_source->priv != NULL && child_source->priv->parent_source == source);
1250 g_return_if_fail (!SOURCE_DESTROYED (source));
1251 g_return_if_fail (!SOURCE_DESTROYED (child_source));
1253 context = source->context;
1256 LOCK_CONTEXT (context);
1258 source->priv->child_sources = g_slist_remove (source->priv->child_sources, child_source);
1259 g_source_destroy_internal (child_source, context, TRUE);
1260 g_source_unref_internal (child_source, context, TRUE);
1263 UNLOCK_CONTEXT (context);
1267 * g_source_set_callback_indirect:
1268 * @source: the source
1269 * @callback_data: pointer to callback data "object"
1270 * @callback_funcs: functions for reference counting @callback_data
1271 * and getting the callback and data
1273 * Sets the callback function storing the data as a refcounted callback
1274 * "object". This is used internally. Note that calling
1275 * g_source_set_callback_indirect() assumes
1276 * an initial reference count on @callback_data, and thus
1277 * @callback_funcs->unref will eventually be called once more
1278 * than @callback_funcs->ref.
1281 g_source_set_callback_indirect (GSource *source,
1282 gpointer callback_data,
1283 GSourceCallbackFuncs *callback_funcs)
1285 GMainContext *context;
1286 gpointer old_cb_data;
1287 GSourceCallbackFuncs *old_cb_funcs;
1289 g_return_if_fail (source != NULL);
1290 g_return_if_fail (callback_funcs != NULL || callback_data == NULL);
1292 context = source->context;
1295 LOCK_CONTEXT (context);
1297 old_cb_data = source->callback_data;
1298 old_cb_funcs = source->callback_funcs;
1300 source->callback_data = callback_data;
1301 source->callback_funcs = callback_funcs;
1304 UNLOCK_CONTEXT (context);
1307 old_cb_funcs->unref (old_cb_data);
1311 g_source_callback_ref (gpointer cb_data)
1313 GSourceCallback *callback = cb_data;
1315 callback->ref_count++;
1320 g_source_callback_unref (gpointer cb_data)
1322 GSourceCallback *callback = cb_data;
1324 callback->ref_count--;
1325 if (callback->ref_count == 0)
1327 if (callback->notify)
1328 callback->notify (callback->data);
1334 g_source_callback_get (gpointer cb_data,
1339 GSourceCallback *callback = cb_data;
1341 *func = callback->func;
1342 *data = callback->data;
1345 static GSourceCallbackFuncs g_source_callback_funcs = {
1346 g_source_callback_ref,
1347 g_source_callback_unref,
1348 g_source_callback_get,
1352 * g_source_set_callback:
1353 * @source: the source
1354 * @func: a callback function
1355 * @data: the data to pass to callback function
1356 * @notify: a function to call when @data is no longer in use, or %NULL.
1358 * Sets the callback function for a source. The callback for a source is
1359 * called from the source's dispatch function.
1361 * The exact type of @func depends on the type of source; ie. you
1362 * should not count on @func being called with @data as its first
1365 * Typically, you won't use this function. Instead use functions specific
1366 * to the type of source you are using.
1369 g_source_set_callback (GSource *source,
1372 GDestroyNotify notify)
1374 GSourceCallback *new_callback;
1376 g_return_if_fail (source != NULL);
1378 new_callback = g_new (GSourceCallback, 1);
1380 new_callback->ref_count = 1;
1381 new_callback->func = func;
1382 new_callback->data = data;
1383 new_callback->notify = notify;
1385 g_source_set_callback_indirect (source, new_callback, &g_source_callback_funcs);
1390 * g_source_set_funcs:
1391 * @source: a #GSource
1392 * @funcs: the new #GSourceFuncs
1394 * Sets the source functions (can be used to override
1395 * default implementations) of an unattached source.
1400 g_source_set_funcs (GSource *source,
1401 GSourceFuncs *funcs)
1403 g_return_if_fail (source != NULL);
1404 g_return_if_fail (source->context == NULL);
1405 g_return_if_fail (source->ref_count > 0);
1406 g_return_if_fail (funcs != NULL);
1408 source->source_funcs = funcs;
1412 g_source_set_priority_unlocked (GSource *source,
1413 GMainContext *context,
1418 source->priority = priority;
1422 /* Remove the source from the context's source and then
1423 * add it back so it is sorted in the correct place
1425 g_source_list_remove (source, source->context);
1426 g_source_list_add (source, source->context);
1428 if (!SOURCE_BLOCKED (source))
1430 tmp_list = source->poll_fds;
1433 g_main_context_remove_poll_unlocked (context, tmp_list->data);
1434 g_main_context_add_poll_unlocked (context, priority, tmp_list->data);
1436 tmp_list = tmp_list->next;
1441 if (source->priv && source->priv->child_sources)
1443 tmp_list = source->priv->child_sources;
1446 g_source_set_priority_unlocked (tmp_list->data, context, priority);
1447 tmp_list = tmp_list->next;
1453 * g_source_set_priority:
1454 * @source: a #GSource
1455 * @priority: the new priority.
1457 * Sets the priority of a source. While the main loop is being run, a
1458 * source will be dispatched if it is ready to be dispatched and no
1459 * sources at a higher (numerically smaller) priority are ready to be
1463 g_source_set_priority (GSource *source,
1466 GMainContext *context;
1468 g_return_if_fail (source != NULL);
1470 context = source->context;
1473 LOCK_CONTEXT (context);
1474 g_source_set_priority_unlocked (source, context, priority);
1476 UNLOCK_CONTEXT (source->context);
1480 * g_source_get_priority:
1481 * @source: a #GSource
1483 * Gets the priority of a source.
1485 * Return value: the priority of the source
1488 g_source_get_priority (GSource *source)
1490 g_return_val_if_fail (source != NULL, 0);
1492 return source->priority;
1496 * g_source_set_can_recurse:
1497 * @source: a #GSource
1498 * @can_recurse: whether recursion is allowed for this source
1500 * Sets whether a source can be called recursively. If @can_recurse is
1501 * %TRUE, then while the source is being dispatched then this source
1502 * will be processed normally. Otherwise, all processing of this
1503 * source is blocked until the dispatch function returns.
1506 g_source_set_can_recurse (GSource *source,
1507 gboolean can_recurse)
1509 GMainContext *context;
1511 g_return_if_fail (source != NULL);
1513 context = source->context;
1516 LOCK_CONTEXT (context);
1519 source->flags |= G_SOURCE_CAN_RECURSE;
1521 source->flags &= ~G_SOURCE_CAN_RECURSE;
1524 UNLOCK_CONTEXT (context);
1528 * g_source_get_can_recurse:
1529 * @source: a #GSource
1531 * Checks whether a source is allowed to be called recursively.
1532 * see g_source_set_can_recurse().
1534 * Return value: whether recursion is allowed.
1537 g_source_get_can_recurse (GSource *source)
1539 g_return_val_if_fail (source != NULL, FALSE);
1541 return (source->flags & G_SOURCE_CAN_RECURSE) != 0;
1546 * g_source_set_name:
1547 * @source: a #GSource
1548 * @name: debug name for the source
1550 * Sets a name for the source, used in debugging and profiling.
1551 * The name defaults to #NULL.
1553 * The source name should describe in a human-readable way
1554 * what the source does. For example, "X11 event queue"
1555 * or "GTK+ repaint idle handler" or whatever it is.
1557 * It is permitted to call this function multiple times, but is not
1558 * recommended due to the potential performance impact. For example,
1559 * one could change the name in the "check" function of a #GSourceFuncs
1560 * to include details like the event type in the source name.
1565 g_source_set_name (GSource *source,
1568 g_return_if_fail (source != NULL);
1570 /* setting back to NULL is allowed, just because it's
1571 * weird if get_name can return NULL but you can't
1575 g_free (source->name);
1576 source->name = g_strdup (name);
1580 * g_source_get_name:
1581 * @source: a #GSource
1583 * Gets a name for the source, used in debugging and profiling.
1584 * The name may be #NULL if it has never been set with
1585 * g_source_set_name().
1587 * Return value: the name of the source
1590 G_CONST_RETURN char*
1591 g_source_get_name (GSource *source)
1593 g_return_val_if_fail (source != NULL, NULL);
1595 return source->name;
1599 * g_source_set_name_by_id:
1600 * @tag: a #GSource ID
1601 * @name: debug name for the source
1603 * Sets the name of a source using its ID.
1605 * This is a convenience utility to set source names from the return
1606 * value of g_idle_add(), g_timeout_add(), etc.
1611 g_source_set_name_by_id (guint tag,
1616 g_return_if_fail (tag > 0);
1618 source = g_main_context_find_source_by_id (NULL, tag);
1622 g_source_set_name (source, name);
1628 * @source: a #GSource
1630 * Increases the reference count on a source by one.
1632 * Return value: @source
1635 g_source_ref (GSource *source)
1637 GMainContext *context;
1639 g_return_val_if_fail (source != NULL, NULL);
1641 context = source->context;
1644 LOCK_CONTEXT (context);
1646 source->ref_count++;
1649 UNLOCK_CONTEXT (context);
1654 /* g_source_unref() but possible to call within context lock
1657 g_source_unref_internal (GSource *source,
1658 GMainContext *context,
1661 gpointer old_cb_data = NULL;
1662 GSourceCallbackFuncs *old_cb_funcs = NULL;
1664 g_return_if_fail (source != NULL);
1666 if (!have_lock && context)
1667 LOCK_CONTEXT (context);
1669 source->ref_count--;
1670 if (source->ref_count == 0)
1672 old_cb_data = source->callback_data;
1673 old_cb_funcs = source->callback_funcs;
1675 source->callback_data = NULL;
1676 source->callback_funcs = NULL;
1680 if (!SOURCE_DESTROYED (source))
1681 g_warning (G_STRLOC ": ref_count == 0, but source was still attached to a context!");
1682 g_source_list_remove (source, context);
1685 if (source->source_funcs->finalize)
1688 UNLOCK_CONTEXT (context);
1689 source->source_funcs->finalize (source);
1691 LOCK_CONTEXT (context);
1694 g_free (source->name);
1695 source->name = NULL;
1697 g_slist_free (source->poll_fds);
1698 source->poll_fds = NULL;
1702 if (!have_lock && context)
1703 UNLOCK_CONTEXT (context);
1708 UNLOCK_CONTEXT (context);
1710 old_cb_funcs->unref (old_cb_data);
1713 LOCK_CONTEXT (context);
1719 * @source: a #GSource
1721 * Decreases the reference count of a source by one. If the
1722 * resulting reference count is zero the source and associated
1723 * memory will be destroyed.
1726 g_source_unref (GSource *source)
1728 g_return_if_fail (source != NULL);
1730 g_source_unref_internal (source, source->context, FALSE);
1734 * g_main_context_find_source_by_id:
1735 * @context: a #GMainContext (if %NULL, the default context will be used)
1736 * @source_id: the source ID, as returned by g_source_get_id().
1738 * Finds a #GSource given a pair of context and ID.
1740 * Return value: the #GSource if found, otherwise, %NULL
1743 g_main_context_find_source_by_id (GMainContext *context,
1748 g_return_val_if_fail (source_id > 0, NULL);
1750 if (context == NULL)
1751 context = g_main_context_default ();
1753 LOCK_CONTEXT (context);
1755 source = context->source_list;
1758 if (!SOURCE_DESTROYED (source) &&
1759 source->source_id == source_id)
1761 source = source->next;
1764 UNLOCK_CONTEXT (context);
1770 * g_main_context_find_source_by_funcs_user_data:
1771 * @context: a #GMainContext (if %NULL, the default context will be used).
1772 * @funcs: the @source_funcs passed to g_source_new().
1773 * @user_data: the user data from the callback.
1775 * Finds a source with the given source functions and user data. If
1776 * multiple sources exist with the same source function and user data,
1777 * the first one found will be returned.
1779 * Return value: the source, if one was found, otherwise %NULL
1782 g_main_context_find_source_by_funcs_user_data (GMainContext *context,
1783 GSourceFuncs *funcs,
1788 g_return_val_if_fail (funcs != NULL, NULL);
1790 if (context == NULL)
1791 context = g_main_context_default ();
1793 LOCK_CONTEXT (context);
1795 source = context->source_list;
1798 if (!SOURCE_DESTROYED (source) &&
1799 source->source_funcs == funcs &&
1800 source->callback_funcs)
1802 GSourceFunc callback;
1803 gpointer callback_data;
1805 source->callback_funcs->get (source->callback_data, source, &callback, &callback_data);
1807 if (callback_data == user_data)
1810 source = source->next;
1813 UNLOCK_CONTEXT (context);
1819 * g_main_context_find_source_by_user_data:
1820 * @context: a #GMainContext
1821 * @user_data: the user_data for the callback.
1823 * Finds a source with the given user data for the callback. If
1824 * multiple sources exist with the same user data, the first
1825 * one found will be returned.
1827 * Return value: the source, if one was found, otherwise %NULL
1830 g_main_context_find_source_by_user_data (GMainContext *context,
1835 if (context == NULL)
1836 context = g_main_context_default ();
1838 LOCK_CONTEXT (context);
1840 source = context->source_list;
1843 if (!SOURCE_DESTROYED (source) &&
1844 source->callback_funcs)
1846 GSourceFunc callback;
1847 gpointer callback_data = NULL;
1849 source->callback_funcs->get (source->callback_data, source, &callback, &callback_data);
1851 if (callback_data == user_data)
1854 source = source->next;
1857 UNLOCK_CONTEXT (context);
1864 * @tag: the ID of the source to remove.
1866 * Removes the source with the given id from the default main context.
1868 * a #GSource is given by g_source_get_id(), or will be returned by the
1869 * functions g_source_attach(), g_idle_add(), g_idle_add_full(),
1870 * g_timeout_add(), g_timeout_add_full(), g_child_watch_add(),
1871 * g_child_watch_add_full(), g_io_add_watch(), and g_io_add_watch_full().
1873 * See also g_source_destroy(). You must use g_source_destroy() for sources
1874 * added to a non-default main context.
1876 * Return value: %TRUE if the source was found and removed.
1879 g_source_remove (guint tag)
1883 g_return_val_if_fail (tag > 0, FALSE);
1885 source = g_main_context_find_source_by_id (NULL, tag);
1887 g_source_destroy (source);
1889 return source != NULL;
1893 * g_source_remove_by_user_data:
1894 * @user_data: the user_data for the callback.
1896 * Removes a source from the default main loop context given the user
1897 * data for the callback. If multiple sources exist with the same user
1898 * data, only one will be destroyed.
1900 * Return value: %TRUE if a source was found and removed.
1903 g_source_remove_by_user_data (gpointer user_data)
1907 source = g_main_context_find_source_by_user_data (NULL, user_data);
1910 g_source_destroy (source);
1918 * g_source_remove_by_funcs_user_data:
1919 * @funcs: The @source_funcs passed to g_source_new()
1920 * @user_data: the user data for the callback
1922 * Removes a source from the default main loop context given the
1923 * source functions and user data. If multiple sources exist with the
1924 * same source functions and user data, only one will be destroyed.
1926 * Return value: %TRUE if a source was found and removed.
1929 g_source_remove_by_funcs_user_data (GSourceFuncs *funcs,
1934 g_return_val_if_fail (funcs != NULL, FALSE);
1936 source = g_main_context_find_source_by_funcs_user_data (NULL, funcs, user_data);
1939 g_source_destroy (source);
1947 * g_get_current_time:
1948 * @result: #GTimeVal structure in which to store current time.
1950 * Equivalent to the UNIX gettimeofday() function, but portable.
1952 * You may find g_get_real_time() to be more convenient.
1955 g_get_current_time (GTimeVal *result)
1960 g_return_if_fail (result != NULL);
1962 /*this is required on alpha, there the timeval structs are int's
1963 not longs and a cast only would fail horribly*/
1964 gettimeofday (&r, NULL);
1965 result->tv_sec = r.tv_sec;
1966 result->tv_usec = r.tv_usec;
1971 g_return_if_fail (result != NULL);
1973 GetSystemTimeAsFileTime (&ft);
1974 memmove (&time64, &ft, sizeof (FILETIME));
1976 /* Convert from 100s of nanoseconds since 1601-01-01
1977 * to Unix epoch. Yes, this is Y2038 unsafe.
1979 time64 -= G_GINT64_CONSTANT (116444736000000000);
1982 result->tv_sec = time64 / 1000000;
1983 result->tv_usec = time64 % 1000000;
1990 * Queries the system wall-clock time.
1992 * This call is functionally equivalent to g_get_current_time() except
1993 * that the return value is often more convenient than dealing with a
1996 * You should only use this call if you are actually interested in the real
1997 * wall-clock time. g_get_monotonic_time() is probably more useful for
1998 * measuring intervals.
2000 * Returns: the number of microseconds since January 1, 1970 UTC.
2005 g_get_real_time (void)
2009 g_get_current_time (&tv);
2011 return (((gint64) tv.tv_sec) * 1000000) + tv.tv_usec;
2015 * g_get_monotonic_time:
2017 * Queries the system monotonic time, if available.
2019 * On POSIX systems with clock_gettime() and %CLOCK_MONOTONIC this call
2020 * is a very shallow wrapper for that. Otherwise, we make a best effort
2021 * that probably involves returning the wall clock time (with at least
2022 * microsecond accuracy, subject to the limitations of the OS kernel).
2024 * Note that, on Windows, "limitations of the OS kernel" is a rather
2025 * substantial statement. Depending on the configuration of the system,
2026 * the wall clock time is updated as infrequently as 64 times a second
2027 * (which is approximately every 16ms).
2029 * Returns: the monotonic time, in microseconds
2034 g_get_monotonic_time (void)
2036 #ifdef HAVE_CLOCK_GETTIME
2037 /* librt clock_gettime() is our first choice */
2039 static int clockid = CLOCK_REALTIME;
2042 #ifdef HAVE_MONOTONIC_CLOCK
2043 /* We have to check if we actually have monotonic clock support.
2045 * There is no thread safety issue here since there is no harm if we
2049 static gboolean checked;
2051 if G_UNLIKELY (!checked)
2053 if (sysconf (_SC_MONOTONIC_CLOCK) >= 0)
2054 clockid = CLOCK_MONOTONIC;
2060 clock_gettime (clockid, &ts);
2062 /* In theory monotonic time can have any epoch.
2064 * glib presently assumes the following:
2066 * 1) The epoch comes some time after the birth of Jesus of Nazareth, but
2067 * not more than 10000 years later.
2069 * 2) The current time also falls sometime within this range.
2071 * These two reasonable assumptions leave us with a maximum deviation from
2072 * the epoch of 10000 years, or 315569520000000000 seconds.
2074 * If we restrict ourselves to this range then the number of microseconds
2075 * will always fit well inside the constraints of a int64 (by a factor of
2078 * If you actually hit the following assertion, probably you should file a
2079 * bug against your operating system for being excessively silly.
2081 g_assert (G_GINT64_CONSTANT (-315569520000000000) < ts.tv_sec &&
2082 ts.tv_sec < G_GINT64_CONSTANT (315569520000000000));
2084 return (((gint64) ts.tv_sec) * 1000000) + (ts.tv_nsec / 1000);
2087 /* It may look like we are discarding accuracy on Windows (since its
2088 * current time is expressed in 100s of nanoseconds) but according to
2089 * many sources, the time is only updated 64 times per second, so
2090 * microsecond accuracy is more than enough.
2095 g_get_current_time (&tv);
2097 return (((gint64) tv.tv_sec) * 1000000) + tv.tv_usec;
2103 g_main_dispatch_free (gpointer dispatch)
2105 g_slice_free (GMainDispatch, dispatch);
2108 /* Running the main loop */
2110 static GMainDispatch *
2113 static GStaticPrivate depth_private = G_STATIC_PRIVATE_INIT;
2114 GMainDispatch *dispatch = g_static_private_get (&depth_private);
2117 dispatch = g_slice_new0 (GMainDispatch);
2118 g_static_private_set (&depth_private, dispatch, g_main_dispatch_free);
2127 * Returns the depth of the stack of calls to
2128 * g_main_context_dispatch() on any #GMainContext in the current thread.
2129 * That is, when called from the toplevel, it gives 0. When
2130 * called from within a callback from g_main_context_iteration()
2131 * (or g_main_loop_run(), etc.) it returns 1. When called from within
2132 * a callback to a recursive call to g_main_context_iterate(),
2133 * it returns 2. And so forth.
2135 * This function is useful in a situation like the following:
2136 * Imagine an extremely simple "garbage collected" system.
2139 * static GList *free_list;
2142 * allocate_memory (gsize size)
2144 * gpointer result = g_malloc (size);
2145 * free_list = g_list_prepend (free_list, result);
2150 * free_allocated_memory (void)
2153 * for (l = free_list; l; l = l->next);
2155 * g_list_free (free_list);
2163 * g_main_context_iteration (NULL, TRUE);
2164 * free_allocated_memory();
2168 * This works from an application, however, if you want to do the same
2169 * thing from a library, it gets more difficult, since you no longer
2170 * control the main loop. You might think you can simply use an idle
2171 * function to make the call to free_allocated_memory(), but that
2172 * doesn't work, since the idle function could be called from a
2173 * recursive callback. This can be fixed by using g_main_depth()
2177 * allocate_memory (gsize size)
2179 * FreeListBlock *block = g_new (FreeListBlock, 1);
2180 * block->mem = g_malloc (size);
2181 * block->depth = g_main_depth ();
2182 * free_list = g_list_prepend (free_list, block);
2183 * return block->mem;
2187 * free_allocated_memory (void)
2191 * int depth = g_main_depth ();
2192 * for (l = free_list; l; );
2194 * GList *next = l->next;
2195 * FreeListBlock *block = l->data;
2196 * if (block->depth > depth)
2198 * g_free (block->mem);
2200 * free_list = g_list_delete_link (free_list, l);
2208 * There is a temptation to use g_main_depth() to solve
2209 * problems with reentrancy. For instance, while waiting for data
2210 * to be received from the network in response to a menu item,
2211 * the menu item might be selected again. It might seem that
2212 * one could make the menu item's callback return immediately
2213 * and do nothing if g_main_depth() returns a value greater than 1.
2214 * However, this should be avoided since the user then sees selecting
2215 * the menu item do nothing. Furthermore, you'll find yourself adding
2216 * these checks all over your code, since there are doubtless many,
2217 * many things that the user could do. Instead, you can use the
2218 * following techniques:
2223 * Use gtk_widget_set_sensitive() or modal dialogs to prevent
2224 * the user from interacting with elements while the main
2225 * loop is recursing.
2230 * Avoid main loop recursion in situations where you can't handle
2231 * arbitrary callbacks. Instead, structure your code so that you
2232 * simply return to the main loop and then get called again when
2233 * there is more work to do.
2238 * Return value: The main loop recursion level in the current thread
2243 GMainDispatch *dispatch = get_dispatch ();
2244 return dispatch->depth;
2248 * g_main_current_source:
2250 * Returns the currently firing source for this thread.
2252 * Return value: The currently firing source or %NULL.
2257 g_main_current_source (void)
2259 GMainDispatch *dispatch = get_dispatch ();
2260 return dispatch->dispatching_sources ? dispatch->dispatching_sources->data : NULL;
2264 * g_source_is_destroyed:
2265 * @source: a #GSource
2267 * Returns whether @source has been destroyed.
2269 * This is important when you operate upon your objects
2270 * from within idle handlers, but may have freed the object
2271 * before the dispatch of your idle handler.
2275 * idle_callback (gpointer data)
2277 * SomeWidget *self = data;
2279 * GDK_THREADS_ENTER (<!-- -->);
2280 * /<!-- -->* do stuff with self *<!-- -->/
2281 * self->idle_id = 0;
2282 * GDK_THREADS_LEAVE (<!-- -->);
2288 * some_widget_do_stuff_later (SomeWidget *self)
2290 * self->idle_id = g_idle_add (idle_callback, self);
2294 * some_widget_finalize (GObject *object)
2296 * SomeWidget *self = SOME_WIDGET (object);
2298 * if (self->idle_id)
2299 * g_source_remove (self->idle_id);
2301 * G_OBJECT_CLASS (parent_class)->finalize (object);
2305 * This will fail in a multi-threaded application if the
2306 * widget is destroyed before the idle handler fires due
2307 * to the use after free in the callback. A solution, to
2308 * this particular problem, is to check to if the source
2309 * has already been destroy within the callback.
2313 * idle_callback (gpointer data)
2315 * SomeWidget *self = data;
2317 * GDK_THREADS_ENTER ();
2318 * if (!g_source_is_destroyed (g_main_current_source ()))
2320 * /<!-- -->* do stuff with self *<!-- -->/
2322 * GDK_THREADS_LEAVE ();
2328 * Return value: %TRUE if the source has been destroyed
2333 g_source_is_destroyed (GSource *source)
2335 return SOURCE_DESTROYED (source);
2338 /* Temporarily remove all this source's file descriptors from the
2339 * poll(), so that if data comes available for one of the file descriptors
2340 * we don't continually spin in the poll()
2342 /* HOLDS: source->context's lock */
2344 block_source (GSource *source)
2348 g_return_if_fail (!SOURCE_BLOCKED (source));
2350 tmp_list = source->poll_fds;
2353 g_main_context_remove_poll_unlocked (source->context, tmp_list->data);
2354 tmp_list = tmp_list->next;
2358 /* HOLDS: source->context's lock */
2360 unblock_source (GSource *source)
2364 g_return_if_fail (!SOURCE_BLOCKED (source)); /* Source already unblocked */
2365 g_return_if_fail (!SOURCE_DESTROYED (source));
2367 tmp_list = source->poll_fds;
2370 g_main_context_add_poll_unlocked (source->context, source->priority, tmp_list->data);
2371 tmp_list = tmp_list->next;
2375 /* HOLDS: context's lock */
2377 g_main_dispatch (GMainContext *context)
2379 GMainDispatch *current = get_dispatch ();
2382 for (i = 0; i < context->pending_dispatches->len; i++)
2384 GSource *source = context->pending_dispatches->pdata[i];
2386 context->pending_dispatches->pdata[i] = NULL;
2389 source->flags &= ~G_SOURCE_READY;
2391 if (!SOURCE_DESTROYED (source))
2393 gboolean was_in_call;
2394 gpointer user_data = NULL;
2395 GSourceFunc callback = NULL;
2396 GSourceCallbackFuncs *cb_funcs;
2398 gboolean need_destroy;
2400 gboolean (*dispatch) (GSource *,
2403 GSList current_source_link;
2405 dispatch = source->source_funcs->dispatch;
2406 cb_funcs = source->callback_funcs;
2407 cb_data = source->callback_data;
2410 cb_funcs->ref (cb_data);
2412 if ((source->flags & G_SOURCE_CAN_RECURSE) == 0)
2413 block_source (source);
2415 was_in_call = source->flags & G_HOOK_FLAG_IN_CALL;
2416 source->flags |= G_HOOK_FLAG_IN_CALL;
2419 cb_funcs->get (cb_data, source, &callback, &user_data);
2421 UNLOCK_CONTEXT (context);
2424 /* The on-stack allocation of the GSList is unconventional, but
2425 * we know that the lifetime of the link is bounded to this
2426 * function as the link is kept in a thread specific list and
2427 * not manipulated outside of this function and its descendants.
2428 * Avoiding the overhead of a g_slist_alloc() is useful as many
2429 * applications do little more than dispatch events.
2431 * This is a performance hack - do not revert to g_slist_prepend()!
2433 current_source_link.data = source;
2434 current_source_link.next = current->dispatching_sources;
2435 current->dispatching_sources = ¤t_source_link;
2436 need_destroy = ! dispatch (source,
2439 g_assert (current->dispatching_sources == ¤t_source_link);
2440 current->dispatching_sources = current_source_link.next;
2444 cb_funcs->unref (cb_data);
2446 LOCK_CONTEXT (context);
2449 source->flags &= ~G_HOOK_FLAG_IN_CALL;
2451 if ((source->flags & G_SOURCE_CAN_RECURSE) == 0 &&
2452 !SOURCE_DESTROYED (source))
2453 unblock_source (source);
2455 /* Note: this depends on the fact that we can't switch
2456 * sources from one main context to another
2458 if (need_destroy && !SOURCE_DESTROYED (source))
2460 g_assert (source->context == context);
2461 g_source_destroy_internal (source, context, TRUE);
2465 SOURCE_UNREF (source, context);
2468 g_ptr_array_set_size (context->pending_dispatches, 0);
2471 /* Holds context's lock */
2472 static inline GSource *
2473 next_valid_source (GMainContext *context,
2476 GSource *new_source = source ? source->next : context->source_list;
2480 if (!SOURCE_DESTROYED (new_source))
2482 new_source->ref_count++;
2486 new_source = new_source->next;
2490 SOURCE_UNREF (source, context);
2496 * g_main_context_acquire:
2497 * @context: a #GMainContext
2499 * Tries to become the owner of the specified context.
2500 * If some other thread is the owner of the context,
2501 * returns %FALSE immediately. Ownership is properly
2502 * recursive: the owner can require ownership again
2503 * and will release ownership when g_main_context_release()
2504 * is called as many times as g_main_context_acquire().
2506 * You must be the owner of a context before you
2507 * can call g_main_context_prepare(), g_main_context_query(),
2508 * g_main_context_check(), g_main_context_dispatch().
2510 * Return value: %TRUE if the operation succeeded, and
2511 * this thread is now the owner of @context.
2514 g_main_context_acquire (GMainContext *context)
2516 #ifdef G_THREADS_ENABLED
2517 gboolean result = FALSE;
2518 GThread *self = G_THREAD_SELF;
2520 if (context == NULL)
2521 context = g_main_context_default ();
2523 LOCK_CONTEXT (context);
2525 if (!context->owner)
2527 context->owner = self;
2528 g_assert (context->owner_count == 0);
2531 if (context->owner == self)
2533 context->owner_count++;
2537 UNLOCK_CONTEXT (context);
2540 #else /* !G_THREADS_ENABLED */
2542 #endif /* G_THREADS_ENABLED */
2546 * g_main_context_release:
2547 * @context: a #GMainContext
2549 * Releases ownership of a context previously acquired by this thread
2550 * with g_main_context_acquire(). If the context was acquired multiple
2551 * times, the ownership will be released only when g_main_context_release()
2552 * is called as many times as it was acquired.
2555 g_main_context_release (GMainContext *context)
2557 #ifdef G_THREADS_ENABLED
2558 if (context == NULL)
2559 context = g_main_context_default ();
2561 LOCK_CONTEXT (context);
2563 context->owner_count--;
2564 if (context->owner_count == 0)
2566 context->owner = NULL;
2568 if (context->waiters)
2570 GMainWaiter *waiter = context->waiters->data;
2571 gboolean loop_internal_waiter =
2572 (waiter->mutex == g_static_mutex_get_mutex (&context->mutex));
2573 context->waiters = g_slist_delete_link (context->waiters,
2575 if (!loop_internal_waiter)
2576 g_mutex_lock (waiter->mutex);
2578 g_cond_signal (waiter->cond);
2580 if (!loop_internal_waiter)
2581 g_mutex_unlock (waiter->mutex);
2585 UNLOCK_CONTEXT (context);
2586 #endif /* G_THREADS_ENABLED */
2590 * g_main_context_wait:
2591 * @context: a #GMainContext
2592 * @cond: a condition variable
2593 * @mutex: a mutex, currently held
2595 * Tries to become the owner of the specified context,
2596 * as with g_main_context_acquire(). But if another thread
2597 * is the owner, atomically drop @mutex and wait on @cond until
2598 * that owner releases ownership or until @cond is signaled, then
2599 * try again (once) to become the owner.
2601 * Return value: %TRUE if the operation succeeded, and
2602 * this thread is now the owner of @context.
2605 g_main_context_wait (GMainContext *context,
2609 #ifdef G_THREADS_ENABLED
2610 gboolean result = FALSE;
2611 GThread *self = G_THREAD_SELF;
2612 gboolean loop_internal_waiter;
2614 if (context == NULL)
2615 context = g_main_context_default ();
2617 loop_internal_waiter = (mutex == g_static_mutex_get_mutex (&context->mutex));
2619 if (!loop_internal_waiter)
2620 LOCK_CONTEXT (context);
2622 if (context->owner && context->owner != self)
2627 waiter.mutex = mutex;
2629 context->waiters = g_slist_append (context->waiters, &waiter);
2631 if (!loop_internal_waiter)
2632 UNLOCK_CONTEXT (context);
2633 g_cond_wait (cond, mutex);
2634 if (!loop_internal_waiter)
2635 LOCK_CONTEXT (context);
2637 context->waiters = g_slist_remove (context->waiters, &waiter);
2640 if (!context->owner)
2642 context->owner = self;
2643 g_assert (context->owner_count == 0);
2646 if (context->owner == self)
2648 context->owner_count++;
2652 if (!loop_internal_waiter)
2653 UNLOCK_CONTEXT (context);
2656 #else /* !G_THREADS_ENABLED */
2658 #endif /* G_THREADS_ENABLED */
2662 * g_main_context_prepare:
2663 * @context: a #GMainContext
2664 * @priority: location to store priority of highest priority
2665 * source already ready.
2667 * Prepares to poll sources within a main loop. The resulting information
2668 * for polling is determined by calling g_main_context_query ().
2670 * Return value: %TRUE if some source is ready to be dispatched
2674 g_main_context_prepare (GMainContext *context,
2679 gint current_priority = G_MAXINT;
2682 if (context == NULL)
2683 context = g_main_context_default ();
2685 LOCK_CONTEXT (context);
2687 context->time_is_fresh = FALSE;
2688 context->real_time_is_fresh = FALSE;
2690 if (context->in_check_or_prepare)
2692 g_warning ("g_main_context_prepare() called recursively from within a source's check() or "
2693 "prepare() member.");
2694 UNLOCK_CONTEXT (context);
2698 #ifdef G_THREADS_ENABLED
2699 if (context->poll_waiting)
2701 g_warning("g_main_context_prepare(): main loop already active in another thread");
2702 UNLOCK_CONTEXT (context);
2706 context->poll_waiting = TRUE;
2707 #endif /* G_THREADS_ENABLED */
2710 /* If recursing, finish up current dispatch, before starting over */
2711 if (context->pending_dispatches)
2714 g_main_dispatch (context, ¤t_time);
2716 UNLOCK_CONTEXT (context);
2721 /* If recursing, clear list of pending dispatches */
2723 for (i = 0; i < context->pending_dispatches->len; i++)
2725 if (context->pending_dispatches->pdata[i])
2726 SOURCE_UNREF ((GSource *)context->pending_dispatches->pdata[i], context);
2728 g_ptr_array_set_size (context->pending_dispatches, 0);
2730 /* Prepare all sources */
2732 context->timeout = -1;
2734 source = next_valid_source (context, NULL);
2737 gint source_timeout = -1;
2739 if ((n_ready > 0) && (source->priority > current_priority))
2741 SOURCE_UNREF (source, context);
2744 if (SOURCE_BLOCKED (source))
2747 if (!(source->flags & G_SOURCE_READY))
2750 gboolean (*prepare) (GSource *source,
2753 prepare = source->source_funcs->prepare;
2754 context->in_check_or_prepare++;
2755 UNLOCK_CONTEXT (context);
2757 result = (*prepare) (source, &source_timeout);
2759 LOCK_CONTEXT (context);
2760 context->in_check_or_prepare--;
2764 GSource *ready_source = source;
2766 while (ready_source)
2768 ready_source->flags |= G_SOURCE_READY;
2769 ready_source = ready_source->priv ? ready_source->priv->parent_source : NULL;
2774 if (source->flags & G_SOURCE_READY)
2777 current_priority = source->priority;
2778 context->timeout = 0;
2781 if (source_timeout >= 0)
2783 if (context->timeout < 0)
2784 context->timeout = source_timeout;
2786 context->timeout = MIN (context->timeout, source_timeout);
2790 source = next_valid_source (context, source);
2793 UNLOCK_CONTEXT (context);
2796 *priority = current_priority;
2798 return (n_ready > 0);
2802 * g_main_context_query:
2803 * @context: a #GMainContext
2804 * @max_priority: maximum priority source to check
2805 * @timeout_: location to store timeout to be used in polling
2806 * @fds: location to store #GPollFD records that need to be polled.
2807 * @n_fds: length of @fds.
2809 * Determines information necessary to poll this main loop.
2811 * Return value: the number of records actually stored in @fds,
2812 * or, if more than @n_fds records need to be stored, the number
2813 * of records that need to be stored.
2816 g_main_context_query (GMainContext *context,
2825 LOCK_CONTEXT (context);
2827 pollrec = context->poll_records;
2829 while (pollrec && max_priority >= pollrec->priority)
2831 /* We need to include entries with fd->events == 0 in the array because
2832 * otherwise if the application changes fd->events behind our back and
2833 * makes it non-zero, we'll be out of sync when we check the fds[] array.
2834 * (Changing fd->events after adding an FD wasn't an anticipated use of
2835 * this API, but it occurs in practice.) */
2838 fds[n_poll].fd = pollrec->fd->fd;
2839 /* In direct contradiction to the Unix98 spec, IRIX runs into
2840 * difficulty if you pass in POLLERR, POLLHUP or POLLNVAL
2841 * flags in the events field of the pollfd while it should
2842 * just ignoring them. So we mask them out here.
2844 fds[n_poll].events = pollrec->fd->events & ~(G_IO_ERR|G_IO_HUP|G_IO_NVAL);
2845 fds[n_poll].revents = 0;
2848 pollrec = pollrec->next;
2852 #ifdef G_THREADS_ENABLED
2853 context->poll_changed = FALSE;
2858 *timeout = context->timeout;
2861 context->time_is_fresh = FALSE;
2862 context->real_time_is_fresh = FALSE;
2866 UNLOCK_CONTEXT (context);
2872 * g_main_context_check:
2873 * @context: a #GMainContext
2874 * @max_priority: the maximum numerical priority of sources to check
2875 * @fds: array of #GPollFD's that was passed to the last call to
2876 * g_main_context_query()
2877 * @n_fds: return value of g_main_context_query()
2879 * Passes the results of polling back to the main loop.
2881 * Return value: %TRUE if some sources are ready to be dispatched.
2884 g_main_context_check (GMainContext *context,
2894 LOCK_CONTEXT (context);
2896 if (context->in_check_or_prepare)
2898 g_warning ("g_main_context_check() called recursively from within a source's check() or "
2899 "prepare() member.");
2900 UNLOCK_CONTEXT (context);
2904 #ifdef G_THREADS_ENABLED
2905 if (!context->poll_waiting)
2909 read (context->wake_up_pipe[0], &a, 1);
2913 context->poll_waiting = FALSE;
2915 /* If the set of poll file descriptors changed, bail out
2916 * and let the main loop rerun
2918 if (context->poll_changed)
2920 UNLOCK_CONTEXT (context);
2923 #endif /* G_THREADS_ENABLED */
2925 pollrec = context->poll_records;
2929 if (pollrec->fd->events)
2930 pollrec->fd->revents = fds[i].revents;
2932 pollrec = pollrec->next;
2936 source = next_valid_source (context, NULL);
2939 if ((n_ready > 0) && (source->priority > max_priority))
2941 SOURCE_UNREF (source, context);
2944 if (SOURCE_BLOCKED (source))
2947 if (!(source->flags & G_SOURCE_READY))
2950 gboolean (*check) (GSource *source);
2952 check = source->source_funcs->check;
2954 context->in_check_or_prepare++;
2955 UNLOCK_CONTEXT (context);
2957 result = (*check) (source);
2959 LOCK_CONTEXT (context);
2960 context->in_check_or_prepare--;
2964 GSource *ready_source = source;
2966 while (ready_source)
2968 ready_source->flags |= G_SOURCE_READY;
2969 ready_source = ready_source->priv ? ready_source->priv->parent_source : NULL;
2974 if (source->flags & G_SOURCE_READY)
2976 source->ref_count++;
2977 g_ptr_array_add (context->pending_dispatches, source);
2981 /* never dispatch sources with less priority than the first
2982 * one we choose to dispatch
2984 max_priority = source->priority;
2988 source = next_valid_source (context, source);
2991 UNLOCK_CONTEXT (context);
2997 * g_main_context_dispatch:
2998 * @context: a #GMainContext
3000 * Dispatches all pending sources.
3003 g_main_context_dispatch (GMainContext *context)
3005 LOCK_CONTEXT (context);
3007 if (context->pending_dispatches->len > 0)
3009 g_main_dispatch (context);
3012 UNLOCK_CONTEXT (context);
3015 /* HOLDS context lock */
3017 g_main_context_iterate (GMainContext *context,
3024 gboolean some_ready;
3025 gint nfds, allocated_nfds;
3026 GPollFD *fds = NULL;
3028 UNLOCK_CONTEXT (context);
3030 #ifdef G_THREADS_ENABLED
3031 if (!g_main_context_acquire (context))
3033 gboolean got_ownership;
3035 LOCK_CONTEXT (context);
3037 g_return_val_if_fail (g_thread_supported (), FALSE);
3043 context->cond = g_cond_new ();
3045 got_ownership = g_main_context_wait (context,
3047 g_static_mutex_get_mutex (&context->mutex));
3053 LOCK_CONTEXT (context);
3054 #endif /* G_THREADS_ENABLED */
3056 if (!context->cached_poll_array)
3058 context->cached_poll_array_size = context->n_poll_records;
3059 context->cached_poll_array = g_new (GPollFD, context->n_poll_records);
3062 allocated_nfds = context->cached_poll_array_size;
3063 fds = context->cached_poll_array;
3065 UNLOCK_CONTEXT (context);
3067 g_main_context_prepare (context, &max_priority);
3069 while ((nfds = g_main_context_query (context, max_priority, &timeout, fds,
3070 allocated_nfds)) > allocated_nfds)
3072 LOCK_CONTEXT (context);
3074 context->cached_poll_array_size = allocated_nfds = nfds;
3075 context->cached_poll_array = fds = g_new (GPollFD, nfds);
3076 UNLOCK_CONTEXT (context);
3082 g_main_context_poll (context, timeout, max_priority, fds, nfds);
3084 some_ready = g_main_context_check (context, max_priority, fds, nfds);
3087 g_main_context_dispatch (context);
3089 #ifdef G_THREADS_ENABLED
3090 g_main_context_release (context);
3091 #endif /* G_THREADS_ENABLED */
3093 LOCK_CONTEXT (context);
3099 * g_main_context_pending:
3100 * @context: a #GMainContext (if %NULL, the default context will be used)
3102 * Checks if any sources have pending events for the given context.
3104 * Return value: %TRUE if events are pending.
3107 g_main_context_pending (GMainContext *context)
3112 context = g_main_context_default();
3114 LOCK_CONTEXT (context);
3115 retval = g_main_context_iterate (context, FALSE, FALSE, G_THREAD_SELF);
3116 UNLOCK_CONTEXT (context);
3122 * g_main_context_iteration:
3123 * @context: a #GMainContext (if %NULL, the default context will be used)
3124 * @may_block: whether the call may block.
3126 * Runs a single iteration for the given main loop. This involves
3127 * checking to see if any event sources are ready to be processed,
3128 * then if no events sources are ready and @may_block is %TRUE, waiting
3129 * for a source to become ready, then dispatching the highest priority
3130 * events sources that are ready. Otherwise, if @may_block is %FALSE
3131 * sources are not waited to become ready, only those highest priority
3132 * events sources will be dispatched (if any), that are ready at this
3133 * given moment without further waiting.
3135 * Note that even when @may_block is %TRUE, it is still possible for
3136 * g_main_context_iteration() to return %FALSE, since the the wait may
3137 * be interrupted for other reasons than an event source becoming ready.
3139 * Return value: %TRUE if events were dispatched.
3142 g_main_context_iteration (GMainContext *context, gboolean may_block)
3147 context = g_main_context_default();
3149 LOCK_CONTEXT (context);
3150 retval = g_main_context_iterate (context, may_block, TRUE, G_THREAD_SELF);
3151 UNLOCK_CONTEXT (context);
3158 * @context: a #GMainContext (if %NULL, the default context will be used).
3159 * @is_running: set to %TRUE to indicate that the loop is running. This
3160 * is not very important since calling g_main_loop_run() will set this to
3163 * Creates a new #GMainLoop structure.
3165 * Return value: a new #GMainLoop.
3168 g_main_loop_new (GMainContext *context,
3169 gboolean is_running)
3174 context = g_main_context_default();
3176 g_main_context_ref (context);
3178 loop = g_new0 (GMainLoop, 1);
3179 loop->context = context;
3180 loop->is_running = is_running != FALSE;
3181 loop->ref_count = 1;
3188 * @loop: a #GMainLoop
3190 * Increases the reference count on a #GMainLoop object by one.
3192 * Return value: @loop
3195 g_main_loop_ref (GMainLoop *loop)
3197 g_return_val_if_fail (loop != NULL, NULL);
3198 g_return_val_if_fail (g_atomic_int_get (&loop->ref_count) > 0, NULL);
3200 g_atomic_int_inc (&loop->ref_count);
3206 * g_main_loop_unref:
3207 * @loop: a #GMainLoop
3209 * Decreases the reference count on a #GMainLoop object by one. If
3210 * the result is zero, free the loop and free all associated memory.
3213 g_main_loop_unref (GMainLoop *loop)
3215 g_return_if_fail (loop != NULL);
3216 g_return_if_fail (g_atomic_int_get (&loop->ref_count) > 0);
3218 if (!g_atomic_int_dec_and_test (&loop->ref_count))
3221 g_main_context_unref (loop->context);
3227 * @loop: a #GMainLoop
3229 * Runs a main loop until g_main_loop_quit() is called on the loop.
3230 * If this is called for the thread of the loop's #GMainContext,
3231 * it will process events from the loop, otherwise it will
3235 g_main_loop_run (GMainLoop *loop)
3237 GThread *self = G_THREAD_SELF;
3239 g_return_if_fail (loop != NULL);
3240 g_return_if_fail (g_atomic_int_get (&loop->ref_count) > 0);
3242 #ifdef G_THREADS_ENABLED
3243 if (!g_main_context_acquire (loop->context))
3245 gboolean got_ownership = FALSE;
3247 /* Another thread owns this context */
3248 if (!g_thread_supported ())
3250 g_warning ("g_main_loop_run() was called from second thread but "
3251 "g_thread_init() was never called.");
3255 LOCK_CONTEXT (loop->context);
3257 g_atomic_int_inc (&loop->ref_count);
3259 if (!loop->is_running)
3260 loop->is_running = TRUE;
3262 if (!loop->context->cond)
3263 loop->context->cond = g_cond_new ();
3265 while (loop->is_running && !got_ownership)
3266 got_ownership = g_main_context_wait (loop->context,
3267 loop->context->cond,
3268 g_static_mutex_get_mutex (&loop->context->mutex));
3270 if (!loop->is_running)
3272 UNLOCK_CONTEXT (loop->context);
3274 g_main_context_release (loop->context);
3275 g_main_loop_unref (loop);
3279 g_assert (got_ownership);
3282 LOCK_CONTEXT (loop->context);
3283 #endif /* G_THREADS_ENABLED */
3285 if (loop->context->in_check_or_prepare)
3287 g_warning ("g_main_loop_run(): called recursively from within a source's "
3288 "check() or prepare() member, iteration not possible.");
3292 g_atomic_int_inc (&loop->ref_count);
3293 loop->is_running = TRUE;
3294 while (loop->is_running)
3295 g_main_context_iterate (loop->context, TRUE, TRUE, self);
3297 UNLOCK_CONTEXT (loop->context);
3299 #ifdef G_THREADS_ENABLED
3300 g_main_context_release (loop->context);
3301 #endif /* G_THREADS_ENABLED */
3303 g_main_loop_unref (loop);
3308 * @loop: a #GMainLoop
3310 * Stops a #GMainLoop from running. Any calls to g_main_loop_run()
3311 * for the loop will return.
3313 * Note that sources that have already been dispatched when
3314 * g_main_loop_quit() is called will still be executed.
3317 g_main_loop_quit (GMainLoop *loop)
3319 g_return_if_fail (loop != NULL);
3320 g_return_if_fail (g_atomic_int_get (&loop->ref_count) > 0);
3322 LOCK_CONTEXT (loop->context);
3323 loop->is_running = FALSE;
3324 g_main_context_wakeup_unlocked (loop->context);
3326 #ifdef G_THREADS_ENABLED
3327 if (loop->context->cond)
3328 g_cond_broadcast (loop->context->cond);
3329 #endif /* G_THREADS_ENABLED */
3331 UNLOCK_CONTEXT (loop->context);
3335 * g_main_loop_is_running:
3336 * @loop: a #GMainLoop.
3338 * Checks to see if the main loop is currently being run via g_main_loop_run().
3340 * Return value: %TRUE if the mainloop is currently being run.
3343 g_main_loop_is_running (GMainLoop *loop)
3345 g_return_val_if_fail (loop != NULL, FALSE);
3346 g_return_val_if_fail (g_atomic_int_get (&loop->ref_count) > 0, FALSE);
3348 return loop->is_running;
3352 * g_main_loop_get_context:
3353 * @loop: a #GMainLoop.
3355 * Returns the #GMainContext of @loop.
3357 * Return value: the #GMainContext of @loop
3360 g_main_loop_get_context (GMainLoop *loop)
3362 g_return_val_if_fail (loop != NULL, NULL);
3363 g_return_val_if_fail (g_atomic_int_get (&loop->ref_count) > 0, NULL);
3365 return loop->context;
3368 /* HOLDS: context's lock */
3370 g_main_context_poll (GMainContext *context,
3376 #ifdef G_MAIN_POLL_DEBUG
3382 GPollFunc poll_func;
3384 if (n_fds || timeout != 0)
3386 #ifdef G_MAIN_POLL_DEBUG
3387 if (_g_main_poll_debug)
3389 g_print ("polling context=%p n=%d timeout=%d\n",
3390 context, n_fds, timeout);
3391 poll_timer = g_timer_new ();
3395 LOCK_CONTEXT (context);
3397 poll_func = context->poll_func;
3399 UNLOCK_CONTEXT (context);
3400 if ((*poll_func) (fds, n_fds, timeout) < 0 && errno != EINTR)
3403 g_warning ("poll(2) failed due to: %s.",
3404 g_strerror (errno));
3406 /* If g_poll () returns -1, it has already called g_warning() */
3410 #ifdef G_MAIN_POLL_DEBUG
3411 if (_g_main_poll_debug)
3413 LOCK_CONTEXT (context);
3415 g_print ("g_main_poll(%d) timeout: %d - elapsed %12.10f seconds",
3418 g_timer_elapsed (poll_timer, NULL));
3419 g_timer_destroy (poll_timer);
3420 pollrec = context->poll_records;
3422 while (pollrec != NULL)
3427 if (fds[i].fd == pollrec->fd->fd &&
3428 pollrec->fd->events &&
3431 g_print (" [" G_POLLFD_FORMAT " :", fds[i].fd);
3432 if (fds[i].revents & G_IO_IN)
3434 if (fds[i].revents & G_IO_OUT)
3436 if (fds[i].revents & G_IO_PRI)
3438 if (fds[i].revents & G_IO_ERR)
3440 if (fds[i].revents & G_IO_HUP)
3442 if (fds[i].revents & G_IO_NVAL)
3448 pollrec = pollrec->next;
3452 UNLOCK_CONTEXT (context);
3455 } /* if (n_fds || timeout != 0) */
3459 * g_main_context_add_poll:
3460 * @context: a #GMainContext (or %NULL for the default context)
3461 * @fd: a #GPollFD structure holding information about a file
3462 * descriptor to watch.
3463 * @priority: the priority for this file descriptor which should be
3464 * the same as the priority used for g_source_attach() to ensure that the
3465 * file descriptor is polled whenever the results may be needed.
3467 * Adds a file descriptor to the set of file descriptors polled for
3468 * this context. This will very seldomly be used directly. Instead
3469 * a typical event source will use g_source_add_poll() instead.
3472 g_main_context_add_poll (GMainContext *context,
3477 context = g_main_context_default ();
3479 g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
3480 g_return_if_fail (fd);
3482 LOCK_CONTEXT (context);
3483 g_main_context_add_poll_unlocked (context, priority, fd);
3484 UNLOCK_CONTEXT (context);
3487 /* HOLDS: main_loop_lock */
3489 g_main_context_add_poll_unlocked (GMainContext *context,
3493 GPollRec *lastrec, *pollrec;
3494 GPollRec *newrec = g_slice_new (GPollRec);
3496 /* This file descriptor may be checked before we ever poll */
3499 newrec->priority = priority;
3502 pollrec = context->poll_records;
3503 while (pollrec && priority >= pollrec->priority)
3506 pollrec = pollrec->next;
3510 lastrec->next = newrec;
3512 context->poll_records = newrec;
3514 newrec->next = pollrec;
3516 context->n_poll_records++;
3518 #ifdef G_THREADS_ENABLED
3519 context->poll_changed = TRUE;
3521 /* Now wake up the main loop if it is waiting in the poll() */
3522 g_main_context_wakeup_unlocked (context);
3527 * g_main_context_remove_poll:
3528 * @context:a #GMainContext
3529 * @fd: a #GPollFD descriptor previously added with g_main_context_add_poll()
3531 * Removes file descriptor from the set of file descriptors to be
3532 * polled for a particular context.
3535 g_main_context_remove_poll (GMainContext *context,
3539 context = g_main_context_default ();
3541 g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
3542 g_return_if_fail (fd);
3544 LOCK_CONTEXT (context);
3545 g_main_context_remove_poll_unlocked (context, fd);
3546 UNLOCK_CONTEXT (context);
3550 g_main_context_remove_poll_unlocked (GMainContext *context,
3553 GPollRec *pollrec, *lastrec;
3556 pollrec = context->poll_records;
3560 if (pollrec->fd == fd)
3562 if (lastrec != NULL)
3563 lastrec->next = pollrec->next;
3565 context->poll_records = pollrec->next;
3567 g_slice_free (GPollRec, pollrec);
3569 context->n_poll_records--;
3573 pollrec = pollrec->next;
3576 #ifdef G_THREADS_ENABLED
3577 context->poll_changed = TRUE;
3579 /* Now wake up the main loop if it is waiting in the poll() */
3580 g_main_context_wakeup_unlocked (context);
3585 * g_source_get_current_time:
3586 * @source: a #GSource
3587 * @timeval: #GTimeVal structure in which to store current time.
3589 * Gets the "current time" to be used when checking
3590 * this source. The advantage of calling this function over
3591 * calling g_get_current_time() directly is that when
3592 * checking multiple sources, GLib can cache a single value
3593 * instead of having to repeatedly get the system time.
3595 * Deprecated: 2.28: use g_source_get_time() instead
3598 g_source_get_current_time (GSource *source,
3601 GMainContext *context;
3603 g_return_if_fail (source->context != NULL);
3605 context = source->context;
3607 LOCK_CONTEXT (context);
3609 if (!context->real_time_is_fresh)
3611 context->real_time = g_get_real_time ();
3612 context->real_time_is_fresh = TRUE;
3615 timeval->tv_sec = context->real_time / 1000000;
3616 timeval->tv_usec = context->real_time % 1000000;
3618 UNLOCK_CONTEXT (context);
3622 * g_source_get_time:
3623 * @source: a #GSource
3625 * Gets the time to be used when checking this source. The advantage of
3626 * calling this function over calling g_get_monotonic_time() directly is
3627 * that when checking multiple sources, GLib can cache a single value
3628 * instead of having to repeatedly get the system monotonic time.
3630 * The time here is the system monotonic time, if available, or some
3631 * other reasonable alternative otherwise. See g_get_monotonic_time().
3633 * Returns: the monotonic time in microseconds
3638 g_source_get_time (GSource *source)
3640 GMainContext *context;
3643 g_return_val_if_fail (source->context != NULL, 0);
3645 context = source->context;
3647 LOCK_CONTEXT (context);
3649 if (!context->time_is_fresh)
3651 context->time = g_get_monotonic_time ();
3652 context->time_is_fresh = TRUE;
3655 result = context->time;
3657 UNLOCK_CONTEXT (context);
3663 * g_main_context_set_poll_func:
3664 * @context: a #GMainContext
3665 * @func: the function to call to poll all file descriptors
3667 * Sets the function to use to handle polling of file descriptors. It
3668 * will be used instead of the poll() system call
3669 * (or GLib's replacement function, which is used where
3670 * poll() isn't available).
3672 * This function could possibly be used to integrate the GLib event
3673 * loop with an external event loop.
3676 g_main_context_set_poll_func (GMainContext *context,
3680 context = g_main_context_default ();
3682 g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
3684 LOCK_CONTEXT (context);
3687 context->poll_func = func;
3689 context->poll_func = g_poll;
3691 UNLOCK_CONTEXT (context);
3695 * g_main_context_get_poll_func:
3696 * @context: a #GMainContext
3698 * Gets the poll function set by g_main_context_set_poll_func().
3700 * Return value: the poll function
3703 g_main_context_get_poll_func (GMainContext *context)
3708 context = g_main_context_default ();
3710 g_return_val_if_fail (g_atomic_int_get (&context->ref_count) > 0, NULL);
3712 LOCK_CONTEXT (context);
3713 result = context->poll_func;
3714 UNLOCK_CONTEXT (context);
3719 /* HOLDS: context's lock */
3720 /* Wake the main loop up from a poll() */
3722 g_main_context_wakeup_unlocked (GMainContext *context)
3724 #ifdef G_THREADS_ENABLED
3725 if (g_thread_supported() && context->poll_waiting)
3727 context->poll_waiting = FALSE;
3729 write (context->wake_up_pipe[1], "A", 1);
3731 ReleaseSemaphore (context->wake_up_semaphore, 1, NULL);
3738 * g_main_context_wakeup:
3739 * @context: a #GMainContext
3741 * If @context is currently waiting in a poll(), interrupt
3742 * the poll(), and continue the iteration process.
3745 g_main_context_wakeup (GMainContext *context)
3748 context = g_main_context_default ();
3750 g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
3752 LOCK_CONTEXT (context);
3753 g_main_context_wakeup_unlocked (context);
3754 UNLOCK_CONTEXT (context);
3758 * g_main_context_is_owner:
3759 * @context: a #GMainContext
3761 * Determines whether this thread holds the (recursive)
3762 * ownership of this #GMaincontext. This is useful to
3763 * know before waiting on another thread that may be
3764 * blocking to get ownership of @context.
3766 * Returns: %TRUE if current thread is owner of @context.
3771 g_main_context_is_owner (GMainContext *context)
3776 context = g_main_context_default ();
3778 #ifdef G_THREADS_ENABLED
3779 LOCK_CONTEXT (context);
3780 is_owner = context->owner == G_THREAD_SELF;
3781 UNLOCK_CONTEXT (context);
3792 g_timeout_set_expiration (GTimeoutSource *timeout_source,
3793 gint64 current_time)
3795 timeout_source->expiration = current_time + timeout_source->interval * 1000;
3797 if (timeout_source->seconds)
3799 static gint timer_perturb = -1;
3801 if (timer_perturb == -1)
3804 * we want a per machine/session unique 'random' value; try the dbus
3805 * address first, that has a UUID in it. If there is no dbus, use the
3806 * hostname for hashing.
3808 const char *session_bus_address = g_getenv ("DBUS_SESSION_BUS_ADDRESS");
3809 if (!session_bus_address)
3810 session_bus_address = g_getenv ("HOSTNAME");
3811 if (session_bus_address)
3812 timer_perturb = ABS ((gint) g_str_hash (session_bus_address)) % 1000000;
3817 /* We want the microseconds part of the timeout to land on the
3818 * 'timer_perturb' mark, but we need to make sure we don't try to
3819 * set the timeout in the past. We do this by ensuring that we
3820 * always only *increase* the expiration time by adding a full
3821 * second in the case that the microsecond portion decreases.
3823 if (timer_perturb < timeout_source->expiration % 1000000)
3824 timeout_source->expiration += 1000000;
3826 timeout_source->expiration =
3827 ((timeout_source->expiration / 1000000) * 1000000) + timer_perturb;
3832 g_timeout_prepare (GSource *source,
3835 GTimeoutSource *timeout_source = (GTimeoutSource *) source;
3836 gint64 now = g_source_get_time (source);
3838 if (now < timeout_source->expiration)
3840 /* Round up to ensure that we don't try again too early */
3841 *timeout = (timeout_source->expiration - now + 999) / 1000;
3850 g_timeout_check (GSource *source)
3852 GTimeoutSource *timeout_source = (GTimeoutSource *) source;
3853 gint64 now = g_source_get_time (source);
3855 return timeout_source->expiration <= now;
3859 g_timeout_dispatch (GSource *source,
3860 GSourceFunc callback,
3863 GTimeoutSource *timeout_source = (GTimeoutSource *)source;
3868 g_warning ("Timeout source dispatched without callback\n"
3869 "You must call g_source_set_callback().");
3873 again = callback (user_data);
3876 g_timeout_set_expiration (timeout_source, g_source_get_time (source));
3882 * g_timeout_source_new:
3883 * @interval: the timeout interval in milliseconds.
3885 * Creates a new timeout source.
3887 * The source will not initially be associated with any #GMainContext
3888 * and must be added to one with g_source_attach() before it will be
3891 * Return value: the newly-created timeout source
3894 g_timeout_source_new (guint interval)
3896 GSource *source = g_source_new (&g_timeout_funcs, sizeof (GTimeoutSource));
3897 GTimeoutSource *timeout_source = (GTimeoutSource *)source;
3899 timeout_source->interval = interval;
3900 g_timeout_set_expiration (timeout_source, g_get_monotonic_time ());
3906 * g_timeout_source_new_seconds:
3907 * @interval: the timeout interval in seconds
3909 * Creates a new timeout source.
3911 * The source will not initially be associated with any #GMainContext
3912 * and must be added to one with g_source_attach() before it will be
3915 * The scheduling granularity/accuracy of this timeout source will be
3918 * Return value: the newly-created timeout source
3923 g_timeout_source_new_seconds (guint interval)
3925 GSource *source = g_source_new (&g_timeout_funcs, sizeof (GTimeoutSource));
3926 GTimeoutSource *timeout_source = (GTimeoutSource *)source;
3928 timeout_source->interval = 1000 * interval;
3929 timeout_source->seconds = TRUE;
3931 g_timeout_set_expiration (timeout_source, g_get_monotonic_time ());
3938 * g_timeout_add_full:
3939 * @priority: the priority of the timeout source. Typically this will be in
3940 * the range between #G_PRIORITY_DEFAULT and #G_PRIORITY_HIGH.
3941 * @interval: the time between calls to the function, in milliseconds
3942 * (1/1000ths of a second)
3943 * @function: function to call
3944 * @data: data to pass to @function
3945 * @notify: function to call when the timeout is removed, or %NULL
3947 * Sets a function to be called at regular intervals, with the given
3948 * priority. The function is called repeatedly until it returns
3949 * %FALSE, at which point the timeout is automatically destroyed and
3950 * the function will not be called again. The @notify function is
3951 * called when the timeout is destroyed. The first call to the
3952 * function will be at the end of the first @interval.
3954 * Note that timeout functions may be delayed, due to the processing of other
3955 * event sources. Thus they should not be relied on for precise timing.
3956 * After each call to the timeout function, the time of the next
3957 * timeout is recalculated based on the current time and the given interval
3958 * (it does not try to 'catch up' time lost in delays).
3960 * This internally creates a main loop source using g_timeout_source_new()
3961 * and attaches it to the main loop context using g_source_attach(). You can
3962 * do these steps manually if you need greater control.
3964 * Return value: the ID (greater than 0) of the event source.
3967 g_timeout_add_full (gint priority,
3969 GSourceFunc function,
3971 GDestroyNotify notify)
3976 g_return_val_if_fail (function != NULL, 0);
3978 source = g_timeout_source_new (interval);
3980 if (priority != G_PRIORITY_DEFAULT)
3981 g_source_set_priority (source, priority);
3983 g_source_set_callback (source, function, data, notify);
3984 id = g_source_attach (source, NULL);
3985 g_source_unref (source);
3992 * @interval: the time between calls to the function, in milliseconds
3993 * (1/1000ths of a second)
3994 * @function: function to call
3995 * @data: data to pass to @function
3997 * Sets a function to be called at regular intervals, with the default
3998 * priority, #G_PRIORITY_DEFAULT. The function is called repeatedly
3999 * until it returns %FALSE, at which point the timeout is automatically
4000 * destroyed and the function will not be called again. The first call
4001 * to the function will be at the end of the first @interval.
4003 * Note that timeout functions may be delayed, due to the processing of other
4004 * event sources. Thus they should not be relied on for precise timing.
4005 * After each call to the timeout function, the time of the next
4006 * timeout is recalculated based on the current time and the given interval
4007 * (it does not try to 'catch up' time lost in delays).
4009 * If you want to have a timer in the "seconds" range and do not care
4010 * about the exact time of the first call of the timer, use the
4011 * g_timeout_add_seconds() function; this function allows for more
4012 * optimizations and more efficient system power usage.
4014 * This internally creates a main loop source using g_timeout_source_new()
4015 * and attaches it to the main loop context using g_source_attach(). You can
4016 * do these steps manually if you need greater control.
4018 * Return value: the ID (greater than 0) of the event source.
4021 g_timeout_add (guint32 interval,
4022 GSourceFunc function,
4025 return g_timeout_add_full (G_PRIORITY_DEFAULT,
4026 interval, function, data, NULL);
4030 * g_timeout_add_seconds_full:
4031 * @priority: the priority of the timeout source. Typically this will be in
4032 * the range between #G_PRIORITY_DEFAULT and #G_PRIORITY_HIGH.
4033 * @interval: the time between calls to the function, in seconds
4034 * @function: function to call
4035 * @data: data to pass to @function
4036 * @notify: function to call when the timeout is removed, or %NULL
4038 * Sets a function to be called at regular intervals, with @priority.
4039 * The function is called repeatedly until it returns %FALSE, at which
4040 * point the timeout is automatically destroyed and the function will
4041 * not be called again.
4043 * Unlike g_timeout_add(), this function operates at whole second granularity.
4044 * The initial starting point of the timer is determined by the implementation
4045 * and the implementation is expected to group multiple timers together so that
4046 * they fire all at the same time.
4047 * To allow this grouping, the @interval to the first timer is rounded
4048 * and can deviate up to one second from the specified interval.
4049 * Subsequent timer iterations will generally run at the specified interval.
4051 * Note that timeout functions may be delayed, due to the processing of other
4052 * event sources. Thus they should not be relied on for precise timing.
4053 * After each call to the timeout function, the time of the next
4054 * timeout is recalculated based on the current time and the given @interval
4056 * If you want timing more precise than whole seconds, use g_timeout_add()
4059 * The grouping of timers to fire at the same time results in a more power
4060 * and CPU efficient behavior so if your timer is in multiples of seconds
4061 * and you don't require the first timer exactly one second from now, the
4062 * use of g_timeout_add_seconds() is preferred over g_timeout_add().
4064 * This internally creates a main loop source using
4065 * g_timeout_source_new_seconds() and attaches it to the main loop context
4066 * using g_source_attach(). You can do these steps manually if you need
4069 * Return value: the ID (greater than 0) of the event source.
4074 g_timeout_add_seconds_full (gint priority,
4076 GSourceFunc function,
4078 GDestroyNotify notify)
4083 g_return_val_if_fail (function != NULL, 0);
4085 source = g_timeout_source_new_seconds (interval);
4087 if (priority != G_PRIORITY_DEFAULT)
4088 g_source_set_priority (source, priority);
4090 g_source_set_callback (source, function, data, notify);
4091 id = g_source_attach (source, NULL);
4092 g_source_unref (source);
4098 * g_timeout_add_seconds:
4099 * @interval: the time between calls to the function, in seconds
4100 * @function: function to call
4101 * @data: data to pass to @function
4103 * Sets a function to be called at regular intervals with the default
4104 * priority, #G_PRIORITY_DEFAULT. The function is called repeatedly until
4105 * it returns %FALSE, at which point the timeout is automatically destroyed
4106 * and the function will not be called again.
4108 * This internally creates a main loop source using
4109 * g_timeout_source_new_seconds() and attaches it to the main loop context
4110 * using g_source_attach(). You can do these steps manually if you need
4111 * greater control. Also see g_timout_add_seconds_full().
4113 * Return value: the ID (greater than 0) of the event source.
4118 g_timeout_add_seconds (guint interval,
4119 GSourceFunc function,
4122 g_return_val_if_fail (function != NULL, 0);
4124 return g_timeout_add_seconds_full (G_PRIORITY_DEFAULT, interval, function, data, NULL);
4127 /* Child watch functions */
4132 g_child_watch_prepare (GSource *source,
4141 g_child_watch_check (GSource *source)
4143 GChildWatchSource *child_watch_source;
4144 gboolean child_exited;
4146 child_watch_source = (GChildWatchSource *) source;
4148 child_exited = child_watch_source->poll.revents & G_IO_IN;
4155 * Note: We do _not_ check for the special value of STILL_ACTIVE
4156 * since we know that the process has exited and doing so runs into
4157 * problems if the child process "happens to return STILL_ACTIVE(259)"
4158 * as Microsoft's Platform SDK puts it.
4160 if (!GetExitCodeProcess (child_watch_source->pid, &child_status))
4162 gchar *emsg = g_win32_error_message (GetLastError ());
4163 g_warning (G_STRLOC ": GetExitCodeProcess() failed: %s", emsg);
4166 child_watch_source->child_status = -1;
4169 child_watch_source->child_status = child_status;
4172 return child_exited;
4175 #else /* G_OS_WIN32 */
4178 check_for_child_exited (GSource *source)
4180 GChildWatchSource *child_watch_source;
4183 /* protect against another SIGCHLD in the middle of this call */
4184 count = child_watch_count;
4186 child_watch_source = (GChildWatchSource *) source;
4188 if (child_watch_source->child_exited)
4191 if (child_watch_source->count < count)
4195 if (waitpid (child_watch_source->pid, &child_status, WNOHANG) > 0)
4197 child_watch_source->child_status = child_status;
4198 child_watch_source->child_exited = TRUE;
4200 child_watch_source->count = count;
4203 return child_watch_source->child_exited;
4207 g_child_watch_prepare (GSource *source,
4212 return check_for_child_exited (source);
4217 g_child_watch_check (GSource *source)
4219 return check_for_child_exited (source);
4222 #endif /* G_OS_WIN32 */
4225 g_child_watch_dispatch (GSource *source,
4226 GSourceFunc callback,
4229 GChildWatchSource *child_watch_source;
4230 GChildWatchFunc child_watch_callback = (GChildWatchFunc) callback;
4232 child_watch_source = (GChildWatchSource *) source;
4236 g_warning ("Child watch source dispatched without callback\n"
4237 "You must call g_source_set_callback().");
4241 (child_watch_callback) (child_watch_source->pid, child_watch_source->child_status, user_data);
4243 /* We never keep a child watch source around as the child is gone */
4250 g_child_watch_signal_handler (int signum)
4252 child_watch_count ++;
4254 if (child_watch_init_state == CHILD_WATCH_INITIALIZED_THREADED)
4256 write (child_watch_wake_up_pipe[1], "B", 1);
4260 /* We count on the signal interrupting the poll in the same thread.
4266 g_child_watch_source_init_single (void)
4268 struct sigaction action;
4270 g_assert (! g_thread_supported());
4271 g_assert (child_watch_init_state == CHILD_WATCH_UNINITIALIZED);
4273 child_watch_init_state = CHILD_WATCH_INITIALIZED_SINGLE;
4275 action.sa_handler = g_child_watch_signal_handler;
4276 sigemptyset (&action.sa_mask);
4277 action.sa_flags = SA_NOCLDSTOP;
4278 sigaction (SIGCHLD, &action, NULL);
4281 G_GNUC_NORETURN static gpointer
4282 child_watch_helper_thread (gpointer data)
4289 read (child_watch_wake_up_pipe[0], b, 20);
4291 /* We were woken up. Wake up all other contexts in all other threads */
4292 G_LOCK (main_context_list);
4293 for (list = main_context_list; list; list = list->next)
4295 GMainContext *context;
4297 context = list->data;
4298 if (g_atomic_int_get (&context->ref_count) > 0)
4299 /* Due to racing conditions we can find ref_count == 0, in
4300 * that case, however, the context is still not destroyed
4301 * and no poll can be active, otherwise the ref_count
4303 g_main_context_wakeup (context);
4305 G_UNLOCK (main_context_list);
4310 g_child_watch_source_init_multi_threaded (void)
4312 GError *error = NULL;
4313 struct sigaction action;
4315 g_assert (g_thread_supported());
4317 if (pipe (child_watch_wake_up_pipe) < 0)
4318 g_error ("Cannot create wake up pipe: %s\n", g_strerror (errno));
4319 fcntl (child_watch_wake_up_pipe[1], F_SETFL, O_NONBLOCK | fcntl (child_watch_wake_up_pipe[1], F_GETFL));
4321 /* We create a helper thread that polls on the wakeup pipe indefinitely */
4322 /* FIXME: Think this through for races */
4323 if (g_thread_create (child_watch_helper_thread, NULL, FALSE, &error) == NULL)
4324 g_error ("Cannot create a thread to monitor child exit status: %s\n", error->message);
4325 child_watch_init_state = CHILD_WATCH_INITIALIZED_THREADED;
4327 action.sa_handler = g_child_watch_signal_handler;
4328 sigemptyset (&action.sa_mask);
4329 action.sa_flags = SA_RESTART | SA_NOCLDSTOP;
4330 sigaction (SIGCHLD, &action, NULL);
4334 g_child_watch_source_init_promote_single_to_threaded (void)
4336 g_child_watch_source_init_multi_threaded ();
4340 g_child_watch_source_init (void)
4342 if (g_thread_supported())
4344 if (child_watch_init_state == CHILD_WATCH_UNINITIALIZED)
4345 g_child_watch_source_init_multi_threaded ();
4346 else if (child_watch_init_state == CHILD_WATCH_INITIALIZED_SINGLE)
4347 g_child_watch_source_init_promote_single_to_threaded ();
4351 if (child_watch_init_state == CHILD_WATCH_UNINITIALIZED)
4352 g_child_watch_source_init_single ();
4356 #endif /* !G_OS_WIN32 */
4359 * g_child_watch_source_new:
4360 * @pid: process to watch. On POSIX the pid of a child process. On
4361 * Windows a handle for a process (which doesn't have to be a child).
4363 * Creates a new child_watch source.
4365 * The source will not initially be associated with any #GMainContext
4366 * and must be added to one with g_source_attach() before it will be
4369 * Note that child watch sources can only be used in conjunction with
4370 * <literal>g_spawn...</literal> when the %G_SPAWN_DO_NOT_REAP_CHILD
4373 * Note that on platforms where #GPid must be explicitly closed
4374 * (see g_spawn_close_pid()) @pid must not be closed while the
4375 * source is still active. Typically, you will want to call
4376 * g_spawn_close_pid() in the callback function for the source.
4378 * Note further that using g_child_watch_source_new() is not
4379 * compatible with calling <literal>waitpid(-1)</literal> in
4380 * the application. Calling waitpid() for individual pids will
4383 * Return value: the newly-created child watch source
4388 g_child_watch_source_new (GPid pid)
4390 GSource *source = g_source_new (&g_child_watch_funcs, sizeof (GChildWatchSource));
4391 GChildWatchSource *child_watch_source = (GChildWatchSource *)source;
4394 child_watch_source->poll.fd = (gintptr) pid;
4395 child_watch_source->poll.events = G_IO_IN;
4397 g_source_add_poll (source, &child_watch_source->poll);
4398 #else /* G_OS_WIN32 */
4399 g_child_watch_source_init ();
4400 #endif /* G_OS_WIN32 */
4402 child_watch_source->pid = pid;
4408 * g_child_watch_add_full:
4409 * @priority: the priority of the idle source. Typically this will be in the
4410 * range between #G_PRIORITY_DEFAULT_IDLE and #G_PRIORITY_HIGH_IDLE.
4411 * @pid: process to watch. On POSIX the pid of a child process. On
4412 * Windows a handle for a process (which doesn't have to be a child).
4413 * @function: function to call
4414 * @data: data to pass to @function
4415 * @notify: function to call when the idle is removed, or %NULL
4417 * Sets a function to be called when the child indicated by @pid
4418 * exits, at the priority @priority.
4420 * If you obtain @pid from g_spawn_async() or g_spawn_async_with_pipes()
4421 * you will need to pass #G_SPAWN_DO_NOT_REAP_CHILD as flag to
4422 * the spawn function for the child watching to work.
4424 * Note that on platforms where #GPid must be explicitly closed
4425 * (see g_spawn_close_pid()) @pid must not be closed while the
4426 * source is still active. Typically, you will want to call
4427 * g_spawn_close_pid() in the callback function for the source.
4429 * GLib supports only a single callback per process id.
4431 * This internally creates a main loop source using
4432 * g_child_watch_source_new() and attaches it to the main loop context
4433 * using g_source_attach(). You can do these steps manually if you
4434 * need greater control.
4436 * Return value: the ID (greater than 0) of the event source.
4441 g_child_watch_add_full (gint priority,
4443 GChildWatchFunc function,
4445 GDestroyNotify notify)
4450 g_return_val_if_fail (function != NULL, 0);
4452 source = g_child_watch_source_new (pid);
4454 if (priority != G_PRIORITY_DEFAULT)
4455 g_source_set_priority (source, priority);
4457 g_source_set_callback (source, (GSourceFunc) function, data, notify);
4458 id = g_source_attach (source, NULL);
4459 g_source_unref (source);
4465 * g_child_watch_add:
4466 * @pid: process id to watch. On POSIX the pid of a child process. On
4467 * Windows a handle for a process (which doesn't have to be a child).
4468 * @function: function to call
4469 * @data: data to pass to @function
4471 * Sets a function to be called when the child indicated by @pid
4472 * exits, at a default priority, #G_PRIORITY_DEFAULT.
4474 * If you obtain @pid from g_spawn_async() or g_spawn_async_with_pipes()
4475 * you will need to pass #G_SPAWN_DO_NOT_REAP_CHILD as flag to
4476 * the spawn function for the child watching to work.
4478 * Note that on platforms where #GPid must be explicitly closed
4479 * (see g_spawn_close_pid()) @pid must not be closed while the
4480 * source is still active. Typically, you will want to call
4481 * g_spawn_close_pid() in the callback function for the source.
4483 * GLib supports only a single callback per process id.
4485 * This internally creates a main loop source using
4486 * g_child_watch_source_new() and attaches it to the main loop context
4487 * using g_source_attach(). You can do these steps manually if you
4488 * need greater control.
4490 * Return value: the ID (greater than 0) of the event source.
4495 g_child_watch_add (GPid pid,
4496 GChildWatchFunc function,
4499 return g_child_watch_add_full (G_PRIORITY_DEFAULT, pid, function, data, NULL);
4503 /* Idle functions */
4506 g_idle_prepare (GSource *source,
4515 g_idle_check (GSource *source)
4521 g_idle_dispatch (GSource *source,
4522 GSourceFunc callback,
4527 g_warning ("Idle source dispatched without callback\n"
4528 "You must call g_source_set_callback().");
4532 return callback (user_data);
4536 * g_idle_source_new:
4538 * Creates a new idle source.
4540 * The source will not initially be associated with any #GMainContext
4541 * and must be added to one with g_source_attach() before it will be
4542 * executed. Note that the default priority for idle sources is
4543 * %G_PRIORITY_DEFAULT_IDLE, as compared to other sources which
4544 * have a default priority of %G_PRIORITY_DEFAULT.
4546 * Return value: the newly-created idle source
4549 g_idle_source_new (void)
4553 source = g_source_new (&g_idle_funcs, sizeof (GSource));
4554 g_source_set_priority (source, G_PRIORITY_DEFAULT_IDLE);
4561 * @priority: the priority of the idle source. Typically this will be in the
4562 * range between #G_PRIORITY_DEFAULT_IDLE and #G_PRIORITY_HIGH_IDLE.
4563 * @function: function to call
4564 * @data: data to pass to @function
4565 * @notify: function to call when the idle is removed, or %NULL
4567 * Adds a function to be called whenever there are no higher priority
4568 * events pending. If the function returns %FALSE it is automatically
4569 * removed from the list of event sources and will not be called again.
4571 * This internally creates a main loop source using g_idle_source_new()
4572 * and attaches it to the main loop context using g_source_attach().
4573 * You can do these steps manually if you need greater control.
4575 * Return value: the ID (greater than 0) of the event source.
4578 g_idle_add_full (gint priority,
4579 GSourceFunc function,
4581 GDestroyNotify notify)
4586 g_return_val_if_fail (function != NULL, 0);
4588 source = g_idle_source_new ();
4590 if (priority != G_PRIORITY_DEFAULT_IDLE)
4591 g_source_set_priority (source, priority);
4593 g_source_set_callback (source, function, data, notify);
4594 id = g_source_attach (source, NULL);
4595 g_source_unref (source);
4602 * @function: function to call
4603 * @data: data to pass to @function.
4605 * Adds a function to be called whenever there are no higher priority
4606 * events pending to the default main loop. The function is given the
4607 * default idle priority, #G_PRIORITY_DEFAULT_IDLE. If the function
4608 * returns %FALSE it is automatically removed from the list of event
4609 * sources and will not be called again.
4611 * This internally creates a main loop source using g_idle_source_new()
4612 * and attaches it to the main loop context using g_source_attach().
4613 * You can do these steps manually if you need greater control.
4615 * Return value: the ID (greater than 0) of the event source.
4618 g_idle_add (GSourceFunc function,
4621 return g_idle_add_full (G_PRIORITY_DEFAULT_IDLE, function, data, NULL);
4625 * g_idle_remove_by_data:
4626 * @data: the data for the idle source's callback.
4628 * Removes the idle function with the given data.
4630 * Return value: %TRUE if an idle source was found and removed.
4633 g_idle_remove_by_data (gpointer data)
4635 return g_source_remove_by_funcs_user_data (&g_idle_funcs, data);
4639 * g_main_context_invoke:
4640 * @context: a #GMainContext, or %NULL
4641 * @function: function to call
4642 * @data: data to pass to @function
4644 * Invokes a function in such a way that @context is owned during the
4645 * invocation of @function.
4647 * If @context is %NULL then the global default main context — as
4648 * returned by g_main_context_default() — is used.
4650 * If @context is owned by the current thread, @function is called
4651 * directly. Otherwise, if @context is the thread-default main context
4652 * of the current thread and g_main_context_acquire() succeeds, then
4653 * @function is called and g_main_context_release() is called
4656 * In any other case, an idle source is created to call @function and
4657 * that source is attached to @context (presumably to be run in another
4658 * thread). The idle source is attached with #G_PRIORITY_DEFAULT
4659 * priority. If you want a different priority, use
4660 * g_main_context_invoke_full().
4662 * Note that, as with normal idle functions, @function should probably
4663 * return %FALSE. If it returns %TRUE, it will be continuously run in a
4664 * loop (and may prevent this call from returning).
4669 g_main_context_invoke (GMainContext *context,
4670 GSourceFunc function,
4673 g_main_context_invoke_full (context,
4675 function, data, NULL);
4679 * g_main_context_invoke_full:
4680 * @context: a #GMainContext, or %NULL
4681 * @priority: the priority at which to run @function
4682 * @function: function to call
4683 * @data: data to pass to @function
4684 * @notify: a function to call when @data is no longer in use, or %NULL.
4686 * Invokes a function in such a way that @context is owned during the
4687 * invocation of @function.
4689 * This function is the same as g_main_context_invoke() except that it
4690 * lets you specify the priority incase @function ends up being
4691 * scheduled as an idle and also lets you give a #GDestroyNotify for @data.
4693 * @notify should not assume that it is called from any particular
4694 * thread or with any particular context acquired.
4699 g_main_context_invoke_full (GMainContext *context,
4701 GSourceFunc function,
4703 GDestroyNotify notify)
4705 g_return_if_fail (function != NULL);
4708 context = g_main_context_default ();
4710 if (g_main_context_is_owner (context))
4712 while (function (data));
4719 GMainContext *thread_default;
4721 thread_default = g_main_context_get_thread_default ();
4723 if (!thread_default)
4724 thread_default = g_main_context_default ();
4726 if (thread_default == context && g_main_context_acquire (context))
4728 while (function (data));
4730 g_main_context_release (context);
4739 source = g_idle_source_new ();
4740 g_source_set_priority (source, priority);
4741 g_source_set_callback (source, function, data, notify);
4742 g_source_attach (source, context);
4743 g_source_unref (source);