1 /* GLIB - Library of useful routines for C programming
2 * Copyright (C) 1995-1997 Peter Mattis, Spencer Kimball and Josh MacDonald
4 * gmain.c: Main loop abstraction, timeouts, and idle functions
5 * Copyright 1998 Owen Taylor
7 * This library is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU Lesser General Public
9 * License as published by the Free Software Foundation; either
10 * version 2 of the License, or (at your option) any later version.
12 * This library is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 * Lesser General Public License for more details.
17 * You should have received a copy of the GNU Lesser General Public
18 * License along with this library; if not, write to the
19 * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
20 * Boston, MA 02111-1307, USA.
24 * Modified by the GLib Team and others 1997-2000. See the AUTHORS
25 * file for a list of people on the GLib Team. See the ChangeLog
26 * files for a list of changes. These files are distributed with
27 * GLib at ftp://ftp.gtk.org/pub/gtk/.
35 #include "glibconfig.h"
37 /* Uncomment the next line (and the corresponding line in gpoll.c) to
38 * enable debugging printouts if the environment variable
39 * G_MAIN_POLL_DEBUG is set to some value.
41 /* #define G_MAIN_POLL_DEBUG */
44 /* Always enable debugging printout on Windows, as it is more often
47 #define G_MAIN_POLL_DEBUG
51 #include "glib-unix.h"
54 #include <sys/eventfd.h>
59 #include <sys/types.h>
62 #ifdef HAVE_SYS_TIME_H
64 #endif /* HAVE_SYS_TIME_H */
67 #endif /* HAVE_UNISTD_H */
74 #endif /* G_OS_WIN32 */
77 #include <sys/socket.h>
79 #endif /* G_OS_BEOS */
84 #include "giochannel.h"
88 #include "gstrfuncs.h"
89 #include "gtestutils.h"
95 #ifdef G_MAIN_POLL_DEBUG
100 #include "gmain-internal.h"
101 #include "glib-private.h"
105 * @title: The Main Event Loop
106 * @short_description: manages all available sources of events
108 * The main event loop manages all the available sources of events for
109 * GLib and GTK+ applications. These events can come from any number of
110 * different types of sources such as file descriptors (plain files,
111 * pipes or sockets) and timeouts. New types of event sources can also
112 * be added using g_source_attach().
114 * To allow multiple independent sets of sources to be handled in
115 * different threads, each source is associated with a #GMainContext.
116 * A GMainContext can only be running in a single thread, but
117 * sources can be added to it and removed from it from other threads.
119 * Each event source is assigned a priority. The default priority,
120 * #G_PRIORITY_DEFAULT, is 0. Values less than 0 denote higher priorities.
121 * Values greater than 0 denote lower priorities. Events from high priority
122 * sources are always processed before events from lower priority sources.
124 * Idle functions can also be added, and assigned a priority. These will
125 * be run whenever no events with a higher priority are ready to be processed.
127 * The #GMainLoop data type represents a main event loop. A GMainLoop is
128 * created with g_main_loop_new(). After adding the initial event sources,
129 * g_main_loop_run() is called. This continuously checks for new events from
130 * each of the event sources and dispatches them. Finally, the processing of
131 * an event from one of the sources leads to a call to g_main_loop_quit() to
132 * exit the main loop, and g_main_loop_run() returns.
134 * It is possible to create new instances of #GMainLoop recursively.
135 * This is often used in GTK+ applications when showing modal dialog
136 * boxes. Note that event sources are associated with a particular
137 * #GMainContext, and will be checked and dispatched for all main
138 * loops associated with that GMainContext.
140 * GTK+ contains wrappers of some of these functions, e.g. gtk_main(),
141 * gtk_main_quit() and gtk_events_pending().
143 * <refsect2><title>Creating new source types</title>
144 * <para>One of the unusual features of the #GMainLoop functionality
145 * is that new types of event source can be created and used in
146 * addition to the builtin type of event source. A new event source
147 * type is used for handling GDK events. A new source type is created
148 * by <firstterm>deriving</firstterm> from the #GSource structure.
149 * The derived type of source is represented by a structure that has
150 * the #GSource structure as a first element, and other elements specific
151 * to the new source type. To create an instance of the new source type,
152 * call g_source_new() passing in the size of the derived structure and
153 * a table of functions. These #GSourceFuncs determine the behavior of
154 * the new source type.</para>
155 * <para>New source types basically interact with the main context
156 * in two ways. Their prepare function in #GSourceFuncs can set a timeout
157 * to determine the maximum amount of time that the main loop will sleep
158 * before checking the source again. In addition, or as well, the source
159 * can add file descriptors to the set that the main context checks using
160 * g_source_add_poll().</para>
162 * <refsect2><title>Customizing the main loop iteration</title>
163 * <para>Single iterations of a #GMainContext can be run with
164 * g_main_context_iteration(). In some cases, more detailed control
165 * of exactly how the details of the main loop work is desired, for
166 * instance, when integrating the #GMainLoop with an external main loop.
167 * In such cases, you can call the component functions of
168 * g_main_context_iteration() directly. These functions are
169 * g_main_context_prepare(), g_main_context_query(),
170 * g_main_context_check() and g_main_context_dispatch().</para>
171 * <para>The operation of these functions can best be seen in terms
172 * of a state diagram, as shown in <xref linkend="mainloop-states"/>.</para>
173 * <figure id="mainloop-states"><title>States of a Main Context</title>
174 * <graphic fileref="mainloop-states.gif" format="GIF"></graphic>
178 * On Unix, the GLib mainloop is incompatible with fork(). Any program
179 * using the mainloop must either exec() or exit() from the child
180 * without returning to the mainloop.
185 typedef struct _GTimeoutSource GTimeoutSource;
186 typedef struct _GChildWatchSource GChildWatchSource;
187 typedef struct _GUnixSignalWatchSource GUnixSignalWatchSource;
188 typedef struct _GPollRec GPollRec;
189 typedef struct _GSourceCallback GSourceCallback;
193 G_SOURCE_READY = 1 << G_HOOK_FLAG_USER_SHIFT,
194 G_SOURCE_CAN_RECURSE = 1 << (G_HOOK_FLAG_USER_SHIFT + 1),
195 G_SOURCE_BLOCKED = 1 << (G_HOOK_FLAG_USER_SHIFT + 2)
198 typedef struct _GSourceList GSourceList;
202 GSource *head, *tail;
206 typedef struct _GMainWaiter GMainWaiter;
214 typedef struct _GMainDispatch GMainDispatch;
216 struct _GMainDispatch
219 GSList *dispatching_sources; /* stack of current sources */
222 #ifdef G_MAIN_POLL_DEBUG
223 gboolean _g_main_poll_debug = FALSE;
228 /* The following lock is used for both the list of sources
229 * and the list of poll records
239 GPtrArray *pending_dispatches;
240 gint timeout; /* Timeout for current iteration */
244 gint in_check_or_prepare;
246 GPollRec *poll_records, *poll_records_tail;
247 guint n_poll_records;
248 GPollFD *cached_poll_array;
249 guint cached_poll_array_size;
255 /* Flag indicating whether the set of fd's changed during a poll */
256 gboolean poll_changed;
261 gboolean time_is_fresh;
264 struct _GSourceCallback
269 GDestroyNotify notify;
274 GMainContext *context;
279 struct _GTimeoutSource
287 struct _GChildWatchSource
294 #else /* G_OS_WIN32 */
295 gboolean child_exited;
296 #endif /* G_OS_WIN32 */
299 struct _GUnixSignalWatchSource
314 struct _GSourcePrivate
316 GSList *child_sources;
317 GSource *parent_source;
320 typedef struct _GSourceIter
322 GMainContext *context;
328 #define LOCK_CONTEXT(context) g_mutex_lock (&context->mutex)
329 #define UNLOCK_CONTEXT(context) g_mutex_unlock (&context->mutex)
330 #define G_THREAD_SELF g_thread_self ()
332 #define SOURCE_DESTROYED(source) (((source)->flags & G_HOOK_FLAG_ACTIVE) == 0)
333 #define SOURCE_BLOCKED(source) (((source)->flags & G_SOURCE_BLOCKED) != 0)
335 #define SOURCE_UNREF(source, context) \
337 if ((source)->ref_count > 1) \
338 (source)->ref_count--; \
340 g_source_unref_internal ((source), (context), TRUE); \
344 /* Forward declarations */
346 static void g_source_unref_internal (GSource *source,
347 GMainContext *context,
349 static void g_source_destroy_internal (GSource *source,
350 GMainContext *context,
352 static void g_source_set_priority_unlocked (GSource *source,
353 GMainContext *context,
355 static void g_main_context_poll (GMainContext *context,
360 static void g_main_context_add_poll_unlocked (GMainContext *context,
363 static void g_main_context_remove_poll_unlocked (GMainContext *context,
366 static void g_source_iter_init (GSourceIter *iter,
367 GMainContext *context,
368 gboolean may_modify);
369 static gboolean g_source_iter_next (GSourceIter *iter,
371 static void g_source_iter_clear (GSourceIter *iter);
373 static gboolean g_timeout_prepare (GSource *source,
375 static gboolean g_timeout_check (GSource *source);
376 static gboolean g_timeout_dispatch (GSource *source,
377 GSourceFunc callback,
379 static gboolean g_child_watch_prepare (GSource *source,
381 static gboolean g_child_watch_check (GSource *source);
382 static gboolean g_child_watch_dispatch (GSource *source,
383 GSourceFunc callback,
385 static void g_child_watch_finalize (GSource *source);
387 static void g_unix_signal_handler (int signum);
388 static gboolean g_unix_signal_watch_prepare (GSource *source,
390 static gboolean g_unix_signal_watch_check (GSource *source);
391 static gboolean g_unix_signal_watch_dispatch (GSource *source,
392 GSourceFunc callback,
394 static void g_unix_signal_watch_finalize (GSource *source);
396 static gboolean g_idle_prepare (GSource *source,
398 static gboolean g_idle_check (GSource *source);
399 static gboolean g_idle_dispatch (GSource *source,
400 GSourceFunc callback,
403 static void block_source (GSource *source);
405 static GMainContext *glib_worker_context;
407 G_LOCK_DEFINE_STATIC (main_loop);
408 static GMainContext *default_main_context;
413 /* UNIX signals work by marking one of these variables then waking the
414 * worker context to check on them and dispatch accordingly.
416 #ifdef HAVE_SIG_ATOMIC_T
417 static volatile sig_atomic_t unix_signal_pending[NSIG];
418 static volatile sig_atomic_t any_unix_signal_pending;
420 static volatile int unix_signal_pending[NSIG];
421 static volatile int any_unix_signal_pending;
424 /* Guards all the data below */
425 G_LOCK_DEFINE_STATIC (unix_signal_lock);
426 static GSList *unix_signal_watches;
427 static GSList *unix_child_watches;
429 static GSourceFuncs g_unix_signal_funcs =
431 g_unix_signal_watch_prepare,
432 g_unix_signal_watch_check,
433 g_unix_signal_watch_dispatch,
434 g_unix_signal_watch_finalize
436 #endif /* !G_OS_WIN32 */
437 G_LOCK_DEFINE_STATIC (main_context_list);
438 static GSList *main_context_list = NULL;
440 GSourceFuncs g_timeout_funcs =
448 GSourceFuncs g_child_watch_funcs =
450 g_child_watch_prepare,
452 g_child_watch_dispatch,
453 g_child_watch_finalize
456 GSourceFuncs g_idle_funcs =
465 * g_main_context_ref:
466 * @context: a #GMainContext
468 * Increases the reference count on a #GMainContext object by one.
470 * Returns: the @context that was passed in (since 2.6)
473 g_main_context_ref (GMainContext *context)
475 g_return_val_if_fail (context != NULL, NULL);
476 g_return_val_if_fail (g_atomic_int_get (&context->ref_count) > 0, NULL);
478 g_atomic_int_inc (&context->ref_count);
484 poll_rec_list_free (GMainContext *context,
487 g_slice_free_chain (GPollRec, list, next);
491 * g_main_context_unref:
492 * @context: a #GMainContext
494 * Decreases the reference count on a #GMainContext object by one. If
495 * the result is zero, free the context and free all associated memory.
498 g_main_context_unref (GMainContext *context)
503 g_return_if_fail (context != NULL);
504 g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
506 if (!g_atomic_int_dec_and_test (&context->ref_count))
509 G_LOCK (main_context_list);
510 main_context_list = g_slist_remove (main_context_list, context);
511 G_UNLOCK (main_context_list);
513 g_source_iter_init (&iter, context, TRUE);
514 while (g_source_iter_next (&iter, &source))
516 source->context = NULL;
517 g_source_destroy_internal (source, context, FALSE);
520 g_mutex_clear (&context->mutex);
522 g_ptr_array_free (context->pending_dispatches, TRUE);
523 g_free (context->cached_poll_array);
525 poll_rec_list_free (context, context->poll_records);
527 g_wakeup_free (context->wakeup);
528 g_cond_clear (&context->cond);
534 * g_main_context_new:
536 * Creates a new #GMainContext structure.
538 * Return value: the new #GMainContext
541 g_main_context_new (void)
543 static gsize initialised;
544 GMainContext *context;
546 if (g_once_init_enter (&initialised))
548 #ifdef G_MAIN_POLL_DEBUG
549 if (getenv ("G_MAIN_POLL_DEBUG") != NULL)
550 _g_main_poll_debug = TRUE;
553 g_once_init_leave (&initialised, TRUE);
556 context = g_new0 (GMainContext, 1);
558 g_mutex_init (&context->mutex);
559 g_cond_init (&context->cond);
561 context->owner = NULL;
562 context->waiters = NULL;
564 context->ref_count = 1;
566 context->next_id = 1;
568 context->source_lists = NULL;
570 context->poll_func = g_poll;
572 context->cached_poll_array = NULL;
573 context->cached_poll_array_size = 0;
575 context->pending_dispatches = g_ptr_array_new ();
577 context->time_is_fresh = FALSE;
579 context->wakeup = g_wakeup_new ();
580 g_wakeup_get_pollfd (context->wakeup, &context->wake_up_rec);
581 g_main_context_add_poll_unlocked (context, 0, &context->wake_up_rec);
583 G_LOCK (main_context_list);
584 main_context_list = g_slist_append (main_context_list, context);
586 #ifdef G_MAIN_POLL_DEBUG
587 if (_g_main_poll_debug)
588 g_print ("created context=%p\n", context);
591 G_UNLOCK (main_context_list);
597 * g_main_context_default:
599 * Returns the global default main context. This is the main context
600 * used for main loop functions when a main loop is not explicitly
601 * specified, and corresponds to the "main" main loop. See also
602 * g_main_context_get_thread_default().
604 * Return value: (transfer none): the global default main context.
607 g_main_context_default (void)
613 if (!default_main_context)
615 default_main_context = g_main_context_new ();
616 #ifdef G_MAIN_POLL_DEBUG
617 if (_g_main_poll_debug)
618 g_print ("default context=%p\n", default_main_context);
622 G_UNLOCK (main_loop);
624 return default_main_context;
628 free_context (gpointer data)
630 GMainContext *context = data;
632 g_main_context_release (context);
634 g_main_context_unref (context);
638 free_context_stack (gpointer data)
640 g_queue_free_full((GQueue *) data, (GDestroyNotify) free_context);
643 static GPrivate thread_context_stack = G_PRIVATE_INIT (free_context_stack);
646 * g_main_context_push_thread_default:
647 * @context: (allow-none): a #GMainContext, or %NULL for the global default context
649 * Acquires @context and sets it as the thread-default context for the
650 * current thread. This will cause certain asynchronous operations
651 * (such as most <link linkend="gio">gio</link>-based I/O) which are
652 * started in this thread to run under @context and deliver their
653 * results to its main loop, rather than running under the global
654 * default context in the main thread. Note that calling this function
655 * changes the context returned by
656 * g_main_context_get_thread_default(), <emphasis>not</emphasis> the
657 * one returned by g_main_context_default(), so it does not affect the
658 * context used by functions like g_idle_add().
660 * Normally you would call this function shortly after creating a new
661 * thread, passing it a #GMainContext which will be run by a
662 * #GMainLoop in that thread, to set a new default context for all
663 * async operations in that thread. (In this case, you don't need to
664 * ever call g_main_context_pop_thread_default().) In some cases
665 * however, you may want to schedule a single operation in a
666 * non-default context, or temporarily use a non-default context in
667 * the main thread. In that case, you can wrap the call to the
668 * asynchronous operation inside a
669 * g_main_context_push_thread_default() /
670 * g_main_context_pop_thread_default() pair, but it is up to you to
671 * ensure that no other asynchronous operations accidentally get
672 * started while the non-default context is active.
674 * Beware that libraries that predate this function may not correctly
675 * handle being used from a thread with a thread-default context. Eg,
676 * see g_file_supports_thread_contexts().
681 g_main_context_push_thread_default (GMainContext *context)
684 gboolean acquired_context;
686 acquired_context = g_main_context_acquire (context);
687 g_return_if_fail (acquired_context);
689 if (context == g_main_context_default ())
692 g_main_context_ref (context);
694 stack = g_private_get (&thread_context_stack);
697 stack = g_queue_new ();
698 g_private_set (&thread_context_stack, stack);
701 g_queue_push_head (stack, context);
705 * g_main_context_pop_thread_default:
706 * @context: (allow-none): a #GMainContext object, or %NULL
708 * Pops @context off the thread-default context stack (verifying that
709 * it was on the top of the stack).
714 g_main_context_pop_thread_default (GMainContext *context)
718 if (context == g_main_context_default ())
721 stack = g_private_get (&thread_context_stack);
723 g_return_if_fail (stack != NULL);
724 g_return_if_fail (g_queue_peek_head (stack) == context);
726 g_queue_pop_head (stack);
728 g_main_context_release (context);
730 g_main_context_unref (context);
734 * g_main_context_get_thread_default:
736 * Gets the thread-default #GMainContext for this thread. Asynchronous
737 * operations that want to be able to be run in contexts other than
738 * the default one should call this method or
739 * g_main_context_ref_thread_default() to get a #GMainContext to add
740 * their #GSource<!-- -->s to. (Note that even in single-threaded
741 * programs applications may sometimes want to temporarily push a
742 * non-default context, so it is not safe to assume that this will
743 * always return %NULL if you are running in the default thread.)
745 * If you need to hold a reference on the context, use
746 * g_main_context_ref_thread_default() instead.
748 * Returns: (transfer none): the thread-default #GMainContext, or
749 * %NULL if the thread-default context is the global default context.
754 g_main_context_get_thread_default (void)
758 stack = g_private_get (&thread_context_stack);
760 return g_queue_peek_head (stack);
766 * g_main_context_ref_thread_default:
768 * Gets the thread-default #GMainContext for this thread, as with
769 * g_main_context_get_thread_default(), but also adds a reference to
770 * it with g_main_context_ref(). In addition, unlike
771 * g_main_context_get_thread_default(), if the thread-default context
772 * is the global default context, this will return that #GMainContext
773 * (with a ref added to it) rather than returning %NULL.
775 * Returns: (transfer full): the thread-default #GMainContext. Unref
776 * with g_main_context_unref() when you are done with it.
781 g_main_context_ref_thread_default (void)
783 GMainContext *context;
785 context = g_main_context_get_thread_default ();
787 context = g_main_context_default ();
788 return g_main_context_ref (context);
791 /* Hooks for adding to the main loop */
795 * @source_funcs: structure containing functions that implement
796 * the sources behavior.
797 * @struct_size: size of the #GSource structure to create.
799 * Creates a new #GSource structure. The size is specified to
800 * allow creating structures derived from #GSource that contain
801 * additional data. The size passed in must be at least
802 * <literal>sizeof (GSource)</literal>.
804 * The source will not initially be associated with any #GMainContext
805 * and must be added to one with g_source_attach() before it will be
808 * Return value: the newly-created #GSource.
811 g_source_new (GSourceFuncs *source_funcs,
816 g_return_val_if_fail (source_funcs != NULL, NULL);
817 g_return_val_if_fail (struct_size >= sizeof (GSource), NULL);
819 source = (GSource*) g_malloc0 (struct_size);
820 source->priv = g_slice_new0 (GSourcePrivate);
821 source->source_funcs = source_funcs;
822 source->ref_count = 1;
824 source->priority = G_PRIORITY_DEFAULT;
826 source->flags = G_HOOK_FLAG_ACTIVE;
828 /* NULL/0 initialization for all other fields */
833 /* Holds context's lock */
835 g_source_iter_init (GSourceIter *iter,
836 GMainContext *context,
839 iter->context = context;
840 iter->current_list = NULL;
842 iter->may_modify = may_modify;
845 /* Holds context's lock */
847 g_source_iter_next (GSourceIter *iter, GSource **source)
849 GSource *next_source;
852 next_source = iter->source->next;
858 if (iter->current_list)
859 iter->current_list = iter->current_list->next;
861 iter->current_list = iter->context->source_lists;
863 if (iter->current_list)
865 GSourceList *source_list = iter->current_list->data;
867 next_source = source_list->head;
871 /* Note: unreffing iter->source could potentially cause its
872 * GSourceList to be removed from source_lists (if iter->source is
873 * the only source in its list, and it is destroyed), so we have to
874 * keep it reffed until after we advance iter->current_list, above.
877 if (iter->source && iter->may_modify)
878 SOURCE_UNREF (iter->source, iter->context);
879 iter->source = next_source;
880 if (iter->source && iter->may_modify)
881 iter->source->ref_count++;
883 *source = iter->source;
884 return *source != NULL;
887 /* Holds context's lock. Only necessary to call if you broke out of
888 * the g_source_iter_next() loop early.
891 g_source_iter_clear (GSourceIter *iter)
893 if (iter->source && iter->may_modify)
895 SOURCE_UNREF (iter->source, iter->context);
900 /* Holds context's lock
903 find_source_list_for_priority (GMainContext *context,
908 GSourceList *source_list;
911 for (iter = context->source_lists; iter != NULL; last = iter, iter = iter->next)
913 source_list = iter->data;
915 if (source_list->priority == priority)
918 if (source_list->priority > priority)
923 source_list = g_slice_new0 (GSourceList);
924 source_list->priority = priority;
925 context->source_lists = g_list_insert_before (context->source_lists,
935 source_list = g_slice_new0 (GSourceList);
936 source_list->priority = priority;
939 context->source_lists = g_list_append (NULL, source_list);
942 /* This just appends source_list to the end of
943 * context->source_lists without having to walk the list again.
945 last = g_list_append (last, source_list);
950 /* Holds context's lock
953 source_add_to_context (GSource *source,
954 GMainContext *context)
956 GSourceList *source_list;
957 GSource *prev, *next;
959 source_list = find_source_list_for_priority (context, source->priority, TRUE);
961 if (source->priv->parent_source)
963 g_assert (source_list->head != NULL);
965 /* Put the source immediately before its parent */
966 prev = source->priv->parent_source->prev;
967 next = source->priv->parent_source;
971 prev = source_list->tail;
979 source_list->tail = source;
985 source_list->head = source;
988 /* Holds context's lock
991 source_remove_from_context (GSource *source,
992 GMainContext *context)
994 GSourceList *source_list;
996 source_list = find_source_list_for_priority (context, source->priority, FALSE);
997 g_return_if_fail (source_list != NULL);
1000 source->prev->next = source->next;
1002 source_list->head = source->next;
1005 source->next->prev = source->prev;
1007 source_list->tail = source->prev;
1009 source->prev = NULL;
1010 source->next = NULL;
1012 if (source_list->head == NULL)
1014 context->source_lists = g_list_remove (context->source_lists, source_list);
1015 g_slice_free (GSourceList, source_list);
1020 g_source_attach_unlocked (GSource *source,
1021 GMainContext *context)
1026 source->context = context;
1027 result = source->source_id = context->next_id++;
1029 source->ref_count++;
1030 source_add_to_context (source, context);
1032 tmp_list = source->poll_fds;
1035 g_main_context_add_poll_unlocked (context, source->priority, tmp_list->data);
1036 tmp_list = tmp_list->next;
1039 tmp_list = source->priv->child_sources;
1042 g_source_attach_unlocked (tmp_list->data, context);
1043 tmp_list = tmp_list->next;
1051 * @source: a #GSource
1052 * @context: (allow-none): a #GMainContext (if %NULL, the default context will be used)
1054 * Adds a #GSource to a @context so that it will be executed within
1055 * that context. Remove it by calling g_source_destroy().
1057 * Return value: the ID (greater than 0) for the source within the
1061 g_source_attach (GSource *source,
1062 GMainContext *context)
1066 g_return_val_if_fail (source->context == NULL, 0);
1067 g_return_val_if_fail (!SOURCE_DESTROYED (source), 0);
1070 context = g_main_context_default ();
1072 LOCK_CONTEXT (context);
1074 result = g_source_attach_unlocked (source, context);
1076 /* If another thread has acquired the context, wake it up since it
1077 * might be in poll() right now.
1079 if (context->owner && context->owner != G_THREAD_SELF)
1080 g_wakeup_signal (context->wakeup);
1082 UNLOCK_CONTEXT (context);
1088 g_source_destroy_internal (GSource *source,
1089 GMainContext *context,
1093 LOCK_CONTEXT (context);
1095 if (!SOURCE_DESTROYED (source))
1097 GSList *sources, *tmp_list;
1098 gpointer old_cb_data;
1099 GSourceCallbackFuncs *old_cb_funcs;
1101 source->flags &= ~G_HOOK_FLAG_ACTIVE;
1103 old_cb_data = source->callback_data;
1104 old_cb_funcs = source->callback_funcs;
1106 source->callback_data = NULL;
1107 source->callback_funcs = NULL;
1111 UNLOCK_CONTEXT (context);
1112 old_cb_funcs->unref (old_cb_data);
1113 LOCK_CONTEXT (context);
1116 if (!SOURCE_BLOCKED (source))
1118 tmp_list = source->poll_fds;
1121 g_main_context_remove_poll_unlocked (context, tmp_list->data);
1122 tmp_list = tmp_list->next;
1126 if (source->priv->child_sources)
1128 sources = tmp_list = source->priv->child_sources;
1129 source->priv->child_sources = NULL;
1132 g_source_destroy_internal (tmp_list->data, context, TRUE);
1133 g_source_unref_internal (tmp_list->data, context, TRUE);
1134 tmp_list = tmp_list->next;
1136 g_slist_free (sources);
1139 if (source->priv->parent_source)
1141 GSource *parent = source->priv->parent_source;
1143 parent->priv->child_sources =
1144 g_slist_remove (parent->priv->child_sources, source);
1145 source->priv->parent_source = NULL;
1148 g_source_unref_internal (source, context, TRUE);
1152 UNLOCK_CONTEXT (context);
1157 * @source: a #GSource
1159 * Removes a source from its #GMainContext, if any, and mark it as
1160 * destroyed. The source cannot be subsequently added to another
1164 g_source_destroy (GSource *source)
1166 GMainContext *context;
1168 g_return_if_fail (source != NULL);
1170 context = source->context;
1173 g_source_destroy_internal (source, context, FALSE);
1175 source->flags &= ~G_HOOK_FLAG_ACTIVE;
1180 * @source: a #GSource
1182 * Returns the numeric ID for a particular source. The ID of a source
1183 * is a positive integer which is unique within a particular main loop
1184 * context. The reverse
1185 * mapping from ID to source is done by g_main_context_find_source_by_id().
1187 * Return value: the ID (greater than 0) for the source
1190 g_source_get_id (GSource *source)
1194 g_return_val_if_fail (source != NULL, 0);
1195 g_return_val_if_fail (source->context != NULL, 0);
1197 LOCK_CONTEXT (source->context);
1198 result = source->source_id;
1199 UNLOCK_CONTEXT (source->context);
1205 * g_source_get_context:
1206 * @source: a #GSource
1208 * Gets the #GMainContext with which the source is associated.
1210 * You can call this on a source that has been destroyed, provided
1211 * that the #GMainContext it was attached to still exists (in which
1212 * case it will return that #GMainContext). In particular, you can
1213 * always call this function on the source returned from
1214 * g_main_current_source(). But calling this function on a source
1215 * whose #GMainContext has been destroyed is an error.
1217 * Return value: (transfer none) (allow-none): the #GMainContext with which the
1218 * source is associated, or %NULL if the context has not
1219 * yet been added to a source.
1222 g_source_get_context (GSource *source)
1224 g_return_val_if_fail (source->context != NULL || !SOURCE_DESTROYED (source), NULL);
1226 return source->context;
1230 * g_source_add_poll:
1231 * @source:a #GSource
1232 * @fd: a #GPollFD structure holding information about a file
1233 * descriptor to watch.
1235 * Adds a file descriptor to the set of file descriptors polled for
1236 * this source. This is usually combined with g_source_new() to add an
1237 * event source. The event source's check function will typically test
1238 * the @revents field in the #GPollFD struct and return %TRUE if events need
1242 g_source_add_poll (GSource *source,
1245 GMainContext *context;
1247 g_return_if_fail (source != NULL);
1248 g_return_if_fail (fd != NULL);
1249 g_return_if_fail (!SOURCE_DESTROYED (source));
1251 context = source->context;
1254 LOCK_CONTEXT (context);
1256 source->poll_fds = g_slist_prepend (source->poll_fds, fd);
1260 if (!SOURCE_BLOCKED (source))
1261 g_main_context_add_poll_unlocked (context, source->priority, fd);
1262 UNLOCK_CONTEXT (context);
1267 * g_source_remove_poll:
1268 * @source:a #GSource
1269 * @fd: a #GPollFD structure previously passed to g_source_add_poll().
1271 * Removes a file descriptor from the set of file descriptors polled for
1275 g_source_remove_poll (GSource *source,
1278 GMainContext *context;
1280 g_return_if_fail (source != NULL);
1281 g_return_if_fail (fd != NULL);
1282 g_return_if_fail (!SOURCE_DESTROYED (source));
1284 context = source->context;
1287 LOCK_CONTEXT (context);
1289 source->poll_fds = g_slist_remove (source->poll_fds, fd);
1293 if (!SOURCE_BLOCKED (source))
1294 g_main_context_remove_poll_unlocked (context, fd);
1295 UNLOCK_CONTEXT (context);
1300 * g_source_add_child_source:
1301 * @source:a #GSource
1302 * @child_source: a second #GSource that @source should "poll"
1304 * Adds @child_source to @source as a "polled" source; when @source is
1305 * added to a #GMainContext, @child_source will be automatically added
1306 * with the same priority, when @child_source is triggered, it will
1307 * cause @source to dispatch (in addition to calling its own
1308 * callback), and when @source is destroyed, it will destroy
1309 * @child_source as well. (@source will also still be dispatched if
1310 * its own prepare/check functions indicate that it is ready.)
1312 * If you don't need @child_source to do anything on its own when it
1313 * triggers, you can call g_source_set_dummy_callback() on it to set a
1314 * callback that does nothing (except return %TRUE if appropriate).
1316 * @source will hold a reference on @child_source while @child_source
1317 * is attached to it.
1322 g_source_add_child_source (GSource *source,
1323 GSource *child_source)
1325 GMainContext *context;
1327 g_return_if_fail (source != NULL);
1328 g_return_if_fail (child_source != NULL);
1329 g_return_if_fail (!SOURCE_DESTROYED (source));
1330 g_return_if_fail (!SOURCE_DESTROYED (child_source));
1331 g_return_if_fail (child_source->context == NULL);
1332 g_return_if_fail (child_source->priv->parent_source == NULL);
1334 context = source->context;
1337 LOCK_CONTEXT (context);
1339 source->priv->child_sources = g_slist_prepend (source->priv->child_sources,
1340 g_source_ref (child_source));
1341 child_source->priv->parent_source = source;
1342 g_source_set_priority_unlocked (child_source, NULL, source->priority);
1343 if (SOURCE_BLOCKED (source))
1344 block_source (child_source);
1348 UNLOCK_CONTEXT (context);
1349 g_source_attach (child_source, context);
1354 * g_source_remove_child_source:
1355 * @source:a #GSource
1356 * @child_source: a #GSource previously passed to
1357 * g_source_add_child_source().
1359 * Detaches @child_source from @source and destroys it.
1364 g_source_remove_child_source (GSource *source,
1365 GSource *child_source)
1367 GMainContext *context;
1369 g_return_if_fail (source != NULL);
1370 g_return_if_fail (child_source != NULL);
1371 g_return_if_fail (child_source->priv->parent_source == source);
1372 g_return_if_fail (!SOURCE_DESTROYED (source));
1373 g_return_if_fail (!SOURCE_DESTROYED (child_source));
1375 context = source->context;
1378 LOCK_CONTEXT (context);
1380 g_source_destroy_internal (child_source, context, TRUE);
1381 g_source_unref_internal (child_source, context, TRUE);
1384 UNLOCK_CONTEXT (context);
1388 * g_source_set_callback_indirect:
1389 * @source: the source
1390 * @callback_data: pointer to callback data "object"
1391 * @callback_funcs: functions for reference counting @callback_data
1392 * and getting the callback and data
1394 * Sets the callback function storing the data as a refcounted callback
1395 * "object". This is used internally. Note that calling
1396 * g_source_set_callback_indirect() assumes
1397 * an initial reference count on @callback_data, and thus
1398 * @callback_funcs->unref will eventually be called once more
1399 * than @callback_funcs->ref.
1402 g_source_set_callback_indirect (GSource *source,
1403 gpointer callback_data,
1404 GSourceCallbackFuncs *callback_funcs)
1406 GMainContext *context;
1407 gpointer old_cb_data;
1408 GSourceCallbackFuncs *old_cb_funcs;
1410 g_return_if_fail (source != NULL);
1411 g_return_if_fail (callback_funcs != NULL || callback_data == NULL);
1413 context = source->context;
1416 LOCK_CONTEXT (context);
1418 old_cb_data = source->callback_data;
1419 old_cb_funcs = source->callback_funcs;
1421 source->callback_data = callback_data;
1422 source->callback_funcs = callback_funcs;
1425 UNLOCK_CONTEXT (context);
1428 old_cb_funcs->unref (old_cb_data);
1432 g_source_callback_ref (gpointer cb_data)
1434 GSourceCallback *callback = cb_data;
1436 callback->ref_count++;
1441 g_source_callback_unref (gpointer cb_data)
1443 GSourceCallback *callback = cb_data;
1445 callback->ref_count--;
1446 if (callback->ref_count == 0)
1448 if (callback->notify)
1449 callback->notify (callback->data);
1455 g_source_callback_get (gpointer cb_data,
1460 GSourceCallback *callback = cb_data;
1462 *func = callback->func;
1463 *data = callback->data;
1466 static GSourceCallbackFuncs g_source_callback_funcs = {
1467 g_source_callback_ref,
1468 g_source_callback_unref,
1469 g_source_callback_get,
1473 * g_source_set_callback:
1474 * @source: the source
1475 * @func: a callback function
1476 * @data: the data to pass to callback function
1477 * @notify: (allow-none): a function to call when @data is no longer in use, or %NULL.
1479 * Sets the callback function for a source. The callback for a source is
1480 * called from the source's dispatch function.
1482 * The exact type of @func depends on the type of source; ie. you
1483 * should not count on @func being called with @data as its first
1486 * Typically, you won't use this function. Instead use functions specific
1487 * to the type of source you are using.
1490 g_source_set_callback (GSource *source,
1493 GDestroyNotify notify)
1495 GSourceCallback *new_callback;
1497 g_return_if_fail (source != NULL);
1499 new_callback = g_new (GSourceCallback, 1);
1501 new_callback->ref_count = 1;
1502 new_callback->func = func;
1503 new_callback->data = data;
1504 new_callback->notify = notify;
1506 g_source_set_callback_indirect (source, new_callback, &g_source_callback_funcs);
1511 * g_source_set_funcs:
1512 * @source: a #GSource
1513 * @funcs: the new #GSourceFuncs
1515 * Sets the source functions (can be used to override
1516 * default implementations) of an unattached source.
1521 g_source_set_funcs (GSource *source,
1522 GSourceFuncs *funcs)
1524 g_return_if_fail (source != NULL);
1525 g_return_if_fail (source->context == NULL);
1526 g_return_if_fail (source->ref_count > 0);
1527 g_return_if_fail (funcs != NULL);
1529 source->source_funcs = funcs;
1533 g_source_set_priority_unlocked (GSource *source,
1534 GMainContext *context,
1539 g_return_if_fail (source->priv->parent_source == NULL ||
1540 source->priv->parent_source->priority == priority);
1544 /* Remove the source from the context's source and then
1545 * add it back after so it is sorted in the correct place
1547 source_remove_from_context (source, source->context);
1550 source->priority = priority;
1554 source_add_to_context (source, source->context);
1556 if (!SOURCE_BLOCKED (source))
1558 tmp_list = source->poll_fds;
1561 g_main_context_remove_poll_unlocked (context, tmp_list->data);
1562 g_main_context_add_poll_unlocked (context, priority, tmp_list->data);
1564 tmp_list = tmp_list->next;
1569 if (source->priv->child_sources)
1571 tmp_list = source->priv->child_sources;
1574 g_source_set_priority_unlocked (tmp_list->data, context, priority);
1575 tmp_list = tmp_list->next;
1581 * g_source_set_priority:
1582 * @source: a #GSource
1583 * @priority: the new priority.
1585 * Sets the priority of a source. While the main loop is being run, a
1586 * source will be dispatched if it is ready to be dispatched and no
1587 * sources at a higher (numerically smaller) priority are ready to be
1591 g_source_set_priority (GSource *source,
1594 GMainContext *context;
1596 g_return_if_fail (source != NULL);
1598 context = source->context;
1601 LOCK_CONTEXT (context);
1602 g_source_set_priority_unlocked (source, context, priority);
1604 UNLOCK_CONTEXT (source->context);
1608 * g_source_get_priority:
1609 * @source: a #GSource
1611 * Gets the priority of a source.
1613 * Return value: the priority of the source
1616 g_source_get_priority (GSource *source)
1618 g_return_val_if_fail (source != NULL, 0);
1620 return source->priority;
1624 * g_source_set_can_recurse:
1625 * @source: a #GSource
1626 * @can_recurse: whether recursion is allowed for this source
1628 * Sets whether a source can be called recursively. If @can_recurse is
1629 * %TRUE, then while the source is being dispatched then this source
1630 * will be processed normally. Otherwise, all processing of this
1631 * source is blocked until the dispatch function returns.
1634 g_source_set_can_recurse (GSource *source,
1635 gboolean can_recurse)
1637 GMainContext *context;
1639 g_return_if_fail (source != NULL);
1641 context = source->context;
1644 LOCK_CONTEXT (context);
1647 source->flags |= G_SOURCE_CAN_RECURSE;
1649 source->flags &= ~G_SOURCE_CAN_RECURSE;
1652 UNLOCK_CONTEXT (context);
1656 * g_source_get_can_recurse:
1657 * @source: a #GSource
1659 * Checks whether a source is allowed to be called recursively.
1660 * see g_source_set_can_recurse().
1662 * Return value: whether recursion is allowed.
1665 g_source_get_can_recurse (GSource *source)
1667 g_return_val_if_fail (source != NULL, FALSE);
1669 return (source->flags & G_SOURCE_CAN_RECURSE) != 0;
1674 * g_source_set_name:
1675 * @source: a #GSource
1676 * @name: debug name for the source
1678 * Sets a name for the source, used in debugging and profiling.
1679 * The name defaults to #NULL.
1681 * The source name should describe in a human-readable way
1682 * what the source does. For example, "X11 event queue"
1683 * or "GTK+ repaint idle handler" or whatever it is.
1685 * It is permitted to call this function multiple times, but is not
1686 * recommended due to the potential performance impact. For example,
1687 * one could change the name in the "check" function of a #GSourceFuncs
1688 * to include details like the event type in the source name.
1693 g_source_set_name (GSource *source,
1696 g_return_if_fail (source != NULL);
1698 /* setting back to NULL is allowed, just because it's
1699 * weird if get_name can return NULL but you can't
1703 g_free (source->name);
1704 source->name = g_strdup (name);
1708 * g_source_get_name:
1709 * @source: a #GSource
1711 * Gets a name for the source, used in debugging and profiling.
1712 * The name may be #NULL if it has never been set with
1713 * g_source_set_name().
1715 * Return value: the name of the source
1719 g_source_get_name (GSource *source)
1721 g_return_val_if_fail (source != NULL, NULL);
1723 return source->name;
1727 * g_source_set_name_by_id:
1728 * @tag: a #GSource ID
1729 * @name: debug name for the source
1731 * Sets the name of a source using its ID.
1733 * This is a convenience utility to set source names from the return
1734 * value of g_idle_add(), g_timeout_add(), etc.
1739 g_source_set_name_by_id (guint tag,
1744 g_return_if_fail (tag > 0);
1746 source = g_main_context_find_source_by_id (NULL, tag);
1750 g_source_set_name (source, name);
1756 * @source: a #GSource
1758 * Increases the reference count on a source by one.
1760 * Return value: @source
1763 g_source_ref (GSource *source)
1765 GMainContext *context;
1767 g_return_val_if_fail (source != NULL, NULL);
1769 context = source->context;
1772 LOCK_CONTEXT (context);
1774 source->ref_count++;
1777 UNLOCK_CONTEXT (context);
1782 /* g_source_unref() but possible to call within context lock
1785 g_source_unref_internal (GSource *source,
1786 GMainContext *context,
1789 gpointer old_cb_data = NULL;
1790 GSourceCallbackFuncs *old_cb_funcs = NULL;
1792 g_return_if_fail (source != NULL);
1794 if (!have_lock && context)
1795 LOCK_CONTEXT (context);
1797 source->ref_count--;
1798 if (source->ref_count == 0)
1800 old_cb_data = source->callback_data;
1801 old_cb_funcs = source->callback_funcs;
1803 source->callback_data = NULL;
1804 source->callback_funcs = NULL;
1808 if (!SOURCE_DESTROYED (source))
1809 g_warning (G_STRLOC ": ref_count == 0, but source was still attached to a context!");
1810 source_remove_from_context (source, context);
1813 if (source->source_funcs->finalize)
1816 UNLOCK_CONTEXT (context);
1817 source->source_funcs->finalize (source);
1819 LOCK_CONTEXT (context);
1822 g_free (source->name);
1823 source->name = NULL;
1825 g_slist_free (source->poll_fds);
1826 source->poll_fds = NULL;
1828 g_slice_free (GSourcePrivate, source->priv);
1829 source->priv = NULL;
1834 if (!have_lock && context)
1835 UNLOCK_CONTEXT (context);
1840 UNLOCK_CONTEXT (context);
1842 old_cb_funcs->unref (old_cb_data);
1845 LOCK_CONTEXT (context);
1851 * @source: a #GSource
1853 * Decreases the reference count of a source by one. If the
1854 * resulting reference count is zero the source and associated
1855 * memory will be destroyed.
1858 g_source_unref (GSource *source)
1860 g_return_if_fail (source != NULL);
1862 g_source_unref_internal (source, source->context, FALSE);
1866 * g_main_context_find_source_by_id:
1867 * @context: (allow-none): a #GMainContext (if %NULL, the default context will be used)
1868 * @source_id: the source ID, as returned by g_source_get_id().
1870 * Finds a #GSource given a pair of context and ID.
1872 * Return value: (transfer none): the #GSource if found, otherwise, %NULL
1875 g_main_context_find_source_by_id (GMainContext *context,
1881 g_return_val_if_fail (source_id > 0, NULL);
1883 if (context == NULL)
1884 context = g_main_context_default ();
1886 LOCK_CONTEXT (context);
1888 g_source_iter_init (&iter, context, FALSE);
1889 while (g_source_iter_next (&iter, &source))
1891 if (!SOURCE_DESTROYED (source) &&
1892 source->source_id == source_id)
1895 g_source_iter_clear (&iter);
1897 UNLOCK_CONTEXT (context);
1903 * g_main_context_find_source_by_funcs_user_data:
1904 * @context: (allow-none): a #GMainContext (if %NULL, the default context will be used).
1905 * @funcs: the @source_funcs passed to g_source_new().
1906 * @user_data: the user data from the callback.
1908 * Finds a source with the given source functions and user data. If
1909 * multiple sources exist with the same source function and user data,
1910 * the first one found will be returned.
1912 * Return value: (transfer none): the source, if one was found, otherwise %NULL
1915 g_main_context_find_source_by_funcs_user_data (GMainContext *context,
1916 GSourceFuncs *funcs,
1922 g_return_val_if_fail (funcs != NULL, NULL);
1924 if (context == NULL)
1925 context = g_main_context_default ();
1927 LOCK_CONTEXT (context);
1929 g_source_iter_init (&iter, context, FALSE);
1930 while (g_source_iter_next (&iter, &source))
1932 if (!SOURCE_DESTROYED (source) &&
1933 source->source_funcs == funcs &&
1934 source->callback_funcs)
1936 GSourceFunc callback;
1937 gpointer callback_data;
1939 source->callback_funcs->get (source->callback_data, source, &callback, &callback_data);
1941 if (callback_data == user_data)
1945 g_source_iter_clear (&iter);
1947 UNLOCK_CONTEXT (context);
1953 * g_main_context_find_source_by_user_data:
1954 * @context: a #GMainContext
1955 * @user_data: the user_data for the callback.
1957 * Finds a source with the given user data for the callback. If
1958 * multiple sources exist with the same user data, the first
1959 * one found will be returned.
1961 * Return value: (transfer none): the source, if one was found, otherwise %NULL
1964 g_main_context_find_source_by_user_data (GMainContext *context,
1970 if (context == NULL)
1971 context = g_main_context_default ();
1973 LOCK_CONTEXT (context);
1975 g_source_iter_init (&iter, context, FALSE);
1976 while (g_source_iter_next (&iter, &source))
1978 if (!SOURCE_DESTROYED (source) &&
1979 source->callback_funcs)
1981 GSourceFunc callback;
1982 gpointer callback_data = NULL;
1984 source->callback_funcs->get (source->callback_data, source, &callback, &callback_data);
1986 if (callback_data == user_data)
1990 g_source_iter_clear (&iter);
1992 UNLOCK_CONTEXT (context);
1999 * @tag: the ID of the source to remove.
2001 * Removes the source with the given id from the default main context.
2003 * a #GSource is given by g_source_get_id(), or will be returned by the
2004 * functions g_source_attach(), g_idle_add(), g_idle_add_full(),
2005 * g_timeout_add(), g_timeout_add_full(), g_child_watch_add(),
2006 * g_child_watch_add_full(), g_io_add_watch(), and g_io_add_watch_full().
2008 * See also g_source_destroy(). You must use g_source_destroy() for sources
2009 * added to a non-default main context.
2011 * Return value: %TRUE if the source was found and removed.
2014 g_source_remove (guint tag)
2018 g_return_val_if_fail (tag > 0, FALSE);
2020 source = g_main_context_find_source_by_id (NULL, tag);
2022 g_source_destroy (source);
2024 return source != NULL;
2028 * g_source_remove_by_user_data:
2029 * @user_data: the user_data for the callback.
2031 * Removes a source from the default main loop context given the user
2032 * data for the callback. If multiple sources exist with the same user
2033 * data, only one will be destroyed.
2035 * Return value: %TRUE if a source was found and removed.
2038 g_source_remove_by_user_data (gpointer user_data)
2042 source = g_main_context_find_source_by_user_data (NULL, user_data);
2045 g_source_destroy (source);
2053 * g_source_remove_by_funcs_user_data:
2054 * @funcs: The @source_funcs passed to g_source_new()
2055 * @user_data: the user data for the callback
2057 * Removes a source from the default main loop context given the
2058 * source functions and user data. If multiple sources exist with the
2059 * same source functions and user data, only one will be destroyed.
2061 * Return value: %TRUE if a source was found and removed.
2064 g_source_remove_by_funcs_user_data (GSourceFuncs *funcs,
2069 g_return_val_if_fail (funcs != NULL, FALSE);
2071 source = g_main_context_find_source_by_funcs_user_data (NULL, funcs, user_data);
2074 g_source_destroy (source);
2082 * g_get_current_time:
2083 * @result: #GTimeVal structure in which to store current time.
2085 * Equivalent to the UNIX gettimeofday() function, but portable.
2087 * You may find g_get_real_time() to be more convenient.
2090 g_get_current_time (GTimeVal *result)
2095 g_return_if_fail (result != NULL);
2097 /*this is required on alpha, there the timeval structs are int's
2098 not longs and a cast only would fail horribly*/
2099 gettimeofday (&r, NULL);
2100 result->tv_sec = r.tv_sec;
2101 result->tv_usec = r.tv_usec;
2106 g_return_if_fail (result != NULL);
2108 GetSystemTimeAsFileTime (&ft);
2109 memmove (&time64, &ft, sizeof (FILETIME));
2111 /* Convert from 100s of nanoseconds since 1601-01-01
2112 * to Unix epoch. Yes, this is Y2038 unsafe.
2114 time64 -= G_GINT64_CONSTANT (116444736000000000);
2117 result->tv_sec = time64 / 1000000;
2118 result->tv_usec = time64 % 1000000;
2125 * Queries the system wall-clock time.
2127 * This call is functionally equivalent to g_get_current_time() except
2128 * that the return value is often more convenient than dealing with a
2131 * You should only use this call if you are actually interested in the real
2132 * wall-clock time. g_get_monotonic_time() is probably more useful for
2133 * measuring intervals.
2135 * Returns: the number of microseconds since January 1, 1970 UTC.
2140 g_get_real_time (void)
2144 g_get_current_time (&tv);
2146 return (((gint64) tv.tv_sec) * 1000000) + tv.tv_usec;
2150 static ULONGLONG (*g_GetTickCount64) (void) = NULL;
2151 static guint32 g_win32_tick_epoch = 0;
2153 G_GNUC_INTERNAL void
2154 g_clock_win32_init (void)
2158 g_GetTickCount64 = NULL;
2159 kernel32 = GetModuleHandle ("KERNEL32.DLL");
2160 if (kernel32 != NULL)
2161 g_GetTickCount64 = (void *) GetProcAddress (kernel32, "GetTickCount64");
2162 g_win32_tick_epoch = ((guint32)GetTickCount()) >> 31;
2167 * g_get_monotonic_time:
2169 * Queries the system monotonic time, if available.
2171 * On POSIX systems with clock_gettime() and <literal>CLOCK_MONOTONIC</literal> this call
2172 * is a very shallow wrapper for that. Otherwise, we make a best effort
2173 * that probably involves returning the wall clock time (with at least
2174 * microsecond accuracy, subject to the limitations of the OS kernel).
2176 * It's important to note that POSIX <literal>CLOCK_MONOTONIC</literal> does
2177 * not count time spent while the machine is suspended.
2179 * On Windows, "limitations of the OS kernel" is a rather substantial
2180 * statement. Depending on the configuration of the system, the wall
2181 * clock time is updated as infrequently as 64 times a second (which
2182 * is approximately every 16ms). Also, on XP (but not on Vista or later)
2183 * the monotonic clock is locally monotonic, but may differ in exact
2184 * value between processes due to timer wrap handling.
2186 * Returns: the monotonic time, in microseconds
2191 g_get_monotonic_time (void)
2193 #ifdef HAVE_CLOCK_GETTIME
2194 /* librt clock_gettime() is our first choice */
2197 #ifdef CLOCK_MONOTONIC
2198 clock_gettime (CLOCK_MONOTONIC, &ts);
2200 clock_gettime (CLOCK_REALTIME, &ts);
2203 /* In theory monotonic time can have any epoch.
2205 * glib presently assumes the following:
2207 * 1) The epoch comes some time after the birth of Jesus of Nazareth, but
2208 * not more than 10000 years later.
2210 * 2) The current time also falls sometime within this range.
2212 * These two reasonable assumptions leave us with a maximum deviation from
2213 * the epoch of 10000 years, or 315569520000000000 seconds.
2215 * If we restrict ourselves to this range then the number of microseconds
2216 * will always fit well inside the constraints of a int64 (by a factor of
2219 * If you actually hit the following assertion, probably you should file a
2220 * bug against your operating system for being excessively silly.
2222 g_assert (G_GINT64_CONSTANT (-315569520000000000) < ts.tv_sec &&
2223 ts.tv_sec < G_GINT64_CONSTANT (315569520000000000));
2225 return (((gint64) ts.tv_sec) * 1000000) + (ts.tv_nsec / 1000);
2227 #elif defined (G_OS_WIN32)
2231 /* There are four sources for the monotonic time on Windows:
2233 * Three are based on a (1 msec accuracy, but only read periodically) clock chip:
2234 * - GetTickCount (GTC)
2235 * 32bit msec counter, updated each ~15msec, wraps in ~50 days
2236 * - GetTickCount64 (GTC64)
2237 * Same as GetTickCount, but extended to 64bit, so no wrap
2238 * Only available in Vista or later
2239 * - timeGetTime (TGT)
2240 * similar to GetTickCount by default: 15msec, 50 day wrap.
2241 * available in winmm.dll (thus known as the multimedia timers)
2242 * However apps can raise the system timer clock frequency using timeBeginPeriod()
2243 * increasing the accuracy up to 1 msec, at a cost in general system performance
2246 * One is based on high precision clocks:
2247 * - QueryPrecisionCounter (QPC)
2248 * This has much higher accuracy, but is not guaranteed monotonic, and
2249 * has lots of complications like clock jumps and different times on different
2250 * CPUs. It also has lower long term accuracy (i.e. it will drift compared to
2251 * the low precision clocks.
2253 * Additionally, the precision available in the timer-based wakeup such as
2254 * MsgWaitForMultipleObjectsEx (which is what the mainloop is based on) is based
2255 * on the TGT resolution, so by default it is ~15msec, but can be increased by apps.
2257 * The QPC timer has too many issues to be used as is. The only way it could be used
2258 * is to use it to interpolate the lower precision clocks. Firefox does something like
2260 * https://bugzilla.mozilla.org/show_bug.cgi?id=363258
2262 * However this seems quite complicated, so we're not doing this right now.
2264 * The approach we take instead is to use the TGT timer, extending it to 64bit
2265 * either by using the GTC64 value, or if that is not available, a process local
2266 * time epoch that we increment when we detect a timer wrap (assumes that we read
2267 * the time at least once every 50 days).
2270 * - We have a globally consistent monotonic clock on Vista and later
2271 * - We have a locally monotonic clock on XP
2272 * - Apps that need higher precision in timeouts and clock reads can call
2273 * timeBeginPeriod() to increase it as much as they want
2276 if (g_GetTickCount64 != NULL)
2278 guint32 ticks_as_32bit;
2280 ticks = g_GetTickCount64 ();
2281 ticks32 = timeGetTime();
2283 /* GTC64 and TGT are sampled at different times, however they
2284 * have the same base and source (msecs since system boot).
2285 * They can differ by as much as -16 to +16 msecs.
2286 * We can't just inject the low bits into the 64bit counter
2287 * as one of the counters can have wrapped in 32bit space and
2288 * the other not. Instead we calculate the signed difference
2289 * in 32bit space and apply that difference to the 64bit counter.
2291 ticks_as_32bit = (guint32)ticks;
2293 /* We could do some 2's complement hack, but we play it safe */
2294 if (ticks32 - ticks_as_32bit <= G_MAXINT32)
2295 ticks += ticks32 - ticks_as_32bit;
2297 ticks -= ticks_as_32bit - ticks32;
2303 epoch = g_atomic_int_get (&g_win32_tick_epoch);
2305 /* Must read ticks after the epoch. Then we're guaranteed
2306 * that the ticks value we read is higher or equal to any
2307 * previous ones that lead to the writing of the epoch.
2309 ticks32 = timeGetTime();
2311 /* We store the MSB of the current time as the LSB
2312 * of the epoch. Comparing these bits lets us detect when
2313 * the 32bit counter has wrapped so we can increase the
2316 * This will work as long as this function is called at
2317 * least once every ~24 days, which is half the wrap time
2318 * of a 32bit msec counter. I think this is pretty likely.
2320 * Note that g_win32_tick_epoch is a process local state,
2321 * so the monotonic clock will not be the same between
2324 if ((ticks32 >> 31) != (epoch & 1))
2327 g_atomic_int_set (&g_win32_tick_epoch, epoch);
2331 ticks = (guint64)ticks32 | ((guint64)epoch) << 31;
2334 return ticks * 1000;
2336 #else /* !HAVE_CLOCK_GETTIME && ! G_OS_WIN32*/
2340 g_get_current_time (&tv);
2342 return (((gint64) tv.tv_sec) * 1000000) + tv.tv_usec;
2347 g_main_dispatch_free (gpointer dispatch)
2349 g_slice_free (GMainDispatch, dispatch);
2352 /* Running the main loop */
2354 static GMainDispatch *
2357 static GPrivate depth_private = G_PRIVATE_INIT (g_main_dispatch_free);
2358 GMainDispatch *dispatch;
2360 dispatch = g_private_get (&depth_private);
2364 dispatch = g_slice_new0 (GMainDispatch);
2365 g_private_set (&depth_private, dispatch);
2374 * Returns the depth of the stack of calls to
2375 * g_main_context_dispatch() on any #GMainContext in the current thread.
2376 * That is, when called from the toplevel, it gives 0. When
2377 * called from within a callback from g_main_context_iteration()
2378 * (or g_main_loop_run(), etc.) it returns 1. When called from within
2379 * a callback to a recursive call to g_main_context_iteration(),
2380 * it returns 2. And so forth.
2382 * This function is useful in a situation like the following:
2383 * Imagine an extremely simple "garbage collected" system.
2386 * static GList *free_list;
2389 * allocate_memory (gsize size)
2391 * gpointer result = g_malloc (size);
2392 * free_list = g_list_prepend (free_list, result);
2397 * free_allocated_memory (void)
2400 * for (l = free_list; l; l = l->next);
2402 * g_list_free (free_list);
2410 * g_main_context_iteration (NULL, TRUE);
2411 * free_allocated_memory();
2415 * This works from an application, however, if you want to do the same
2416 * thing from a library, it gets more difficult, since you no longer
2417 * control the main loop. You might think you can simply use an idle
2418 * function to make the call to free_allocated_memory(), but that
2419 * doesn't work, since the idle function could be called from a
2420 * recursive callback. This can be fixed by using g_main_depth()
2424 * allocate_memory (gsize size)
2426 * FreeListBlock *block = g_new (FreeListBlock, 1);
2427 * block->mem = g_malloc (size);
2428 * block->depth = g_main_depth ();
2429 * free_list = g_list_prepend (free_list, block);
2430 * return block->mem;
2434 * free_allocated_memory (void)
2438 * int depth = g_main_depth ();
2439 * for (l = free_list; l; );
2441 * GList *next = l->next;
2442 * FreeListBlock *block = l->data;
2443 * if (block->depth > depth)
2445 * g_free (block->mem);
2447 * free_list = g_list_delete_link (free_list, l);
2455 * There is a temptation to use g_main_depth() to solve
2456 * problems with reentrancy. For instance, while waiting for data
2457 * to be received from the network in response to a menu item,
2458 * the menu item might be selected again. It might seem that
2459 * one could make the menu item's callback return immediately
2460 * and do nothing if g_main_depth() returns a value greater than 1.
2461 * However, this should be avoided since the user then sees selecting
2462 * the menu item do nothing. Furthermore, you'll find yourself adding
2463 * these checks all over your code, since there are doubtless many,
2464 * many things that the user could do. Instead, you can use the
2465 * following techniques:
2470 * Use gtk_widget_set_sensitive() or modal dialogs to prevent
2471 * the user from interacting with elements while the main
2472 * loop is recursing.
2477 * Avoid main loop recursion in situations where you can't handle
2478 * arbitrary callbacks. Instead, structure your code so that you
2479 * simply return to the main loop and then get called again when
2480 * there is more work to do.
2485 * Return value: The main loop recursion level in the current thread
2490 GMainDispatch *dispatch = get_dispatch ();
2491 return dispatch->depth;
2495 * g_main_current_source:
2497 * Returns the currently firing source for this thread.
2499 * Return value: (transfer none): The currently firing source or %NULL.
2504 g_main_current_source (void)
2506 GMainDispatch *dispatch = get_dispatch ();
2507 return dispatch->dispatching_sources ? dispatch->dispatching_sources->data : NULL;
2511 * g_source_is_destroyed:
2512 * @source: a #GSource
2514 * Returns whether @source has been destroyed.
2516 * This is important when you operate upon your objects
2517 * from within idle handlers, but may have freed the object
2518 * before the dispatch of your idle handler.
2522 * idle_callback (gpointer data)
2524 * SomeWidget *self = data;
2526 * GDK_THREADS_ENTER (<!-- -->);
2527 * /<!-- -->* do stuff with self *<!-- -->/
2528 * self->idle_id = 0;
2529 * GDK_THREADS_LEAVE (<!-- -->);
2531 * return G_SOURCE_REMOVE;
2535 * some_widget_do_stuff_later (SomeWidget *self)
2537 * self->idle_id = g_idle_add (idle_callback, self);
2541 * some_widget_finalize (GObject *object)
2543 * SomeWidget *self = SOME_WIDGET (object);
2545 * if (self->idle_id)
2546 * g_source_remove (self->idle_id);
2548 * G_OBJECT_CLASS (parent_class)->finalize (object);
2552 * This will fail in a multi-threaded application if the
2553 * widget is destroyed before the idle handler fires due
2554 * to the use after free in the callback. A solution, to
2555 * this particular problem, is to check to if the source
2556 * has already been destroy within the callback.
2560 * idle_callback (gpointer data)
2562 * SomeWidget *self = data;
2564 * GDK_THREADS_ENTER ();
2565 * if (!g_source_is_destroyed (g_main_current_source ()))
2567 * /<!-- -->* do stuff with self *<!-- -->/
2569 * GDK_THREADS_LEAVE ();
2575 * Return value: %TRUE if the source has been destroyed
2580 g_source_is_destroyed (GSource *source)
2582 return SOURCE_DESTROYED (source);
2585 /* Temporarily remove all this source's file descriptors from the
2586 * poll(), so that if data comes available for one of the file descriptors
2587 * we don't continually spin in the poll()
2589 /* HOLDS: source->context's lock */
2591 block_source (GSource *source)
2595 g_return_if_fail (!SOURCE_BLOCKED (source));
2597 source->flags |= G_SOURCE_BLOCKED;
2599 tmp_list = source->poll_fds;
2602 g_main_context_remove_poll_unlocked (source->context, tmp_list->data);
2603 tmp_list = tmp_list->next;
2606 if (source->priv && source->priv->child_sources)
2608 tmp_list = source->priv->child_sources;
2611 block_source (tmp_list->data);
2612 tmp_list = tmp_list->next;
2617 /* HOLDS: source->context's lock */
2619 unblock_source (GSource *source)
2623 g_return_if_fail (SOURCE_BLOCKED (source)); /* Source already unblocked */
2624 g_return_if_fail (!SOURCE_DESTROYED (source));
2626 source->flags &= ~G_SOURCE_BLOCKED;
2628 tmp_list = source->poll_fds;
2631 g_main_context_add_poll_unlocked (source->context, source->priority, tmp_list->data);
2632 tmp_list = tmp_list->next;
2635 if (source->priv && source->priv->child_sources)
2637 tmp_list = source->priv->child_sources;
2640 unblock_source (tmp_list->data);
2641 tmp_list = tmp_list->next;
2646 /* HOLDS: context's lock */
2648 g_main_dispatch (GMainContext *context)
2650 GMainDispatch *current = get_dispatch ();
2653 for (i = 0; i < context->pending_dispatches->len; i++)
2655 GSource *source = context->pending_dispatches->pdata[i];
2657 context->pending_dispatches->pdata[i] = NULL;
2660 source->flags &= ~G_SOURCE_READY;
2662 if (!SOURCE_DESTROYED (source))
2664 gboolean was_in_call;
2665 gpointer user_data = NULL;
2666 GSourceFunc callback = NULL;
2667 GSourceCallbackFuncs *cb_funcs;
2669 gboolean need_destroy;
2671 gboolean (*dispatch) (GSource *,
2674 GSList current_source_link;
2676 dispatch = source->source_funcs->dispatch;
2677 cb_funcs = source->callback_funcs;
2678 cb_data = source->callback_data;
2681 cb_funcs->ref (cb_data);
2683 if ((source->flags & G_SOURCE_CAN_RECURSE) == 0)
2684 block_source (source);
2686 was_in_call = source->flags & G_HOOK_FLAG_IN_CALL;
2687 source->flags |= G_HOOK_FLAG_IN_CALL;
2690 cb_funcs->get (cb_data, source, &callback, &user_data);
2692 UNLOCK_CONTEXT (context);
2695 /* The on-stack allocation of the GSList is unconventional, but
2696 * we know that the lifetime of the link is bounded to this
2697 * function as the link is kept in a thread specific list and
2698 * not manipulated outside of this function and its descendants.
2699 * Avoiding the overhead of a g_slist_alloc() is useful as many
2700 * applications do little more than dispatch events.
2702 * This is a performance hack - do not revert to g_slist_prepend()!
2704 current_source_link.data = source;
2705 current_source_link.next = current->dispatching_sources;
2706 current->dispatching_sources = ¤t_source_link;
2707 need_destroy = ! dispatch (source,
2710 g_assert (current->dispatching_sources == ¤t_source_link);
2711 current->dispatching_sources = current_source_link.next;
2715 cb_funcs->unref (cb_data);
2717 LOCK_CONTEXT (context);
2720 source->flags &= ~G_HOOK_FLAG_IN_CALL;
2722 if (SOURCE_BLOCKED (source) && !SOURCE_DESTROYED (source))
2723 unblock_source (source);
2725 /* Note: this depends on the fact that we can't switch
2726 * sources from one main context to another
2728 if (need_destroy && !SOURCE_DESTROYED (source))
2730 g_assert (source->context == context);
2731 g_source_destroy_internal (source, context, TRUE);
2735 SOURCE_UNREF (source, context);
2738 g_ptr_array_set_size (context->pending_dispatches, 0);
2742 * g_main_context_acquire:
2743 * @context: a #GMainContext
2745 * Tries to become the owner of the specified context.
2746 * If some other thread is the owner of the context,
2747 * returns %FALSE immediately. Ownership is properly
2748 * recursive: the owner can require ownership again
2749 * and will release ownership when g_main_context_release()
2750 * is called as many times as g_main_context_acquire().
2752 * You must be the owner of a context before you
2753 * can call g_main_context_prepare(), g_main_context_query(),
2754 * g_main_context_check(), g_main_context_dispatch().
2756 * Return value: %TRUE if the operation succeeded, and
2757 * this thread is now the owner of @context.
2760 g_main_context_acquire (GMainContext *context)
2762 gboolean result = FALSE;
2763 GThread *self = G_THREAD_SELF;
2765 if (context == NULL)
2766 context = g_main_context_default ();
2768 LOCK_CONTEXT (context);
2770 if (!context->owner)
2772 context->owner = self;
2773 g_assert (context->owner_count == 0);
2776 if (context->owner == self)
2778 context->owner_count++;
2782 UNLOCK_CONTEXT (context);
2788 * g_main_context_release:
2789 * @context: a #GMainContext
2791 * Releases ownership of a context previously acquired by this thread
2792 * with g_main_context_acquire(). If the context was acquired multiple
2793 * times, the ownership will be released only when g_main_context_release()
2794 * is called as many times as it was acquired.
2797 g_main_context_release (GMainContext *context)
2799 if (context == NULL)
2800 context = g_main_context_default ();
2802 LOCK_CONTEXT (context);
2804 context->owner_count--;
2805 if (context->owner_count == 0)
2807 context->owner = NULL;
2809 if (context->waiters)
2811 GMainWaiter *waiter = context->waiters->data;
2812 gboolean loop_internal_waiter = (waiter->mutex == &context->mutex);
2813 context->waiters = g_slist_delete_link (context->waiters,
2815 if (!loop_internal_waiter)
2816 g_mutex_lock (waiter->mutex);
2818 g_cond_signal (waiter->cond);
2820 if (!loop_internal_waiter)
2821 g_mutex_unlock (waiter->mutex);
2825 UNLOCK_CONTEXT (context);
2829 * g_main_context_wait:
2830 * @context: a #GMainContext
2831 * @cond: a condition variable
2832 * @mutex: a mutex, currently held
2834 * Tries to become the owner of the specified context,
2835 * as with g_main_context_acquire(). But if another thread
2836 * is the owner, atomically drop @mutex and wait on @cond until
2837 * that owner releases ownership or until @cond is signaled, then
2838 * try again (once) to become the owner.
2840 * Return value: %TRUE if the operation succeeded, and
2841 * this thread is now the owner of @context.
2844 g_main_context_wait (GMainContext *context,
2848 gboolean result = FALSE;
2849 GThread *self = G_THREAD_SELF;
2850 gboolean loop_internal_waiter;
2852 if (context == NULL)
2853 context = g_main_context_default ();
2855 loop_internal_waiter = (mutex == &context->mutex);
2857 if (!loop_internal_waiter)
2858 LOCK_CONTEXT (context);
2860 if (context->owner && context->owner != self)
2865 waiter.mutex = mutex;
2867 context->waiters = g_slist_append (context->waiters, &waiter);
2869 if (!loop_internal_waiter)
2870 UNLOCK_CONTEXT (context);
2871 g_cond_wait (cond, mutex);
2872 if (!loop_internal_waiter)
2873 LOCK_CONTEXT (context);
2875 context->waiters = g_slist_remove (context->waiters, &waiter);
2878 if (!context->owner)
2880 context->owner = self;
2881 g_assert (context->owner_count == 0);
2884 if (context->owner == self)
2886 context->owner_count++;
2890 if (!loop_internal_waiter)
2891 UNLOCK_CONTEXT (context);
2897 * g_main_context_prepare:
2898 * @context: a #GMainContext
2899 * @priority: location to store priority of highest priority
2900 * source already ready.
2902 * Prepares to poll sources within a main loop. The resulting information
2903 * for polling is determined by calling g_main_context_query ().
2905 * Return value: %TRUE if some source is ready to be dispatched
2909 g_main_context_prepare (GMainContext *context,
2914 gint current_priority = G_MAXINT;
2918 if (context == NULL)
2919 context = g_main_context_default ();
2921 LOCK_CONTEXT (context);
2923 context->time_is_fresh = FALSE;
2925 if (context->in_check_or_prepare)
2927 g_warning ("g_main_context_prepare() called recursively from within a source's check() or "
2928 "prepare() member.");
2929 UNLOCK_CONTEXT (context);
2934 /* If recursing, finish up current dispatch, before starting over */
2935 if (context->pending_dispatches)
2938 g_main_dispatch (context, ¤t_time);
2940 UNLOCK_CONTEXT (context);
2945 /* If recursing, clear list of pending dispatches */
2947 for (i = 0; i < context->pending_dispatches->len; i++)
2949 if (context->pending_dispatches->pdata[i])
2950 SOURCE_UNREF ((GSource *)context->pending_dispatches->pdata[i], context);
2952 g_ptr_array_set_size (context->pending_dispatches, 0);
2954 /* Prepare all sources */
2956 context->timeout = -1;
2958 g_source_iter_init (&iter, context, TRUE);
2959 while (g_source_iter_next (&iter, &source))
2961 gint source_timeout = -1;
2963 if (SOURCE_DESTROYED (source) || SOURCE_BLOCKED (source))
2965 if ((n_ready > 0) && (source->priority > current_priority))
2968 if (!(source->flags & G_SOURCE_READY))
2971 gboolean (*prepare) (GSource *source,
2974 prepare = source->source_funcs->prepare;
2975 context->in_check_or_prepare++;
2976 UNLOCK_CONTEXT (context);
2978 result = (*prepare) (source, &source_timeout);
2980 LOCK_CONTEXT (context);
2981 context->in_check_or_prepare--;
2985 GSource *ready_source = source;
2987 while (ready_source)
2989 ready_source->flags |= G_SOURCE_READY;
2990 ready_source = ready_source->priv->parent_source;
2995 if (source->flags & G_SOURCE_READY)
2998 current_priority = source->priority;
2999 context->timeout = 0;
3002 if (source_timeout >= 0)
3004 if (context->timeout < 0)
3005 context->timeout = source_timeout;
3007 context->timeout = MIN (context->timeout, source_timeout);
3010 g_source_iter_clear (&iter);
3012 UNLOCK_CONTEXT (context);
3015 *priority = current_priority;
3017 return (n_ready > 0);
3021 * g_main_context_query:
3022 * @context: a #GMainContext
3023 * @max_priority: maximum priority source to check
3024 * @timeout_: (out): location to store timeout to be used in polling
3025 * @fds: (out caller-allocates) (array length=n_fds): location to
3026 * store #GPollFD records that need to be polled.
3027 * @n_fds: length of @fds.
3029 * Determines information necessary to poll this main loop.
3031 * Return value: the number of records actually stored in @fds,
3032 * or, if more than @n_fds records need to be stored, the number
3033 * of records that need to be stored.
3036 g_main_context_query (GMainContext *context,
3045 LOCK_CONTEXT (context);
3047 pollrec = context->poll_records;
3049 while (pollrec && max_priority >= pollrec->priority)
3051 /* We need to include entries with fd->events == 0 in the array because
3052 * otherwise if the application changes fd->events behind our back and
3053 * makes it non-zero, we'll be out of sync when we check the fds[] array.
3054 * (Changing fd->events after adding an FD wasn't an anticipated use of
3055 * this API, but it occurs in practice.) */
3058 fds[n_poll].fd = pollrec->fd->fd;
3059 /* In direct contradiction to the Unix98 spec, IRIX runs into
3060 * difficulty if you pass in POLLERR, POLLHUP or POLLNVAL
3061 * flags in the events field of the pollfd while it should
3062 * just ignoring them. So we mask them out here.
3064 fds[n_poll].events = pollrec->fd->events & ~(G_IO_ERR|G_IO_HUP|G_IO_NVAL);
3065 fds[n_poll].revents = 0;
3068 pollrec = pollrec->next;
3072 context->poll_changed = FALSE;
3076 *timeout = context->timeout;
3078 context->time_is_fresh = FALSE;
3081 UNLOCK_CONTEXT (context);
3087 * g_main_context_check:
3088 * @context: a #GMainContext
3089 * @max_priority: the maximum numerical priority of sources to check
3090 * @fds: (array length=n_fds): array of #GPollFD's that was passed to
3091 * the last call to g_main_context_query()
3092 * @n_fds: return value of g_main_context_query()
3094 * Passes the results of polling back to the main loop.
3096 * Return value: %TRUE if some sources are ready to be dispatched.
3099 g_main_context_check (GMainContext *context,
3110 LOCK_CONTEXT (context);
3112 if (context->in_check_or_prepare)
3114 g_warning ("g_main_context_check() called recursively from within a source's check() or "
3115 "prepare() member.");
3116 UNLOCK_CONTEXT (context);
3120 if (context->wake_up_rec.revents)
3121 g_wakeup_acknowledge (context->wakeup);
3123 /* If the set of poll file descriptors changed, bail out
3124 * and let the main loop rerun
3126 if (context->poll_changed)
3128 UNLOCK_CONTEXT (context);
3132 pollrec = context->poll_records;
3136 if (pollrec->fd->events)
3137 pollrec->fd->revents = fds[i].revents;
3139 pollrec = pollrec->next;
3143 g_source_iter_init (&iter, context, TRUE);
3144 while (g_source_iter_next (&iter, &source))
3146 if (SOURCE_DESTROYED (source) || SOURCE_BLOCKED (source))
3148 if ((n_ready > 0) && (source->priority > max_priority))
3151 if (!(source->flags & G_SOURCE_READY))
3154 gboolean (*check) (GSource *source);
3156 check = source->source_funcs->check;
3158 context->in_check_or_prepare++;
3159 UNLOCK_CONTEXT (context);
3161 result = (*check) (source);
3163 LOCK_CONTEXT (context);
3164 context->in_check_or_prepare--;
3168 GSource *ready_source = source;
3170 while (ready_source)
3172 ready_source->flags |= G_SOURCE_READY;
3173 ready_source = ready_source->priv->parent_source;
3178 if (source->flags & G_SOURCE_READY)
3180 source->ref_count++;
3181 g_ptr_array_add (context->pending_dispatches, source);
3185 /* never dispatch sources with less priority than the first
3186 * one we choose to dispatch
3188 max_priority = source->priority;
3191 g_source_iter_clear (&iter);
3193 UNLOCK_CONTEXT (context);
3199 * g_main_context_dispatch:
3200 * @context: a #GMainContext
3202 * Dispatches all pending sources.
3205 g_main_context_dispatch (GMainContext *context)
3207 LOCK_CONTEXT (context);
3209 if (context->pending_dispatches->len > 0)
3211 g_main_dispatch (context);
3214 UNLOCK_CONTEXT (context);
3217 /* HOLDS context lock */
3219 g_main_context_iterate (GMainContext *context,
3226 gboolean some_ready;
3227 gint nfds, allocated_nfds;
3228 GPollFD *fds = NULL;
3230 UNLOCK_CONTEXT (context);
3232 if (!g_main_context_acquire (context))
3234 gboolean got_ownership;
3236 LOCK_CONTEXT (context);
3241 got_ownership = g_main_context_wait (context,
3249 LOCK_CONTEXT (context);
3251 if (!context->cached_poll_array)
3253 context->cached_poll_array_size = context->n_poll_records;
3254 context->cached_poll_array = g_new (GPollFD, context->n_poll_records);
3257 allocated_nfds = context->cached_poll_array_size;
3258 fds = context->cached_poll_array;
3260 UNLOCK_CONTEXT (context);
3262 g_main_context_prepare (context, &max_priority);
3264 while ((nfds = g_main_context_query (context, max_priority, &timeout, fds,
3265 allocated_nfds)) > allocated_nfds)
3267 LOCK_CONTEXT (context);
3269 context->cached_poll_array_size = allocated_nfds = nfds;
3270 context->cached_poll_array = fds = g_new (GPollFD, nfds);
3271 UNLOCK_CONTEXT (context);
3277 g_main_context_poll (context, timeout, max_priority, fds, nfds);
3279 some_ready = g_main_context_check (context, max_priority, fds, nfds);
3282 g_main_context_dispatch (context);
3284 g_main_context_release (context);
3286 LOCK_CONTEXT (context);
3292 * g_main_context_pending:
3293 * @context: (allow-none): a #GMainContext (if %NULL, the default context will be used)
3295 * Checks if any sources have pending events for the given context.
3297 * Return value: %TRUE if events are pending.
3300 g_main_context_pending (GMainContext *context)
3305 context = g_main_context_default();
3307 LOCK_CONTEXT (context);
3308 retval = g_main_context_iterate (context, FALSE, FALSE, G_THREAD_SELF);
3309 UNLOCK_CONTEXT (context);
3315 * g_main_context_iteration:
3316 * @context: (allow-none): a #GMainContext (if %NULL, the default context will be used)
3317 * @may_block: whether the call may block.
3319 * Runs a single iteration for the given main loop. This involves
3320 * checking to see if any event sources are ready to be processed,
3321 * then if no events sources are ready and @may_block is %TRUE, waiting
3322 * for a source to become ready, then dispatching the highest priority
3323 * events sources that are ready. Otherwise, if @may_block is %FALSE
3324 * sources are not waited to become ready, only those highest priority
3325 * events sources will be dispatched (if any), that are ready at this
3326 * given moment without further waiting.
3328 * Note that even when @may_block is %TRUE, it is still possible for
3329 * g_main_context_iteration() to return %FALSE, since the wait may
3330 * be interrupted for other reasons than an event source becoming ready.
3332 * Return value: %TRUE if events were dispatched.
3335 g_main_context_iteration (GMainContext *context, gboolean may_block)
3340 context = g_main_context_default();
3342 LOCK_CONTEXT (context);
3343 retval = g_main_context_iterate (context, may_block, TRUE, G_THREAD_SELF);
3344 UNLOCK_CONTEXT (context);
3351 * @context: (allow-none): a #GMainContext (if %NULL, the default context will be used).
3352 * @is_running: set to %TRUE to indicate that the loop is running. This
3353 * is not very important since calling g_main_loop_run() will set this to
3356 * Creates a new #GMainLoop structure.
3358 * Return value: a new #GMainLoop.
3361 g_main_loop_new (GMainContext *context,
3362 gboolean is_running)
3367 context = g_main_context_default();
3369 g_main_context_ref (context);
3371 loop = g_new0 (GMainLoop, 1);
3372 loop->context = context;
3373 loop->is_running = is_running != FALSE;
3374 loop->ref_count = 1;
3381 * @loop: a #GMainLoop
3383 * Increases the reference count on a #GMainLoop object by one.
3385 * Return value: @loop
3388 g_main_loop_ref (GMainLoop *loop)
3390 g_return_val_if_fail (loop != NULL, NULL);
3391 g_return_val_if_fail (g_atomic_int_get (&loop->ref_count) > 0, NULL);
3393 g_atomic_int_inc (&loop->ref_count);
3399 * g_main_loop_unref:
3400 * @loop: a #GMainLoop
3402 * Decreases the reference count on a #GMainLoop object by one. If
3403 * the result is zero, free the loop and free all associated memory.
3406 g_main_loop_unref (GMainLoop *loop)
3408 g_return_if_fail (loop != NULL);
3409 g_return_if_fail (g_atomic_int_get (&loop->ref_count) > 0);
3411 if (!g_atomic_int_dec_and_test (&loop->ref_count))
3414 g_main_context_unref (loop->context);
3420 * @loop: a #GMainLoop
3422 * Runs a main loop until g_main_loop_quit() is called on the loop.
3423 * If this is called for the thread of the loop's #GMainContext,
3424 * it will process events from the loop, otherwise it will
3428 g_main_loop_run (GMainLoop *loop)
3430 GThread *self = G_THREAD_SELF;
3432 g_return_if_fail (loop != NULL);
3433 g_return_if_fail (g_atomic_int_get (&loop->ref_count) > 0);
3435 if (!g_main_context_acquire (loop->context))
3437 gboolean got_ownership = FALSE;
3439 /* Another thread owns this context */
3440 LOCK_CONTEXT (loop->context);
3442 g_atomic_int_inc (&loop->ref_count);
3444 if (!loop->is_running)
3445 loop->is_running = TRUE;
3447 while (loop->is_running && !got_ownership)
3448 got_ownership = g_main_context_wait (loop->context,
3449 &loop->context->cond,
3450 &loop->context->mutex);
3452 if (!loop->is_running)
3454 UNLOCK_CONTEXT (loop->context);
3456 g_main_context_release (loop->context);
3457 g_main_loop_unref (loop);
3461 g_assert (got_ownership);
3464 LOCK_CONTEXT (loop->context);
3466 if (loop->context->in_check_or_prepare)
3468 g_warning ("g_main_loop_run(): called recursively from within a source's "
3469 "check() or prepare() member, iteration not possible.");
3473 g_atomic_int_inc (&loop->ref_count);
3474 loop->is_running = TRUE;
3475 while (loop->is_running)
3476 g_main_context_iterate (loop->context, TRUE, TRUE, self);
3478 UNLOCK_CONTEXT (loop->context);
3480 g_main_context_release (loop->context);
3482 g_main_loop_unref (loop);
3487 * @loop: a #GMainLoop
3489 * Stops a #GMainLoop from running. Any calls to g_main_loop_run()
3490 * for the loop will return.
3492 * Note that sources that have already been dispatched when
3493 * g_main_loop_quit() is called will still be executed.
3496 g_main_loop_quit (GMainLoop *loop)
3498 g_return_if_fail (loop != NULL);
3499 g_return_if_fail (g_atomic_int_get (&loop->ref_count) > 0);
3501 LOCK_CONTEXT (loop->context);
3502 loop->is_running = FALSE;
3503 g_wakeup_signal (loop->context->wakeup);
3505 g_cond_broadcast (&loop->context->cond);
3507 UNLOCK_CONTEXT (loop->context);
3511 * g_main_loop_is_running:
3512 * @loop: a #GMainLoop.
3514 * Checks to see if the main loop is currently being run via g_main_loop_run().
3516 * Return value: %TRUE if the mainloop is currently being run.
3519 g_main_loop_is_running (GMainLoop *loop)
3521 g_return_val_if_fail (loop != NULL, FALSE);
3522 g_return_val_if_fail (g_atomic_int_get (&loop->ref_count) > 0, FALSE);
3524 return loop->is_running;
3528 * g_main_loop_get_context:
3529 * @loop: a #GMainLoop.
3531 * Returns the #GMainContext of @loop.
3533 * Return value: (transfer none): the #GMainContext of @loop
3536 g_main_loop_get_context (GMainLoop *loop)
3538 g_return_val_if_fail (loop != NULL, NULL);
3539 g_return_val_if_fail (g_atomic_int_get (&loop->ref_count) > 0, NULL);
3541 return loop->context;
3544 /* HOLDS: context's lock */
3546 g_main_context_poll (GMainContext *context,
3552 #ifdef G_MAIN_POLL_DEBUG
3558 GPollFunc poll_func;
3560 if (n_fds || timeout != 0)
3562 #ifdef G_MAIN_POLL_DEBUG
3563 if (_g_main_poll_debug)
3565 g_print ("polling context=%p n=%d timeout=%d\n",
3566 context, n_fds, timeout);
3567 poll_timer = g_timer_new ();
3571 LOCK_CONTEXT (context);
3573 poll_func = context->poll_func;
3575 UNLOCK_CONTEXT (context);
3576 if ((*poll_func) (fds, n_fds, timeout) < 0 && errno != EINTR)
3579 g_warning ("poll(2) failed due to: %s.",
3580 g_strerror (errno));
3582 /* If g_poll () returns -1, it has already called g_warning() */
3586 #ifdef G_MAIN_POLL_DEBUG
3587 if (_g_main_poll_debug)
3589 LOCK_CONTEXT (context);
3591 g_print ("g_main_poll(%d) timeout: %d - elapsed %12.10f seconds",
3594 g_timer_elapsed (poll_timer, NULL));
3595 g_timer_destroy (poll_timer);
3596 pollrec = context->poll_records;
3598 while (pollrec != NULL)
3603 if (fds[i].fd == pollrec->fd->fd &&
3604 pollrec->fd->events &&
3607 g_print (" [" G_POLLFD_FORMAT " :", fds[i].fd);
3608 if (fds[i].revents & G_IO_IN)
3610 if (fds[i].revents & G_IO_OUT)
3612 if (fds[i].revents & G_IO_PRI)
3614 if (fds[i].revents & G_IO_ERR)
3616 if (fds[i].revents & G_IO_HUP)
3618 if (fds[i].revents & G_IO_NVAL)
3624 pollrec = pollrec->next;
3628 UNLOCK_CONTEXT (context);
3631 } /* if (n_fds || timeout != 0) */
3635 * g_main_context_add_poll:
3636 * @context: (allow-none): a #GMainContext (or %NULL for the default context)
3637 * @fd: a #GPollFD structure holding information about a file
3638 * descriptor to watch.
3639 * @priority: the priority for this file descriptor which should be
3640 * the same as the priority used for g_source_attach() to ensure that the
3641 * file descriptor is polled whenever the results may be needed.
3643 * Adds a file descriptor to the set of file descriptors polled for
3644 * this context. This will very seldom be used directly. Instead
3645 * a typical event source will use g_source_add_poll() instead.
3648 g_main_context_add_poll (GMainContext *context,
3653 context = g_main_context_default ();
3655 g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
3656 g_return_if_fail (fd);
3658 LOCK_CONTEXT (context);
3659 g_main_context_add_poll_unlocked (context, priority, fd);
3660 UNLOCK_CONTEXT (context);
3663 /* HOLDS: main_loop_lock */
3665 g_main_context_add_poll_unlocked (GMainContext *context,
3669 GPollRec *prevrec, *nextrec;
3670 GPollRec *newrec = g_slice_new (GPollRec);
3672 /* This file descriptor may be checked before we ever poll */
3675 newrec->priority = priority;
3677 prevrec = context->poll_records_tail;
3679 while (prevrec && priority < prevrec->priority)
3682 prevrec = prevrec->prev;
3686 prevrec->next = newrec;
3688 context->poll_records = newrec;
3690 newrec->prev = prevrec;
3691 newrec->next = nextrec;
3694 nextrec->prev = newrec;
3696 context->poll_records_tail = newrec;
3698 context->n_poll_records++;
3700 context->poll_changed = TRUE;
3702 /* Now wake up the main loop if it is waiting in the poll() */
3703 g_wakeup_signal (context->wakeup);
3707 * g_main_context_remove_poll:
3708 * @context:a #GMainContext
3709 * @fd: a #GPollFD descriptor previously added with g_main_context_add_poll()
3711 * Removes file descriptor from the set of file descriptors to be
3712 * polled for a particular context.
3715 g_main_context_remove_poll (GMainContext *context,
3719 context = g_main_context_default ();
3721 g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
3722 g_return_if_fail (fd);
3724 LOCK_CONTEXT (context);
3725 g_main_context_remove_poll_unlocked (context, fd);
3726 UNLOCK_CONTEXT (context);
3730 g_main_context_remove_poll_unlocked (GMainContext *context,
3733 GPollRec *pollrec, *prevrec, *nextrec;
3736 pollrec = context->poll_records;
3740 nextrec = pollrec->next;
3741 if (pollrec->fd == fd)
3743 if (prevrec != NULL)
3744 prevrec->next = nextrec;
3746 context->poll_records = nextrec;
3748 if (nextrec != NULL)
3749 nextrec->prev = prevrec;
3751 context->poll_records_tail = prevrec;
3753 g_slice_free (GPollRec, pollrec);
3755 context->n_poll_records--;
3762 context->poll_changed = TRUE;
3764 /* Now wake up the main loop if it is waiting in the poll() */
3765 g_wakeup_signal (context->wakeup);
3769 * g_source_get_current_time:
3770 * @source: a #GSource
3771 * @timeval: #GTimeVal structure in which to store current time.
3773 * This function ignores @source and is otherwise the same as
3774 * g_get_current_time().
3776 * Deprecated: 2.28: use g_source_get_time() instead
3779 g_source_get_current_time (GSource *source,
3782 g_get_current_time (timeval);
3786 * g_source_get_time:
3787 * @source: a #GSource
3789 * Gets the time to be used when checking this source. The advantage of
3790 * calling this function over calling g_get_monotonic_time() directly is
3791 * that when checking multiple sources, GLib can cache a single value
3792 * instead of having to repeatedly get the system monotonic time.
3794 * The time here is the system monotonic time, if available, or some
3795 * other reasonable alternative otherwise. See g_get_monotonic_time().
3797 * Returns: the monotonic time in microseconds
3802 g_source_get_time (GSource *source)
3804 GMainContext *context;
3807 g_return_val_if_fail (source->context != NULL, 0);
3809 context = source->context;
3811 LOCK_CONTEXT (context);
3813 if (!context->time_is_fresh)
3815 context->time = g_get_monotonic_time ();
3816 context->time_is_fresh = TRUE;
3819 result = context->time;
3821 UNLOCK_CONTEXT (context);
3827 * g_main_context_set_poll_func:
3828 * @context: a #GMainContext
3829 * @func: the function to call to poll all file descriptors
3831 * Sets the function to use to handle polling of file descriptors. It
3832 * will be used instead of the poll() system call
3833 * (or GLib's replacement function, which is used where
3834 * poll() isn't available).
3836 * This function could possibly be used to integrate the GLib event
3837 * loop with an external event loop.
3840 g_main_context_set_poll_func (GMainContext *context,
3844 context = g_main_context_default ();
3846 g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
3848 LOCK_CONTEXT (context);
3851 context->poll_func = func;
3853 context->poll_func = g_poll;
3855 UNLOCK_CONTEXT (context);
3859 * g_main_context_get_poll_func:
3860 * @context: a #GMainContext
3862 * Gets the poll function set by g_main_context_set_poll_func().
3864 * Return value: the poll function
3867 g_main_context_get_poll_func (GMainContext *context)
3872 context = g_main_context_default ();
3874 g_return_val_if_fail (g_atomic_int_get (&context->ref_count) > 0, NULL);
3876 LOCK_CONTEXT (context);
3877 result = context->poll_func;
3878 UNLOCK_CONTEXT (context);
3884 * g_main_context_wakeup:
3885 * @context: a #GMainContext
3887 * If @context is currently waiting in a poll(), interrupt
3888 * the poll(), and continue the iteration process.
3891 g_main_context_wakeup (GMainContext *context)
3894 context = g_main_context_default ();
3896 g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
3898 g_wakeup_signal (context->wakeup);
3902 * g_main_context_is_owner:
3903 * @context: a #GMainContext
3905 * Determines whether this thread holds the (recursive)
3906 * ownership of this #GMainContext. This is useful to
3907 * know before waiting on another thread that may be
3908 * blocking to get ownership of @context.
3910 * Returns: %TRUE if current thread is owner of @context.
3915 g_main_context_is_owner (GMainContext *context)
3920 context = g_main_context_default ();
3922 LOCK_CONTEXT (context);
3923 is_owner = context->owner == G_THREAD_SELF;
3924 UNLOCK_CONTEXT (context);
3932 g_timeout_set_expiration (GTimeoutSource *timeout_source,
3933 gint64 current_time)
3935 timeout_source->expiration = current_time +
3936 (guint64) timeout_source->interval * 1000;
3938 if (timeout_source->seconds)
3941 static gint timer_perturb = -1;
3943 if (timer_perturb == -1)
3946 * we want a per machine/session unique 'random' value; try the dbus
3947 * address first, that has a UUID in it. If there is no dbus, use the
3948 * hostname for hashing.
3950 const char *session_bus_address = g_getenv ("DBUS_SESSION_BUS_ADDRESS");
3951 if (!session_bus_address)
3952 session_bus_address = g_getenv ("HOSTNAME");
3953 if (session_bus_address)
3954 timer_perturb = ABS ((gint) g_str_hash (session_bus_address)) % 1000000;
3959 /* We want the microseconds part of the timeout to land on the
3960 * 'timer_perturb' mark, but we need to make sure we don't try to
3961 * set the timeout in the past. We do this by ensuring that we
3962 * always only *increase* the expiration time by adding a full
3963 * second in the case that the microsecond portion decreases.
3965 timeout_source->expiration -= timer_perturb;
3967 remainder = timeout_source->expiration % 1000000;
3968 if (remainder >= 1000000/4)
3969 timeout_source->expiration += 1000000;
3971 timeout_source->expiration -= remainder;
3972 timeout_source->expiration += timer_perturb;
3977 g_timeout_prepare (GSource *source,
3980 GTimeoutSource *timeout_source = (GTimeoutSource *) source;
3981 gint64 now = g_source_get_time (source);
3983 if (now < timeout_source->expiration)
3985 /* Round up to ensure that we don't try again too early */
3986 *timeout = (timeout_source->expiration - now + 999) / 1000;
3995 g_timeout_check (GSource *source)
3997 GTimeoutSource *timeout_source = (GTimeoutSource *) source;
3998 gint64 now = g_source_get_time (source);
4000 return timeout_source->expiration <= now;
4004 g_timeout_dispatch (GSource *source,
4005 GSourceFunc callback,
4008 GTimeoutSource *timeout_source = (GTimeoutSource *)source;
4013 g_warning ("Timeout source dispatched without callback\n"
4014 "You must call g_source_set_callback().");
4018 again = callback (user_data);
4021 g_timeout_set_expiration (timeout_source, g_source_get_time (source));
4027 * g_timeout_source_new:
4028 * @interval: the timeout interval in milliseconds.
4030 * Creates a new timeout source.
4032 * The source will not initially be associated with any #GMainContext
4033 * and must be added to one with g_source_attach() before it will be
4036 * The interval given is in terms of monotonic time, not wall clock
4037 * time. See g_get_monotonic_time().
4039 * Return value: the newly-created timeout source
4042 g_timeout_source_new (guint interval)
4044 GSource *source = g_source_new (&g_timeout_funcs, sizeof (GTimeoutSource));
4045 GTimeoutSource *timeout_source = (GTimeoutSource *)source;
4047 timeout_source->interval = interval;
4048 g_timeout_set_expiration (timeout_source, g_get_monotonic_time ());
4054 * g_timeout_source_new_seconds:
4055 * @interval: the timeout interval in seconds
4057 * Creates a new timeout source.
4059 * The source will not initially be associated with any #GMainContext
4060 * and must be added to one with g_source_attach() before it will be
4063 * The scheduling granularity/accuracy of this timeout source will be
4066 * The interval given in terms of monotonic time, not wall clock time.
4067 * See g_get_monotonic_time().
4069 * Return value: the newly-created timeout source
4074 g_timeout_source_new_seconds (guint interval)
4076 GSource *source = g_source_new (&g_timeout_funcs, sizeof (GTimeoutSource));
4077 GTimeoutSource *timeout_source = (GTimeoutSource *)source;
4079 timeout_source->interval = 1000 * interval;
4080 timeout_source->seconds = TRUE;
4082 g_timeout_set_expiration (timeout_source, g_get_monotonic_time ());
4089 * g_timeout_add_full:
4090 * @priority: the priority of the timeout source. Typically this will be in
4091 * the range between #G_PRIORITY_DEFAULT and #G_PRIORITY_HIGH.
4092 * @interval: the time between calls to the function, in milliseconds
4093 * (1/1000ths of a second)
4094 * @function: function to call
4095 * @data: data to pass to @function
4096 * @notify: (allow-none): function to call when the timeout is removed, or %NULL
4098 * Sets a function to be called at regular intervals, with the given
4099 * priority. The function is called repeatedly until it returns
4100 * %FALSE, at which point the timeout is automatically destroyed and
4101 * the function will not be called again. The @notify function is
4102 * called when the timeout is destroyed. The first call to the
4103 * function will be at the end of the first @interval.
4105 * Note that timeout functions may be delayed, due to the processing of other
4106 * event sources. Thus they should not be relied on for precise timing.
4107 * After each call to the timeout function, the time of the next
4108 * timeout is recalculated based on the current time and the given interval
4109 * (it does not try to 'catch up' time lost in delays).
4111 * This internally creates a main loop source using g_timeout_source_new()
4112 * and attaches it to the main loop context using g_source_attach(). You can
4113 * do these steps manually if you need greater control.
4115 * The interval given in terms of monotonic time, not wall clock time.
4116 * See g_get_monotonic_time().
4118 * Return value: the ID (greater than 0) of the event source.
4119 * Rename to: g_timeout_add
4122 g_timeout_add_full (gint priority,
4124 GSourceFunc function,
4126 GDestroyNotify notify)
4131 g_return_val_if_fail (function != NULL, 0);
4133 source = g_timeout_source_new (interval);
4135 if (priority != G_PRIORITY_DEFAULT)
4136 g_source_set_priority (source, priority);
4138 g_source_set_callback (source, function, data, notify);
4139 id = g_source_attach (source, NULL);
4140 g_source_unref (source);
4147 * @interval: the time between calls to the function, in milliseconds
4148 * (1/1000ths of a second)
4149 * @function: function to call
4150 * @data: data to pass to @function
4152 * Sets a function to be called at regular intervals, with the default
4153 * priority, #G_PRIORITY_DEFAULT. The function is called repeatedly
4154 * until it returns %FALSE, at which point the timeout is automatically
4155 * destroyed and the function will not be called again. The first call
4156 * to the function will be at the end of the first @interval.
4158 * Note that timeout functions may be delayed, due to the processing of other
4159 * event sources. Thus they should not be relied on for precise timing.
4160 * After each call to the timeout function, the time of the next
4161 * timeout is recalculated based on the current time and the given interval
4162 * (it does not try to 'catch up' time lost in delays).
4164 * If you want to have a timer in the "seconds" range and do not care
4165 * about the exact time of the first call of the timer, use the
4166 * g_timeout_add_seconds() function; this function allows for more
4167 * optimizations and more efficient system power usage.
4169 * This internally creates a main loop source using g_timeout_source_new()
4170 * and attaches it to the main loop context using g_source_attach(). You can
4171 * do these steps manually if you need greater control.
4173 * The interval given is in terms of monotonic time, not wall clock
4174 * time. See g_get_monotonic_time().
4176 * Return value: the ID (greater than 0) of the event source.
4179 g_timeout_add (guint32 interval,
4180 GSourceFunc function,
4183 return g_timeout_add_full (G_PRIORITY_DEFAULT,
4184 interval, function, data, NULL);
4188 * g_timeout_add_seconds_full:
4189 * @priority: the priority of the timeout source. Typically this will be in
4190 * the range between #G_PRIORITY_DEFAULT and #G_PRIORITY_HIGH.
4191 * @interval: the time between calls to the function, in seconds
4192 * @function: function to call
4193 * @data: data to pass to @function
4194 * @notify: (allow-none): function to call when the timeout is removed, or %NULL
4196 * Sets a function to be called at regular intervals, with @priority.
4197 * The function is called repeatedly until it returns %FALSE, at which
4198 * point the timeout is automatically destroyed and the function will
4199 * not be called again.
4201 * Unlike g_timeout_add(), this function operates at whole second granularity.
4202 * The initial starting point of the timer is determined by the implementation
4203 * and the implementation is expected to group multiple timers together so that
4204 * they fire all at the same time.
4205 * To allow this grouping, the @interval to the first timer is rounded
4206 * and can deviate up to one second from the specified interval.
4207 * Subsequent timer iterations will generally run at the specified interval.
4209 * Note that timeout functions may be delayed, due to the processing of other
4210 * event sources. Thus they should not be relied on for precise timing.
4211 * After each call to the timeout function, the time of the next
4212 * timeout is recalculated based on the current time and the given @interval
4214 * If you want timing more precise than whole seconds, use g_timeout_add()
4217 * The grouping of timers to fire at the same time results in a more power
4218 * and CPU efficient behavior so if your timer is in multiples of seconds
4219 * and you don't require the first timer exactly one second from now, the
4220 * use of g_timeout_add_seconds() is preferred over g_timeout_add().
4222 * This internally creates a main loop source using
4223 * g_timeout_source_new_seconds() and attaches it to the main loop context
4224 * using g_source_attach(). You can do these steps manually if you need
4227 * The interval given is in terms of monotonic time, not wall clock
4228 * time. See g_get_monotonic_time().
4230 * Return value: the ID (greater than 0) of the event source.
4232 * Rename to: g_timeout_add_seconds
4236 g_timeout_add_seconds_full (gint priority,
4238 GSourceFunc function,
4240 GDestroyNotify notify)
4245 g_return_val_if_fail (function != NULL, 0);
4247 source = g_timeout_source_new_seconds (interval);
4249 if (priority != G_PRIORITY_DEFAULT)
4250 g_source_set_priority (source, priority);
4252 g_source_set_callback (source, function, data, notify);
4253 id = g_source_attach (source, NULL);
4254 g_source_unref (source);
4260 * g_timeout_add_seconds:
4261 * @interval: the time between calls to the function, in seconds
4262 * @function: function to call
4263 * @data: data to pass to @function
4265 * Sets a function to be called at regular intervals with the default
4266 * priority, #G_PRIORITY_DEFAULT. The function is called repeatedly until
4267 * it returns %FALSE, at which point the timeout is automatically destroyed
4268 * and the function will not be called again.
4270 * This internally creates a main loop source using
4271 * g_timeout_source_new_seconds() and attaches it to the main loop context
4272 * using g_source_attach(). You can do these steps manually if you need
4273 * greater control. Also see g_timeout_add_seconds_full().
4275 * Note that the first call of the timer may not be precise for timeouts
4276 * of one second. If you need finer precision and have such a timeout,
4277 * you may want to use g_timeout_add() instead.
4279 * The interval given is in terms of monotonic time, not wall clock
4280 * time. See g_get_monotonic_time().
4282 * Return value: the ID (greater than 0) of the event source.
4287 g_timeout_add_seconds (guint interval,
4288 GSourceFunc function,
4291 g_return_val_if_fail (function != NULL, 0);
4293 return g_timeout_add_seconds_full (G_PRIORITY_DEFAULT, interval, function, data, NULL);
4296 /* Child watch functions */
4301 g_child_watch_prepare (GSource *source,
4309 g_child_watch_check (GSource *source)
4311 GChildWatchSource *child_watch_source;
4312 gboolean child_exited;
4314 child_watch_source = (GChildWatchSource *) source;
4316 child_exited = child_watch_source->poll.revents & G_IO_IN;
4323 * Note: We do _not_ check for the special value of STILL_ACTIVE
4324 * since we know that the process has exited and doing so runs into
4325 * problems if the child process "happens to return STILL_ACTIVE(259)"
4326 * as Microsoft's Platform SDK puts it.
4328 if (!GetExitCodeProcess (child_watch_source->pid, &child_status))
4330 gchar *emsg = g_win32_error_message (GetLastError ());
4331 g_warning (G_STRLOC ": GetExitCodeProcess() failed: %s", emsg);
4334 child_watch_source->child_status = -1;
4337 child_watch_source->child_status = child_status;
4340 return child_exited;
4344 g_child_watch_finalize (GSource *source)
4348 #else /* G_OS_WIN32 */
4351 wake_source (GSource *source)
4353 GMainContext *context;
4355 /* This should be thread-safe:
4357 * - if the source is currently being added to a context, that
4358 * context will be woken up anyway
4360 * - if the source is currently being destroyed, we simply need not
4363 * - the memory for the source will remain valid until after the
4364 * source finalize function was called (which would remove the
4365 * source from the global list which we are currently holding the
4368 * - the GMainContext will either be NULL or point to a live
4371 * - the GMainContext will remain valid since we hold the
4372 * main_context_list lock
4374 * Since we are holding a lot of locks here, don't try to enter any
4375 * more GMainContext functions for fear of dealock -- just hit the
4376 * GWakeup and run. Even if that's safe now, it could easily become
4377 * unsafe with some very minor changes in the future, and signal
4378 * handling is not the most well-tested codepath.
4380 G_LOCK(main_context_list);
4381 context = source->context;
4383 g_wakeup_signal (context->wakeup);
4384 G_UNLOCK(main_context_list);
4388 dispatch_unix_signals (void)
4392 /* clear this first incase another one arrives while we're processing */
4393 any_unix_signal_pending = FALSE;
4395 G_LOCK(unix_signal_lock);
4397 /* handle GChildWatchSource instances */
4398 if (unix_signal_pending[SIGCHLD])
4400 unix_signal_pending[SIGCHLD] = FALSE;
4402 /* The only way we can do this is to scan all of the children.
4404 * The docs promise that we will not reap children that we are not
4405 * explicitly watching, so that ties our hands from calling
4406 * waitpid(-1). We also can't use siginfo's si_pid field since if
4407 * multiple SIGCHLD arrive at the same time, one of them can be
4408 * dropped (since a given UNIX signal can only be pending once).
4410 for (node = unix_child_watches; node; node = node->next)
4412 GChildWatchSource *source = node->data;
4414 if (!source->child_exited)
4416 if (waitpid (source->pid, &source->child_status, WNOHANG) > 0)
4418 source->child_exited = TRUE;
4420 wake_source ((GSource *) source);
4426 /* handle GUnixSignalWatchSource instances */
4427 for (node = unix_signal_watches; node; node = node->next)
4429 GUnixSignalWatchSource *source = node->data;
4431 if (!source->pending)
4433 if (unix_signal_pending[source->signum])
4435 unix_signal_pending[source->signum] = FALSE;
4436 source->pending = TRUE;
4438 wake_source ((GSource *) source);
4443 G_UNLOCK(unix_signal_lock);
4447 g_child_watch_prepare (GSource *source,
4450 GChildWatchSource *child_watch_source;
4452 child_watch_source = (GChildWatchSource *) source;
4454 return child_watch_source->child_exited;
4458 g_child_watch_check (GSource *source)
4460 GChildWatchSource *child_watch_source;
4462 child_watch_source = (GChildWatchSource *) source;
4464 return child_watch_source->child_exited;
4468 g_unix_signal_watch_prepare (GSource *source,
4471 GUnixSignalWatchSource *unix_signal_source;
4473 unix_signal_source = (GUnixSignalWatchSource *) source;
4475 return unix_signal_source->pending;
4479 g_unix_signal_watch_check (GSource *source)
4481 GUnixSignalWatchSource *unix_signal_source;
4483 unix_signal_source = (GUnixSignalWatchSource *) source;
4485 return unix_signal_source->pending;
4489 g_unix_signal_watch_dispatch (GSource *source,
4490 GSourceFunc callback,
4493 GUnixSignalWatchSource *unix_signal_source;
4495 unix_signal_source = (GUnixSignalWatchSource *) source;
4499 g_warning ("Unix signal source dispatched without callback\n"
4500 "You must call g_source_set_callback().");
4504 (callback) (user_data);
4506 unix_signal_source->pending = FALSE;
4512 ensure_unix_signal_handler_installed_unlocked (int signum)
4514 static sigset_t installed_signal_mask;
4515 static gboolean initialized;
4516 struct sigaction action;
4520 sigemptyset (&installed_signal_mask);
4521 g_get_worker_context ();
4525 if (sigismember (&installed_signal_mask, signum))
4528 sigaddset (&installed_signal_mask, signum);
4530 action.sa_handler = g_unix_signal_handler;
4531 sigemptyset (&action.sa_mask);
4532 action.sa_flags = SA_RESTART | SA_NOCLDSTOP;
4533 sigaction (signum, &action, NULL);
4537 _g_main_create_unix_signal_watch (int signum)
4540 GUnixSignalWatchSource *unix_signal_source;
4542 source = g_source_new (&g_unix_signal_funcs, sizeof (GUnixSignalWatchSource));
4543 unix_signal_source = (GUnixSignalWatchSource *) source;
4545 unix_signal_source->signum = signum;
4546 unix_signal_source->pending = FALSE;
4548 G_LOCK (unix_signal_lock);
4549 ensure_unix_signal_handler_installed_unlocked (signum);
4550 unix_signal_watches = g_slist_prepend (unix_signal_watches, unix_signal_source);
4551 if (unix_signal_pending[signum])
4552 unix_signal_source->pending = TRUE;
4553 unix_signal_pending[signum] = FALSE;
4554 G_UNLOCK (unix_signal_lock);
4560 g_unix_signal_watch_finalize (GSource *source)
4562 G_LOCK (unix_signal_lock);
4563 unix_signal_watches = g_slist_remove (unix_signal_watches, source);
4564 G_UNLOCK (unix_signal_lock);
4568 g_child_watch_finalize (GSource *source)
4570 G_LOCK (unix_signal_lock);
4571 unix_child_watches = g_slist_remove (unix_child_watches, source);
4572 G_UNLOCK (unix_signal_lock);
4575 #endif /* G_OS_WIN32 */
4578 g_child_watch_dispatch (GSource *source,
4579 GSourceFunc callback,
4582 GChildWatchSource *child_watch_source;
4583 GChildWatchFunc child_watch_callback = (GChildWatchFunc) callback;
4585 child_watch_source = (GChildWatchSource *) source;
4589 g_warning ("Child watch source dispatched without callback\n"
4590 "You must call g_source_set_callback().");
4594 (child_watch_callback) (child_watch_source->pid, child_watch_source->child_status, user_data);
4596 /* We never keep a child watch source around as the child is gone */
4603 g_unix_signal_handler (int signum)
4605 unix_signal_pending[signum] = TRUE;
4606 any_unix_signal_pending = TRUE;
4608 g_wakeup_signal (glib_worker_context->wakeup);
4611 #endif /* !G_OS_WIN32 */
4614 * g_child_watch_source_new:
4615 * @pid: process to watch. On POSIX the pid of a child process. On
4616 * Windows a handle for a process (which doesn't have to be a child).
4618 * Creates a new child_watch source.
4620 * The source will not initially be associated with any #GMainContext
4621 * and must be added to one with g_source_attach() before it will be
4624 * Note that child watch sources can only be used in conjunction with
4625 * <literal>g_spawn...</literal> when the %G_SPAWN_DO_NOT_REAP_CHILD
4628 * Note that on platforms where #GPid must be explicitly closed
4629 * (see g_spawn_close_pid()) @pid must not be closed while the
4630 * source is still active. Typically, you will want to call
4631 * g_spawn_close_pid() in the callback function for the source.
4633 * Note further that using g_child_watch_source_new() is not
4634 * compatible with calling <literal>waitpid(-1)</literal> in
4635 * the application. Calling waitpid() for individual pids will
4638 * Return value: the newly-created child watch source
4643 g_child_watch_source_new (GPid pid)
4645 GSource *source = g_source_new (&g_child_watch_funcs, sizeof (GChildWatchSource));
4646 GChildWatchSource *child_watch_source = (GChildWatchSource *)source;
4648 child_watch_source->pid = pid;
4651 child_watch_source->poll.fd = (gintptr) pid;
4652 child_watch_source->poll.events = G_IO_IN;
4654 g_source_add_poll (source, &child_watch_source->poll);
4655 #else /* G_OS_WIN32 */
4656 G_LOCK (unix_signal_lock);
4657 ensure_unix_signal_handler_installed_unlocked (SIGCHLD);
4658 unix_child_watches = g_slist_prepend (unix_child_watches, child_watch_source);
4659 if (waitpid (pid, &child_watch_source->child_status, WNOHANG) > 0)
4660 child_watch_source->child_exited = TRUE;
4661 G_UNLOCK (unix_signal_lock);
4662 #endif /* G_OS_WIN32 */
4668 * g_child_watch_add_full:
4669 * @priority: the priority of the idle source. Typically this will be in the
4670 * range between #G_PRIORITY_DEFAULT_IDLE and #G_PRIORITY_HIGH_IDLE.
4671 * @pid: process to watch. On POSIX the pid of a child process. On
4672 * Windows a handle for a process (which doesn't have to be a child).
4673 * @function: function to call
4674 * @data: data to pass to @function
4675 * @notify: (allow-none): function to call when the idle is removed, or %NULL
4677 * Sets a function to be called when the child indicated by @pid
4678 * exits, at the priority @priority.
4680 * If you obtain @pid from g_spawn_async() or g_spawn_async_with_pipes()
4681 * you will need to pass #G_SPAWN_DO_NOT_REAP_CHILD as flag to
4682 * the spawn function for the child watching to work.
4684 * In many programs, you will want to call g_spawn_check_exit_status()
4685 * in the callback to determine whether or not the child exited
4688 * Also, note that on platforms where #GPid must be explicitly closed
4689 * (see g_spawn_close_pid()) @pid must not be closed while the source
4690 * is still active. Typically, you should invoke g_spawn_close_pid()
4691 * in the callback function for the source.
4693 * GLib supports only a single callback per process id.
4695 * This internally creates a main loop source using
4696 * g_child_watch_source_new() and attaches it to the main loop context
4697 * using g_source_attach(). You can do these steps manually if you
4698 * need greater control.
4700 * Return value: the ID (greater than 0) of the event source.
4702 * Rename to: g_child_watch_add
4706 g_child_watch_add_full (gint priority,
4708 GChildWatchFunc function,
4710 GDestroyNotify notify)
4715 g_return_val_if_fail (function != NULL, 0);
4717 source = g_child_watch_source_new (pid);
4719 if (priority != G_PRIORITY_DEFAULT)
4720 g_source_set_priority (source, priority);
4722 g_source_set_callback (source, (GSourceFunc) function, data, notify);
4723 id = g_source_attach (source, NULL);
4724 g_source_unref (source);
4730 * g_child_watch_add:
4731 * @pid: process id to watch. On POSIX the pid of a child process. On
4732 * Windows a handle for a process (which doesn't have to be a child).
4733 * @function: function to call
4734 * @data: data to pass to @function
4736 * Sets a function to be called when the child indicated by @pid
4737 * exits, at a default priority, #G_PRIORITY_DEFAULT.
4739 * If you obtain @pid from g_spawn_async() or g_spawn_async_with_pipes()
4740 * you will need to pass #G_SPAWN_DO_NOT_REAP_CHILD as flag to
4741 * the spawn function for the child watching to work.
4743 * Note that on platforms where #GPid must be explicitly closed
4744 * (see g_spawn_close_pid()) @pid must not be closed while the
4745 * source is still active. Typically, you will want to call
4746 * g_spawn_close_pid() in the callback function for the source.
4748 * GLib supports only a single callback per process id.
4750 * This internally creates a main loop source using
4751 * g_child_watch_source_new() and attaches it to the main loop context
4752 * using g_source_attach(). You can do these steps manually if you
4753 * need greater control.
4755 * Return value: the ID (greater than 0) of the event source.
4760 g_child_watch_add (GPid pid,
4761 GChildWatchFunc function,
4764 return g_child_watch_add_full (G_PRIORITY_DEFAULT, pid, function, data, NULL);
4768 /* Idle functions */
4771 g_idle_prepare (GSource *source,
4780 g_idle_check (GSource *source)
4786 g_idle_dispatch (GSource *source,
4787 GSourceFunc callback,
4792 g_warning ("Idle source dispatched without callback\n"
4793 "You must call g_source_set_callback().");
4797 return callback (user_data);
4801 * g_idle_source_new:
4803 * Creates a new idle source.
4805 * The source will not initially be associated with any #GMainContext
4806 * and must be added to one with g_source_attach() before it will be
4807 * executed. Note that the default priority for idle sources is
4808 * %G_PRIORITY_DEFAULT_IDLE, as compared to other sources which
4809 * have a default priority of %G_PRIORITY_DEFAULT.
4811 * Return value: the newly-created idle source
4814 g_idle_source_new (void)
4818 source = g_source_new (&g_idle_funcs, sizeof (GSource));
4819 g_source_set_priority (source, G_PRIORITY_DEFAULT_IDLE);
4826 * @priority: the priority of the idle source. Typically this will be in the
4827 * range between #G_PRIORITY_DEFAULT_IDLE and #G_PRIORITY_HIGH_IDLE.
4828 * @function: function to call
4829 * @data: data to pass to @function
4830 * @notify: (allow-none): function to call when the idle is removed, or %NULL
4832 * Adds a function to be called whenever there are no higher priority
4833 * events pending. If the function returns %FALSE it is automatically
4834 * removed from the list of event sources and will not be called again.
4836 * This internally creates a main loop source using g_idle_source_new()
4837 * and attaches it to the main loop context using g_source_attach().
4838 * You can do these steps manually if you need greater control.
4840 * Return value: the ID (greater than 0) of the event source.
4841 * Rename to: g_idle_add
4844 g_idle_add_full (gint priority,
4845 GSourceFunc function,
4847 GDestroyNotify notify)
4852 g_return_val_if_fail (function != NULL, 0);
4854 source = g_idle_source_new ();
4856 if (priority != G_PRIORITY_DEFAULT_IDLE)
4857 g_source_set_priority (source, priority);
4859 g_source_set_callback (source, function, data, notify);
4860 id = g_source_attach (source, NULL);
4861 g_source_unref (source);
4868 * @function: function to call
4869 * @data: data to pass to @function.
4871 * Adds a function to be called whenever there are no higher priority
4872 * events pending to the default main loop. The function is given the
4873 * default idle priority, #G_PRIORITY_DEFAULT_IDLE. If the function
4874 * returns %FALSE it is automatically removed from the list of event
4875 * sources and will not be called again.
4877 * This internally creates a main loop source using g_idle_source_new()
4878 * and attaches it to the main loop context using g_source_attach().
4879 * You can do these steps manually if you need greater control.
4881 * Return value: the ID (greater than 0) of the event source.
4884 g_idle_add (GSourceFunc function,
4887 return g_idle_add_full (G_PRIORITY_DEFAULT_IDLE, function, data, NULL);
4891 * g_idle_remove_by_data:
4892 * @data: the data for the idle source's callback.
4894 * Removes the idle function with the given data.
4896 * Return value: %TRUE if an idle source was found and removed.
4899 g_idle_remove_by_data (gpointer data)
4901 return g_source_remove_by_funcs_user_data (&g_idle_funcs, data);
4905 * g_main_context_invoke:
4906 * @context: (allow-none): a #GMainContext, or %NULL
4907 * @function: function to call
4908 * @data: data to pass to @function
4910 * Invokes a function in such a way that @context is owned during the
4911 * invocation of @function.
4913 * If @context is %NULL then the global default main context — as
4914 * returned by g_main_context_default() — is used.
4916 * If @context is owned by the current thread, @function is called
4917 * directly. Otherwise, if @context is the thread-default main context
4918 * of the current thread and g_main_context_acquire() succeeds, then
4919 * @function is called and g_main_context_release() is called
4922 * In any other case, an idle source is created to call @function and
4923 * that source is attached to @context (presumably to be run in another
4924 * thread). The idle source is attached with #G_PRIORITY_DEFAULT
4925 * priority. If you want a different priority, use
4926 * g_main_context_invoke_full().
4928 * Note that, as with normal idle functions, @function should probably
4929 * return %FALSE. If it returns %TRUE, it will be continuously run in a
4930 * loop (and may prevent this call from returning).
4935 g_main_context_invoke (GMainContext *context,
4936 GSourceFunc function,
4939 g_main_context_invoke_full (context,
4941 function, data, NULL);
4945 * g_main_context_invoke_full:
4946 * @context: (allow-none): a #GMainContext, or %NULL
4947 * @priority: the priority at which to run @function
4948 * @function: function to call
4949 * @data: data to pass to @function
4950 * @notify: (allow-none): a function to call when @data is no longer in use, or %NULL.
4952 * Invokes a function in such a way that @context is owned during the
4953 * invocation of @function.
4955 * This function is the same as g_main_context_invoke() except that it
4956 * lets you specify the priority incase @function ends up being
4957 * scheduled as an idle and also lets you give a #GDestroyNotify for @data.
4959 * @notify should not assume that it is called from any particular
4960 * thread or with any particular context acquired.
4965 g_main_context_invoke_full (GMainContext *context,
4967 GSourceFunc function,
4969 GDestroyNotify notify)
4971 g_return_if_fail (function != NULL);
4974 context = g_main_context_default ();
4976 if (g_main_context_is_owner (context))
4978 while (function (data));
4985 GMainContext *thread_default;
4987 thread_default = g_main_context_get_thread_default ();
4989 if (!thread_default)
4990 thread_default = g_main_context_default ();
4992 if (thread_default == context && g_main_context_acquire (context))
4994 while (function (data));
4996 g_main_context_release (context);
5005 source = g_idle_source_new ();
5006 g_source_set_priority (source, priority);
5007 g_source_set_callback (source, function, data, notify);
5008 g_source_attach (source, context);
5009 g_source_unref (source);
5015 glib_worker_main (gpointer data)
5019 g_main_context_iteration (glib_worker_context, TRUE);
5022 if (any_unix_signal_pending)
5023 dispatch_unix_signals ();
5027 return NULL; /* worst GCC warning message ever... */
5031 g_get_worker_context (void)
5033 static gsize initialised;
5035 if (g_once_init_enter (&initialised))
5037 /* mask all signals in the worker thread */
5043 pthread_sigmask (SIG_SETMASK, &all, &prev_mask);
5045 glib_worker_context = g_main_context_new ();
5046 g_thread_new ("gmain", glib_worker_main, NULL);
5048 pthread_sigmask (SIG_SETMASK, &prev_mask, NULL);
5050 g_once_init_leave (&initialised, TRUE);
5053 return glib_worker_context;