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"
55 #include <sys/types.h>
58 #ifdef HAVE_SYS_TIME_H
60 #endif /* HAVE_SYS_TIME_H */
63 #endif /* HAVE_UNISTD_H */
70 #endif /* G_OS_WIN32 */
73 #include <sys/socket.h>
75 #endif /* G_OS_BEOS */
80 #include "giochannel.h"
84 #include "gstrfuncs.h"
85 #include "gtestutils.h"
86 #include "gthreadprivate.h"
92 #ifdef G_MAIN_POLL_DEBUG
98 * @title: The Main Event Loop
99 * @short_description: manages all available sources of events
101 * The main event loop manages all the available sources of events for
102 * GLib and GTK+ applications. These events can come from any number of
103 * different types of sources such as file descriptors (plain files,
104 * pipes or sockets) and timeouts. New types of event sources can also
105 * be added using g_source_attach().
107 * To allow multiple independent sets of sources to be handled in
108 * different threads, each source is associated with a #GMainContext.
109 * A GMainContext can only be running in a single thread, but
110 * sources can be added to it and removed from it from other threads.
112 * Each event source is assigned a priority. The default priority,
113 * #G_PRIORITY_DEFAULT, is 0. Values less than 0 denote higher priorities.
114 * Values greater than 0 denote lower priorities. Events from high priority
115 * sources are always processed before events from lower priority sources.
117 * Idle functions can also be added, and assigned a priority. These will
118 * be run whenever no events with a higher priority are ready to be processed.
120 * The #GMainLoop data type represents a main event loop. A GMainLoop is
121 * created with g_main_loop_new(). After adding the initial event sources,
122 * g_main_loop_run() is called. This continuously checks for new events from
123 * each of the event sources and dispatches them. Finally, the processing of
124 * an event from one of the sources leads to a call to g_main_loop_quit() to
125 * exit the main loop, and g_main_loop_run() returns.
127 * It is possible to create new instances of #GMainLoop recursively.
128 * This is often used in GTK+ applications when showing modal dialog
129 * boxes. Note that event sources are associated with a particular
130 * #GMainContext, and will be checked and dispatched for all main
131 * loops associated with that GMainContext.
133 * GTK+ contains wrappers of some of these functions, e.g. gtk_main(),
134 * gtk_main_quit() and gtk_events_pending().
136 * <refsect2><title>Creating new source types</title>
137 * <para>One of the unusual features of the #GMainLoop functionality
138 * is that new types of event source can be created and used in
139 * addition to the builtin type of event source. A new event source
140 * type is used for handling GDK events. A new source type is created
141 * by <firstterm>deriving</firstterm> from the #GSource structure.
142 * The derived type of source is represented by a structure that has
143 * the #GSource structure as a first element, and other elements specific
144 * to the new source type. To create an instance of the new source type,
145 * call g_source_new() passing in the size of the derived structure and
146 * a table of functions. These #GSourceFuncs determine the behavior of
147 * the new source type.</para>
148 * <para>New source types basically interact with the main context
149 * in two ways. Their prepare function in #GSourceFuncs can set a timeout
150 * to determine the maximum amount of time that the main loop will sleep
151 * before checking the source again. In addition, or as well, the source
152 * can add file descriptors to the set that the main context checks using
153 * g_source_add_poll().</para>
155 * <refsect2><title>Customizing the main loop iteration</title>
156 * <para>Single iterations of a #GMainContext can be run with
157 * g_main_context_iteration(). In some cases, more detailed control
158 * of exactly how the details of the main loop work is desired, for
159 * instance, when integrating the #GMainLoop with an external main loop.
160 * In such cases, you can call the component functions of
161 * g_main_context_iteration() directly. These functions are
162 * g_main_context_prepare(), g_main_context_query(),
163 * g_main_context_check() and g_main_context_dispatch().</para>
164 * <para>The operation of these functions can best be seen in terms
165 * of a state diagram, as shown in <xref linkend="mainloop-states"/>.</para>
166 * <figure id="mainloop-states"><title>States of a Main Context</title>
167 * <graphic fileref="mainloop-states.gif" format="GIF"></graphic>
174 typedef struct _GTimeoutSource GTimeoutSource;
175 typedef struct _GChildWatchSource GChildWatchSource;
176 typedef struct _GUnixSignalWatchSource GUnixSignalWatchSource;
177 typedef struct _GPollRec GPollRec;
178 typedef struct _GSourceCallback GSourceCallback;
182 G_SOURCE_READY = 1 << G_HOOK_FLAG_USER_SHIFT,
183 G_SOURCE_CAN_RECURSE = 1 << (G_HOOK_FLAG_USER_SHIFT + 1)
186 #ifdef G_THREADS_ENABLED
187 typedef struct _GMainWaiter GMainWaiter;
196 typedef struct _GMainDispatch GMainDispatch;
198 struct _GMainDispatch
201 GSList *dispatching_sources; /* stack of current sources */
204 #ifdef G_MAIN_POLL_DEBUG
205 gboolean _g_main_poll_debug = FALSE;
210 #ifdef G_THREADS_ENABLED
211 /* The following lock is used for both the list of sources
212 * and the list of poll records
223 GPtrArray *pending_dispatches;
224 gint timeout; /* Timeout for current iteration */
227 GSource *source_list;
228 gint in_check_or_prepare;
230 GPollRec *poll_records, *poll_records_tail;
231 guint n_poll_records;
232 GPollFD *cached_poll_array;
233 guint cached_poll_array_size;
235 #ifdef G_THREADS_ENABLED
237 /* this pipe is used to wake up the main loop when a source is added.
239 gint wake_up_pipe[2];
240 #else /* G_OS_WIN32 */
241 HANDLE wake_up_semaphore;
242 #endif /* G_OS_WIN32 */
245 gboolean poll_waiting;
247 /* Flag indicating whether the set of fd's changed during a poll */
248 gboolean poll_changed;
249 #endif /* G_THREADS_ENABLED */
254 gboolean time_is_fresh;
256 gboolean real_time_is_fresh;
259 struct _GSourceCallback
264 GDestroyNotify notify;
269 GMainContext *context;
274 struct _GTimeoutSource
282 struct _GChildWatchSource
289 #else /* G_OS_WIN32 */
291 gboolean child_exited;
292 #endif /* G_OS_WIN32 */
295 struct _GUnixSignalWatchSource
310 struct _GSourcePrivate
312 GSList *child_sources;
313 GSource *parent_source;
316 #ifdef G_THREADS_ENABLED
317 #define LOCK_CONTEXT(context) g_static_mutex_lock (&context->mutex)
318 #define UNLOCK_CONTEXT(context) g_static_mutex_unlock (&context->mutex)
319 #define G_THREAD_SELF g_thread_self ()
321 #define LOCK_CONTEXT(context) (void)0
322 #define UNLOCK_CONTEXT(context) (void)0
323 #define G_THREAD_SELF NULL
326 #define SOURCE_DESTROYED(source) (((source)->flags & G_HOOK_FLAG_ACTIVE) == 0)
327 #define SOURCE_BLOCKED(source) (((source)->flags & G_HOOK_FLAG_IN_CALL) != 0 && \
328 ((source)->flags & G_SOURCE_CAN_RECURSE) == 0)
330 #define SOURCE_UNREF(source, context) \
332 if ((source)->ref_count > 1) \
333 (source)->ref_count--; \
335 g_source_unref_internal ((source), (context), TRUE); \
339 /* Forward declarations */
341 static void g_source_unref_internal (GSource *source,
342 GMainContext *context,
344 static void g_source_destroy_internal (GSource *source,
345 GMainContext *context,
347 static void g_source_set_priority_unlocked (GSource *source,
348 GMainContext *context,
350 static void g_main_context_poll (GMainContext *context,
355 static void g_main_context_add_poll_unlocked (GMainContext *context,
358 static void g_main_context_remove_poll_unlocked (GMainContext *context,
360 static void g_main_context_wakeup_unlocked (GMainContext *context);
362 static void _g_main_wake_up_all_contexts (void);
364 static gboolean g_timeout_prepare (GSource *source,
366 static gboolean g_timeout_check (GSource *source);
367 static gboolean g_timeout_dispatch (GSource *source,
368 GSourceFunc callback,
370 static gboolean g_child_watch_prepare (GSource *source,
372 static gboolean g_child_watch_check (GSource *source);
373 static gboolean g_child_watch_dispatch (GSource *source,
374 GSourceFunc callback,
377 static gpointer unix_signal_helper_thread (gpointer data) G_GNUC_NORETURN;
378 static void g_unix_signal_handler (int signum);
379 static gboolean g_unix_signal_watch_prepare (GSource *source,
381 static gboolean g_unix_signal_watch_check (GSource *source);
382 static gboolean g_unix_signal_watch_dispatch (GSource *source,
383 GSourceFunc callback,
385 static void g_unix_signal_watch_finalize (GSource *source);
387 static gboolean g_idle_prepare (GSource *source,
389 static gboolean g_idle_check (GSource *source);
390 static gboolean g_idle_dispatch (GSource *source,
391 GSourceFunc callback,
394 G_LOCK_DEFINE_STATIC (main_loop);
395 static GMainContext *default_main_context;
396 static GSList *main_contexts_without_pipe = NULL;
400 /* The UNIX signal pipe contains a single byte specifying which
401 * signal was received.
403 #define _UNIX_SIGNAL_PIPE_SIGCHLD_CHAR 'C'
404 #define _UNIX_SIGNAL_PIPE_SIGHUP_CHAR 'H'
405 #define _UNIX_SIGNAL_PIPE_SIGINT_CHAR 'I'
406 #define _UNIX_SIGNAL_PIPE_SIGTERM_CHAR 'T'
407 /* Guards all the data below */
408 G_LOCK_DEFINE_STATIC (unix_signal_lock);
410 UNIX_SIGNAL_UNINITIALIZED = 0,
411 UNIX_SIGNAL_INITIALIZED_SINGLE,
412 UNIX_SIGNAL_INITIALIZED_THREADED
414 static gint unix_signal_init_state = UNIX_SIGNAL_UNINITIALIZED;
416 gboolean sigchld_handler_installed : 1;
417 gboolean sighup_handler_installed : 1;
418 gboolean sigint_handler_installed : 1;
419 gboolean sigterm_handler_installed : 1;
421 /* These are only used in the UNIX_SIGNAL_INITIALIZED_SINGLE case */
422 gboolean sighup_delivered : 1;
423 gboolean sigint_delivered : 1;
424 gboolean sigterm_delivered : 1;
426 static UnixSignalState unix_signal_state;
427 static gint unix_signal_wake_up_pipe[2];
428 GSList *unix_signal_watches;
430 /* Not guarded ( FIXME should it be? ) */
431 static gint child_watch_count = 1;
433 static GSourceFuncs g_unix_signal_funcs =
435 g_unix_signal_watch_prepare,
436 g_unix_signal_watch_check,
437 g_unix_signal_watch_dispatch,
438 g_unix_signal_watch_finalize
440 #endif /* !G_OS_WIN32 */
441 G_LOCK_DEFINE_STATIC (main_context_list);
442 static GSList *main_context_list = NULL;
444 GSourceFuncs g_timeout_funcs =
452 GSourceFuncs g_child_watch_funcs =
454 g_child_watch_prepare,
456 g_child_watch_dispatch,
460 GSourceFuncs g_idle_funcs =
469 * g_main_context_ref:
470 * @context: a #GMainContext
472 * Increases the reference count on a #GMainContext object by one.
474 * Returns: the @context that was passed in (since 2.6)
477 g_main_context_ref (GMainContext *context)
479 g_return_val_if_fail (context != NULL, NULL);
480 g_return_val_if_fail (g_atomic_int_get (&context->ref_count) > 0, NULL);
482 g_atomic_int_inc (&context->ref_count);
488 poll_rec_list_free (GMainContext *context,
491 g_slice_free_chain (GPollRec, list, next);
495 * g_main_context_unref:
496 * @context: a #GMainContext
498 * Decreases the reference count on a #GMainContext object by one. If
499 * the result is zero, free the context and free all associated memory.
502 g_main_context_unref (GMainContext *context)
505 g_return_if_fail (context != NULL);
506 g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
508 if (!g_atomic_int_dec_and_test (&context->ref_count))
511 G_LOCK (main_context_list);
512 main_context_list = g_slist_remove (main_context_list, context);
513 G_UNLOCK (main_context_list);
515 source = context->source_list;
518 GSource *next = source->next;
519 g_source_destroy_internal (source, context, FALSE);
523 #ifdef G_THREADS_ENABLED
524 g_static_mutex_free (&context->mutex);
527 g_ptr_array_free (context->pending_dispatches, TRUE);
528 g_free (context->cached_poll_array);
530 poll_rec_list_free (context, context->poll_records);
532 #ifdef G_THREADS_ENABLED
533 if (g_thread_supported())
536 close (context->wake_up_pipe[0]);
537 close (context->wake_up_pipe[1]);
539 CloseHandle (context->wake_up_semaphore);
543 main_contexts_without_pipe = g_slist_remove (main_contexts_without_pipe,
546 if (context->cond != NULL)
547 g_cond_free (context->cond);
553 #ifdef G_THREADS_ENABLED
555 g_main_context_init_pipe (GMainContext *context)
557 GError *error = NULL;
560 if (context->wake_up_pipe[0] != -1)
563 if (!g_unix_open_pipe (context->wake_up_pipe, FD_CLOEXEC, &error))
564 g_error ("Cannot create pipe main loop wake-up: %s", error->message);
566 context->wake_up_rec.fd = context->wake_up_pipe[0];
567 context->wake_up_rec.events = G_IO_IN;
569 if (context->wake_up_semaphore != NULL)
571 context->wake_up_semaphore = CreateSemaphore (NULL, 0, 100, NULL);
572 if (context->wake_up_semaphore == NULL)
573 g_error ("Cannot create wake-up semaphore: %s",
574 g_win32_error_message (GetLastError ()));
575 context->wake_up_rec.fd = (gintptr) context->wake_up_semaphore;
576 context->wake_up_rec.events = G_IO_IN;
578 if (_g_main_poll_debug)
579 g_print ("wake-up semaphore: %p\n", context->wake_up_semaphore);
581 g_main_context_add_poll_unlocked (context, 0, &context->wake_up_rec);
585 _g_main_thread_init (void)
587 GSList *curr = main_contexts_without_pipe;
590 g_main_context_init_pipe ((GMainContext *)curr->data);
593 g_slist_free (main_contexts_without_pipe);
594 main_contexts_without_pipe = NULL;
596 #endif /* G_THREADS_ENABLED */
599 * g_main_context_new:
601 * Creates a new #GMainContext structure.
603 * Return value: the new #GMainContext
606 g_main_context_new (void)
608 GMainContext *context = g_new0 (GMainContext, 1);
610 #ifdef G_MAIN_POLL_DEBUG
612 static gboolean beenhere = FALSE;
616 if (getenv ("G_MAIN_POLL_DEBUG") != NULL)
617 _g_main_poll_debug = TRUE;
623 #ifdef G_THREADS_ENABLED
624 g_static_mutex_init (&context->mutex);
626 context->owner = NULL;
627 context->waiters = NULL;
630 context->wake_up_pipe[0] = -1;
631 context->wake_up_pipe[1] = -1;
633 context->wake_up_semaphore = NULL;
637 context->ref_count = 1;
639 context->next_id = 1;
641 context->source_list = NULL;
643 context->poll_func = g_poll;
645 context->cached_poll_array = NULL;
646 context->cached_poll_array_size = 0;
648 context->pending_dispatches = g_ptr_array_new ();
650 context->time_is_fresh = FALSE;
651 context->real_time_is_fresh = FALSE;
653 #ifdef G_THREADS_ENABLED
654 if (g_thread_supported ())
655 g_main_context_init_pipe (context);
657 main_contexts_without_pipe = g_slist_prepend (main_contexts_without_pipe,
661 G_LOCK (main_context_list);
662 main_context_list = g_slist_append (main_context_list, context);
664 #ifdef G_MAIN_POLL_DEBUG
665 if (_g_main_poll_debug)
666 g_print ("created context=%p\n", context);
669 G_UNLOCK (main_context_list);
675 * g_main_context_default:
677 * Returns the global default main context. This is the main context
678 * used for main loop functions when a main loop is not explicitly
679 * specified, and corresponds to the "main" main loop. See also
680 * g_main_context_get_thread_default().
682 * Return value: the global default main context.
685 g_main_context_default (void)
691 if (!default_main_context)
693 default_main_context = g_main_context_new ();
694 #ifdef G_MAIN_POLL_DEBUG
695 if (_g_main_poll_debug)
696 g_print ("default context=%p\n", default_main_context);
700 G_UNLOCK (main_loop);
702 return default_main_context;
705 static GStaticPrivate thread_context_stack = G_STATIC_PRIVATE_INIT;
708 free_context_stack (gpointer data)
710 GQueue *stack = data;
711 GMainContext *context;
713 while (!g_queue_is_empty (stack))
715 context = g_queue_pop_head (stack);
716 g_main_context_release (context);
718 g_main_context_unref (context);
720 g_queue_free (stack);
724 * g_main_context_push_thread_default:
725 * @context: a #GMainContext, or %NULL for the global default context
727 * Acquires @context and sets it as the thread-default context for the
728 * current thread. This will cause certain asynchronous operations
729 * (such as most <link linkend="gio">gio</link>-based I/O) which are
730 * started in this thread to run under @context and deliver their
731 * results to its main loop, rather than running under the global
732 * default context in the main thread. Note that calling this function
733 * changes the context returned by
734 * g_main_context_get_thread_default(), <emphasis>not</emphasis> the
735 * one returned by g_main_context_default(), so it does not affect the
736 * context used by functions like g_idle_add().
738 * Normally you would call this function shortly after creating a new
739 * thread, passing it a #GMainContext which will be run by a
740 * #GMainLoop in that thread, to set a new default context for all
741 * async operations in that thread. (In this case, you don't need to
742 * ever call g_main_context_pop_thread_default().) In some cases
743 * however, you may want to schedule a single operation in a
744 * non-default context, or temporarily use a non-default context in
745 * the main thread. In that case, you can wrap the call to the
746 * asynchronous operation inside a
747 * g_main_context_push_thread_default() /
748 * g_main_context_pop_thread_default() pair, but it is up to you to
749 * ensure that no other asynchronous operations accidentally get
750 * started while the non-default context is active.
752 * Beware that libraries that predate this function may not correctly
753 * handle being used from a thread with a thread-default context. Eg,
754 * see g_file_supports_thread_contexts().
759 g_main_context_push_thread_default (GMainContext *context)
762 gboolean acquired_context;
764 acquired_context = g_main_context_acquire (context);
765 g_return_if_fail (acquired_context);
767 if (context == g_main_context_default ())
770 g_main_context_ref (context);
772 stack = g_static_private_get (&thread_context_stack);
775 stack = g_queue_new ();
776 g_static_private_set (&thread_context_stack, stack,
780 g_queue_push_head (stack, context);
784 * g_main_context_pop_thread_default:
785 * @context: a #GMainContext object, or %NULL
787 * Pops @context off the thread-default context stack (verifying that
788 * it was on the top of the stack).
793 g_main_context_pop_thread_default (GMainContext *context)
797 if (context == g_main_context_default ())
800 stack = g_static_private_get (&thread_context_stack);
802 g_return_if_fail (stack != NULL);
803 g_return_if_fail (g_queue_peek_head (stack) == context);
805 g_queue_pop_head (stack);
807 g_main_context_release (context);
809 g_main_context_unref (context);
813 * g_main_context_get_thread_default:
815 * Gets the thread-default #GMainContext for this thread. Asynchronous
816 * operations that want to be able to be run in contexts other than
817 * the default one should call this method to get a #GMainContext to
818 * add their #GSource<!-- -->s to. (Note that even in single-threaded
819 * programs applications may sometimes want to temporarily push a
820 * non-default context, so it is not safe to assume that this will
821 * always return %NULL if threads are not initialized.)
823 * Returns: the thread-default #GMainContext, or %NULL if the
824 * thread-default context is the global default context.
829 g_main_context_get_thread_default (void)
833 stack = g_static_private_get (&thread_context_stack);
835 return g_queue_peek_head (stack);
840 /* Hooks for adding to the main loop */
844 * @source_funcs: structure containing functions that implement
845 * the sources behavior.
846 * @struct_size: size of the #GSource structure to create.
848 * Creates a new #GSource structure. The size is specified to
849 * allow creating structures derived from #GSource that contain
850 * additional data. The size passed in must be at least
851 * <literal>sizeof (GSource)</literal>.
853 * The source will not initially be associated with any #GMainContext
854 * and must be added to one with g_source_attach() before it will be
857 * Return value: the newly-created #GSource.
860 g_source_new (GSourceFuncs *source_funcs,
865 g_return_val_if_fail (source_funcs != NULL, NULL);
866 g_return_val_if_fail (struct_size >= sizeof (GSource), NULL);
868 source = (GSource*) g_malloc0 (struct_size);
870 source->source_funcs = source_funcs;
871 source->ref_count = 1;
873 source->priority = G_PRIORITY_DEFAULT;
875 source->flags = G_HOOK_FLAG_ACTIVE;
877 /* NULL/0 initialization for all other fields */
882 /* Holds context's lock
885 g_source_list_add (GSource *source,
886 GMainContext *context)
888 GSource *tmp_source, *last_source;
890 if (source->priv && source->priv->parent_source)
892 /* Put the source immediately before its parent */
893 tmp_source = source->priv->parent_source;
894 last_source = source->priv->parent_source->prev;
899 tmp_source = context->source_list;
900 while (tmp_source && tmp_source->priority <= source->priority)
902 last_source = tmp_source;
903 tmp_source = tmp_source->next;
907 source->next = tmp_source;
909 tmp_source->prev = source;
911 source->prev = last_source;
913 last_source->next = source;
915 context->source_list = source;
918 /* Holds context's lock
921 g_source_list_remove (GSource *source,
922 GMainContext *context)
925 source->prev->next = source->next;
927 context->source_list = source->next;
930 source->next->prev = source->prev;
937 g_source_attach_unlocked (GSource *source,
938 GMainContext *context)
943 source->context = context;
944 result = source->source_id = context->next_id++;
947 g_source_list_add (source, context);
949 tmp_list = source->poll_fds;
952 g_main_context_add_poll_unlocked (context, source->priority, tmp_list->data);
953 tmp_list = tmp_list->next;
958 tmp_list = source->priv->child_sources;
961 g_source_attach_unlocked (tmp_list->data, context);
962 tmp_list = tmp_list->next;
971 * @source: a #GSource
972 * @context: a #GMainContext (if %NULL, the default context will be used)
974 * Adds a #GSource to a @context so that it will be executed within
975 * that context. Remove it by calling g_source_destroy().
977 * Return value: the ID (greater than 0) for the source within the
981 g_source_attach (GSource *source,
982 GMainContext *context)
986 g_return_val_if_fail (source->context == NULL, 0);
987 g_return_val_if_fail (!SOURCE_DESTROYED (source), 0);
990 context = g_main_context_default ();
992 LOCK_CONTEXT (context);
994 result = g_source_attach_unlocked (source, context);
996 #ifdef G_THREADS_ENABLED
997 /* Now wake up the main loop if it is waiting in the poll() */
998 g_main_context_wakeup_unlocked (context);
1001 UNLOCK_CONTEXT (context);
1007 g_source_destroy_internal (GSource *source,
1008 GMainContext *context,
1012 LOCK_CONTEXT (context);
1014 if (!SOURCE_DESTROYED (source))
1017 gpointer old_cb_data;
1018 GSourceCallbackFuncs *old_cb_funcs;
1020 source->flags &= ~G_HOOK_FLAG_ACTIVE;
1022 old_cb_data = source->callback_data;
1023 old_cb_funcs = source->callback_funcs;
1025 source->callback_data = NULL;
1026 source->callback_funcs = NULL;
1030 UNLOCK_CONTEXT (context);
1031 old_cb_funcs->unref (old_cb_data);
1032 LOCK_CONTEXT (context);
1035 if (!SOURCE_BLOCKED (source))
1037 tmp_list = source->poll_fds;
1040 g_main_context_remove_poll_unlocked (context, tmp_list->data);
1041 tmp_list = tmp_list->next;
1045 if (source->priv && source->priv->child_sources)
1047 /* This is safe because even if a child_source finalizer or
1048 * closure notify tried to modify source->priv->child_sources
1049 * from outside the lock, it would fail since
1050 * SOURCE_DESTROYED(source) is now TRUE.
1052 tmp_list = source->priv->child_sources;
1055 g_source_destroy_internal (tmp_list->data, context, TRUE);
1056 g_source_unref_internal (tmp_list->data, context, TRUE);
1057 tmp_list = tmp_list->next;
1059 g_slist_free (source->priv->child_sources);
1060 source->priv->child_sources = NULL;
1063 g_source_unref_internal (source, context, TRUE);
1067 UNLOCK_CONTEXT (context);
1072 * @source: a #GSource
1074 * Removes a source from its #GMainContext, if any, and mark it as
1075 * destroyed. The source cannot be subsequently added to another
1079 g_source_destroy (GSource *source)
1081 GMainContext *context;
1083 g_return_if_fail (source != NULL);
1085 context = source->context;
1088 g_source_destroy_internal (source, context, FALSE);
1090 source->flags &= ~G_HOOK_FLAG_ACTIVE;
1095 * @source: a #GSource
1097 * Returns the numeric ID for a particular source. The ID of a source
1098 * is a positive integer which is unique within a particular main loop
1099 * context. The reverse
1100 * mapping from ID to source is done by g_main_context_find_source_by_id().
1102 * Return value: the ID (greater than 0) for the source
1105 g_source_get_id (GSource *source)
1109 g_return_val_if_fail (source != NULL, 0);
1110 g_return_val_if_fail (source->context != NULL, 0);
1112 LOCK_CONTEXT (source->context);
1113 result = source->source_id;
1114 UNLOCK_CONTEXT (source->context);
1120 * g_source_get_context:
1121 * @source: a #GSource
1123 * Gets the #GMainContext with which the source is associated.
1124 * Calling this function on a destroyed source is an error.
1126 * Return value: the #GMainContext with which the source is associated,
1127 * or %NULL if the context has not yet been added
1131 g_source_get_context (GSource *source)
1133 g_return_val_if_fail (!SOURCE_DESTROYED (source), NULL);
1135 return source->context;
1139 * g_source_add_poll:
1140 * @source:a #GSource
1141 * @fd: a #GPollFD structure holding information about a file
1142 * descriptor to watch.
1144 * Adds a file descriptor to the set of file descriptors polled for
1145 * this source. This is usually combined with g_source_new() to add an
1146 * event source. The event source's check function will typically test
1147 * the @revents field in the #GPollFD struct and return %TRUE if events need
1151 g_source_add_poll (GSource *source,
1154 GMainContext *context;
1156 g_return_if_fail (source != NULL);
1157 g_return_if_fail (fd != NULL);
1158 g_return_if_fail (!SOURCE_DESTROYED (source));
1160 context = source->context;
1163 LOCK_CONTEXT (context);
1165 source->poll_fds = g_slist_prepend (source->poll_fds, fd);
1169 if (!SOURCE_BLOCKED (source))
1170 g_main_context_add_poll_unlocked (context, source->priority, fd);
1171 UNLOCK_CONTEXT (context);
1176 * g_source_remove_poll:
1177 * @source:a #GSource
1178 * @fd: a #GPollFD structure previously passed to g_source_add_poll().
1180 * Removes a file descriptor from the set of file descriptors polled for
1184 g_source_remove_poll (GSource *source,
1187 GMainContext *context;
1189 g_return_if_fail (source != NULL);
1190 g_return_if_fail (fd != NULL);
1191 g_return_if_fail (!SOURCE_DESTROYED (source));
1193 context = source->context;
1196 LOCK_CONTEXT (context);
1198 source->poll_fds = g_slist_remove (source->poll_fds, fd);
1202 if (!SOURCE_BLOCKED (source))
1203 g_main_context_remove_poll_unlocked (context, fd);
1204 UNLOCK_CONTEXT (context);
1209 * g_source_add_child_source:
1210 * @source:a #GSource
1211 * @child_source: a second #GSource that @source should "poll"
1213 * Adds @child_source to @source as a "polled" source; when @source is
1214 * added to a #GMainContext, @child_source will be automatically added
1215 * with the same priority, when @child_source is triggered, it will
1216 * cause @source to dispatch (in addition to calling its own
1217 * callback), and when @source is destroyed, it will destroy
1218 * @child_source as well. (@source will also still be dispatched if
1219 * its own prepare/check functions indicate that it is ready.)
1221 * If you don't need @child_source to do anything on its own when it
1222 * triggers, you can call g_source_set_dummy_callback() on it to set a
1223 * callback that does nothing (except return %TRUE if appropriate).
1225 * @source will hold a reference on @child_source while @child_source
1226 * is attached to it.
1231 g_source_add_child_source (GSource *source,
1232 GSource *child_source)
1234 GMainContext *context;
1236 g_return_if_fail (source != NULL);
1237 g_return_if_fail (child_source != NULL);
1238 g_return_if_fail (!SOURCE_DESTROYED (source));
1239 g_return_if_fail (!SOURCE_DESTROYED (child_source));
1240 g_return_if_fail (child_source->context == NULL);
1241 g_return_if_fail (child_source->priv == NULL || child_source->priv->parent_source == NULL);
1243 context = source->context;
1246 LOCK_CONTEXT (context);
1249 source->priv = g_slice_new0 (GSourcePrivate);
1250 if (!child_source->priv)
1251 child_source->priv = g_slice_new0 (GSourcePrivate);
1253 source->priv->child_sources = g_slist_prepend (source->priv->child_sources,
1254 g_source_ref (child_source));
1255 child_source->priv->parent_source = source;
1256 g_source_set_priority_unlocked (child_source, context, source->priority);
1260 UNLOCK_CONTEXT (context);
1261 g_source_attach (child_source, context);
1266 * g_source_remove_child_source:
1267 * @source:a #GSource
1268 * @child_source: a #GSource previously passed to
1269 * g_source_add_child_source().
1271 * Detaches @child_source from @source and destroys it.
1276 g_source_remove_child_source (GSource *source,
1277 GSource *child_source)
1279 GMainContext *context;
1281 g_return_if_fail (source != NULL);
1282 g_return_if_fail (child_source != NULL);
1283 g_return_if_fail (child_source->priv != NULL && child_source->priv->parent_source == source);
1284 g_return_if_fail (!SOURCE_DESTROYED (source));
1285 g_return_if_fail (!SOURCE_DESTROYED (child_source));
1287 context = source->context;
1290 LOCK_CONTEXT (context);
1292 source->priv->child_sources = g_slist_remove (source->priv->child_sources, child_source);
1293 g_source_destroy_internal (child_source, context, TRUE);
1294 g_source_unref_internal (child_source, context, TRUE);
1297 UNLOCK_CONTEXT (context);
1301 * g_source_set_callback_indirect:
1302 * @source: the source
1303 * @callback_data: pointer to callback data "object"
1304 * @callback_funcs: functions for reference counting @callback_data
1305 * and getting the callback and data
1307 * Sets the callback function storing the data as a refcounted callback
1308 * "object". This is used internally. Note that calling
1309 * g_source_set_callback_indirect() assumes
1310 * an initial reference count on @callback_data, and thus
1311 * @callback_funcs->unref will eventually be called once more
1312 * than @callback_funcs->ref.
1315 g_source_set_callback_indirect (GSource *source,
1316 gpointer callback_data,
1317 GSourceCallbackFuncs *callback_funcs)
1319 GMainContext *context;
1320 gpointer old_cb_data;
1321 GSourceCallbackFuncs *old_cb_funcs;
1323 g_return_if_fail (source != NULL);
1324 g_return_if_fail (callback_funcs != NULL || callback_data == NULL);
1326 context = source->context;
1329 LOCK_CONTEXT (context);
1331 old_cb_data = source->callback_data;
1332 old_cb_funcs = source->callback_funcs;
1334 source->callback_data = callback_data;
1335 source->callback_funcs = callback_funcs;
1338 UNLOCK_CONTEXT (context);
1341 old_cb_funcs->unref (old_cb_data);
1345 g_source_callback_ref (gpointer cb_data)
1347 GSourceCallback *callback = cb_data;
1349 callback->ref_count++;
1354 g_source_callback_unref (gpointer cb_data)
1356 GSourceCallback *callback = cb_data;
1358 callback->ref_count--;
1359 if (callback->ref_count == 0)
1361 if (callback->notify)
1362 callback->notify (callback->data);
1368 g_source_callback_get (gpointer cb_data,
1373 GSourceCallback *callback = cb_data;
1375 *func = callback->func;
1376 *data = callback->data;
1379 static GSourceCallbackFuncs g_source_callback_funcs = {
1380 g_source_callback_ref,
1381 g_source_callback_unref,
1382 g_source_callback_get,
1386 * g_source_set_callback:
1387 * @source: the source
1388 * @func: a callback function
1389 * @data: the data to pass to callback function
1390 * @notify: a function to call when @data is no longer in use, or %NULL.
1392 * Sets the callback function for a source. The callback for a source is
1393 * called from the source's dispatch function.
1395 * The exact type of @func depends on the type of source; ie. you
1396 * should not count on @func being called with @data as its first
1399 * Typically, you won't use this function. Instead use functions specific
1400 * to the type of source you are using.
1403 g_source_set_callback (GSource *source,
1406 GDestroyNotify notify)
1408 GSourceCallback *new_callback;
1410 g_return_if_fail (source != NULL);
1412 new_callback = g_new (GSourceCallback, 1);
1414 new_callback->ref_count = 1;
1415 new_callback->func = func;
1416 new_callback->data = data;
1417 new_callback->notify = notify;
1419 g_source_set_callback_indirect (source, new_callback, &g_source_callback_funcs);
1424 * g_source_set_funcs:
1425 * @source: a #GSource
1426 * @funcs: the new #GSourceFuncs
1428 * Sets the source functions (can be used to override
1429 * default implementations) of an unattached source.
1434 g_source_set_funcs (GSource *source,
1435 GSourceFuncs *funcs)
1437 g_return_if_fail (source != NULL);
1438 g_return_if_fail (source->context == NULL);
1439 g_return_if_fail (source->ref_count > 0);
1440 g_return_if_fail (funcs != NULL);
1442 source->source_funcs = funcs;
1446 g_source_set_priority_unlocked (GSource *source,
1447 GMainContext *context,
1452 source->priority = priority;
1456 /* Remove the source from the context's source and then
1457 * add it back so it is sorted in the correct place
1459 g_source_list_remove (source, source->context);
1460 g_source_list_add (source, source->context);
1462 if (!SOURCE_BLOCKED (source))
1464 tmp_list = source->poll_fds;
1467 g_main_context_remove_poll_unlocked (context, tmp_list->data);
1468 g_main_context_add_poll_unlocked (context, priority, tmp_list->data);
1470 tmp_list = tmp_list->next;
1475 if (source->priv && source->priv->child_sources)
1477 tmp_list = source->priv->child_sources;
1480 g_source_set_priority_unlocked (tmp_list->data, context, priority);
1481 tmp_list = tmp_list->next;
1487 * g_source_set_priority:
1488 * @source: a #GSource
1489 * @priority: the new priority.
1491 * Sets the priority of a source. While the main loop is being run, a
1492 * source will be dispatched if it is ready to be dispatched and no
1493 * sources at a higher (numerically smaller) priority are ready to be
1497 g_source_set_priority (GSource *source,
1500 GMainContext *context;
1502 g_return_if_fail (source != NULL);
1504 context = source->context;
1507 LOCK_CONTEXT (context);
1508 g_source_set_priority_unlocked (source, context, priority);
1510 UNLOCK_CONTEXT (source->context);
1514 * g_source_get_priority:
1515 * @source: a #GSource
1517 * Gets the priority of a source.
1519 * Return value: the priority of the source
1522 g_source_get_priority (GSource *source)
1524 g_return_val_if_fail (source != NULL, 0);
1526 return source->priority;
1530 * g_source_set_can_recurse:
1531 * @source: a #GSource
1532 * @can_recurse: whether recursion is allowed for this source
1534 * Sets whether a source can be called recursively. If @can_recurse is
1535 * %TRUE, then while the source is being dispatched then this source
1536 * will be processed normally. Otherwise, all processing of this
1537 * source is blocked until the dispatch function returns.
1540 g_source_set_can_recurse (GSource *source,
1541 gboolean can_recurse)
1543 GMainContext *context;
1545 g_return_if_fail (source != NULL);
1547 context = source->context;
1550 LOCK_CONTEXT (context);
1553 source->flags |= G_SOURCE_CAN_RECURSE;
1555 source->flags &= ~G_SOURCE_CAN_RECURSE;
1558 UNLOCK_CONTEXT (context);
1562 * g_source_get_can_recurse:
1563 * @source: a #GSource
1565 * Checks whether a source is allowed to be called recursively.
1566 * see g_source_set_can_recurse().
1568 * Return value: whether recursion is allowed.
1571 g_source_get_can_recurse (GSource *source)
1573 g_return_val_if_fail (source != NULL, FALSE);
1575 return (source->flags & G_SOURCE_CAN_RECURSE) != 0;
1580 * g_source_set_name:
1581 * @source: a #GSource
1582 * @name: debug name for the source
1584 * Sets a name for the source, used in debugging and profiling.
1585 * The name defaults to #NULL.
1587 * The source name should describe in a human-readable way
1588 * what the source does. For example, "X11 event queue"
1589 * or "GTK+ repaint idle handler" or whatever it is.
1591 * It is permitted to call this function multiple times, but is not
1592 * recommended due to the potential performance impact. For example,
1593 * one could change the name in the "check" function of a #GSourceFuncs
1594 * to include details like the event type in the source name.
1599 g_source_set_name (GSource *source,
1602 g_return_if_fail (source != NULL);
1604 /* setting back to NULL is allowed, just because it's
1605 * weird if get_name can return NULL but you can't
1609 g_free (source->name);
1610 source->name = g_strdup (name);
1614 * g_source_get_name:
1615 * @source: a #GSource
1617 * Gets a name for the source, used in debugging and profiling.
1618 * The name may be #NULL if it has never been set with
1619 * g_source_set_name().
1621 * Return value: the name of the source
1624 G_CONST_RETURN char*
1625 g_source_get_name (GSource *source)
1627 g_return_val_if_fail (source != NULL, NULL);
1629 return source->name;
1633 * g_source_set_name_by_id:
1634 * @tag: a #GSource ID
1635 * @name: debug name for the source
1637 * Sets the name of a source using its ID.
1639 * This is a convenience utility to set source names from the return
1640 * value of g_idle_add(), g_timeout_add(), etc.
1645 g_source_set_name_by_id (guint tag,
1650 g_return_if_fail (tag > 0);
1652 source = g_main_context_find_source_by_id (NULL, tag);
1656 g_source_set_name (source, name);
1662 * @source: a #GSource
1664 * Increases the reference count on a source by one.
1666 * Return value: @source
1669 g_source_ref (GSource *source)
1671 GMainContext *context;
1673 g_return_val_if_fail (source != NULL, NULL);
1675 context = source->context;
1678 LOCK_CONTEXT (context);
1680 source->ref_count++;
1683 UNLOCK_CONTEXT (context);
1688 /* g_source_unref() but possible to call within context lock
1691 g_source_unref_internal (GSource *source,
1692 GMainContext *context,
1695 gpointer old_cb_data = NULL;
1696 GSourceCallbackFuncs *old_cb_funcs = NULL;
1698 g_return_if_fail (source != NULL);
1700 if (!have_lock && context)
1701 LOCK_CONTEXT (context);
1703 source->ref_count--;
1704 if (source->ref_count == 0)
1706 old_cb_data = source->callback_data;
1707 old_cb_funcs = source->callback_funcs;
1709 source->callback_data = NULL;
1710 source->callback_funcs = NULL;
1714 if (!SOURCE_DESTROYED (source))
1715 g_warning (G_STRLOC ": ref_count == 0, but source was still attached to a context!");
1716 g_source_list_remove (source, context);
1719 if (source->source_funcs->finalize)
1722 UNLOCK_CONTEXT (context);
1723 source->source_funcs->finalize (source);
1725 LOCK_CONTEXT (context);
1728 g_free (source->name);
1729 source->name = NULL;
1731 g_slist_free (source->poll_fds);
1732 source->poll_fds = NULL;
1736 g_slice_free (GSourcePrivate, source->priv);
1737 source->priv = NULL;
1743 if (!have_lock && context)
1744 UNLOCK_CONTEXT (context);
1749 UNLOCK_CONTEXT (context);
1751 old_cb_funcs->unref (old_cb_data);
1754 LOCK_CONTEXT (context);
1760 * @source: a #GSource
1762 * Decreases the reference count of a source by one. If the
1763 * resulting reference count is zero the source and associated
1764 * memory will be destroyed.
1767 g_source_unref (GSource *source)
1769 g_return_if_fail (source != NULL);
1771 g_source_unref_internal (source, source->context, FALSE);
1775 * g_main_context_find_source_by_id:
1776 * @context: a #GMainContext (if %NULL, the default context will be used)
1777 * @source_id: the source ID, as returned by g_source_get_id().
1779 * Finds a #GSource given a pair of context and ID.
1781 * Return value: the #GSource if found, otherwise, %NULL
1784 g_main_context_find_source_by_id (GMainContext *context,
1789 g_return_val_if_fail (source_id > 0, NULL);
1791 if (context == NULL)
1792 context = g_main_context_default ();
1794 LOCK_CONTEXT (context);
1796 source = context->source_list;
1799 if (!SOURCE_DESTROYED (source) &&
1800 source->source_id == source_id)
1802 source = source->next;
1805 UNLOCK_CONTEXT (context);
1811 * g_main_context_find_source_by_funcs_user_data:
1812 * @context: a #GMainContext (if %NULL, the default context will be used).
1813 * @funcs: the @source_funcs passed to g_source_new().
1814 * @user_data: the user data from the callback.
1816 * Finds a source with the given source functions and user data. If
1817 * multiple sources exist with the same source function and user data,
1818 * the first one found will be returned.
1820 * Return value: the source, if one was found, otherwise %NULL
1823 g_main_context_find_source_by_funcs_user_data (GMainContext *context,
1824 GSourceFuncs *funcs,
1829 g_return_val_if_fail (funcs != NULL, NULL);
1831 if (context == NULL)
1832 context = g_main_context_default ();
1834 LOCK_CONTEXT (context);
1836 source = context->source_list;
1839 if (!SOURCE_DESTROYED (source) &&
1840 source->source_funcs == funcs &&
1841 source->callback_funcs)
1843 GSourceFunc callback;
1844 gpointer callback_data;
1846 source->callback_funcs->get (source->callback_data, source, &callback, &callback_data);
1848 if (callback_data == user_data)
1851 source = source->next;
1854 UNLOCK_CONTEXT (context);
1860 * g_main_context_find_source_by_user_data:
1861 * @context: a #GMainContext
1862 * @user_data: the user_data for the callback.
1864 * Finds a source with the given user data for the callback. If
1865 * multiple sources exist with the same user data, the first
1866 * one found will be returned.
1868 * Return value: the source, if one was found, otherwise %NULL
1871 g_main_context_find_source_by_user_data (GMainContext *context,
1876 if (context == NULL)
1877 context = g_main_context_default ();
1879 LOCK_CONTEXT (context);
1881 source = context->source_list;
1884 if (!SOURCE_DESTROYED (source) &&
1885 source->callback_funcs)
1887 GSourceFunc callback;
1888 gpointer callback_data = NULL;
1890 source->callback_funcs->get (source->callback_data, source, &callback, &callback_data);
1892 if (callback_data == user_data)
1895 source = source->next;
1898 UNLOCK_CONTEXT (context);
1905 * @tag: the ID of the source to remove.
1907 * Removes the source with the given id from the default main context.
1909 * a #GSource is given by g_source_get_id(), or will be returned by the
1910 * functions g_source_attach(), g_idle_add(), g_idle_add_full(),
1911 * g_timeout_add(), g_timeout_add_full(), g_child_watch_add(),
1912 * g_child_watch_add_full(), g_io_add_watch(), and g_io_add_watch_full().
1914 * See also g_source_destroy(). You must use g_source_destroy() for sources
1915 * added to a non-default main context.
1917 * Return value: %TRUE if the source was found and removed.
1920 g_source_remove (guint tag)
1924 g_return_val_if_fail (tag > 0, FALSE);
1926 source = g_main_context_find_source_by_id (NULL, tag);
1928 g_source_destroy (source);
1930 return source != NULL;
1934 * g_source_remove_by_user_data:
1935 * @user_data: the user_data for the callback.
1937 * Removes a source from the default main loop context given the user
1938 * data for the callback. If multiple sources exist with the same user
1939 * data, only one will be destroyed.
1941 * Return value: %TRUE if a source was found and removed.
1944 g_source_remove_by_user_data (gpointer user_data)
1948 source = g_main_context_find_source_by_user_data (NULL, user_data);
1951 g_source_destroy (source);
1959 * g_source_remove_by_funcs_user_data:
1960 * @funcs: The @source_funcs passed to g_source_new()
1961 * @user_data: the user data for the callback
1963 * Removes a source from the default main loop context given the
1964 * source functions and user data. If multiple sources exist with the
1965 * same source functions and user data, only one will be destroyed.
1967 * Return value: %TRUE if a source was found and removed.
1970 g_source_remove_by_funcs_user_data (GSourceFuncs *funcs,
1975 g_return_val_if_fail (funcs != NULL, FALSE);
1977 source = g_main_context_find_source_by_funcs_user_data (NULL, funcs, user_data);
1980 g_source_destroy (source);
1988 * g_get_current_time:
1989 * @result: #GTimeVal structure in which to store current time.
1991 * Equivalent to the UNIX gettimeofday() function, but portable.
1993 * You may find g_get_real_time() to be more convenient.
1996 g_get_current_time (GTimeVal *result)
2001 g_return_if_fail (result != NULL);
2003 /*this is required on alpha, there the timeval structs are int's
2004 not longs and a cast only would fail horribly*/
2005 gettimeofday (&r, NULL);
2006 result->tv_sec = r.tv_sec;
2007 result->tv_usec = r.tv_usec;
2012 g_return_if_fail (result != NULL);
2014 GetSystemTimeAsFileTime (&ft);
2015 memmove (&time64, &ft, sizeof (FILETIME));
2017 /* Convert from 100s of nanoseconds since 1601-01-01
2018 * to Unix epoch. Yes, this is Y2038 unsafe.
2020 time64 -= G_GINT64_CONSTANT (116444736000000000);
2023 result->tv_sec = time64 / 1000000;
2024 result->tv_usec = time64 % 1000000;
2031 * Queries the system wall-clock time.
2033 * This call is functionally equivalent to g_get_current_time() except
2034 * that the return value is often more convenient than dealing with a
2037 * You should only use this call if you are actually interested in the real
2038 * wall-clock time. g_get_monotonic_time() is probably more useful for
2039 * measuring intervals.
2041 * Returns: the number of microseconds since January 1, 1970 UTC.
2046 g_get_real_time (void)
2050 g_get_current_time (&tv);
2052 return (((gint64) tv.tv_sec) * 1000000) + tv.tv_usec;
2056 * g_get_monotonic_time:
2058 * Queries the system monotonic time, if available.
2060 * On POSIX systems with clock_gettime() and %CLOCK_MONOTONIC this call
2061 * is a very shallow wrapper for that. Otherwise, we make a best effort
2062 * that probably involves returning the wall clock time (with at least
2063 * microsecond accuracy, subject to the limitations of the OS kernel).
2065 * Note that, on Windows, "limitations of the OS kernel" is a rather
2066 * substantial statement. Depending on the configuration of the system,
2067 * the wall clock time is updated as infrequently as 64 times a second
2068 * (which is approximately every 16ms).
2070 * Returns: the monotonic time, in microseconds
2075 g_get_monotonic_time (void)
2077 #ifdef HAVE_CLOCK_GETTIME
2078 /* librt clock_gettime() is our first choice */
2080 static int clockid = CLOCK_REALTIME;
2083 #ifdef HAVE_MONOTONIC_CLOCK
2084 /* We have to check if we actually have monotonic clock support.
2086 * There is no thread safety issue here since there is no harm if we
2090 static gboolean checked;
2092 if G_UNLIKELY (!checked)
2094 if (sysconf (_SC_MONOTONIC_CLOCK) >= 0)
2095 clockid = CLOCK_MONOTONIC;
2101 clock_gettime (clockid, &ts);
2103 /* In theory monotonic time can have any epoch.
2105 * glib presently assumes the following:
2107 * 1) The epoch comes some time after the birth of Jesus of Nazareth, but
2108 * not more than 10000 years later.
2110 * 2) The current time also falls sometime within this range.
2112 * These two reasonable assumptions leave us with a maximum deviation from
2113 * the epoch of 10000 years, or 315569520000000000 seconds.
2115 * If we restrict ourselves to this range then the number of microseconds
2116 * will always fit well inside the constraints of a int64 (by a factor of
2119 * If you actually hit the following assertion, probably you should file a
2120 * bug against your operating system for being excessively silly.
2122 g_assert (G_GINT64_CONSTANT (-315569520000000000) < ts.tv_sec &&
2123 ts.tv_sec < G_GINT64_CONSTANT (315569520000000000));
2125 return (((gint64) ts.tv_sec) * 1000000) + (ts.tv_nsec / 1000);
2128 /* It may look like we are discarding accuracy on Windows (since its
2129 * current time is expressed in 100s of nanoseconds) but according to
2130 * many sources, the time is only updated 64 times per second, so
2131 * microsecond accuracy is more than enough.
2136 g_get_current_time (&tv);
2138 return (((gint64) tv.tv_sec) * 1000000) + tv.tv_usec;
2144 g_main_dispatch_free (gpointer dispatch)
2146 g_slice_free (GMainDispatch, dispatch);
2149 /* Running the main loop */
2151 static GMainDispatch *
2154 static GStaticPrivate depth_private = G_STATIC_PRIVATE_INIT;
2155 GMainDispatch *dispatch = g_static_private_get (&depth_private);
2158 dispatch = g_slice_new0 (GMainDispatch);
2159 g_static_private_set (&depth_private, dispatch, g_main_dispatch_free);
2168 * Returns the depth of the stack of calls to
2169 * g_main_context_dispatch() on any #GMainContext in the current thread.
2170 * That is, when called from the toplevel, it gives 0. When
2171 * called from within a callback from g_main_context_iteration()
2172 * (or g_main_loop_run(), etc.) it returns 1. When called from within
2173 * a callback to a recursive call to g_main_context_iteration(),
2174 * it returns 2. And so forth.
2176 * This function is useful in a situation like the following:
2177 * Imagine an extremely simple "garbage collected" system.
2180 * static GList *free_list;
2183 * allocate_memory (gsize size)
2185 * gpointer result = g_malloc (size);
2186 * free_list = g_list_prepend (free_list, result);
2191 * free_allocated_memory (void)
2194 * for (l = free_list; l; l = l->next);
2196 * g_list_free (free_list);
2204 * g_main_context_iteration (NULL, TRUE);
2205 * free_allocated_memory();
2209 * This works from an application, however, if you want to do the same
2210 * thing from a library, it gets more difficult, since you no longer
2211 * control the main loop. You might think you can simply use an idle
2212 * function to make the call to free_allocated_memory(), but that
2213 * doesn't work, since the idle function could be called from a
2214 * recursive callback. This can be fixed by using g_main_depth()
2218 * allocate_memory (gsize size)
2220 * FreeListBlock *block = g_new (FreeListBlock, 1);
2221 * block->mem = g_malloc (size);
2222 * block->depth = g_main_depth ();
2223 * free_list = g_list_prepend (free_list, block);
2224 * return block->mem;
2228 * free_allocated_memory (void)
2232 * int depth = g_main_depth ();
2233 * for (l = free_list; l; );
2235 * GList *next = l->next;
2236 * FreeListBlock *block = l->data;
2237 * if (block->depth > depth)
2239 * g_free (block->mem);
2241 * free_list = g_list_delete_link (free_list, l);
2249 * There is a temptation to use g_main_depth() to solve
2250 * problems with reentrancy. For instance, while waiting for data
2251 * to be received from the network in response to a menu item,
2252 * the menu item might be selected again. It might seem that
2253 * one could make the menu item's callback return immediately
2254 * and do nothing if g_main_depth() returns a value greater than 1.
2255 * However, this should be avoided since the user then sees selecting
2256 * the menu item do nothing. Furthermore, you'll find yourself adding
2257 * these checks all over your code, since there are doubtless many,
2258 * many things that the user could do. Instead, you can use the
2259 * following techniques:
2264 * Use gtk_widget_set_sensitive() or modal dialogs to prevent
2265 * the user from interacting with elements while the main
2266 * loop is recursing.
2271 * Avoid main loop recursion in situations where you can't handle
2272 * arbitrary callbacks. Instead, structure your code so that you
2273 * simply return to the main loop and then get called again when
2274 * there is more work to do.
2279 * Return value: The main loop recursion level in the current thread
2284 GMainDispatch *dispatch = get_dispatch ();
2285 return dispatch->depth;
2289 * g_main_current_source:
2291 * Returns the currently firing source for this thread.
2293 * Return value: The currently firing source or %NULL.
2298 g_main_current_source (void)
2300 GMainDispatch *dispatch = get_dispatch ();
2301 return dispatch->dispatching_sources ? dispatch->dispatching_sources->data : NULL;
2305 * g_source_is_destroyed:
2306 * @source: a #GSource
2308 * Returns whether @source has been destroyed.
2310 * This is important when you operate upon your objects
2311 * from within idle handlers, but may have freed the object
2312 * before the dispatch of your idle handler.
2316 * idle_callback (gpointer data)
2318 * SomeWidget *self = data;
2320 * GDK_THREADS_ENTER (<!-- -->);
2321 * /<!-- -->* do stuff with self *<!-- -->/
2322 * self->idle_id = 0;
2323 * GDK_THREADS_LEAVE (<!-- -->);
2329 * some_widget_do_stuff_later (SomeWidget *self)
2331 * self->idle_id = g_idle_add (idle_callback, self);
2335 * some_widget_finalize (GObject *object)
2337 * SomeWidget *self = SOME_WIDGET (object);
2339 * if (self->idle_id)
2340 * g_source_remove (self->idle_id);
2342 * G_OBJECT_CLASS (parent_class)->finalize (object);
2346 * This will fail in a multi-threaded application if the
2347 * widget is destroyed before the idle handler fires due
2348 * to the use after free in the callback. A solution, to
2349 * this particular problem, is to check to if the source
2350 * has already been destroy within the callback.
2354 * idle_callback (gpointer data)
2356 * SomeWidget *self = data;
2358 * GDK_THREADS_ENTER ();
2359 * if (!g_source_is_destroyed (g_main_current_source ()))
2361 * /<!-- -->* do stuff with self *<!-- -->/
2363 * GDK_THREADS_LEAVE ();
2369 * Return value: %TRUE if the source has been destroyed
2374 g_source_is_destroyed (GSource *source)
2376 return SOURCE_DESTROYED (source);
2379 /* Temporarily remove all this source's file descriptors from the
2380 * poll(), so that if data comes available for one of the file descriptors
2381 * we don't continually spin in the poll()
2383 /* HOLDS: source->context's lock */
2385 block_source (GSource *source)
2389 g_return_if_fail (!SOURCE_BLOCKED (source));
2391 tmp_list = source->poll_fds;
2394 g_main_context_remove_poll_unlocked (source->context, tmp_list->data);
2395 tmp_list = tmp_list->next;
2399 /* HOLDS: source->context's lock */
2401 unblock_source (GSource *source)
2405 g_return_if_fail (!SOURCE_BLOCKED (source)); /* Source already unblocked */
2406 g_return_if_fail (!SOURCE_DESTROYED (source));
2408 tmp_list = source->poll_fds;
2411 g_main_context_add_poll_unlocked (source->context, source->priority, tmp_list->data);
2412 tmp_list = tmp_list->next;
2416 /* HOLDS: context's lock */
2418 g_main_dispatch (GMainContext *context)
2420 GMainDispatch *current = get_dispatch ();
2423 for (i = 0; i < context->pending_dispatches->len; i++)
2425 GSource *source = context->pending_dispatches->pdata[i];
2427 context->pending_dispatches->pdata[i] = NULL;
2430 source->flags &= ~G_SOURCE_READY;
2432 if (!SOURCE_DESTROYED (source))
2434 gboolean was_in_call;
2435 gpointer user_data = NULL;
2436 GSourceFunc callback = NULL;
2437 GSourceCallbackFuncs *cb_funcs;
2439 gboolean need_destroy;
2441 gboolean (*dispatch) (GSource *,
2444 GSList current_source_link;
2446 dispatch = source->source_funcs->dispatch;
2447 cb_funcs = source->callback_funcs;
2448 cb_data = source->callback_data;
2451 cb_funcs->ref (cb_data);
2453 if ((source->flags & G_SOURCE_CAN_RECURSE) == 0)
2454 block_source (source);
2456 was_in_call = source->flags & G_HOOK_FLAG_IN_CALL;
2457 source->flags |= G_HOOK_FLAG_IN_CALL;
2460 cb_funcs->get (cb_data, source, &callback, &user_data);
2462 UNLOCK_CONTEXT (context);
2465 /* The on-stack allocation of the GSList is unconventional, but
2466 * we know that the lifetime of the link is bounded to this
2467 * function as the link is kept in a thread specific list and
2468 * not manipulated outside of this function and its descendants.
2469 * Avoiding the overhead of a g_slist_alloc() is useful as many
2470 * applications do little more than dispatch events.
2472 * This is a performance hack - do not revert to g_slist_prepend()!
2474 current_source_link.data = source;
2475 current_source_link.next = current->dispatching_sources;
2476 current->dispatching_sources = ¤t_source_link;
2477 need_destroy = ! dispatch (source,
2480 g_assert (current->dispatching_sources == ¤t_source_link);
2481 current->dispatching_sources = current_source_link.next;
2485 cb_funcs->unref (cb_data);
2487 LOCK_CONTEXT (context);
2490 source->flags &= ~G_HOOK_FLAG_IN_CALL;
2492 if ((source->flags & G_SOURCE_CAN_RECURSE) == 0 &&
2493 !SOURCE_DESTROYED (source))
2494 unblock_source (source);
2496 /* Note: this depends on the fact that we can't switch
2497 * sources from one main context to another
2499 if (need_destroy && !SOURCE_DESTROYED (source))
2501 g_assert (source->context == context);
2502 g_source_destroy_internal (source, context, TRUE);
2506 SOURCE_UNREF (source, context);
2509 g_ptr_array_set_size (context->pending_dispatches, 0);
2512 /* Holds context's lock */
2513 static inline GSource *
2514 next_valid_source (GMainContext *context,
2517 GSource *new_source = source ? source->next : context->source_list;
2521 if (!SOURCE_DESTROYED (new_source))
2523 new_source->ref_count++;
2527 new_source = new_source->next;
2531 SOURCE_UNREF (source, context);
2537 * g_main_context_acquire:
2538 * @context: a #GMainContext
2540 * Tries to become the owner of the specified context.
2541 * If some other thread is the owner of the context,
2542 * returns %FALSE immediately. Ownership is properly
2543 * recursive: the owner can require ownership again
2544 * and will release ownership when g_main_context_release()
2545 * is called as many times as g_main_context_acquire().
2547 * You must be the owner of a context before you
2548 * can call g_main_context_prepare(), g_main_context_query(),
2549 * g_main_context_check(), g_main_context_dispatch().
2551 * Return value: %TRUE if the operation succeeded, and
2552 * this thread is now the owner of @context.
2555 g_main_context_acquire (GMainContext *context)
2557 #ifdef G_THREADS_ENABLED
2558 gboolean result = FALSE;
2559 GThread *self = G_THREAD_SELF;
2561 if (context == NULL)
2562 context = g_main_context_default ();
2564 LOCK_CONTEXT (context);
2566 if (!context->owner)
2568 context->owner = self;
2569 g_assert (context->owner_count == 0);
2572 if (context->owner == self)
2574 context->owner_count++;
2578 UNLOCK_CONTEXT (context);
2581 #else /* !G_THREADS_ENABLED */
2583 #endif /* G_THREADS_ENABLED */
2587 * g_main_context_release:
2588 * @context: a #GMainContext
2590 * Releases ownership of a context previously acquired by this thread
2591 * with g_main_context_acquire(). If the context was acquired multiple
2592 * times, the ownership will be released only when g_main_context_release()
2593 * is called as many times as it was acquired.
2596 g_main_context_release (GMainContext *context)
2598 #ifdef G_THREADS_ENABLED
2599 if (context == NULL)
2600 context = g_main_context_default ();
2602 LOCK_CONTEXT (context);
2604 context->owner_count--;
2605 if (context->owner_count == 0)
2607 context->owner = NULL;
2609 if (context->waiters)
2611 GMainWaiter *waiter = context->waiters->data;
2612 gboolean loop_internal_waiter =
2613 (waiter->mutex == g_static_mutex_get_mutex (&context->mutex));
2614 context->waiters = g_slist_delete_link (context->waiters,
2616 if (!loop_internal_waiter)
2617 g_mutex_lock (waiter->mutex);
2619 g_cond_signal (waiter->cond);
2621 if (!loop_internal_waiter)
2622 g_mutex_unlock (waiter->mutex);
2626 UNLOCK_CONTEXT (context);
2627 #endif /* G_THREADS_ENABLED */
2631 * g_main_context_wait:
2632 * @context: a #GMainContext
2633 * @cond: a condition variable
2634 * @mutex: a mutex, currently held
2636 * Tries to become the owner of the specified context,
2637 * as with g_main_context_acquire(). But if another thread
2638 * is the owner, atomically drop @mutex and wait on @cond until
2639 * that owner releases ownership or until @cond is signaled, then
2640 * try again (once) to become the owner.
2642 * Return value: %TRUE if the operation succeeded, and
2643 * this thread is now the owner of @context.
2646 g_main_context_wait (GMainContext *context,
2650 #ifdef G_THREADS_ENABLED
2651 gboolean result = FALSE;
2652 GThread *self = G_THREAD_SELF;
2653 gboolean loop_internal_waiter;
2655 if (context == NULL)
2656 context = g_main_context_default ();
2658 loop_internal_waiter = (mutex == g_static_mutex_get_mutex (&context->mutex));
2660 if (!loop_internal_waiter)
2661 LOCK_CONTEXT (context);
2663 if (context->owner && context->owner != self)
2668 waiter.mutex = mutex;
2670 context->waiters = g_slist_append (context->waiters, &waiter);
2672 if (!loop_internal_waiter)
2673 UNLOCK_CONTEXT (context);
2674 g_cond_wait (cond, mutex);
2675 if (!loop_internal_waiter)
2676 LOCK_CONTEXT (context);
2678 context->waiters = g_slist_remove (context->waiters, &waiter);
2681 if (!context->owner)
2683 context->owner = self;
2684 g_assert (context->owner_count == 0);
2687 if (context->owner == self)
2689 context->owner_count++;
2693 if (!loop_internal_waiter)
2694 UNLOCK_CONTEXT (context);
2697 #else /* !G_THREADS_ENABLED */
2699 #endif /* G_THREADS_ENABLED */
2703 * g_main_context_prepare:
2704 * @context: a #GMainContext
2705 * @priority: location to store priority of highest priority
2706 * source already ready.
2708 * Prepares to poll sources within a main loop. The resulting information
2709 * for polling is determined by calling g_main_context_query ().
2711 * Return value: %TRUE if some source is ready to be dispatched
2715 g_main_context_prepare (GMainContext *context,
2720 gint current_priority = G_MAXINT;
2723 if (context == NULL)
2724 context = g_main_context_default ();
2726 LOCK_CONTEXT (context);
2728 context->time_is_fresh = FALSE;
2729 context->real_time_is_fresh = FALSE;
2731 if (context->in_check_or_prepare)
2733 g_warning ("g_main_context_prepare() called recursively from within a source's check() or "
2734 "prepare() member.");
2735 UNLOCK_CONTEXT (context);
2739 #ifdef G_THREADS_ENABLED
2740 if (context->poll_waiting)
2742 g_warning("g_main_context_prepare(): main loop already active in another thread");
2743 UNLOCK_CONTEXT (context);
2747 context->poll_waiting = TRUE;
2748 #endif /* G_THREADS_ENABLED */
2751 /* If recursing, finish up current dispatch, before starting over */
2752 if (context->pending_dispatches)
2755 g_main_dispatch (context, ¤t_time);
2757 UNLOCK_CONTEXT (context);
2762 /* If recursing, clear list of pending dispatches */
2764 for (i = 0; i < context->pending_dispatches->len; i++)
2766 if (context->pending_dispatches->pdata[i])
2767 SOURCE_UNREF ((GSource *)context->pending_dispatches->pdata[i], context);
2769 g_ptr_array_set_size (context->pending_dispatches, 0);
2771 /* Prepare all sources */
2773 context->timeout = -1;
2775 source = next_valid_source (context, NULL);
2778 gint source_timeout = -1;
2780 if ((n_ready > 0) && (source->priority > current_priority))
2782 SOURCE_UNREF (source, context);
2785 if (SOURCE_BLOCKED (source))
2788 if (!(source->flags & G_SOURCE_READY))
2791 gboolean (*prepare) (GSource *source,
2794 prepare = source->source_funcs->prepare;
2795 context->in_check_or_prepare++;
2796 UNLOCK_CONTEXT (context);
2798 result = (*prepare) (source, &source_timeout);
2800 LOCK_CONTEXT (context);
2801 context->in_check_or_prepare--;
2805 GSource *ready_source = source;
2807 while (ready_source)
2809 ready_source->flags |= G_SOURCE_READY;
2810 ready_source = ready_source->priv ? ready_source->priv->parent_source : NULL;
2815 if (source->flags & G_SOURCE_READY)
2818 current_priority = source->priority;
2819 context->timeout = 0;
2822 if (source_timeout >= 0)
2824 if (context->timeout < 0)
2825 context->timeout = source_timeout;
2827 context->timeout = MIN (context->timeout, source_timeout);
2831 source = next_valid_source (context, source);
2834 UNLOCK_CONTEXT (context);
2837 *priority = current_priority;
2839 return (n_ready > 0);
2843 * g_main_context_query:
2844 * @context: a #GMainContext
2845 * @max_priority: maximum priority source to check
2846 * @timeout_: location to store timeout to be used in polling
2847 * @fds: location to store #GPollFD records that need to be polled.
2848 * @n_fds: length of @fds.
2850 * Determines information necessary to poll this main loop.
2852 * Return value: the number of records actually stored in @fds,
2853 * or, if more than @n_fds records need to be stored, the number
2854 * of records that need to be stored.
2857 g_main_context_query (GMainContext *context,
2866 LOCK_CONTEXT (context);
2868 pollrec = context->poll_records;
2870 while (pollrec && max_priority >= pollrec->priority)
2872 /* We need to include entries with fd->events == 0 in the array because
2873 * otherwise if the application changes fd->events behind our back and
2874 * makes it non-zero, we'll be out of sync when we check the fds[] array.
2875 * (Changing fd->events after adding an FD wasn't an anticipated use of
2876 * this API, but it occurs in practice.) */
2879 fds[n_poll].fd = pollrec->fd->fd;
2880 /* In direct contradiction to the Unix98 spec, IRIX runs into
2881 * difficulty if you pass in POLLERR, POLLHUP or POLLNVAL
2882 * flags in the events field of the pollfd while it should
2883 * just ignoring them. So we mask them out here.
2885 fds[n_poll].events = pollrec->fd->events & ~(G_IO_ERR|G_IO_HUP|G_IO_NVAL);
2886 fds[n_poll].revents = 0;
2889 pollrec = pollrec->next;
2893 #ifdef G_THREADS_ENABLED
2894 context->poll_changed = FALSE;
2899 *timeout = context->timeout;
2902 context->time_is_fresh = FALSE;
2903 context->real_time_is_fresh = FALSE;
2907 UNLOCK_CONTEXT (context);
2913 * g_main_context_check:
2914 * @context: a #GMainContext
2915 * @max_priority: the maximum numerical priority of sources to check
2916 * @fds: array of #GPollFD's that was passed to the last call to
2917 * g_main_context_query()
2918 * @n_fds: return value of g_main_context_query()
2920 * Passes the results of polling back to the main loop.
2922 * Return value: %TRUE if some sources are ready to be dispatched.
2925 g_main_context_check (GMainContext *context,
2935 LOCK_CONTEXT (context);
2937 if (context->in_check_or_prepare)
2939 g_warning ("g_main_context_check() called recursively from within a source's check() or "
2940 "prepare() member.");
2941 UNLOCK_CONTEXT (context);
2945 #ifdef G_THREADS_ENABLED
2946 if (!context->poll_waiting)
2950 read (context->wake_up_pipe[0], &a, 1);
2954 context->poll_waiting = FALSE;
2956 /* If the set of poll file descriptors changed, bail out
2957 * and let the main loop rerun
2959 if (context->poll_changed)
2961 UNLOCK_CONTEXT (context);
2964 #endif /* G_THREADS_ENABLED */
2966 pollrec = context->poll_records;
2970 if (pollrec->fd->events)
2971 pollrec->fd->revents = fds[i].revents;
2973 pollrec = pollrec->next;
2977 source = next_valid_source (context, NULL);
2980 if ((n_ready > 0) && (source->priority > max_priority))
2982 SOURCE_UNREF (source, context);
2985 if (SOURCE_BLOCKED (source))
2988 if (!(source->flags & G_SOURCE_READY))
2991 gboolean (*check) (GSource *source);
2993 check = source->source_funcs->check;
2995 context->in_check_or_prepare++;
2996 UNLOCK_CONTEXT (context);
2998 result = (*check) (source);
3000 LOCK_CONTEXT (context);
3001 context->in_check_or_prepare--;
3005 GSource *ready_source = source;
3007 while (ready_source)
3009 ready_source->flags |= G_SOURCE_READY;
3010 ready_source = ready_source->priv ? ready_source->priv->parent_source : NULL;
3015 if (source->flags & G_SOURCE_READY)
3017 source->ref_count++;
3018 g_ptr_array_add (context->pending_dispatches, source);
3022 /* never dispatch sources with less priority than the first
3023 * one we choose to dispatch
3025 max_priority = source->priority;
3029 source = next_valid_source (context, source);
3032 UNLOCK_CONTEXT (context);
3038 * g_main_context_dispatch:
3039 * @context: a #GMainContext
3041 * Dispatches all pending sources.
3044 g_main_context_dispatch (GMainContext *context)
3046 LOCK_CONTEXT (context);
3048 if (context->pending_dispatches->len > 0)
3050 g_main_dispatch (context);
3053 UNLOCK_CONTEXT (context);
3056 /* HOLDS context lock */
3058 g_main_context_iterate (GMainContext *context,
3065 gboolean some_ready;
3066 gint nfds, allocated_nfds;
3067 GPollFD *fds = NULL;
3069 UNLOCK_CONTEXT (context);
3071 #ifdef G_THREADS_ENABLED
3072 if (!g_main_context_acquire (context))
3074 gboolean got_ownership;
3076 LOCK_CONTEXT (context);
3078 g_return_val_if_fail (g_thread_supported (), FALSE);
3084 context->cond = g_cond_new ();
3086 got_ownership = g_main_context_wait (context,
3088 g_static_mutex_get_mutex (&context->mutex));
3094 LOCK_CONTEXT (context);
3095 #endif /* G_THREADS_ENABLED */
3097 if (!context->cached_poll_array)
3099 context->cached_poll_array_size = context->n_poll_records;
3100 context->cached_poll_array = g_new (GPollFD, context->n_poll_records);
3103 allocated_nfds = context->cached_poll_array_size;
3104 fds = context->cached_poll_array;
3106 UNLOCK_CONTEXT (context);
3108 g_main_context_prepare (context, &max_priority);
3110 while ((nfds = g_main_context_query (context, max_priority, &timeout, fds,
3111 allocated_nfds)) > allocated_nfds)
3113 LOCK_CONTEXT (context);
3115 context->cached_poll_array_size = allocated_nfds = nfds;
3116 context->cached_poll_array = fds = g_new (GPollFD, nfds);
3117 UNLOCK_CONTEXT (context);
3123 g_main_context_poll (context, timeout, max_priority, fds, nfds);
3125 some_ready = g_main_context_check (context, max_priority, fds, nfds);
3128 g_main_context_dispatch (context);
3130 #ifdef G_THREADS_ENABLED
3131 g_main_context_release (context);
3132 #endif /* G_THREADS_ENABLED */
3134 LOCK_CONTEXT (context);
3140 * g_main_context_pending:
3141 * @context: a #GMainContext (if %NULL, the default context will be used)
3143 * Checks if any sources have pending events for the given context.
3145 * Return value: %TRUE if events are pending.
3148 g_main_context_pending (GMainContext *context)
3153 context = g_main_context_default();
3155 LOCK_CONTEXT (context);
3156 retval = g_main_context_iterate (context, FALSE, FALSE, G_THREAD_SELF);
3157 UNLOCK_CONTEXT (context);
3163 * g_main_context_iteration:
3164 * @context: a #GMainContext (if %NULL, the default context will be used)
3165 * @may_block: whether the call may block.
3167 * Runs a single iteration for the given main loop. This involves
3168 * checking to see if any event sources are ready to be processed,
3169 * then if no events sources are ready and @may_block is %TRUE, waiting
3170 * for a source to become ready, then dispatching the highest priority
3171 * events sources that are ready. Otherwise, if @may_block is %FALSE
3172 * sources are not waited to become ready, only those highest priority
3173 * events sources will be dispatched (if any), that are ready at this
3174 * given moment without further waiting.
3176 * Note that even when @may_block is %TRUE, it is still possible for
3177 * g_main_context_iteration() to return %FALSE, since the the wait may
3178 * be interrupted for other reasons than an event source becoming ready.
3180 * Return value: %TRUE if events were dispatched.
3183 g_main_context_iteration (GMainContext *context, gboolean may_block)
3188 context = g_main_context_default();
3190 LOCK_CONTEXT (context);
3191 retval = g_main_context_iterate (context, may_block, TRUE, G_THREAD_SELF);
3192 UNLOCK_CONTEXT (context);
3199 * @context: a #GMainContext (if %NULL, the default context will be used).
3200 * @is_running: set to %TRUE to indicate that the loop is running. This
3201 * is not very important since calling g_main_loop_run() will set this to
3204 * Creates a new #GMainLoop structure.
3206 * Return value: a new #GMainLoop.
3209 g_main_loop_new (GMainContext *context,
3210 gboolean is_running)
3215 context = g_main_context_default();
3217 g_main_context_ref (context);
3219 loop = g_new0 (GMainLoop, 1);
3220 loop->context = context;
3221 loop->is_running = is_running != FALSE;
3222 loop->ref_count = 1;
3229 * @loop: a #GMainLoop
3231 * Increases the reference count on a #GMainLoop object by one.
3233 * Return value: @loop
3236 g_main_loop_ref (GMainLoop *loop)
3238 g_return_val_if_fail (loop != NULL, NULL);
3239 g_return_val_if_fail (g_atomic_int_get (&loop->ref_count) > 0, NULL);
3241 g_atomic_int_inc (&loop->ref_count);
3247 * g_main_loop_unref:
3248 * @loop: a #GMainLoop
3250 * Decreases the reference count on a #GMainLoop object by one. If
3251 * the result is zero, free the loop and free all associated memory.
3254 g_main_loop_unref (GMainLoop *loop)
3256 g_return_if_fail (loop != NULL);
3257 g_return_if_fail (g_atomic_int_get (&loop->ref_count) > 0);
3259 if (!g_atomic_int_dec_and_test (&loop->ref_count))
3262 g_main_context_unref (loop->context);
3268 * @loop: a #GMainLoop
3270 * Runs a main loop until g_main_loop_quit() is called on the loop.
3271 * If this is called for the thread of the loop's #GMainContext,
3272 * it will process events from the loop, otherwise it will
3276 g_main_loop_run (GMainLoop *loop)
3278 GThread *self = G_THREAD_SELF;
3280 g_return_if_fail (loop != NULL);
3281 g_return_if_fail (g_atomic_int_get (&loop->ref_count) > 0);
3283 #ifdef G_THREADS_ENABLED
3284 if (!g_main_context_acquire (loop->context))
3286 gboolean got_ownership = FALSE;
3288 /* Another thread owns this context */
3289 if (!g_thread_supported ())
3291 g_warning ("g_main_loop_run() was called from second thread but "
3292 "g_thread_init() was never called.");
3296 LOCK_CONTEXT (loop->context);
3298 g_atomic_int_inc (&loop->ref_count);
3300 if (!loop->is_running)
3301 loop->is_running = TRUE;
3303 if (!loop->context->cond)
3304 loop->context->cond = g_cond_new ();
3306 while (loop->is_running && !got_ownership)
3307 got_ownership = g_main_context_wait (loop->context,
3308 loop->context->cond,
3309 g_static_mutex_get_mutex (&loop->context->mutex));
3311 if (!loop->is_running)
3313 UNLOCK_CONTEXT (loop->context);
3315 g_main_context_release (loop->context);
3316 g_main_loop_unref (loop);
3320 g_assert (got_ownership);
3323 LOCK_CONTEXT (loop->context);
3324 #endif /* G_THREADS_ENABLED */
3326 if (loop->context->in_check_or_prepare)
3328 g_warning ("g_main_loop_run(): called recursively from within a source's "
3329 "check() or prepare() member, iteration not possible.");
3333 g_atomic_int_inc (&loop->ref_count);
3334 loop->is_running = TRUE;
3335 while (loop->is_running)
3336 g_main_context_iterate (loop->context, TRUE, TRUE, self);
3338 UNLOCK_CONTEXT (loop->context);
3340 #ifdef G_THREADS_ENABLED
3341 g_main_context_release (loop->context);
3342 #endif /* G_THREADS_ENABLED */
3344 g_main_loop_unref (loop);
3349 * @loop: a #GMainLoop
3351 * Stops a #GMainLoop from running. Any calls to g_main_loop_run()
3352 * for the loop will return.
3354 * Note that sources that have already been dispatched when
3355 * g_main_loop_quit() is called will still be executed.
3358 g_main_loop_quit (GMainLoop *loop)
3360 g_return_if_fail (loop != NULL);
3361 g_return_if_fail (g_atomic_int_get (&loop->ref_count) > 0);
3363 LOCK_CONTEXT (loop->context);
3364 loop->is_running = FALSE;
3365 g_main_context_wakeup_unlocked (loop->context);
3367 #ifdef G_THREADS_ENABLED
3368 if (loop->context->cond)
3369 g_cond_broadcast (loop->context->cond);
3370 #endif /* G_THREADS_ENABLED */
3372 UNLOCK_CONTEXT (loop->context);
3376 * g_main_loop_is_running:
3377 * @loop: a #GMainLoop.
3379 * Checks to see if the main loop is currently being run via g_main_loop_run().
3381 * Return value: %TRUE if the mainloop is currently being run.
3384 g_main_loop_is_running (GMainLoop *loop)
3386 g_return_val_if_fail (loop != NULL, FALSE);
3387 g_return_val_if_fail (g_atomic_int_get (&loop->ref_count) > 0, FALSE);
3389 return loop->is_running;
3393 * g_main_loop_get_context:
3394 * @loop: a #GMainLoop.
3396 * Returns the #GMainContext of @loop.
3398 * Return value: the #GMainContext of @loop
3401 g_main_loop_get_context (GMainLoop *loop)
3403 g_return_val_if_fail (loop != NULL, NULL);
3404 g_return_val_if_fail (g_atomic_int_get (&loop->ref_count) > 0, NULL);
3406 return loop->context;
3409 /* HOLDS: context's lock */
3411 g_main_context_poll (GMainContext *context,
3417 #ifdef G_MAIN_POLL_DEBUG
3423 GPollFunc poll_func;
3425 if (n_fds || timeout != 0)
3427 #ifdef G_MAIN_POLL_DEBUG
3428 if (_g_main_poll_debug)
3430 g_print ("polling context=%p n=%d timeout=%d\n",
3431 context, n_fds, timeout);
3432 poll_timer = g_timer_new ();
3436 LOCK_CONTEXT (context);
3438 poll_func = context->poll_func;
3440 UNLOCK_CONTEXT (context);
3441 if ((*poll_func) (fds, n_fds, timeout) < 0 && errno != EINTR)
3444 g_warning ("poll(2) failed due to: %s.",
3445 g_strerror (errno));
3447 /* If g_poll () returns -1, it has already called g_warning() */
3451 #ifdef G_MAIN_POLL_DEBUG
3452 if (_g_main_poll_debug)
3454 LOCK_CONTEXT (context);
3456 g_print ("g_main_poll(%d) timeout: %d - elapsed %12.10f seconds",
3459 g_timer_elapsed (poll_timer, NULL));
3460 g_timer_destroy (poll_timer);
3461 pollrec = context->poll_records;
3463 while (pollrec != NULL)
3468 if (fds[i].fd == pollrec->fd->fd &&
3469 pollrec->fd->events &&
3472 g_print (" [" G_POLLFD_FORMAT " :", fds[i].fd);
3473 if (fds[i].revents & G_IO_IN)
3475 if (fds[i].revents & G_IO_OUT)
3477 if (fds[i].revents & G_IO_PRI)
3479 if (fds[i].revents & G_IO_ERR)
3481 if (fds[i].revents & G_IO_HUP)
3483 if (fds[i].revents & G_IO_NVAL)
3489 pollrec = pollrec->next;
3493 UNLOCK_CONTEXT (context);
3496 } /* if (n_fds || timeout != 0) */
3500 * g_main_context_add_poll:
3501 * @context: a #GMainContext (or %NULL for the default context)
3502 * @fd: a #GPollFD structure holding information about a file
3503 * descriptor to watch.
3504 * @priority: the priority for this file descriptor which should be
3505 * the same as the priority used for g_source_attach() to ensure that the
3506 * file descriptor is polled whenever the results may be needed.
3508 * Adds a file descriptor to the set of file descriptors polled for
3509 * this context. This will very seldomly be used directly. Instead
3510 * a typical event source will use g_source_add_poll() instead.
3513 g_main_context_add_poll (GMainContext *context,
3518 context = g_main_context_default ();
3520 g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
3521 g_return_if_fail (fd);
3523 LOCK_CONTEXT (context);
3524 g_main_context_add_poll_unlocked (context, priority, fd);
3525 UNLOCK_CONTEXT (context);
3528 /* HOLDS: main_loop_lock */
3530 g_main_context_add_poll_unlocked (GMainContext *context,
3534 GPollRec *prevrec, *nextrec;
3535 GPollRec *newrec = g_slice_new (GPollRec);
3537 /* This file descriptor may be checked before we ever poll */
3540 newrec->priority = priority;
3542 prevrec = context->poll_records_tail;
3544 while (prevrec && priority < prevrec->priority)
3547 prevrec = prevrec->prev;
3551 prevrec->next = newrec;
3553 context->poll_records = newrec;
3555 newrec->prev = prevrec;
3556 newrec->next = nextrec;
3559 nextrec->prev = newrec;
3561 context->poll_records_tail = newrec;
3563 context->n_poll_records++;
3565 #ifdef G_THREADS_ENABLED
3566 context->poll_changed = TRUE;
3568 /* Now wake up the main loop if it is waiting in the poll() */
3569 g_main_context_wakeup_unlocked (context);
3574 * g_main_context_remove_poll:
3575 * @context:a #GMainContext
3576 * @fd: a #GPollFD descriptor previously added with g_main_context_add_poll()
3578 * Removes file descriptor from the set of file descriptors to be
3579 * polled for a particular context.
3582 g_main_context_remove_poll (GMainContext *context,
3586 context = g_main_context_default ();
3588 g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
3589 g_return_if_fail (fd);
3591 LOCK_CONTEXT (context);
3592 g_main_context_remove_poll_unlocked (context, fd);
3593 UNLOCK_CONTEXT (context);
3597 g_main_context_remove_poll_unlocked (GMainContext *context,
3600 GPollRec *pollrec, *prevrec, *nextrec;
3603 pollrec = context->poll_records;
3607 nextrec = pollrec->next;
3608 if (pollrec->fd == fd)
3610 if (prevrec != NULL)
3611 prevrec->next = nextrec;
3613 context->poll_records = nextrec;
3615 if (nextrec != NULL)
3616 nextrec->prev = prevrec;
3618 context->poll_records_tail = prevrec;
3620 g_slice_free (GPollRec, pollrec);
3622 context->n_poll_records--;
3629 #ifdef G_THREADS_ENABLED
3630 context->poll_changed = TRUE;
3632 /* Now wake up the main loop if it is waiting in the poll() */
3633 g_main_context_wakeup_unlocked (context);
3638 * g_source_get_current_time:
3639 * @source: a #GSource
3640 * @timeval: #GTimeVal structure in which to store current time.
3642 * Gets the "current time" to be used when checking
3643 * this source. The advantage of calling this function over
3644 * calling g_get_current_time() directly is that when
3645 * checking multiple sources, GLib can cache a single value
3646 * instead of having to repeatedly get the system time.
3648 * Deprecated: 2.28: use g_source_get_time() instead
3651 g_source_get_current_time (GSource *source,
3654 GMainContext *context;
3656 g_return_if_fail (source->context != NULL);
3658 context = source->context;
3660 LOCK_CONTEXT (context);
3662 if (!context->real_time_is_fresh)
3664 context->real_time = g_get_real_time ();
3665 context->real_time_is_fresh = TRUE;
3668 timeval->tv_sec = context->real_time / 1000000;
3669 timeval->tv_usec = context->real_time % 1000000;
3671 UNLOCK_CONTEXT (context);
3675 * g_source_get_time:
3676 * @source: a #GSource
3678 * Gets the time to be used when checking this source. The advantage of
3679 * calling this function over calling g_get_monotonic_time() directly is
3680 * that when checking multiple sources, GLib can cache a single value
3681 * instead of having to repeatedly get the system monotonic time.
3683 * The time here is the system monotonic time, if available, or some
3684 * other reasonable alternative otherwise. See g_get_monotonic_time().
3686 * Returns: the monotonic time in microseconds
3691 g_source_get_time (GSource *source)
3693 GMainContext *context;
3696 g_return_val_if_fail (source->context != NULL, 0);
3698 context = source->context;
3700 LOCK_CONTEXT (context);
3702 if (!context->time_is_fresh)
3704 context->time = g_get_monotonic_time ();
3705 context->time_is_fresh = TRUE;
3708 result = context->time;
3710 UNLOCK_CONTEXT (context);
3716 * g_main_context_set_poll_func:
3717 * @context: a #GMainContext
3718 * @func: the function to call to poll all file descriptors
3720 * Sets the function to use to handle polling of file descriptors. It
3721 * will be used instead of the poll() system call
3722 * (or GLib's replacement function, which is used where
3723 * poll() isn't available).
3725 * This function could possibly be used to integrate the GLib event
3726 * loop with an external event loop.
3729 g_main_context_set_poll_func (GMainContext *context,
3733 context = g_main_context_default ();
3735 g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
3737 LOCK_CONTEXT (context);
3740 context->poll_func = func;
3742 context->poll_func = g_poll;
3744 UNLOCK_CONTEXT (context);
3748 * g_main_context_get_poll_func:
3749 * @context: a #GMainContext
3751 * Gets the poll function set by g_main_context_set_poll_func().
3753 * Return value: the poll function
3756 g_main_context_get_poll_func (GMainContext *context)
3761 context = g_main_context_default ();
3763 g_return_val_if_fail (g_atomic_int_get (&context->ref_count) > 0, NULL);
3765 LOCK_CONTEXT (context);
3766 result = context->poll_func;
3767 UNLOCK_CONTEXT (context);
3773 _g_main_wake_up_all_contexts (void)
3777 /* We were woken up. Wake up all other contexts in all other threads */
3778 G_LOCK (main_context_list);
3779 for (list = main_context_list; list; list = list->next)
3781 GMainContext *context;
3783 context = list->data;
3784 if (g_atomic_int_get (&context->ref_count) > 0)
3785 /* Due to racing conditions we can find ref_count == 0, in
3786 * that case, however, the context is still not destroyed
3787 * and no poll can be active, otherwise the ref_count
3790 g_main_context_wakeup (context);
3792 G_UNLOCK (main_context_list);
3796 /* HOLDS: context's lock */
3797 /* Wake the main loop up from a poll() */
3799 g_main_context_wakeup_unlocked (GMainContext *context)
3801 #ifdef G_THREADS_ENABLED
3802 if (g_thread_supported() && context->poll_waiting)
3804 context->poll_waiting = FALSE;
3806 write (context->wake_up_pipe[1], "A", 1);
3808 ReleaseSemaphore (context->wake_up_semaphore, 1, NULL);
3815 * g_main_context_wakeup:
3816 * @context: a #GMainContext
3818 * If @context is currently waiting in a poll(), interrupt
3819 * the poll(), and continue the iteration process.
3822 g_main_context_wakeup (GMainContext *context)
3825 context = g_main_context_default ();
3827 g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
3829 LOCK_CONTEXT (context);
3830 g_main_context_wakeup_unlocked (context);
3831 UNLOCK_CONTEXT (context);
3835 * g_main_context_is_owner:
3836 * @context: a #GMainContext
3838 * Determines whether this thread holds the (recursive)
3839 * ownership of this #GMaincontext. This is useful to
3840 * know before waiting on another thread that may be
3841 * blocking to get ownership of @context.
3843 * Returns: %TRUE if current thread is owner of @context.
3848 g_main_context_is_owner (GMainContext *context)
3853 context = g_main_context_default ();
3855 #ifdef G_THREADS_ENABLED
3856 LOCK_CONTEXT (context);
3857 is_owner = context->owner == G_THREAD_SELF;
3858 UNLOCK_CONTEXT (context);
3869 g_timeout_set_expiration (GTimeoutSource *timeout_source,
3870 gint64 current_time)
3872 timeout_source->expiration = current_time +
3873 (guint64) timeout_source->interval * 1000;
3875 if (timeout_source->seconds)
3878 static gint timer_perturb = -1;
3880 if (timer_perturb == -1)
3883 * we want a per machine/session unique 'random' value; try the dbus
3884 * address first, that has a UUID in it. If there is no dbus, use the
3885 * hostname for hashing.
3887 const char *session_bus_address = g_getenv ("DBUS_SESSION_BUS_ADDRESS");
3888 if (!session_bus_address)
3889 session_bus_address = g_getenv ("HOSTNAME");
3890 if (session_bus_address)
3891 timer_perturb = ABS ((gint) g_str_hash (session_bus_address)) % 1000000;
3896 /* We want the microseconds part of the timeout to land on the
3897 * 'timer_perturb' mark, but we need to make sure we don't try to
3898 * set the timeout in the past. We do this by ensuring that we
3899 * always only *increase* the expiration time by adding a full
3900 * second in the case that the microsecond portion decreases.
3902 timeout_source->expiration -= timer_perturb;
3904 remainder = timeout_source->expiration % 1000000;
3905 if (remainder >= 1000000/4)
3906 timeout_source->expiration += 1000000;
3908 timeout_source->expiration -= remainder;
3909 timeout_source->expiration += timer_perturb;
3914 g_timeout_prepare (GSource *source,
3917 GTimeoutSource *timeout_source = (GTimeoutSource *) source;
3918 gint64 now = g_source_get_time (source);
3920 if (now < timeout_source->expiration)
3922 /* Round up to ensure that we don't try again too early */
3923 *timeout = (timeout_source->expiration - now + 999) / 1000;
3932 g_timeout_check (GSource *source)
3934 GTimeoutSource *timeout_source = (GTimeoutSource *) source;
3935 gint64 now = g_source_get_time (source);
3937 return timeout_source->expiration <= now;
3941 g_timeout_dispatch (GSource *source,
3942 GSourceFunc callback,
3945 GTimeoutSource *timeout_source = (GTimeoutSource *)source;
3950 g_warning ("Timeout source dispatched without callback\n"
3951 "You must call g_source_set_callback().");
3955 again = callback (user_data);
3958 g_timeout_set_expiration (timeout_source, g_source_get_time (source));
3964 * g_timeout_source_new:
3965 * @interval: the timeout interval in milliseconds.
3967 * Creates a new timeout source.
3969 * The source will not initially be associated with any #GMainContext
3970 * and must be added to one with g_source_attach() before it will be
3973 * Return value: the newly-created timeout source
3976 g_timeout_source_new (guint interval)
3978 GSource *source = g_source_new (&g_timeout_funcs, sizeof (GTimeoutSource));
3979 GTimeoutSource *timeout_source = (GTimeoutSource *)source;
3981 timeout_source->interval = interval;
3982 g_timeout_set_expiration (timeout_source, g_get_monotonic_time ());
3988 * g_timeout_source_new_seconds:
3989 * @interval: the timeout interval in seconds
3991 * Creates a new timeout source.
3993 * The source will not initially be associated with any #GMainContext
3994 * and must be added to one with g_source_attach() before it will be
3997 * The scheduling granularity/accuracy of this timeout source will be
4000 * Return value: the newly-created timeout source
4005 g_timeout_source_new_seconds (guint interval)
4007 GSource *source = g_source_new (&g_timeout_funcs, sizeof (GTimeoutSource));
4008 GTimeoutSource *timeout_source = (GTimeoutSource *)source;
4010 timeout_source->interval = 1000 * interval;
4011 timeout_source->seconds = TRUE;
4013 g_timeout_set_expiration (timeout_source, g_get_monotonic_time ());
4020 * g_timeout_add_full:
4021 * @priority: the priority of the timeout source. Typically this will be in
4022 * the range between #G_PRIORITY_DEFAULT and #G_PRIORITY_HIGH.
4023 * @interval: the time between calls to the function, in milliseconds
4024 * (1/1000ths of a second)
4025 * @function: function to call
4026 * @data: data to pass to @function
4027 * @notify: function to call when the timeout is removed, or %NULL
4029 * Sets a function to be called at regular intervals, with the given
4030 * priority. The function is called repeatedly until it returns
4031 * %FALSE, at which point the timeout is automatically destroyed and
4032 * the function will not be called again. The @notify function is
4033 * called when the timeout is destroyed. The first call to the
4034 * function will be at the end of the first @interval.
4036 * Note that timeout functions may be delayed, due to the processing of other
4037 * event sources. Thus they should not be relied on for precise timing.
4038 * After each call to the timeout function, the time of the next
4039 * timeout is recalculated based on the current time and the given interval
4040 * (it does not try to 'catch up' time lost in delays).
4042 * This internally creates a main loop source using g_timeout_source_new()
4043 * and attaches it to the main loop context using g_source_attach(). You can
4044 * do these steps manually if you need greater control.
4046 * Return value: the ID (greater than 0) of the event source.
4049 g_timeout_add_full (gint priority,
4051 GSourceFunc function,
4053 GDestroyNotify notify)
4058 g_return_val_if_fail (function != NULL, 0);
4060 source = g_timeout_source_new (interval);
4062 if (priority != G_PRIORITY_DEFAULT)
4063 g_source_set_priority (source, priority);
4065 g_source_set_callback (source, function, data, notify);
4066 id = g_source_attach (source, NULL);
4067 g_source_unref (source);
4074 * @interval: the time between calls to the function, in milliseconds
4075 * (1/1000ths of a second)
4076 * @function: function to call
4077 * @data: data to pass to @function
4079 * Sets a function to be called at regular intervals, with the default
4080 * priority, #G_PRIORITY_DEFAULT. The function is called repeatedly
4081 * until it returns %FALSE, at which point the timeout is automatically
4082 * destroyed and the function will not be called again. The first call
4083 * to the function will be at the end of the first @interval.
4085 * Note that timeout functions may be delayed, due to the processing of other
4086 * event sources. Thus they should not be relied on for precise timing.
4087 * After each call to the timeout function, the time of the next
4088 * timeout is recalculated based on the current time and the given interval
4089 * (it does not try to 'catch up' time lost in delays).
4091 * If you want to have a timer in the "seconds" range and do not care
4092 * about the exact time of the first call of the timer, use the
4093 * g_timeout_add_seconds() function; this function allows for more
4094 * optimizations and more efficient system power usage.
4096 * This internally creates a main loop source using g_timeout_source_new()
4097 * and attaches it to the main loop context using g_source_attach(). You can
4098 * do these steps manually if you need greater control.
4100 * Return value: the ID (greater than 0) of the event source.
4103 g_timeout_add (guint32 interval,
4104 GSourceFunc function,
4107 return g_timeout_add_full (G_PRIORITY_DEFAULT,
4108 interval, function, data, NULL);
4112 * g_timeout_add_seconds_full:
4113 * @priority: the priority of the timeout source. Typically this will be in
4114 * the range between #G_PRIORITY_DEFAULT and #G_PRIORITY_HIGH.
4115 * @interval: the time between calls to the function, in seconds
4116 * @function: function to call
4117 * @data: data to pass to @function
4118 * @notify: function to call when the timeout is removed, or %NULL
4120 * Sets a function to be called at regular intervals, with @priority.
4121 * The function is called repeatedly until it returns %FALSE, at which
4122 * point the timeout is automatically destroyed and the function will
4123 * not be called again.
4125 * Unlike g_timeout_add(), this function operates at whole second granularity.
4126 * The initial starting point of the timer is determined by the implementation
4127 * and the implementation is expected to group multiple timers together so that
4128 * they fire all at the same time.
4129 * To allow this grouping, the @interval to the first timer is rounded
4130 * and can deviate up to one second from the specified interval.
4131 * Subsequent timer iterations will generally run at the specified interval.
4133 * Note that timeout functions may be delayed, due to the processing of other
4134 * event sources. Thus they should not be relied on for precise timing.
4135 * After each call to the timeout function, the time of the next
4136 * timeout is recalculated based on the current time and the given @interval
4138 * If you want timing more precise than whole seconds, use g_timeout_add()
4141 * The grouping of timers to fire at the same time results in a more power
4142 * and CPU efficient behavior so if your timer is in multiples of seconds
4143 * and you don't require the first timer exactly one second from now, the
4144 * use of g_timeout_add_seconds() is preferred over g_timeout_add().
4146 * This internally creates a main loop source using
4147 * g_timeout_source_new_seconds() and attaches it to the main loop context
4148 * using g_source_attach(). You can do these steps manually if you need
4151 * Return value: the ID (greater than 0) of the event source.
4156 g_timeout_add_seconds_full (gint priority,
4158 GSourceFunc function,
4160 GDestroyNotify notify)
4165 g_return_val_if_fail (function != NULL, 0);
4167 source = g_timeout_source_new_seconds (interval);
4169 if (priority != G_PRIORITY_DEFAULT)
4170 g_source_set_priority (source, priority);
4172 g_source_set_callback (source, function, data, notify);
4173 id = g_source_attach (source, NULL);
4174 g_source_unref (source);
4180 * g_timeout_add_seconds:
4181 * @interval: the time between calls to the function, in seconds
4182 * @function: function to call
4183 * @data: data to pass to @function
4185 * Sets a function to be called at regular intervals with the default
4186 * priority, #G_PRIORITY_DEFAULT. The function is called repeatedly until
4187 * it returns %FALSE, at which point the timeout is automatically destroyed
4188 * and the function will not be called again.
4190 * This internally creates a main loop source using
4191 * g_timeout_source_new_seconds() and attaches it to the main loop context
4192 * using g_source_attach(). You can do these steps manually if you need
4193 * greater control. Also see g_timeout_add_seconds_full().
4195 * Note that the first call of the timer may not be precise for timeouts
4196 * of one second. If you need finer precision and have such a timeout,
4197 * you may want to use g_timeout_add() instead.
4199 * Return value: the ID (greater than 0) of the event source.
4204 g_timeout_add_seconds (guint interval,
4205 GSourceFunc function,
4208 g_return_val_if_fail (function != NULL, 0);
4210 return g_timeout_add_seconds_full (G_PRIORITY_DEFAULT, interval, function, data, NULL);
4213 /* Child watch functions */
4218 g_child_watch_prepare (GSource *source,
4227 g_child_watch_check (GSource *source)
4229 GChildWatchSource *child_watch_source;
4230 gboolean child_exited;
4232 child_watch_source = (GChildWatchSource *) source;
4234 child_exited = child_watch_source->poll.revents & G_IO_IN;
4241 * Note: We do _not_ check for the special value of STILL_ACTIVE
4242 * since we know that the process has exited and doing so runs into
4243 * problems if the child process "happens to return STILL_ACTIVE(259)"
4244 * as Microsoft's Platform SDK puts it.
4246 if (!GetExitCodeProcess (child_watch_source->pid, &child_status))
4248 gchar *emsg = g_win32_error_message (GetLastError ());
4249 g_warning (G_STRLOC ": GetExitCodeProcess() failed: %s", emsg);
4252 child_watch_source->child_status = -1;
4255 child_watch_source->child_status = child_status;
4258 return child_exited;
4261 #else /* G_OS_WIN32 */
4264 check_for_child_exited (GSource *source)
4266 GChildWatchSource *child_watch_source;
4269 /* protect against another SIGCHLD in the middle of this call */
4270 count = child_watch_count;
4272 child_watch_source = (GChildWatchSource *) source;
4274 if (child_watch_source->child_exited)
4277 if (child_watch_source->count < count)
4281 if (waitpid (child_watch_source->pid, &child_status, WNOHANG) > 0)
4283 child_watch_source->child_status = child_status;
4284 child_watch_source->child_exited = TRUE;
4286 child_watch_source->count = count;
4289 return child_watch_source->child_exited;
4293 g_child_watch_prepare (GSource *source,
4298 return check_for_child_exited (source);
4302 g_child_watch_check (GSource *source)
4304 return check_for_child_exited (source);
4308 check_for_signal_delivery (GSource *source)
4310 GUnixSignalWatchSource *unix_signal_source = (GUnixSignalWatchSource*) source;
4313 G_LOCK (unix_signal_lock);
4314 if (unix_signal_init_state == UNIX_SIGNAL_INITIALIZED_SINGLE)
4316 switch (unix_signal_source->signum)
4319 delivered = unix_signal_state.sighup_delivered;
4322 delivered = unix_signal_state.sigint_delivered;
4325 delivered = unix_signal_state.sigterm_delivered;
4328 g_assert_not_reached ();
4335 g_assert (unix_signal_init_state == UNIX_SIGNAL_INITIALIZED_THREADED);
4336 delivered = unix_signal_source->pending;
4338 G_UNLOCK (unix_signal_lock);
4344 g_unix_signal_watch_prepare (GSource *source,
4349 return check_for_signal_delivery (source);
4353 g_unix_signal_watch_check (GSource *source)
4355 return check_for_signal_delivery (source);
4359 g_unix_signal_watch_dispatch (GSource *source,
4360 GSourceFunc callback,
4363 GUnixSignalWatchSource *unix_signal_source;
4365 unix_signal_source = (GUnixSignalWatchSource *) source;
4369 g_warning ("Unix signal source dispatched without callback\n"
4370 "You must call g_source_set_callback().");
4374 (callback) (user_data);
4376 G_LOCK (unix_signal_lock);
4377 if (unix_signal_init_state == UNIX_SIGNAL_INITIALIZED_SINGLE)
4379 switch (unix_signal_source->signum)
4382 unix_signal_state.sighup_delivered = FALSE;
4385 unix_signal_state.sigint_delivered = FALSE;
4388 unix_signal_state.sigterm_delivered = FALSE;
4394 g_assert (unix_signal_init_state == UNIX_SIGNAL_INITIALIZED_THREADED);
4395 unix_signal_source->pending = FALSE;
4397 G_UNLOCK (unix_signal_lock);
4403 ensure_unix_signal_handler_installed_unlocked (int signum)
4405 struct sigaction action;
4406 GError *error = NULL;
4408 if (unix_signal_init_state == UNIX_SIGNAL_UNINITIALIZED
4409 || unix_signal_init_state == UNIX_SIGNAL_INITIALIZED_SINGLE)
4411 if (!g_thread_supported ())
4413 /* There is nothing to do for initializing in the non-threaded
4416 if (unix_signal_init_state == UNIX_SIGNAL_UNINITIALIZED)
4417 unix_signal_init_state = UNIX_SIGNAL_INITIALIZED_SINGLE;
4421 if (!g_unix_open_pipe (unix_signal_wake_up_pipe, FD_CLOEXEC, &error))
4422 g_error ("Cannot create UNIX signal wake up pipe: %s\n", error->message);
4423 g_unix_set_fd_nonblocking (unix_signal_wake_up_pipe[1], TRUE, NULL);
4425 /* We create a helper thread that polls on the wakeup pipe indefinitely */
4426 if (g_thread_create (unix_signal_helper_thread, NULL, FALSE, &error) == NULL)
4427 g_error ("Cannot create a thread to monitor UNIX signals: %s\n", error->message);
4429 unix_signal_init_state = UNIX_SIGNAL_INITIALIZED_THREADED;
4436 if (unix_signal_state.sigchld_handler_installed)
4438 unix_signal_state.sigchld_handler_installed = TRUE;
4440 if (unix_signal_state.sighup_handler_installed)
4442 unix_signal_state.sighup_handler_installed = TRUE;
4445 if (unix_signal_state.sigint_handler_installed)
4447 unix_signal_state.sigint_handler_installed = TRUE;
4450 if (unix_signal_state.sigterm_handler_installed)
4452 unix_signal_state.sigterm_handler_installed = TRUE;
4456 action.sa_handler = g_unix_signal_handler;
4457 sigemptyset (&action.sa_mask);
4458 action.sa_flags = SA_RESTART | SA_NOCLDSTOP;
4459 sigaction (signum, &action, NULL);
4463 _g_main_create_unix_signal_watch (int signum)
4466 GUnixSignalWatchSource *unix_signal_source;
4468 source = g_source_new (&g_unix_signal_funcs, sizeof (GUnixSignalWatchSource));
4469 unix_signal_source = (GUnixSignalWatchSource *) source;
4471 unix_signal_source->signum = signum;
4472 unix_signal_source->pending = FALSE;
4474 G_LOCK (unix_signal_lock);
4475 ensure_unix_signal_handler_installed_unlocked (signum);
4476 unix_signal_watches = g_slist_prepend (unix_signal_watches, unix_signal_source);
4477 G_UNLOCK (unix_signal_lock);
4483 g_unix_signal_watch_finalize (GSource *source)
4485 G_LOCK (unix_signal_lock);
4486 unix_signal_watches = g_slist_remove (unix_signal_watches, source);
4487 G_UNLOCK (unix_signal_lock);
4490 #endif /* G_OS_WIN32 */
4493 g_child_watch_dispatch (GSource *source,
4494 GSourceFunc callback,
4497 GChildWatchSource *child_watch_source;
4498 GChildWatchFunc child_watch_callback = (GChildWatchFunc) callback;
4500 child_watch_source = (GChildWatchSource *) source;
4504 g_warning ("Child watch source dispatched without callback\n"
4505 "You must call g_source_set_callback().");
4509 (child_watch_callback) (child_watch_source->pid, child_watch_source->child_status, user_data);
4511 /* We never keep a child watch source around as the child is gone */
4518 g_unix_signal_handler (int signum)
4520 if (signum == SIGCHLD)
4521 child_watch_count ++;
4523 if (unix_signal_init_state == UNIX_SIGNAL_INITIALIZED_THREADED)
4529 buf[0] = _UNIX_SIGNAL_PIPE_SIGCHLD_CHAR;
4532 buf[0] = _UNIX_SIGNAL_PIPE_SIGHUP_CHAR;
4535 buf[0] = _UNIX_SIGNAL_PIPE_SIGINT_CHAR;
4538 buf[0] = _UNIX_SIGNAL_PIPE_SIGTERM_CHAR;
4541 /* Shouldn't happen */
4544 write (unix_signal_wake_up_pipe[1], buf, 1);
4548 /* We count on the signal interrupting the poll in the same thread. */
4552 /* Nothing to do - the handler will call waitpid() */
4555 unix_signal_state.sighup_delivered = TRUE;
4558 unix_signal_state.sigint_delivered = TRUE;
4561 unix_signal_state.sigterm_delivered = TRUE;
4564 g_assert_not_reached ();
4571 deliver_unix_signal (int signum)
4574 g_assert (signum == SIGHUP || signum == SIGINT || signum == SIGTERM);
4576 G_LOCK (unix_signal_lock);
4577 for (iter = unix_signal_watches; iter; iter = iter->next)
4579 GUnixSignalWatchSource *source = iter->data;
4581 if (source->signum != signum)
4584 source->pending = TRUE;
4586 G_UNLOCK (unix_signal_lock);
4590 * This thread is created whenever anything in GLib needs
4591 * to deal with UNIX signals; at present, just SIGCHLD
4592 * from g_child_watch_source_new().
4594 * Note: We could eventually make this thread a more public interface
4595 * and allow e.g. GDBus to use it instead of its own worker thread.
4598 unix_signal_helper_thread (gpointer data)
4603 ssize_t i, bytes_read;
4604 gboolean sigterm_received = FALSE;
4605 gboolean sigint_received = FALSE;
4606 gboolean sighup_received = FALSE;
4608 bytes_read = read (unix_signal_wake_up_pipe[0], b, sizeof (b));
4611 g_warning ("Failed to read from child watch wake up pipe: %s",
4613 /* Not much we can do here sanely; just wait a second and hope
4616 g_usleep (G_USEC_PER_SEC);
4619 for (i = 0; i < bytes_read; i++)
4623 case _UNIX_SIGNAL_PIPE_SIGCHLD_CHAR:
4624 /* The child watch source will call waitpid() in its
4625 * prepare() and check() methods; however, we don't
4626 * know which pid exited, so we need to wake up
4627 * all contexts. Note: actually we could get the pid
4628 * from the "siginfo_t" via the handler, but to pass
4629 * that info down the pipe would require a more structured
4630 * data stream (as opposed to a single byte).
4633 case _UNIX_SIGNAL_PIPE_SIGTERM_CHAR:
4634 sigterm_received = TRUE;
4636 case _UNIX_SIGNAL_PIPE_SIGHUP_CHAR:
4637 sighup_received = TRUE;
4639 case _UNIX_SIGNAL_PIPE_SIGINT_CHAR:
4640 sigint_received = TRUE;
4643 g_warning ("Invalid char '%c' read from child watch pipe", b[i]);
4646 if (sigterm_received)
4647 deliver_unix_signal (SIGTERM);
4648 if (sigint_received)
4649 deliver_unix_signal (SIGINT);
4650 if (sighup_received)
4651 deliver_unix_signal (SIGHUP);
4652 _g_main_wake_up_all_contexts ();
4658 g_child_watch_source_init (void)
4660 G_LOCK (unix_signal_lock);
4661 ensure_unix_signal_handler_installed_unlocked (SIGCHLD);
4662 G_UNLOCK (unix_signal_lock);
4665 #endif /* !G_OS_WIN32 */
4668 * g_child_watch_source_new:
4669 * @pid: process to watch. On POSIX the pid of a child process. On
4670 * Windows a handle for a process (which doesn't have to be a child).
4672 * Creates a new child_watch source.
4674 * The source will not initially be associated with any #GMainContext
4675 * and must be added to one with g_source_attach() before it will be
4678 * Note that child watch sources can only be used in conjunction with
4679 * <literal>g_spawn...</literal> when the %G_SPAWN_DO_NOT_REAP_CHILD
4682 * Note that on platforms where #GPid must be explicitly closed
4683 * (see g_spawn_close_pid()) @pid must not be closed while the
4684 * source is still active. Typically, you will want to call
4685 * g_spawn_close_pid() in the callback function for the source.
4687 * Note further that using g_child_watch_source_new() is not
4688 * compatible with calling <literal>waitpid(-1)</literal> in
4689 * the application. Calling waitpid() for individual pids will
4692 * Return value: the newly-created child watch source
4697 g_child_watch_source_new (GPid pid)
4699 GSource *source = g_source_new (&g_child_watch_funcs, sizeof (GChildWatchSource));
4700 GChildWatchSource *child_watch_source = (GChildWatchSource *)source;
4703 child_watch_source->poll.fd = (gintptr) pid;
4704 child_watch_source->poll.events = G_IO_IN;
4706 g_source_add_poll (source, &child_watch_source->poll);
4707 #else /* G_OS_WIN32 */
4708 g_child_watch_source_init ();
4709 #endif /* G_OS_WIN32 */
4711 child_watch_source->pid = pid;
4717 * g_child_watch_add_full:
4718 * @priority: the priority of the idle source. Typically this will be in the
4719 * range between #G_PRIORITY_DEFAULT_IDLE and #G_PRIORITY_HIGH_IDLE.
4720 * @pid: process to watch. On POSIX the pid of a child process. On
4721 * Windows a handle for a process (which doesn't have to be a child).
4722 * @function: function to call
4723 * @data: data to pass to @function
4724 * @notify: function to call when the idle is removed, or %NULL
4726 * Sets a function to be called when the child indicated by @pid
4727 * exits, at the priority @priority.
4729 * If you obtain @pid from g_spawn_async() or g_spawn_async_with_pipes()
4730 * you will need to pass #G_SPAWN_DO_NOT_REAP_CHILD as flag to
4731 * the spawn function for the child watching to work.
4733 * Note that on platforms where #GPid must be explicitly closed
4734 * (see g_spawn_close_pid()) @pid must not be closed while the
4735 * source is still active. Typically, you will want to call
4736 * g_spawn_close_pid() in the callback function for the source.
4738 * GLib supports only a single callback per process id.
4740 * This internally creates a main loop source using
4741 * g_child_watch_source_new() and attaches it to the main loop context
4742 * using g_source_attach(). You can do these steps manually if you
4743 * need greater control.
4745 * Return value: the ID (greater than 0) of the event source.
4750 g_child_watch_add_full (gint priority,
4752 GChildWatchFunc function,
4754 GDestroyNotify notify)
4759 g_return_val_if_fail (function != NULL, 0);
4761 source = g_child_watch_source_new (pid);
4763 if (priority != G_PRIORITY_DEFAULT)
4764 g_source_set_priority (source, priority);
4766 g_source_set_callback (source, (GSourceFunc) function, data, notify);
4767 id = g_source_attach (source, NULL);
4768 g_source_unref (source);
4774 * g_child_watch_add:
4775 * @pid: process id to watch. On POSIX the pid of a child process. On
4776 * Windows a handle for a process (which doesn't have to be a child).
4777 * @function: function to call
4778 * @data: data to pass to @function
4780 * Sets a function to be called when the child indicated by @pid
4781 * exits, at a default priority, #G_PRIORITY_DEFAULT.
4783 * If you obtain @pid from g_spawn_async() or g_spawn_async_with_pipes()
4784 * you will need to pass #G_SPAWN_DO_NOT_REAP_CHILD as flag to
4785 * the spawn function for the child watching to work.
4787 * Note that on platforms where #GPid must be explicitly closed
4788 * (see g_spawn_close_pid()) @pid must not be closed while the
4789 * source is still active. Typically, you will want to call
4790 * g_spawn_close_pid() in the callback function for the source.
4792 * GLib supports only a single callback per process id.
4794 * This internally creates a main loop source using
4795 * g_child_watch_source_new() and attaches it to the main loop context
4796 * using g_source_attach(). You can do these steps manually if you
4797 * need greater control.
4799 * Return value: the ID (greater than 0) of the event source.
4804 g_child_watch_add (GPid pid,
4805 GChildWatchFunc function,
4808 return g_child_watch_add_full (G_PRIORITY_DEFAULT, pid, function, data, NULL);
4812 /* Idle functions */
4815 g_idle_prepare (GSource *source,
4824 g_idle_check (GSource *source)
4830 g_idle_dispatch (GSource *source,
4831 GSourceFunc callback,
4836 g_warning ("Idle source dispatched without callback\n"
4837 "You must call g_source_set_callback().");
4841 return callback (user_data);
4845 * g_idle_source_new:
4847 * Creates a new idle source.
4849 * The source will not initially be associated with any #GMainContext
4850 * and must be added to one with g_source_attach() before it will be
4851 * executed. Note that the default priority for idle sources is
4852 * %G_PRIORITY_DEFAULT_IDLE, as compared to other sources which
4853 * have a default priority of %G_PRIORITY_DEFAULT.
4855 * Return value: the newly-created idle source
4858 g_idle_source_new (void)
4862 source = g_source_new (&g_idle_funcs, sizeof (GSource));
4863 g_source_set_priority (source, G_PRIORITY_DEFAULT_IDLE);
4870 * @priority: the priority of the idle source. Typically this will be in the
4871 * range between #G_PRIORITY_DEFAULT_IDLE and #G_PRIORITY_HIGH_IDLE.
4872 * @function: function to call
4873 * @data: data to pass to @function
4874 * @notify: function to call when the idle is removed, or %NULL
4876 * Adds a function to be called whenever there are no higher priority
4877 * events pending. If the function returns %FALSE it is automatically
4878 * removed from the list of event sources and will not be called again.
4880 * This internally creates a main loop source using g_idle_source_new()
4881 * and attaches it to the main loop context using g_source_attach().
4882 * You can do these steps manually if you need greater control.
4884 * Return value: the ID (greater than 0) of the event source.
4887 g_idle_add_full (gint priority,
4888 GSourceFunc function,
4890 GDestroyNotify notify)
4895 g_return_val_if_fail (function != NULL, 0);
4897 source = g_idle_source_new ();
4899 if (priority != G_PRIORITY_DEFAULT_IDLE)
4900 g_source_set_priority (source, priority);
4902 g_source_set_callback (source, function, data, notify);
4903 id = g_source_attach (source, NULL);
4904 g_source_unref (source);
4911 * @function: function to call
4912 * @data: data to pass to @function.
4914 * Adds a function to be called whenever there are no higher priority
4915 * events pending to the default main loop. The function is given the
4916 * default idle priority, #G_PRIORITY_DEFAULT_IDLE. If the function
4917 * returns %FALSE it is automatically removed from the list of event
4918 * sources and will not be called again.
4920 * This internally creates a main loop source using g_idle_source_new()
4921 * and attaches it to the main loop context using g_source_attach().
4922 * You can do these steps manually if you need greater control.
4924 * Return value: the ID (greater than 0) of the event source.
4927 g_idle_add (GSourceFunc function,
4930 return g_idle_add_full (G_PRIORITY_DEFAULT_IDLE, function, data, NULL);
4934 * g_idle_remove_by_data:
4935 * @data: the data for the idle source's callback.
4937 * Removes the idle function with the given data.
4939 * Return value: %TRUE if an idle source was found and removed.
4942 g_idle_remove_by_data (gpointer data)
4944 return g_source_remove_by_funcs_user_data (&g_idle_funcs, data);
4948 * g_main_context_invoke:
4949 * @context: a #GMainContext, or %NULL
4950 * @function: function to call
4951 * @data: data to pass to @function
4953 * Invokes a function in such a way that @context is owned during the
4954 * invocation of @function.
4956 * If @context is %NULL then the global default main context — as
4957 * returned by g_main_context_default() — is used.
4959 * If @context is owned by the current thread, @function is called
4960 * directly. Otherwise, if @context is the thread-default main context
4961 * of the current thread and g_main_context_acquire() succeeds, then
4962 * @function is called and g_main_context_release() is called
4965 * In any other case, an idle source is created to call @function and
4966 * that source is attached to @context (presumably to be run in another
4967 * thread). The idle source is attached with #G_PRIORITY_DEFAULT
4968 * priority. If you want a different priority, use
4969 * g_main_context_invoke_full().
4971 * Note that, as with normal idle functions, @function should probably
4972 * return %FALSE. If it returns %TRUE, it will be continuously run in a
4973 * loop (and may prevent this call from returning).
4978 g_main_context_invoke (GMainContext *context,
4979 GSourceFunc function,
4982 g_main_context_invoke_full (context,
4984 function, data, NULL);
4988 * g_main_context_invoke_full:
4989 * @context: a #GMainContext, or %NULL
4990 * @priority: the priority at which to run @function
4991 * @function: function to call
4992 * @data: data to pass to @function
4993 * @notify: a function to call when @data is no longer in use, or %NULL.
4995 * Invokes a function in such a way that @context is owned during the
4996 * invocation of @function.
4998 * This function is the same as g_main_context_invoke() except that it
4999 * lets you specify the priority incase @function ends up being
5000 * scheduled as an idle and also lets you give a #GDestroyNotify for @data.
5002 * @notify should not assume that it is called from any particular
5003 * thread or with any particular context acquired.
5008 g_main_context_invoke_full (GMainContext *context,
5010 GSourceFunc function,
5012 GDestroyNotify notify)
5014 g_return_if_fail (function != NULL);
5017 context = g_main_context_default ();
5019 if (g_main_context_is_owner (context))
5021 while (function (data));
5028 GMainContext *thread_default;
5030 thread_default = g_main_context_get_thread_default ();
5032 if (!thread_default)
5033 thread_default = g_main_context_default ();
5035 if (thread_default == context && g_main_context_acquire (context))
5037 while (function (data));
5039 g_main_context_release (context);
5048 source = g_idle_source_new ();
5049 g_source_set_priority (source, priority);
5050 g_source_set_callback (source, function, data, notify);
5051 g_source_attach (source, context);
5052 g_source_unref (source);